text:
import * as chalk from 'chalk';
import * as fs from 'fs';
import * as path from 'path';
import type * as typescript from 'typescript';
import * as webpack from 'webpack';

import { makeAfterCompile } from './after-compile';
import { getCompiler, getCompilerOptions } from './compilerSetup';
import { getConfigFile, getConfigParseResult } from './config';
import {
  declarationRegex,
  dtsDtsxOrDtsDtsxMapRegex,
  EOL,
  tsTsxRegex,
} from './constants';
import { getTSInstanceFromCache, setTSInstanceInCache } from './instance-cache';
import { FilePathKey, LoaderOptions, TSFiles, TSInstance } from './interfaces';
import * as logger from './logger';
import {
  getSolutionErrors,
  makeServicesHost,
  makeSolutionBuilderHost,
  makeWatchHost,
} from './servicesHost';
import {
  appendSuffixesIfMatch,
  ensureProgram,
  formatErrors,
  isReferencedFile,
  makeError,
  supportsSolutionBuild,
  useCaseSensitiveFileNames,
} from './utils';
import { makeWatchRun } from './watch-run';

const instancesBySolutionBuilderConfigs = new Map<FilePathKey, TSInstance>();

/**
 * The loader is executed once for each file seen by webpack. However, we need to keep
 * a persistent instance of TypeScript that contains all of the files in the program
 * along with definition files and options. This function either creates an instance
 * or returns the existing one. Multiple instances are possible by using the
 * `instance` property.
 */
export function getTypeScriptInstance(
  loaderOptions: LoaderOptions,
  loader: webpack.LoaderContext<LoaderOptions>
): { instance?: TSInstance; error?: webpack.WebpackError } {
  const existing = getTSInstanceFromCache(
    loader._compiler!,
    loaderOptions.instance
  );
  if (existing) {
    if (!existing.initialSetupPending) {
      ensureProgram(existing);
    }
    return { instance: existing };
  }

  const level =
    loaderOptions.colors && chalk.supportsColor ? chalk.supportsColor.level : 0;
  const colors = new chalk.Instance({ level });
  const log = logger.makeLogger(loaderOptions, colors);
  const compiler = getCompiler(loaderOptions, log);

  if (compiler.errorMessage !== undefined) {
    return {
      error: makeError(loaderOptions, colors.red(compiler.errorMessage), ''),
    };
  }

  return successfulTypeScriptInstance(
    loaderOptions,
    loader,
    log,
    colors,
    compiler.compiler!,
    compiler.compilerCompatible!,
    compiler.compilerDetailsLogMessage!
  );
}

function createFilePathKeyMapper(
  compiler: typeof typescript,
  loaderOptions: LoaderOptions
) {
  // Cache file path key - a map lookup is much faster than filesystem/regex operations & the result will never change
  const filePathMapperCache = new Map<string, FilePathKey>();
  // FileName lowercasing copied from typescript
  const fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_\. ]+/g;
  return useCaseSensitiveFileNames(compiler, loaderOptions)
    ? pathResolve
    : toFileNameLowerCase;

  function pathResolve(filePath: string) {
    let cachedPath = filePathMapperCache.get(filePath);
    if (!cachedPath) {
      cachedPath = path.resolve(filePath) as FilePathKey;
      filePathMapperCache.set(filePath, cachedPath);
    }
    return cachedPath;
  }

  function toFileNameLowerCase(filePath: string) {
    let cachedPath = filePathMapperCache.get(filePath);
    if (!cachedPath) {
      const filePathKey = pathResolve(filePath);
      cachedPath = fileNameLowerCaseRegExp.test(filePathKey)
        ? (filePathKey.replace(fileNameLowerCaseRegExp, ch =>
            ch.toLowerCase()
          ) as FilePathKey)
        : filePathKey;
      filePathMapperCache.set(filePath, cachedPath);
    }
    return cachedPath;
  }
}

function successfulTypeScriptInstance(
  loaderOptions: LoaderOptions,
  loader: webpack.LoaderContext<LoaderOptions>,
  log: logger.Logger,
  colors: chalk.Chalk,
  compiler: typeof typescript,
  compilerCompatible: boolean,
  compilerDetailsLogMessage: string
) {
  const configFileAndPath = getConfigFile(
    compiler,
    colors,
    loader,
    loaderOptions,
    compilerCompatible,
    log,
    compilerDetailsLogMessage!
  );

  if (configFileAndPath.configFileError !== undefined) {
    const { message, file } = configFileAndPath.configFileError;
    return {
      error: makeError(
        loaderOptions,
        colors.red('error while reading tsconfig.json:' + EOL + message),
        file
      ),
    };
  }

  const { configFilePath, configFile } = configFileAndPath;
  const filePathKeyMapper = createFilePathKeyMapper(compiler, loaderOptions);
  if (configFilePath && loaderOptions.projectReferences) {
    const configFileKey = filePathKeyMapper(configFilePath);
    const existing = getExistingSolutionBuilderHost(configFileKey);
    if (existing) {
      // Reuse the instance if config file for project references is shared.
      setTSInstanceInCache(loader._compiler, loaderOptions.instance, existing);
      return { instance: existing };
    }
  }

  const module = loader._module!;
  const basePath = loaderOptions.context || path.dirname(configFilePath || '');
  const configParseResult = getConfigParseResult(
    compiler,
    configFile,
    basePath,
    configFilePath,
    loaderOptions
  );

  if (configParseResult.errors.length > 0 && !loaderOptions.happyPackMode) {
    const errors = formatErrors(
      configParseResult.errors,
      loaderOptions,
      colors,
      compiler,
      { file: configFilePath },
      loader.context
    );

    errors.forEach(error => module.addError(error));

    return {
      error: makeError(
        loaderOptions,
        colors.red('error while parsing tsconfig.json'),
        configFilePath || ''
      ),
    };
  }

  const compilerOptions = getCompilerOptions(configParseResult, compiler);
  const rootFileNames = new Set<string>();
  const files: TSFiles = new Map();
  const otherFiles: TSFiles = new Map();

  const appendTsTsxSuffixesIfRequired =
    loaderOptions.appendTsSuffixTo.length > 0 ||
    loaderOptions.appendTsxSuffixTo.length > 0
      ? (filePath: string) =>
          appendSuffixesIfMatch(
            {
              '.ts': loaderOptions.appendTsSuffixTo,
              '.tsx': loaderOptions.appendTsxSuffixTo,
            },
            filePath
          )
      : (filePath: string) => filePath;

  if (loaderOptions.transpileOnly) {
    // quick return for transpiling
    // we do need to check for any issues with TS options though
    const transpileInstance: TSInstance = {
      compiler,
      compilerOptions,
      appendTsTsxSuffixesIfRequired,
      loaderOptions,
      rootFileNames,
      files,
      otherFiles,
      version: 0,
      program: undefined, // temporary, to be set later
      dependencyGraph: new Map(),
      transformers: {} as typescript.CustomTransformers, // this is only set temporarily, custom transformers are created further down
      colors,
      initialSetupPending: true,
      reportTranspileErrors: true,
      configFilePath,
      configParseResult,
      log,
      filePathKeyMapper,
    };

    setTSInstanceInCache(
      loader._compiler,
      loaderOptions.instance,
      transpileInstance
    );
    return { instance: transpileInstance };
  }

  // Load initial files (core lib files, any files specified in tsconfig.json)
  let normalizedFilePath: string;
  try {
    const filesToLoad = loaderOptions.onlyCompileBundledFiles
      ? configParseResult.fileNames.filter(fileName =>
          dtsDtsxOrDtsDtsxMapRegex.test(fileName)
        )
      : configParseResult.fileNames;
    filesToLoad.forEach(filePath => {
      normalizedFilePath = path.normalize(filePath);
      files.set(filePathKeyMapper(normalizedFilePath), {
        fileName: normalizedFilePath,
        text: fs.readFileSync(normalizedFilePath, 'utf-8'),
        version: 0,
      });
      rootFileNames.add(normalizedFilePath);
    });
  } catch (exc) {
    return {
      error: makeError(
        loaderOptions,
        colors.red(
          `A file specified in tsconfig.json could not be found: ${normalizedFilePath!}`
        ),
        normalizedFilePath!
      ),
    };
  }

  const instance: TSInstance = {
    compiler,
    compilerOptions,
    appendTsTsxSuffixesIfRequired,
    loaderOptions,
    rootFileNames,
    files,
    otherFiles,
    languageService: null,
    version: 0,
    transformers: {} as typescript.CustomTransformers, // this is only set temporarily, custom transformers are created further down
    dependencyGraph: new Map(),
    colors,
    initialSetupPending: true,
    configFilePath,
    configParseResult,
    log,
    filePathKeyMapper,
  };

  setTSInstanceInCache(loader._compiler, loaderOptions.instance, instance);
  return { instance };
}

function getExistingSolutionBuilderHost(key: FilePathKey) {
  const existing = instancesBySolutionBuilderConfigs.get(key);
  if (existing) return existing;
  for (const instance of instancesBySolutionBuilderConfigs.values()) {
    if (instance.solutionBuilderHost!.configFileInfo.has(key)) {
      return instance;
    }
  }
  return undefined;
}

function addAssetHooks(
  loader: webpack.LoaderContext<LoaderOptions>,
  instance: TSInstance
) {
  // makeAfterCompile is a closure.  It returns a function which closes over the variable checkAllFilesForErrors
  // We need to get the function once and then reuse it, otherwise it will be recreated each time
  // and all files will always be checked.
  const cachedMakeAfterCompile = makeAfterCompile(
    instance,
    instance.configFilePath
  );

  const makeAssetsCallback = (compilation: webpack.Compilation) => {
    compilation.hooks.processAssets.tap(
      {
        name: 'ts-loader',
        stage: webpack.Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL,
      },
      () => {
        cachedMakeAfterCompile(compilation, () => {
          return null;
        });
      }
    );
  };

  // We need to add the hook above for each run.
  // For the first run, we just need to add the hook to loader._compilation
  makeAssetsCallback(loader._compilation!);

  // For future calls in watch mode we need to watch for a new compilation and add the hook
  loader._compiler!.hooks.compilation.tap('ts-loader', makeAssetsCallback);
}

export function initializeInstance(
  loader: webpack.LoaderContext<LoaderOptions>,
  instance: TSInstance
) {
  if (!instance.initialSetupPending) {
    return;
  }

  instance.initialSetupPending = false;

  // same strategy as https://github.com/s-panferov/awesome-typescript-loader/pull/531/files
  let { getCustomTransformers: customerTransformers } = instance.loaderOptions;
  let getCustomTransformers = Function.prototype;

  if (typeof customerTransformers === 'function') {
    getCustomTransformers = customerTransformers;
  } else if (typeof customerTransformers === 'string') {
    try {
      customerTransformers = require(customerTransformers);
    } catch (err) {
      throw new Error(
        `Failed to load customTransformers from "${
          instance.loaderOptions.getCustomTransformers
        }": ${err instanceof Error ? err.message : 'unknown error'}`
      );
    }

    if (typeof customerTransformers !== 'function') {
      throw new Error(
        `Custom transformers in "${
          instance.loaderOptions.getCustomTransformers
        }" should export a function, got ${typeof customerTransformers}`
      );
    }
    getCustomTransformers = customerTransformers;
  }

  if (instance.loaderOptions.transpileOnly) {
    const program = (instance.program =
      instance.configParseResult.projectReferences !== undefined
        ? instance.compiler.createProgram({
            rootNames: instance.configParseResult.fileNames,
            options: instance.configParseResult.options,
            projectReferences: instance.configParseResult.projectReferences,
          })
        : instance.compiler.createProgram([], instance.compilerOptions));

    const getProgram = () => program;
    instance.transformers = getCustomTransformers(program, getProgram);
    // Setup watch run for solution building
    if (instance.solutionBuilderHost) {
      addAssetHooks(loader, instance);
      loader._compiler!.hooks.watchRun.tapAsync(
        'ts-loader',
        makeWatchRun(instance, loader)
      );
    }
  } else {
    if (!loader._compiler!.hooks) {
      throw new Error(
        "You may be using an old version of webpack; please check you're using at least version 4"
      );
    }

    if (instance.loaderOptions.experimentalWatchApi) {
      instance.log.logInfo('Using watch api');

      // If there is api available for watch, use it instead of language service
      instance.watchHost = makeWatchHost(
        getScriptRegexp(instance),
        loader,
        instance,
        instance.configParseResult.projectReferences
      );
      instance.watchOfFilesAndCompilerOptions =
        instance.compiler.createWatchProgram(instance.watchHost);
      instance.builderProgram =
        instance.watchOfFilesAndCompilerOptions.getProgram();

      const getProgram = () => instance.builderProgram?.getProgram();
      instance.program = getProgram();
      instance.transformers = getCustomTransformers(
        instance.program,
        getProgram
      );
    } else {
      instance.servicesHost = makeServicesHost(
        getScriptRegexp(instance),
        loader,
        instance,
        instance.configParseResult.projectReferences
      );

      instance.languageService = instance.compiler.createLanguageService(
        instance.servicesHost,
        instance.compiler.createDocumentRegistry()
      );

      const getProgram = () => instance.languageService!.getProgram();
      instance.transformers = getCustomTransformers(getProgram(), getProgram);
    }

    addAssetHooks(loader, instance);

    loader._compiler!.hooks.watchRun.tapAsync(
      'ts-loader',
      makeWatchRun(instance, loader)
    );
  }
}

function getScriptRegexp(instance: TSInstance) {
  // If resolveJsonModules is set, we should accept json files
  if (instance.configParseResult.options.resolveJsonModule) {
    // if allowJs is set then we should accept js(x) files
    return instance.configParseResult.options.allowJs === true
      ? /\.([cm]?[tj]s|[tj]sx|json)$/i
      : /\.([cm]?ts|tsx|json)$/i;
  }
  // if allowJs is set then we should accept js(x) files
  return instance.configParseResult.options.allowJs === true
    ? /\.([cm]?[tj]s|[tj]sx)$/i
    : /\.([cm]?ts|tsx)$/i;
}

export function reportTranspileErrors(
  instance: TSInstance,
  loader: webpack.LoaderContext<LoaderOptions>
) {
  if (!instance.reportTranspileErrors) {
    return;
  }
  const module = loader._module;
  instance.reportTranspileErrors = false;
  // happypack does not have _module.errors - see https://github.com/TypeStrong/ts-loader/issues/336
  if (!instance.loaderOptions.happyPackMode) {
    const solutionErrors: webpack.WebpackError[] = getSolutionErrors(
      instance,
      loader.context
    );
    const diagnostics = instance.program!.getOptionsDiagnostics();
    const errors = formatErrors(
      diagnostics,
      instance.loaderOptions,
      instance.colors,
      instance.compiler,
      { file: instance.configFilePath || 'tsconfig.json' },
      loader.context
    );

    [...solutionErrors, ...errors].forEach(error => module!.addError(error));
  }
}

export function buildSolutionReferences(
  instance: TSInstance,
  loader: webpack.LoaderContext<LoaderOptions>
) {
  if (!supportsSolutionBuild(instance)) {
    return;
  }
  if (!instance.solutionBuilderHost) {
    // Use solution builder
    instance.log.logInfo('Using SolutionBuilder api');
    const scriptRegex = getScriptRegexp(instance);
    instance.solutionBuilderHost = makeSolutionBuilderHost(
      scriptRegex,
      loader,
      instance
    );
    const solutionBuilder = instance.compiler.createSolutionBuilderWithWatch(
      instance.solutionBuilderHost,
      instance.configParseResult.projectReferences!.map(ref => ref.path),
      { verbose: true }
    );
    solutionBuilder.build();
    instance.solutionBuilderHost.ensureAllReferenceTimestamps();
    instancesBySolutionBuilderConfigs.set(
      instance.filePathKeyMapper(instance.configFilePath!),
      instance
    );
  } else {
    instance.solutionBuilderHost.buildReferences();
  }
}

export function forEachResolvedProjectReference<T>(
  resolvedProjectReferences:
    | readonly (typescript.ResolvedProjectReference | undefined)[]
    | undefined,
  cb: (
    resolvedProjectReference: typescript.ResolvedProjectReference
  ) => T | undefined
): T | undefined {
  let seenResolvedRefs: typescript.ResolvedProjectReference[] | undefined;
  return worker(resolvedProjectReferences);
  function worker(
    resolvedRefs:
      | readonly (typescript.ResolvedProjectReference | undefined)[]
      | undefined
  ): T | undefined {
    if (resolvedRefs) {
      for (const resolvedRef of resolvedRefs) {
        if (!resolvedRef) {
          continue;
        }
        if (
          seenResolvedRefs &&
          seenResolvedRefs.some(seenRef => seenRef === resolvedRef)
        ) {
          // ignore recursives
          continue;
        }

        (seenResolvedRefs || (seenResolvedRefs = [])).push(resolvedRef);
        const result = cb(resolvedRef) || worker(resolvedRef.references);
        if (result) {
          return result;
        }
      }
    }
    return undefined;
  }
}

// This code is here as a temporary holder
function fileExtensionIs(fileName: string, ext: string) {
  return fileName.endsWith(ext);
}

function rootDirOfOptions(
  instance: TSInstance,
  configFile: typescript.ParsedCommandLine
) {
  return (
    configFile.options.rootDir ||
    (instance.compiler as any).getDirectoryPath(
      configFile.options.configFilePath
    )
  );
}

function getOutputPathWithoutChangingExt(
  instance: TSInstance,
  inputFileName: string,
  configFile: typescript.ParsedCommandLine,
  ignoreCase: boolean,
  outputDir: string | undefined
) {
  return outputDir
    ? (instance.compiler as any).resolvePath(
        outputDir,
        (instance.compiler as any).getRelativePathFromDirectory(
          rootDirOfOptions(instance, configFile),
          inputFileName,
          ignoreCase
        )
      )
    : inputFileName;
}

function getOutputJSFileName(
  instance: TSInstance,
  inputFileName: string,
  configFile: typescript.ParsedCommandLine,
  ignoreCase: boolean
) {
  if (configFile.options.emitDeclarationOnly) {
    return undefined;
  }
  const isJsonFile = fileExtensionIs(inputFileName, '.json');
  const outputFileName = (instance.compiler as any).changeExtension(
    getOutputPathWithoutChangingExt(
      instance,
      inputFileName,
      configFile,
      ignoreCase,
      configFile.options.outDir
    ),
    isJsonFile
      ? '.json'
      : fileExtensionIs(inputFileName, '.tsx') &&
        configFile.options.jsx === instance.compiler.JsxEmit.Preserve
      ? '.jsx'
      : '.js'
  );
  return !isJsonFile ||
    (instance.compiler as any).comparePaths(
      inputFileName,
      outputFileName,
      configFile.options.configFilePath,
      ignoreCase
    ) !== (instance.compiler as any).Comparison.EqualTo
    ? outputFileName
    : undefined;
}

export function getOutputFileNames(
  instance: TSInstance,
  configFile: typescript.ParsedCommandLine,
  inputFileName: string
): string[] {
  const ignoreCase = !useCaseSensitiveFileNames(
    instance.compiler,
    instance.loaderOptions
  );
  if ((instance.compiler as any).getOutputFileNames) {
    return (instance.compiler as any).getOutputFileNames(
      configFile,
      inputFileName,
      ignoreCase
    );
  }
  const outputs: string[] = [];
  const addOutput = (fileName: string | undefined) =>
    fileName && outputs.push(fileName);
  const js = getOutputJSFileName(
    instance,
    inputFileName,
    configFile,
    ignoreCase
  );
  addOutput(js);
  if (!fileExtensionIs(inputFileName, '.json')) {
    if (js && configFile.options.sourceMap) {
      addOutput(`${js}.map`);
    }
    if (
      (configFile.options.declaration || configFile.options.composite) &&
      (instance.compiler as any).hasTSFileExtension(inputFileName)
    ) {
      const dts = (instance.compiler as any).getOutputDeclarationFileName(
        inputFileName,
        configFile,
        ignoreCase
      );
      addOutput(dts);
      if (configFile.options.declarationMap) {
        addOutput(`${dts}.map`);
      }
    }
  }

  return outputs;
}

export function getInputFileNameFromOutput(
  instance: TSInstance,
  filePath: string
): string | undefined {
  if (filePath.match(tsTsxRegex) && !declarationRegex.test(filePath)) {
    return undefined;
  }
  if (instance.solutionBuilderHost) {
    return instance.solutionBuilderHost.getInputFileNameFromOutput(filePath);
  }
  const program = ensureProgram(instance);
  return (
    program &&
    program.getResolvedProjectReferences &&
    forEachResolvedProjectReference(
      program.getResolvedProjectReferences(),
      ({ commandLine }) => {
        const { options, fileNames } = commandLine;
        if (!options.outFile && !options.out) {
          const input = fileNames.find(file =>
            getOutputFileNames(instance, commandLine, file).find(
              name => path.resolve(name) === filePath
            )
          );
          return input && path.resolve(input);
        }
        return undefined;
      }
    )
  );
}

export function getEmitFromWatchHost(instance: TSInstance, filePath?: string) {
  const program = ensureProgram(instance);
  const builderProgram = instance.builderProgram;
  if (builderProgram && program) {
    if (filePath) {
      const existing = instance.watchHost!.outputFiles.get(
        instance.filePathKeyMapper(filePath)
      );
      if (existing) {
        return existing;
      }
    }

    const outputFiles: typescript.OutputFile[] = [];
    const writeFile: typescript.WriteFileCallback = (
      fileName,
      text,
      writeByteOrderMark
    ) => {
      if (fileName.endsWith('.tsbuildinfo')) {
        instance.watchHost!.tsbuildinfo = {
          name: fileName,
          writeByteOrderMark,
          text,
        };
      } else {
        outputFiles.push({ name: fileName, writeByteOrderMark, text });
      }
    };

    const sourceFile = filePath ? program.getSourceFile(filePath) : undefined;
    // Try emit Next file
    while (true) {
      const result = builderProgram.emitNextAffectedFile(
        writeFile,
        /*cancellationToken*/ undefined,
        /*emitOnlyDtsFiles*/ false,
        instance.transformers
      );
      if (!result) {
        break;
      }

      // Only put the output file in the cache if the source came from webpack and
      // was processed by the loaders
      if (result.affected === sourceFile) {
        instance.watchHost!.outputFiles.set(
          instance.filePathKeyMapper(
            (result.affected as typescript.SourceFile).fileName
          ),
          outputFiles.slice()
        );
        return outputFiles;
      }
    }
  }
  return undefined;
}

export function getEmitOutput(instance: TSInstance, filePath: string) {
  if (fileExtensionIs(filePath, instance.compiler.Extension.Dts)) {
    return [];
  }
  if (isReferencedFile(instance, filePath)) {
    return instance.solutionBuilderHost!.getOutputFilesFromReferencedProjectInput(
      filePath
    );
  }
  const program = ensureProgram(instance);
  if (program !== undefined) {
    const sourceFile = program.getSourceFile(filePath);
    const outputFiles: typescript.OutputFile[] = [];
    const writeFile = (
      fileName: string,
      text: string,
      writeByteOrderMark: boolean
    ) => outputFiles.push({ name: fileName, writeByteOrderMark, text });
    const outputFilesFromWatch = getEmitFromWatchHost(instance, filePath);
    if (outputFilesFromWatch) {
      return outputFilesFromWatch;
    }
    program.emit(
      sourceFile,
      writeFile,
      /*cancellationToken*/ undefined,
      /*emitOnlyDtsFiles*/ false,
      instance.transformers
    );
    return outputFiles;
  } else {
    // Emit Javascript
    return instance.languageService!.getProgram()!.getSourceFile(filePath) ===
      undefined
      ? []
      : instance.languageService!.getEmitOutput(filePath).outputFiles;
  }
}


text:
package metrics

import (
	"log"
	"time"
)

// LogElapsedTime logs time since start. Typically used with a defer statement:
//  defer LogElapsedTime(time.Now(), "myfunction")
// time.Now() will be evaluated instantly, but the logging won't occur until
// until the end of the function
func LogElapsedTime(start time.Time, name string) {
	elapsed := time.Since(start)
	log.Printf("%s took %s", name, elapsed)
}

redpajama_set_name: RedPajamaGithub


text:
from ..models import  *
import json

def topTenRanking(request):
    try:
        rankingObj = rankingSet.objects.filter(questionID=request['questionID']).order_by('-userScore')
        objCount = rankingObj.count()
    except Exception as e:
        return '404-1'
    try:
        topTenObj = Top10Model.objects.filter(questionID = request['questionID'])
        if topTenObj.count() == 0:
            topTenObj = Top10Model()
            if objCount < 10:
                rank = 0
                rankData = []
                for i in rankingObj[:objCount]:
                    rank = rank+1
                    rankData.append({"userName":i.userName,"Rank":rank,"userScore":i.userScore})
                topTenObj.questionID = request['questionID']
                topTenObj.top10User = json.dumps(rankData)
                topTenObj.save()
                return rankData
            else:
                rank=0
                rankData = []
                for i in rankingObj[:10]:
                    rank = rank+1
                    rankData.append({"userName":i.userName,"Rank":rank,"userScore":i.userScore})
                topTenObj.questionID = request['questionID']
                topTenObj.top10User = json.dumps(rankData)
                topTenObj.save()
                return rankData

        else:
            return "202-2"
    except Exception as e:
        return '400-1'


text:
package api

import (
	"fmt"
	"testing"

	"github.com/goharbor/harbor/src/common"
	"github.com/goharbor/harbor/src/core/config"
	"github.com/stretchr/testify/assert"
)

func TestGetConfig(t *testing.T) {
	fmt.Println("Testing getting configurations")
	assert := assert.New(t)
	apiTest := newHarborAPI()

	// case 1: get configurations without admin role
	code, _, err := apiTest.GetConfig(*testUser)
	if err != nil {
		t.Fatalf("failed to get configurations: %v", err)
	}

	assert.Equal(401, code, "the status code of getting configurations with non-admin user should be 401")

	// case 2: get configurations with admin role
	code, cfg, err := apiTest.GetConfig(*admin)
	if err != nil {
		t.Fatalf("failed to get configurations: %v", err)
	}

	if !assert.Equal(200, code, "the status code of getting configurations with admin user should be 200") {
		return
	}
	t.Logf("cfg: %+v", cfg)
	mode := cfg[common.AUTHMode].Value.(string)
	assert.Equal(common.DBAuth, mode, fmt.Sprintf("the auth mode should be %s", common.DBAuth))
	ccc, err := config.GetSystemCfg()
	if err != nil {
		t.Logf("failed to get system configurations: %v", err)
	}
	t.Logf("%v", ccc)
}

func TestInternalConfig(t *testing.T) {
	fmt.Println("Testing internal configurations")
	assert := assert.New(t)
	apiTest := newHarborAPI()

	// case 1: get configurations without admin role
	code, _, err := apiTest.GetInternalConfig(*testUser)
	if err != nil {
		t.Fatalf("failed to get configurations: %v", err)
	}

	assert.Equal(401, code, "the status code of getting configurations with non-admin user should be 401")

	// case 2: get configurations with admin role
	code, _, err = apiTest.GetInternalConfig(*admin)
	if err != nil {
		t.Fatalf("failed to get configurations: %v", err)
	}

	if !assert.Equal(200, code, "the status code of getting configurations with admin user should be 200") {
		return
	}
}

func TestPutConfig(t *testing.T) {
	fmt.Println("Testing modifying configurations")
	assert := assert.New(t)
	apiTest := newHarborAPI()

	cfg := map[string]interface{}{
		common.TokenExpiration: 60,
	}

	code, err := apiTest.PutConfig(*admin, cfg)
	if err != nil {
		t.Fatalf("failed to get configurations: %v", err)
	}

	if !assert.Equal(200, code, "the status code of modifying configurations with admin user should be 200") {
		return
	}
	ccc, err := config.GetSystemCfg()
	if err != nil {
		t.Logf("failed to get system configurations: %v", err)
	}
	t.Logf("%v", ccc)
}

func TestPutConfigMaxLength(t *testing.T) {
	fmt.Println("Testing modifying configurations with max length.")
	assert := assert.New(t)
	apiTest := newHarborAPI()

	// length is 512,expected code: 200
	cfg := map[string]interface{}{
		common.LDAPGroupSearchFilter: "OSWvgTrQJuhiPRZt7eCReNku29vrtMBBD2cZt6jl7LQN4OZQcirqEhS2vCnkW8X1OAHMJxiO1LyEY26j" +
			"YhBEiUFliPKDUt8Q9endowT3H60nJibEnCkSRVjix7QujXKRzlmvxcOK76v1oZAoWeHSwwtv7tZrOk16Jj5LTGYdLOnZd2LIgBniTKmceL" +
			"VY5WOgcpmgQCfI5HLbzWsmAqmFfbsDbadirrEDiXYYfZQ0LnF8s6sD4H13eImgenAumXEsBRH43FT37AbNXNxzlaSs8IQYEdPLaMyKoXFb" +
			"rfa0LPipwXnU7bl54IlWOTXwCwum0JGS4qBiMl6LwKUBle34ObZ9fTLh5dFOVE1GdzrGE0kQ7qUmYjMZafQbSXzV80zTc22aZt3RQa9Gxt" +
			"Dn2VqtgcoKAiZHkEySStiwOJtZpwuplyy1jcM3DcN0R9b8IidYAWOsriqetUBThqb75XIZTXAaRWhHLw4ayROYiaw8dPuLRjeVKhdyznqq" +
			"AKxQGyvm",
	}
	code200, _ := apiTest.PutConfig(*admin, cfg)
	assert.Equal(200, code200, "the status code of modifying configurations with admin user should be 200")

	// length is 1059,expected code: 500
	cfg = map[string]interface{}{
		common.LDAPGroupSearchFilter: "YU2YcM13JtSx5jtBiftTjfaEM9KZFQ0XA5fKQHU02E9Xe0aLYaSy7YBokrTA8oHFjSkWFSgWZJ6FEmTS" +
			"Vy5Ovsy5to2kWnFtbVNX3pzbeQpZeAqK3mEGnXdMkMSQu9WTq74s99GpwjEdA628pcZqLx6wCR0IvwryqIcNoRtqPlUcuRGODWA8ZXaC0d" +
			"Qs7cRUYSe8onHsM2c9JWuUS8Jv4E7KggfytrxeKAT0WGP5DBZsB7rHZKxoAppE3C0NueEeC4yV791PUOODJt9rc0RrcD6ORUIO5RriCwym" +
			"IinJZa03MtTk3vGFTmL9wM0wEYZP3fEBmoiB0iF8o4wkHGyMpNJoDyPuo7huuCbipAXClEcX1R7xD4aijTF9iOMKymvsObMZ4qqI7flco5" +
			"yLFf7W8cpSisk3YJSvxDWfrl91WT4IFE5KHK976DgLQJhTZ8msGOImnFiUGtuIUNQpOgFFtlXJV41OltSsjW5jwAzxcko0MFkOIc7XuPjB" +
			"XMrdjC9poYldrxNFrGOPFSyh19iS2UWKayKrtnhvDYAWrNCqOmRs01awEXBlwHp17VcLuze6XGCx7ZoPQX1Nu4uF1InAGpSm1B3pKtteeR" +
			"WNNeLZjmNGNuiorHyxLTx1bQTfkG2UzZTTR0e2XatiXt5nCDxSqP2OkOxH7dew36fm9LpkFbmgtlxWxjHX8buYzSJCAjTqqwW3rHCEfQjv" +
			"B4T7CTJrAgehCG9zL82P59DQbGXXWqRHbw5g9QszREQys1m56SHLosNptVPUwy7vD70rRf5s8knohW5npEZS9f3RGel64mj5g7bQBBkopx" +
			"f6uac3MlJAe9d6C0B7fexZJABln2kCtXXYzITflICISwxuZ0YXHJmT2sMSIpn9VwMnMidV4JsM2BD8ykExZ5QyeVyOCXHDxvRvFwQwjQfR" +
			"kkqQmtFREitKWl5njO8wLJw0XyeIVAej75NsGKKZWVjyaupaM9Bqn6NFrWjELFacLox6OCcRIDSDl3ntNN8tIzGOF7aXVCIqljJl0IL9Pz" +
			"NenmmubaNm48YjfkBk8MqOUSYJYaFkO1qCKbVdMg7yTqKEHgSUqEkoFPoJMH6GAozC",
	}
	code500, _ := apiTest.PutConfig(*admin, cfg)
	assert.Equal(500, code500, "the status code of modifying configurations with admin user should be 500")
}


text:
'use strict';

/*
 * QuickBlox JavaScript SDK
 *
 * Configuration Module
 *
 * NOTE:
 *  - config.webrtc.statsReportTimeInterval [integer, sec]:
 *  could add listener onCallStatsReport(session, userId, bytesReceived) if
 *  want to get stats (bytesReceived) about peer every X sec;
 */

var config = {
  version: '2.15.1',
  buildNumber: '1139',
  creds: {
    'appId': 0,
    'authKey': '',
    'authSecret': '',
    'accountKey': ''
  },
  endpoints: {
    api: 'api.quickblox.com',
    chat: 'chat.quickblox.com',
    muc: 'muc.chat.quickblox.com'
  },
  hash: 'sha1',
  streamManagement: {
    enable: false
  },
  chatProtocol: {
    bosh: 'https://chat.quickblox.com:5281',
    websocket: 'wss://chat.quickblox.com:5291',
    active: 2
  },
  pingTimeout: 30,
  pingLocalhostTimeInterval: 5,
  chatReconnectionTimeInterval: 5,
  webrtc: {
    answerTimeInterval: 60,
    autoReject: true,
    incomingLimit: 1,
    dialingTimeInterval: 5,
    disconnectTimeInterval: 30,
    statsReportTimeInterval: false,
    iceServers: [
      {
        urls: ['turn:turn.quickblox.com', 'stun:turn.quickblox.com'],
        username: 'quickblox',
        credential: 'baccb97ba2d92d71e26eb9886da5f1e0'
      }
    ]
  },
  urls: {
    account: 'account_settings',
    session: 'session',
    login: 'login',
    users: 'users',
    chat: 'chat',
    blobs: 'blobs',
    geodata: 'geodata',
    pushtokens: 'push_tokens',
    subscriptions: 'subscriptions',
    events: 'events',
    data: 'data',
    addressbook: 'address_book',
    addressbookRegistered: 'address_book/registered_users',
    type: '.json'
  },
  on: {
    sessionExpired: null
  },
  timeout: null,
  debug: {
    mode: 0,
    file: null
  },
  addISOTime: false,
  qbTokenExpirationDate: null,
  liveSessionInterval: 120,
};

config.set = function(options) {
  if (typeof options.endpoints === 'object' && options.endpoints.chat) {
    config.endpoints.muc = 'muc.'+options.endpoints.chat;
    config.chatProtocol.bosh = 'https://'+options.endpoints.chat+':5281';
    config.chatProtocol.websocket = 'wss://'+options.endpoints.chat+':5291';
  }

  Object.keys(options).forEach(function(key) {
    if(key !== 'set' && config.hasOwnProperty(key)) {
      if(typeof options[key] !== 'object') {
        config[key] = options[key];
      } else {
        Object.keys(options[key]).forEach(function(nextkey) {
          if(config[key].hasOwnProperty(nextkey)){
            config[key][nextkey] = options[key][nextkey];
          }
        });
      }
    }

    // backward compatibility: for config.iceServers
    if(key === 'iceServers') {
      config.webrtc.iceServers = options[key];
    }
  });
};

config.updateSessionExpirationDate = function (tokenExpirationDate, headerHasToken = false) {
  var connectionTimeLag = 1; // minute
  var newDate;
  if (headerHasToken) {
    var d = tokenExpirationDate.replaceAll('-','/');
    newDate = new Date(d);
    newDate.setMinutes ( newDate.getMinutes() - connectionTimeLag);
  }
  else {
    newDate = new Date(tokenExpirationDate);
    newDate.setMinutes ( newDate.getMinutes() - connectionTimeLag);
    newDate.setMinutes ( newDate.getMinutes() + config.liveSessionInterval );
  }
  config.qbTokenExpirationDate = newDate;
};

module.exports = config;


text:
package org.teavm.vm;

import java.util.Map;
import java.util.Properties;
import org.teavm.common.ServiceRepository;
import org.teavm.dependency.DependencyInfo;
import org.teavm.diagnostics.Diagnostics;
import org.teavm.model.ClassReaderSource;

public interface TeaVMTargetController {
    boolean wasCancelled();

    ClassLoader getClassLoader();

    ClassReaderSource getUnprocessedClassSource();

    DependencyInfo getDependencyInfo();

    Diagnostics getDiagnostics();

    Properties getProperties();

    ServiceRepository getServices();

    boolean isIncremental();

    Map<String, TeaVMEntryPoint> getEntryPoints();

    Map<String, String> getExportedClasses();
}


text:
"""\
This is a python port of "Goose" orignialy licensed to Gravity.com
under one or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.

Python port was written by Xavier Grangier for Recrutae

Gravity.com licenses this file
to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from HTMLParser import HTMLParser
from goose.text import innerTrim
from goose.parsers import Parser
import re

class OutputFormatter(object):

    def __init__(self, config):
        self.topNode = None
        self.config = config
        self.stopwordsCls = config.stopwordsCls

    def getLanguage(self, article):
        """\
        Returns the language is by the article or
        the configuration language
        """
        # we don't want to force the target laguage
        # so we use the article.metaLang
        if self.config.useMetaLanguge == True:
            if article.metaLang:
                return article.metaLang[:2]
        return self.config.targetLanguage

    def getTopNode(self):
        return self.topNode

    def getFormattedText(self, article):
        self.topNode = article.topNode
        return self.convertToText(article)

    def convertToText(self,article):
        text = Parser.getFormattedText(self.topNode)
        lines = text.split(u'\n')
        good_lines = []
        for line in lines:
            if re.search('[^ \xa0]',line): good_lines.append(line.strip())
        text = u'\n'.join(good_lines)
        Parser.adjustTopNode(article)
        return text

class StandardOutputFormatter(OutputFormatter):
    pass


text:
package dk.jarry.todo.boundary;

import java.util.List;

import javax.inject.Inject;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import dk.jarry.todo.entity.ToDo;

@Path("todos")
public class ToDoResource {

	@Context
	UriInfo context;

	@Inject
	ToDoService toDoService;

	@POST
	public Response create(ToDo toDo) {

		try {
			ToDo create = toDoService.create(toDo);
			return Response.created(context.getAbsolutePathBuilder().path(create.getId().toString()).build()).build();
		} catch (Exception e) {
			return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
		}

	}

	@GET
	@Path("{id}")
	public Response read(@PathParam("id") String id) {
		Response.ResponseBuilder response;
		try {
			ToDo todo = toDoService.read(id);
			if (todo == null) {
				response = Response.status(Response.Status.NOT_FOUND);
			} else {
				response = Response.ok(todo);
			}
		} catch (Exception e) {
			return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
		}
		return response.build();
	}

	@PUT
	@Path("{id}")
	public Response update(@PathParam("id") String id, ToDo todo) {
		Response.ResponseBuilder response;
		try {
			if (toDoService.read( id) != null) {
				toDoService.update(todo);
				response = Response.status(Response.Status.NO_CONTENT);
			} else {
				response = Response.status(Response.Status.NOT_FOUND);
			}
		} catch (Exception e) {
			response = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
		}
		return response.build();
	}

	@DELETE
	@Path("{id}")
	public Response delte(@PathParam("id") String id) {
		Response.ResponseBuilder response;
		try {
			if (toDoService.read( id) != null) {
				toDoService.delete(id);
				response = Response.ok();
			} else {
				response = Response.status(Response.Status.NOT_FOUND);
			}
		} catch (Exception e) {
			response = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
		}
		return response.build();
	}

	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public Response list(@DefaultValue("0") @QueryParam("from") Long from,
			@DefaultValue("50") @QueryParam("limit") Long limit) throws Exception {
		Response.ResponseBuilder response;
		try {
			List<ToDo> list = toDoService.list(from, limit);
			response = Response.ok(list);
			return response.build();
		} catch (Exception e) {
			response = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
		}
		return response.build();
	}

}


text:
FROM ubuntu:16.04
MAINTAINER Brandon B. Jozsa <bjozsa@jinkit.com>

# Update, Upgrade and Install Prerequisites
RUN apt-get --quiet update ;\
    apt-get --quiet upgrade -y ;\
    apt-get update && apt-get install -y \
      git \
      python-pcapy \
      schedtool ;\
    apt-get clean ;\
    rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

# Download Maltrail
RUN git clone https://github.com/stamparm/maltrail.git ;\
    mkdir -p /var/log/maltrail/

WORKDIR /maltrail

# Start the server-ui on exposed port definition (below)
CMD "/usr/bin/python server.py"

# Add exposed ports
EXPOSE 8338

# Set the entrypoint for the container
ENTRYPOINT ["/usr/bin/python", "/maltrail/sensor.py"]


text:
namespace kudu {
class MaintenanceManager;
class MaintenanceOp;
class MonoDelta;
class ThreadPool;
class ThreadPoolToken;
template <typename Sig>
class Callback;

namespace consensus {
class ConsensusMetadataManager;
class TransactionStatusPB;
}

namespace clock {
class Clock;
}

namespace log {
class LogAnchorRegistry;
} // namespace log

namespace rpc {
class Messenger;
class ResultTracker;
} // namespace rpc

namespace tablet {
class AlterSchemaTransactionState;
class TabletStatusPB;
class TransactionDriver;
class WriteTransactionState;

// A replica in a tablet consensus configuration, which coordinates writes to tablets.
// Each time Write() is called this class appends a new entry to a replicated
// state machine through a consensus algorithm, which makes sure that other
// peers see the same updates in the same order. In addition to this, this
// class also splits the work and coordinates multi-threaded execution.
class TabletReplica : public RefCountedThreadSafe<TabletReplica>,
                      public consensus::ReplicaTransactionFactory {
 public:
  TabletReplica(scoped_refptr<TabletMetadata> meta,
                scoped_refptr<consensus::ConsensusMetadataManager> cmeta_manager,
                consensus::RaftPeerPB local_peer_pb,
                ThreadPool* apply_pool,
                Callback<void(const std::string& reason)> mark_dirty_clbk);

  // Initializes RaftConsensus.
  // This must be called before publishing the instance to other threads.
  // If this fails, the TabletReplica instance remains in a NOT_INITIALIZED
  // state.
  Status Init(ThreadPool* raft_pool);

  // Starts the TabletReplica, making it available for Write()s. If this
  // TabletReplica is part of a consensus configuration this will connect it to other replicas
  // in the consensus configuration.
  Status Start(const consensus::ConsensusBootstrapInfo& bootstrap_info,
               std::shared_ptr<tablet::Tablet> tablet,
               scoped_refptr<clock::Clock> clock,
               std::shared_ptr<rpc::Messenger> messenger,
               scoped_refptr<rpc::ResultTracker> result_tracker,
               scoped_refptr<log::Log> log,
               ThreadPool* prepare_pool);

  // Synchronously transition this replica to STOPPED state from any other
  // state. This also stops RaftConsensus. If a Stop() operation is already in
  // progress, blocks until that operation is complete.
  // See tablet/metadata.proto for a description of legal state transitions.
  void Stop();

  // Synchronously transition this replica to SHUTDOWN state from any other state.
  // See tablet/metadata.proto for a description of legal state transitions.
  //
  // If 'error_' has been set to a non-OK status, the final state will be
  // FAILED instead of SHUTDOWN.
  void Shutdown();

  // Check that the tablet is in a RUNNING state.
  Status CheckRunning() const;

  // Wait until the tablet is in a RUNNING state or if there's a timeout.
  // TODO have a way to wait for any state?
  Status WaitUntilConsensusRunning(const MonoDelta& timeout);

  // Submits a write to a tablet and executes it asynchronously.
  // The caller is expected to build and pass a TransactionContext that points
  // to the RPC WriteRequest, WriteResponse, RpcContext and to the tablet's
  // MvccManager.
  Status SubmitWrite(std::unique_ptr<WriteTransactionState> tx_state);

  // Called by the tablet service to start an alter schema transaction.
  //
  // The transaction contains all the information required to execute the
  // AlterSchema operation and send the response back.
  //
  // If the returned Status is OK, the response to the client will be sent
  // asynchronously. Otherwise the tablet service will have to send the response directly.
  //
  // The AlterSchema operation is taking the tablet component lock in exclusive mode
  // meaning that no other operation on the tablet can be executed while the
  // AlterSchema is in progress.
  Status SubmitAlterSchema(std::unique_ptr<AlterSchemaTransactionState> tx_state);

  void GetTabletStatusPB(TabletStatusPB* status_pb_out) const;

  // Used by consensus to create and start a new ReplicaTransaction.
  virtual Status StartReplicaTransaction(
      const scoped_refptr<consensus::ConsensusRound>& round) OVERRIDE;

  consensus::RaftConsensus* consensus() {
    std::lock_guard<simple_spinlock> lock(lock_);
    return consensus_.get();
  }

  std::shared_ptr<consensus::RaftConsensus> shared_consensus() const {
    std::lock_guard<simple_spinlock> lock(lock_);
    return consensus_;
  }

  Tablet* tablet() const {
    std::lock_guard<simple_spinlock> lock(lock_);
    return tablet_.get();
  }

  scoped_refptr<consensus::TimeManager> time_manager() const {
    return consensus_->time_manager();
  }

  std::shared_ptr<Tablet> shared_tablet() const {
    std::lock_guard<simple_spinlock> lock(lock_);
    return tablet_;
  }

  const TabletStatePB state() const {
    std::lock_guard<simple_spinlock> lock(lock_);
    return state_;
  }

  std::string StateName() const;

  const TabletDataState data_state() const {
    std::lock_guard<simple_spinlock> lock(lock_);
    return meta_->tablet_data_state();
  }

  // Returns the current Raft configuration.
  const consensus::RaftConfigPB RaftConfig() const;

  // Sets the tablet to a BOOTSTRAPPING state, indicating it is starting up.
  void SetBootstrapping();

  // Set a user-readable status message about the tablet. This may appear on
  // the Web UI, for example.
  void SetStatusMessage(const std::string& status);

  // Retrieve the last human-readable status of this tablet replica.
  std::string last_status() const;

  // Sets the error to the provided one.
  void SetError(const Status& error);

  // Returns the error that occurred, when state is FAILED.
  Status error() const {
    std::lock_guard<simple_spinlock> lock(lock_);
    return error_;
  }

  // Returns a human-readable string indicating the state of the tablet.
  // Typically this looks like "NOT_STARTED", "TABLET_DATA_COPYING",
  // etc. For use in places like the Web UI.
  std::string HumanReadableState() const;

  // Adds list of transactions in-flight at the time of the call to 'out'.
  void GetInFlightTransactions(Transaction::TraceType trace_type,
                               std::vector<consensus::TransactionStatusPB>* out) const;

  // Returns the log indexes to be retained for durability and to catch up peers.
  // Used for selection of log segments to delete during Log GC.
  log::RetentionIndexes GetRetentionIndexes() const;

  // See Log::GetReplaySizeMap(...).
  //
  // Returns a non-ok status if the tablet isn't running.
  Status GetReplaySizeMap(std::map<int64_t, int64_t>* replay_size_map) const;

  // Returns the amount of bytes that would be GC'd if RunLogGC() was called.
  //
  // Returns a non-ok status if the tablet isn't running.
  Status GetGCableDataSize(int64_t* retention_size) const;

  // Return a pointer to the Log.
  // TabletReplica keeps a reference to Log after Init().
  log::Log* log() const {
    return log_.get();
  }

  clock::Clock* clock() {
    return clock_.get();
  }

  const scoped_refptr<log::LogAnchorRegistry>& log_anchor_registry() const {
    return log_anchor_registry_;
  }

  // Returns the tablet_id of the tablet managed by this TabletReplica.
  // Returns the correct tablet_id even if the underlying tablet is not available
  // yet.
  const std::string& tablet_id() const { return tablet_id_; }

  // Convenience method to return the permanent_uuid of this peer.
  std::string permanent_uuid() const { return tablet_->metadata()->fs_manager()->uuid(); }

  Status NewLeaderTransactionDriver(gscoped_ptr<Transaction> transaction,
                                    scoped_refptr<TransactionDriver>* driver);

  Status NewReplicaTransactionDriver(gscoped_ptr<Transaction> transaction,
                                     scoped_refptr<TransactionDriver>* driver);

  // Tells the tablet's log to garbage collect.
  Status RunLogGC();

  // Register the maintenance ops associated with this peer's tablet, also invokes
  // Tablet::RegisterMaintenanceOps().
  void RegisterMaintenanceOps(MaintenanceManager* maint_mgr);

  // Unregister the maintenance ops associated with this replica's tablet.
  void UnregisterMaintenanceOps();

  // Cancels the maintenance ops associated with this replica's tablet.
  // Only to be used in tests.
  void CancelMaintenanceOpsForTests();

  // Stops further I/O on the replica.
  void MakeUnavailable(const Status& error);

  // Return pointer to the transaction tracker for this peer.
  const TransactionTracker* transaction_tracker() const { return &txn_tracker_; }

  const scoped_refptr<TabletMetadata>& tablet_metadata() const {
    return meta_;
  }

  // Marks the tablet as dirty so that it's included in the next heartbeat.
  void MarkTabletDirty(const std::string& reason) {
    mark_dirty_clbk_.Run(reason);
  }

  // Return the total on-disk size of this tablet replica, in bytes.
  size_t OnDiskSize() const;

 private:
  friend class RefCountedThreadSafe<TabletReplica>;
  friend class TabletReplicaTest;
  FRIEND_TEST(TabletReplicaTest, TestMRSAnchorPreventsLogGC);
  FRIEND_TEST(TabletReplicaTest, TestDMSAnchorPreventsLogGC);
  FRIEND_TEST(TabletReplicaTest, TestActiveTransactionPreventsLogGC);

  ~TabletReplica();

  // Wait until the TabletReplica is fully in STOPPED, SHUTDOWN, or FAILED
  // state.
  void WaitUntilStopped();

  std::string LogPrefix() const;
  // Transition to another state. Requires that the caller hold 'lock_' if the
  // object has already published to other threads. See tablet/metadata.proto
  // for state descriptions and legal state transitions.
  void set_state(TabletStatePB new_state);

  const scoped_refptr<TabletMetadata> meta_;
  const scoped_refptr<consensus::ConsensusMetadataManager> cmeta_manager_;

  const std::string tablet_id_;
  const consensus::RaftPeerPB local_peer_pb_;
  scoped_refptr<log::LogAnchorRegistry> log_anchor_registry_; // Assigned in tablet_replica-test

  // Pool that executes apply tasks for transactions. This is a multi-threaded
  // pool, constructor-injected by either the Master (for system tables) or
  // the Tablet server.
  ThreadPool* const apply_pool_;

  // Function to mark this TabletReplica's tablet as dirty in the TSTabletManager.
  //
  // Must be called whenever cluster membership or leadership changes, or when
  // the tablet's schema changes.
  const Callback<void(const std::string& reason)> mark_dirty_clbk_;

  TabletStatePB state_;
  Status error_;
  TransactionTracker txn_tracker_;
  TransactionOrderVerifier txn_order_verifier_;
  scoped_refptr<log::Log> log_;
  std::shared_ptr<Tablet> tablet_;
  std::shared_ptr<rpc::Messenger> messenger_;
  std::shared_ptr<consensus::RaftConsensus> consensus_;
  simple_spinlock prepare_replicate_lock_;

  // Lock protecting state_, last_status_, as well as pointers to collaborating
  // classes such as tablet_, consensus_, and maintenance_ops_.
  mutable simple_spinlock lock_;

  // The human-readable last status of the tablet, displayed on the web page, command line
  // tools, etc.
  std::string last_status_;

  // Lock taken during Init/Shutdown which ensures that only a single thread
  // attempts to perform major lifecycle operations (Init/Shutdown) at once.
  // This must be acquired before acquiring lock_ if they are acquired together.
  // We don't just use lock_ since the lifecycle operations may take a while
  // and we'd like other threads to be able to quickly poll the state_ variable
  // during them in order to reject RPCs, etc.
  mutable simple_spinlock state_change_lock_;

  // Token for serial task submission to the server-wide transaction prepare pool.
  std::unique_ptr<ThreadPoolToken> prepare_pool_token_;

  scoped_refptr<clock::Clock> clock_;

  // List of maintenance operations for the tablet that need information that only the peer
  // can provide.
  std::vector<MaintenanceOp*> maintenance_ops_;

  // The result tracker for writes.
  scoped_refptr<rpc::ResultTracker> result_tracker_;

  FunctionGaugeDetacher metric_detacher_;

  DISALLOW_COPY_AND_ASSIGN(TabletReplica);
};

// A callback to wait for the in-flight transactions to complete and to flush
// the Log when they do.
// Tablet is passed as a raw pointer as this callback is set in TabletMetadata and
// were we to keep the tablet as a shared_ptr a circular dependency would occur:
// callback->tablet->metadata->callback. Since the tablet indirectly owns this
// callback we know that is must still be alive when it fires.
class FlushInflightsToLogCallback : public RefCountedThreadSafe<FlushInflightsToLogCallback> {
 public:
  FlushInflightsToLogCallback(Tablet* tablet,
                              const scoped_refptr<log::Log>& log)
   : tablet_(tablet),
     log_(log) {}

  Status WaitForInflightsAndFlushLog();

 private:
  Tablet* tablet_;
  scoped_refptr<log::Log> log_;
};

}  // namespace tablet
}  // namespace kudu


text:
#include <linux/device.h>
#include <linux/genhd.h>
#include <linux/mm.h>

#include "zram_drv.h"

static u64 zram_stat64_read(struct zram *zram, u64 *v)
{
	u64 val;

	spin_lock(&zram->stat64_lock);
	val = *v;
	spin_unlock(&zram->stat64_lock);

	return val;
}

static struct zram *dev_to_zram(struct device *dev)
{
	int i;
	struct zram *zram = NULL;

	for (i = 0; i < zram_get_num_devices(); i++) {
		zram = &zram_devices[i];
		if (disk_to_dev(zram->disk) == dev)
			break;
	}

	return zram;
}

static ssize_t disksize_show(struct device *dev,
		struct device_attribute *attr, char *buf)
{
	struct zram *zram = dev_to_zram(dev);

	return sprintf(buf, "%llu\n", zram->disksize);
}

static ssize_t disksize_store(struct device *dev,
		struct device_attribute *attr, const char *buf, size_t len)
{
	int ret;
	u64 disksize;
	struct zram *zram = dev_to_zram(dev);

	ret = kstrtoull(buf, 10, &disksize);
	if (ret)
		return ret;

	down_write(&zram->init_lock);
	if (zram->init_done) {
		up_write(&zram->init_lock);
		pr_info("Cannot change disksize for initialized device\n");
		return -EBUSY;
	}

	zram->disksize = PAGE_ALIGN(disksize);
	set_capacity(zram->disk, zram->disksize >> SECTOR_SHIFT);
	up_write(&zram->init_lock);

	return len;
}

static ssize_t initstate_show(struct device *dev,
		struct device_attribute *attr, char *buf)
{
	struct zram *zram = dev_to_zram(dev);

	return sprintf(buf, "%u\n", zram->init_done);
}

static ssize_t reset_store(struct device *dev,
		struct device_attribute *attr, const char *buf, size_t len)
{
	int ret;
	unsigned short do_reset;
	struct zram *zram;
	struct block_device *bdev;

	zram = dev_to_zram(dev);
	bdev = bdget_disk(zram->disk, 0);

	/* Do not reset an active device! */
	if (bdev->bd_holders)
		return -EBUSY;

	ret = kstrtou16(buf, 10, &do_reset);
	if (ret)
		return ret;

	if (!do_reset)
		return -EINVAL;

	/* Make sure all pending I/O is finished */
	if (bdev)
		fsync_bdev(bdev);

	down_write(&zram->init_lock);
	if (zram->init_done)
		__zram_reset_device(zram);
	up_write(&zram->init_lock);

	return len;
}

static ssize_t num_reads_show(struct device *dev,
		struct device_attribute *attr, char *buf)
{
	struct zram *zram = dev_to_zram(dev);

	return sprintf(buf, "%llu\n",
		zram_stat64_read(zram, &zram->stats.num_reads));
}

static ssize_t num_writes_show(struct device *dev,
		struct device_attribute *attr, char *buf)
{
	struct zram *zram = dev_to_zram(dev);

	return sprintf(buf, "%llu\n",
		zram_stat64_read(zram, &zram->stats.num_writes));
}

static ssize_t invalid_io_show(struct device *dev,
		struct device_attribute *attr, char *buf)
{
	struct zram *zram = dev_to_zram(dev);

	return sprintf(buf, "%llu\n",
		zram_stat64_read(zram, &zram->stats.invalid_io));
}

static ssize_t notify_free_show(struct device *dev,
		struct device_attribute *attr, char *buf)
{
	struct zram *zram = dev_to_zram(dev);

	return sprintf(buf, "%llu\n",
		zram_stat64_read(zram, &zram->stats.notify_free));
}

static ssize_t zero_pages_show(struct device *dev,
		struct device_attribute *attr, char *buf)
{
	struct zram *zram = dev_to_zram(dev);

	return sprintf(buf, "%u\n", zram->stats.pages_zero);
}

static ssize_t orig_data_size_show(struct device *dev,
		struct device_attribute *attr, char *buf)
{
	struct zram *zram = dev_to_zram(dev);

	return sprintf(buf, "%llu\n",
		(u64)(zram->stats.pages_stored) << PAGE_SHIFT);
}

static ssize_t compr_data_size_show(struct device *dev,
		struct device_attribute *attr, char *buf)
{
	struct zram *zram = dev_to_zram(dev);

	return sprintf(buf, "%llu\n",
		zram_stat64_read(zram, &zram->stats.compr_size));
}

static ssize_t mem_used_total_show(struct device *dev,
		struct device_attribute *attr, char *buf)
{
	u64 val = 0;
	struct zram *zram = dev_to_zram(dev);

	if (zram->init_done) {
		val = zs_get_total_size_bytes(zram->mem_pool) +
			((u64)(zram->stats.pages_expand) << PAGE_SHIFT);
	}

	return sprintf(buf, "%llu\n", val);
}

static DEVICE_ATTR(disksize, S_IRUGO | S_IWUSR,
		disksize_show, disksize_store);
static DEVICE_ATTR(initstate, S_IRUGO, initstate_show, NULL);
static DEVICE_ATTR(reset, S_IWUSR, NULL, reset_store);
static DEVICE_ATTR(num_reads, S_IRUGO, num_reads_show, NULL);
static DEVICE_ATTR(num_writes, S_IRUGO, num_writes_show, NULL);
static DEVICE_ATTR(invalid_io, S_IRUGO, invalid_io_show, NULL);
static DEVICE_ATTR(notify_free, S_IRUGO, notify_free_show, NULL);
static DEVICE_ATTR(zero_pages, S_IRUGO, zero_pages_show, NULL);
static DEVICE_ATTR(orig_data_size, S_IRUGO, orig_data_size_show, NULL);
static DEVICE_ATTR(compr_data_size, S_IRUGO, compr_data_size_show, NULL);
static DEVICE_ATTR(mem_used_total, S_IRUGO, mem_used_total_show, NULL);

static struct attribute *zram_disk_attrs[] = {
	&dev_attr_disksize.attr,
	&dev_attr_initstate.attr,
	&dev_attr_reset.attr,
	&dev_attr_num_reads.attr,
	&dev_attr_num_writes.attr,
	&dev_attr_invalid_io.attr,
	&dev_attr_notify_free.attr,
	&dev_attr_zero_pages.attr,
	&dev_attr_orig_data_size.attr,
	&dev_attr_compr_data_size.attr,
	&dev_attr_mem_used_total.attr,
	NULL,
};

struct attribute_group zram_disk_attr_group = {
	.attrs = zram_disk_attrs,
};


text:
package com.facebook.buck.java;

import static com.facebook.buck.java.JavaCompilationConstants.DEFAULT_JAVAC_OPTIONS;
import static org.junit.Assert.assertEquals;

import com.facebook.buck.cli.BuckConfig;
import com.facebook.buck.event.BuckEventBus;
import com.facebook.buck.event.BuckEventBusFactory;
import com.facebook.buck.io.ExecutableFinder;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.json.DefaultProjectBuildFileParserFactory;
import com.facebook.buck.json.ProjectBuildFileParserFactory;
import com.facebook.buck.json.ProjectBuildFileParserOptions;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.parser.ParserConfig;
import com.facebook.buck.python.PythonBuckConfig;
import com.facebook.buck.rules.DefaultKnownBuildRuleTypes;
import com.facebook.buck.rules.Description;
import com.facebook.buck.testutil.TestConsole;
import com.facebook.buck.testutil.integration.DebuggableTemporaryFolder;
import com.facebook.buck.testutil.integration.ProjectWorkspace;
import com.facebook.buck.testutil.integration.TestDataHelper;
import com.facebook.buck.util.environment.Platform;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.SetMultimap;

import org.junit.Rule;
import org.junit.Test;

import java.io.IOException;

public class JavaSymbolFinderIntegrationTest {

  @Rule
  public DebuggableTemporaryFolder temporaryFolder = new DebuggableTemporaryFolder();

  @Test
  public void shouldFindTargetDefiningSymbol() throws IOException, InterruptedException {
    ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(
        this, "symbol_finder", temporaryFolder);
    workspace.setUp();

    ProjectFilesystem projectFilesystem = new ProjectFilesystem(temporaryFolder.getRootPath());

    BuckConfig config = BuckConfig.createFromFiles(
        projectFilesystem,
        ImmutableList.of(projectFilesystem.getFileForRelativePath(".buckconfig")),
        Platform.detect(),
        ImmutableMap.copyOf(System.getenv()));
    ParserConfig parserConfig = new ParserConfig(config);
    PythonBuckConfig pythonBuckConfig = new PythonBuckConfig(
        config,
        new ExecutableFinder());
    ImmutableSet<Description<?>> allDescriptions =
        DefaultKnownBuildRuleTypes
        .getDefaultKnownBuildRuleTypes(projectFilesystem)
        .getAllDescriptions();
    SrcRootsFinder srcRootsFinder = new SrcRootsFinder(projectFilesystem);
    ProjectBuildFileParserFactory projectBuildFileParserFactory =
        new DefaultProjectBuildFileParserFactory(
            ProjectBuildFileParserOptions.builder()
                .setProjectRoot(projectFilesystem.getRootPath())
                .setPythonInterpreter(pythonBuckConfig.getPythonInterpreter())
                .setAllowEmptyGlobs(parserConfig.getAllowEmptyGlobs())
                .setBuildFileName(parserConfig.getBuildFileName())
                .setDefaultIncludes(parserConfig.getDefaultIncludes())
                .setDescriptions(allDescriptions)
                .build());
    BuckEventBus buckEventBus = BuckEventBusFactory.newInstance();
    JavaSymbolFinder finder = new JavaSymbolFinder(
        projectFilesystem,
        srcRootsFinder,
        DEFAULT_JAVAC_OPTIONS,
        projectBuildFileParserFactory,
        config,
        buckEventBus,
        new TestConsole(),
        ImmutableMap.copyOf(System.getenv()));

    SetMultimap<String, BuildTarget> foundTargets =
        finder.findTargetsForSymbols(ImmutableSet.of("com.example.a.A"));

    assertEquals(
        "JavaSymbolFinder failed to find the right target.",
        ImmutableSetMultimap.of(
            "com.example.a.A",
            BuildTarget.builder("//java/com/example/a", "a").build()),
        foundTargets);
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.android.alexdet.mgr870"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:maxSdkVersion="18"
        android:minSdkVersion="16"
        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_UPDATES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.android.alexdet.mgr870.controller.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


text:
function mdalegend(varargin)
   h = legend(varargin{:});
   set(h, 'EdgeColor', mdadata.LEGEND_EDGE_COLOR);
end


text:
extern "C" {
#endif

  int openmc_calculate_volumes();
  int openmc_cell_filter_get_bins(int32_t index, const int32_t** cells, int32_t* n);
  int openmc_cell_get_fill(int32_t index, int* type, int32_t** indices, int32_t* n);
  int openmc_cell_get_id(int32_t index, int32_t* id);
  int openmc_cell_get_temperature(int32_t index, const int32_t* instance, double* T);
  int openmc_cell_get_name(int32_t index, const char** name);
  int openmc_cell_set_name(int32_t index, const char* name);
  int openmc_cell_set_fill(int32_t index, int type, int32_t n, const int32_t* indices);
  int openmc_cell_set_id(int32_t index, int32_t id);
  int openmc_cell_set_temperature(int32_t index, double T, const int32_t* instance, bool set_contained = false);
  int openmc_energy_filter_get_bins(int32_t index, const double** energies, size_t* n);
  int openmc_energy_filter_set_bins(int32_t index, size_t n, const double* energies);
  int openmc_energyfunc_filter_get_energy(int32_t index, size_t* n, const double** energy);
  int openmc_energyfunc_filter_get_y(int32_t index, size_t* n, const double** y);
  int openmc_energyfunc_filter_set_data(int32_t index, size_t n,
                                        const double* energies, const double* y);
  int openmc_extend_cells(int32_t n, int32_t* index_start, int32_t* index_end);
  int openmc_extend_filters(int32_t n, int32_t* index_start, int32_t* index_end);
  int openmc_extend_materials(int32_t n, int32_t* index_start, int32_t* index_end);
  int openmc_extend_meshes(int32_t n, const char* type, int32_t* index_start,
                           int32_t* index_end);
  int openmc_extend_tallies(int32_t n, int32_t* index_start, int32_t* index_end);
  int openmc_filter_get_id(int32_t index, int32_t* id);
  int openmc_filter_get_type(int32_t index, char* type);
  int openmc_filter_set_id(int32_t index, int32_t id);
  int openmc_finalize();
  int openmc_find_cell(const double* xyz, int32_t* index, int32_t* instance);
  int openmc_cell_bounding_box(const int32_t index, double* llc, double* urc);
  int openmc_global_bounding_box(double* llc, double* urc);
  int openmc_fission_bank(void** ptr, int64_t* n);
  int openmc_get_cell_index(int32_t id, int32_t* index);
  int openmc_get_filter_index(int32_t id, int32_t* index);
  void openmc_get_filter_next_id(int32_t* id);
  int openmc_get_keff(double k_combined[]);
  int openmc_get_material_index(int32_t id, int32_t* index);
  int openmc_get_mesh_index(int32_t id, int32_t* index);
  int openmc_get_n_batches(int* n_batches, bool get_max_batches);
  int openmc_get_nuclide_index(const char name[], int* index);
  int64_t openmc_get_seed();
  int openmc_get_tally_index(int32_t id, int32_t* index);
  void openmc_get_tally_next_id(int32_t* id);
  int openmc_global_tallies(double** ptr);
  int openmc_hard_reset();
  int openmc_init(int argc, char* argv[], const void* intracomm);
  bool openmc_is_statepoint_batch();
  int openmc_legendre_filter_get_order(int32_t index, int* order);
  int openmc_legendre_filter_set_order(int32_t index, int order);
  int openmc_load_nuclide(const char* name, const double* temps, int n);
  int openmc_material_add_nuclide(int32_t index, const char name[], double density);
  int openmc_material_get_densities(int32_t index, const int** nuclides, const double** densities, int* n);
  int openmc_material_get_id(int32_t index, int32_t* id);
  int openmc_material_get_fissionable(int32_t index, bool* fissionable);
  int openmc_material_get_density(int32_t index, double* density);
  int openmc_material_get_volume(int32_t index, double* volume);
  int openmc_material_set_density(int32_t index, double density, const char* units);
  int openmc_material_set_densities(int32_t index, int n, const char** name, const double* density);
  int openmc_material_set_id(int32_t index, int32_t id);
  int openmc_material_get_name(int32_t index, const char** name);
  int openmc_material_set_name(int32_t index, const char* name);
  int openmc_material_set_volume(int32_t index, double volume);
  int openmc_material_filter_get_bins(int32_t index, const int32_t** bins, size_t* n);
  int openmc_material_filter_set_bins(int32_t index, size_t n, const int32_t* bins);
  int openmc_mesh_filter_get_mesh(int32_t index, int32_t* index_mesh);
  int openmc_mesh_filter_set_mesh(int32_t index, int32_t index_mesh);
  int openmc_mesh_get_id(int32_t index, int32_t* id);
  int openmc_mesh_set_id(int32_t index, int32_t id);
  int openmc_meshsurface_filter_get_mesh(int32_t index, int32_t* index_mesh);
  int openmc_meshsurface_filter_set_mesh(int32_t index, int32_t index_mesh);
  int openmc_new_filter(const char* type, int32_t* index);
  int openmc_next_batch(int* status);
  int openmc_nuclide_name(int index, const char** name);
  int openmc_plot_geometry();
  int openmc_id_map(const void* slice, int32_t* data_out);
  int openmc_property_map(const void* slice, double* data_out);
  int openmc_rectilinear_mesh_get_grid(int32_t index, double** grid_x, int* nx,
                       double** grid_y, int* ny, double** grid_z, int* nz);
  int openmc_rectilinear_mesh_set_grid(int32_t index, const double* grid_x,
                       const int nx, const double* grid_y, const int ny,
                       const double* grid_z, const int nz);
  int openmc_regular_mesh_get_dimension(int32_t index, int** id, int* n);
  int openmc_regular_mesh_get_params(int32_t index, double** ll, double** ur, double** width, int* n);
  int openmc_regular_mesh_set_dimension(int32_t index, int n, const int* dims);
  int openmc_regular_mesh_set_params(int32_t index, int n, const double* ll, const double* ur, const double* width);
  int openmc_reset();
  int openmc_reset_timers();
  int openmc_run();
  void openmc_set_seed(int64_t new_seed);
  int openmc_set_n_batches(int32_t n_batches, bool set_max_batches,
                           bool add_statepoint_batch);
  int openmc_simulation_finalize();
  int openmc_simulation_init();
  int openmc_source_bank(void** ptr, int64_t* n);
  int openmc_spatial_legendre_filter_get_order(int32_t index, int* order);
  int openmc_spatial_legendre_filter_get_params(int32_t index, int* axis, double* min, double* max);
  int openmc_spatial_legendre_filter_set_order(int32_t index, int order);
  int openmc_spatial_legendre_filter_set_params(int32_t index, const int* axis,
                                                const double* min, const double* max);
  int openmc_sphharm_filter_get_order(int32_t index, int* order);
  int openmc_sphharm_filter_get_cosine(int32_t index, char cosine[]);
  int openmc_sphharm_filter_set_order(int32_t index, int order);
  int openmc_sphharm_filter_set_cosine(int32_t index, const char cosine[]);
  int openmc_statepoint_write(const char* filename, bool* write_source);
  int openmc_tally_allocate(int32_t index, const char* type);
  int openmc_tally_get_active(int32_t index, bool* active);
  int openmc_tally_get_estimator(int32_t index, int* estimator);
  int openmc_tally_get_id(int32_t index, int32_t* id);
  int openmc_tally_get_filters(int32_t index, const int32_t** indices, size_t* n);
  int openmc_tally_get_n_realizations(int32_t index, int32_t* n);
  int openmc_tally_get_nuclides(int32_t index, int** nuclides, int* n);
  int openmc_tally_get_scores(int32_t index, int** scores, int* n);
  int openmc_tally_get_type(int32_t index, int32_t* type);
  int openmc_tally_get_writable(int32_t index, bool* writable);
  int openmc_tally_reset(int32_t index);
  int openmc_tally_results(int32_t index, double** ptr, size_t shape_[3]);
  int openmc_tally_set_active(int32_t index, bool active);
  int openmc_tally_set_estimator(int32_t index, const char* estimator);
  int openmc_tally_set_filters(int32_t index, size_t n, const int32_t* indices);
  int openmc_tally_set_id(int32_t index, int32_t id);
  int openmc_tally_set_nuclides(int32_t index, int n, const char** nuclides);
  int openmc_tally_set_scores(int32_t index, int n, const char** scores);
  int openmc_tally_set_type(int32_t index, const char* type);
  int openmc_tally_set_writable(int32_t index, bool writable);
  int openmc_zernike_filter_get_order(int32_t index, int* order);
  int openmc_zernike_filter_get_params(int32_t index, double* x, double* y, double* r);
  int openmc_zernike_filter_set_order(int32_t index, int order);
  int openmc_zernike_filter_set_params(int32_t index, const double* x,
                                       const double* y, const double* r);

  //! Sets the mesh and energy grid for CMFD reweight
  //! \param[in] meshtyally_id id of CMFD Mesh Tally
  //! \param[in] cmfd_indices indices storing spatial and energy dimensions of CMFD problem
  //! \param[in] norm CMFD normalization factor
  extern "C" void openmc_initialize_mesh_egrid(const int meshtally_id, const int* cmfd_indices,
                                               const double norm);

  //! Sets the mesh and energy grid for CMFD reweight
  //! \param[in] feedback whether or not to run CMFD feedback
  //! \param[in] cmfd_src computed CMFD source
  extern "C" void openmc_cmfd_reweight(const bool feedback, const double* cmfd_src);

  //! Sets the fixed variables that are used for CMFD linear solver
  //! \param[in] indptr CSR format index pointer array of loss matrix
  //! \param[in] len_indptr length of indptr
  //! \param[in] indices CSR format index array of loss matrix
  //! \param[in] n_elements number of non-zero elements in CMFD loss matrix
  //! \param[in] dim dimension n of nxn CMFD loss matrix
  //! \param[in] spectral spectral radius of CMFD matrices and tolerances
  //! \param[in] map coremap for problem, storing accelerated regions
  //! \param[in] use_all_threads whether to use all threads when running CMFD solver
  extern "C" void openmc_initialize_linsolver(const int* indptr, int len_indptr,
                                              const int* indices, int n_elements,
                                              int dim, double spectral,
                                              const int* map, bool use_all_threads);

  //! Runs a Gauss Seidel linear solver to solve CMFD matrix equations
  //! linear solver
  //! \param[in] A_data CSR format data array of coefficient matrix
  //! \param[in] b right hand side vector
  //! \param[out] x unknown vector
  //! \param[in] tol tolerance on final error
  //! \return number of inner iterations required to reach convergence
  extern "C" int openmc_run_linsolver(const double* A_data, const double* b,
                                      double* x, double tol);

  // Error codes
  extern int OPENMC_E_UNASSIGNED;
  extern int OPENMC_E_ALLOCATE;
  extern int OPENMC_E_OUT_OF_BOUNDS;
  extern int OPENMC_E_INVALID_SIZE;
  extern int OPENMC_E_INVALID_ARGUMENT;
  extern int OPENMC_E_INVALID_TYPE;
  extern int OPENMC_E_INVALID_ID;
  extern int OPENMC_E_GEOMETRY;
  extern int OPENMC_E_DATA;
  extern int OPENMC_E_PHYSICS;
  extern int OPENMC_E_WARNING;

  // Global variables
  extern char openmc_err_msg[256];

#ifdef __cplusplus
}
#endif

#endif // OPENMC_CAPI_H


text: <?php echo $kontendash;?>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Diplodina ischaemi Morochk.

### Remarks
null


text:
inline auto count() {
   using std::begin;
   using std::end;
   using std::distance;
   return sequence_manipulator([](sequence<auto> s) mutable {
         return static_cast<std::size_t>(distance(begin(s), end(s)));
      });
}

template<class Predicate>
inline auto count(Predicate p) {
   using std::begin;
   using std::end;
   using std::count_if;
   return sequence_manipulator([=](sequence<auto> s) mutable {
         return count_if(begin(s), end(s), p);
      });
}

template<class Comp=std::less<void>>
inline auto max(Comp &&comp={}) {
   using std::begin;
   using std::end;

   return sequence_manipulator([comp](sequence<auto> s) mutable {
         typedef typename decltype(s)::value_type S;

         auto i = begin(s);
         auto e = end(s);
         if (i == e) {
            throw std::range_error("Min/Max cannot be computed on empty sequence.");
         }

         S result{*i};
         for (++i; i != e; ++i) {
            if (comp(result, *i)) {
               result = *i;
            }
         }

         return result;
      });
}

template<class Comp=std::less<void>>
inline auto min(Comp &&comp={}) {
   using std::begin;
   using std::end;

   return sequence_manipulator([comp](sequence<auto> s) mutable {
         typedef typename decltype(s)::value_type S;

         auto i = begin(s);
         auto e = end(s);
         if (i == e) {
            throw std::range_error("Min/Max cannot be computed on empty sequence.");
         }

         S result{*i};
         for (++i; i != e; ++i) {
            if (comp(*i, result)) {
               result = *i;
            }
         }

         return result;
      });
}

template<class Comp=std::less<void>>
inline auto minmax(Comp &&comp={}) {
   using std::begin;
   using std::end;
   using std::make_pair;

   return sequence_manipulator([comp](sequence<auto> s) mutable {
         typedef typename decltype(s)::value_type S;

         auto i = begin(s);
         auto e = end(s);
         if (i == e) {
            throw std::range_error("Min/Max cannot be computed on empty sequence.");
         }

         S min_result{*i};
         S max_result{*i};
         for (++i; i != e; ++i) {
            if (comp(*i, min_result)) {
               min_result = *i;
            }
            else if (comp(max_result, *i)) {
               max_result = *i;
            }
         }

         return make_pair(min_result, max_result);
      });
}

template<class T, class Add=std::plus<void>>
inline auto sum(T init={}, Add &&add=Add{}) {
   using std::begin;
   using std::end;
   using std::accumulate;

   return sequence_manipulator([=](sequence<auto> s) mutable {
         return accumulate(begin(s), end(s), init, add);
      });
}

template<class Add=std::plus<void>, class Divide=std::divides<void>>
inline auto avg(Add &&add={}, Divide &&divide={}) {
   using std::begin;
   using std::end;

   return sequence_manipulator([=](sequence<auto> s) mutable {
         typedef typename decltype(s)::value_type S;

         auto i = begin(s);
         auto e = end(s);
         if (i == e) {
            throw std::domain_error("Cannot compute average on empty sequence.");
         }

         S den{1};
         S num{*i};
         for (++i; i != e; ++i) {
            num = add(num, *i);
            den += S{1};
         }
         return divide(num, den);
      });
}

template<class T, class R, class Add=std::plus<void>, class Multiply=std::multiplies<void>>
inline auto inner_product(sequence<R> r, T init={}, Add &&add={}, Multiply &&multiply={}) {
   using std::begin;
   using std::end;
   using std::inner_product;
   using std::move;

   return sequence_manipulator([r=move(r), init, add, multiply](sequence<auto> l) mutable {
         return inner_product(begin(l), end(l), begin(r), init, add, multiply);
      });
}

#endif


text:
layout: post
date: 2017-05-13
title: "Nicole Spose Jolies of : MODEL JOAB16525 2016 Sleeveless Chapel Train Ballgown"
category: Nicole Spose
tags: [Nicole Spose,Ballgown,Sweetheart,Chapel Train,Sleeveless,2016]
---
### Nicole Spose Jolies of : MODEL JOAB16525
Just **$299.99**
### 2016  Sleeveless Chapel Train Ballgown

BRANDS	Nicole Spose

Silhouette	Ballgown

Neckline	Sweetheart

Hemline/Train	Chapel Train

Sleeve	Sleeveless

Years	2016

Buy it: [https://www.readybrides.com/en/nicole-spose/3698-nicole-spose-joab16525.html](https://www.readybrides.com/en/nicole-spose/3698-nicole-spose-joab16525.html)


text:
import paddle.fluid as fluid

def all_vocab_network(vocab_size,
                      hid_size=100,
                      init_low_bound=-0.04,
                      init_high_bound=0.04):
    """ network definition """
    emb_lr_x = 10.0
    gru_lr_x = 1.0
    fc_lr_x = 1.0
    # Input data
    src_wordseq = fluid.layers.data(
        name="src_wordseq", shape=[1], dtype="int64", lod_level=1)
    dst_wordseq = fluid.layers.data(
        name="dst_wordseq", shape=[1], dtype="int64", lod_level=1)

    emb = fluid.layers.embedding(
        input=src_wordseq,
        size=[vocab_size, hid_size],
        param_attr=fluid.ParamAttr(
            initializer=fluid.initializer.Uniform(
                low=init_low_bound, high=init_high_bound),
            learning_rate=emb_lr_x),
        is_sparse=True)
    fc0 = fluid.layers.fc(input=emb,
                          size=hid_size * 3,
                          param_attr=fluid.ParamAttr(
                              initializer=fluid.initializer.Uniform(
                                  low=init_low_bound, high=init_high_bound),
                              learning_rate=gru_lr_x))
    gru_h0 = fluid.layers.dynamic_gru(
        input=fc0,
        size=hid_size,
        param_attr=fluid.ParamAttr(
            initializer=fluid.initializer.Uniform(
                low=init_low_bound, high=init_high_bound),
            learning_rate=gru_lr_x))

    fc = fluid.layers.fc(input=gru_h0,
                         size=vocab_size,
                         act='softmax',
                         param_attr=fluid.ParamAttr(
                             initializer=fluid.initializer.Uniform(
                                 low=init_low_bound, high=init_high_bound),
                             learning_rate=fc_lr_x))
    cost = fluid.layers.cross_entropy(input=fc, label=dst_wordseq)
    acc = fluid.layers.accuracy(input=fc, label=dst_wordseq, k=20)
    avg_cost = fluid.layers.mean(x=cost)
    return src_wordseq, dst_wordseq, avg_cost, acc

def train_bpr_network(vocab_size, neg_size, hid_size, drop_out=0.2):
    """ network definition """
    emb_lr_x = 1.0
    gru_lr_x = 1.0
    fc_lr_x = 1.0
    # Input data
    src = fluid.layers.data(name="src", shape=[1], dtype="int64", lod_level=1)
    pos_label = fluid.layers.data(
        name="pos_label", shape=[1], dtype="int64", lod_level=1)
    label = fluid.layers.data(
        name="label", shape=[neg_size + 1], dtype="int64", lod_level=1)

    emb_src = fluid.layers.embedding(
        input=src,
        size=[vocab_size, hid_size],
        param_attr=fluid.ParamAttr(
            name="emb",
            initializer=fluid.initializer.XavierInitializer(),
            learning_rate=emb_lr_x))

    emb_src_drop = fluid.layers.dropout(emb_src, dropout_prob=drop_out)

    fc0 = fluid.layers.fc(input=emb_src_drop,
                          size=hid_size * 3,
                          param_attr=fluid.ParamAttr(
                              name="gru_fc",
                              initializer=fluid.initializer.XavierInitializer(),
                              learning_rate=gru_lr_x),
                          bias_attr=False)
    gru_h0 = fluid.layers.dynamic_gru(
        input=fc0,
        size=hid_size,
        param_attr=fluid.ParamAttr(
            name="dy_gru.param",
            initializer=fluid.initializer.XavierInitializer(),
            learning_rate=gru_lr_x),
        bias_attr="dy_gru.bias")
    gru_h0_drop = fluid.layers.dropout(gru_h0, dropout_prob=drop_out)

    label_re = fluid.layers.sequence_reshape(input=label, new_dim=1)
    emb_label = fluid.layers.embedding(
        input=label_re,
        size=[vocab_size, hid_size],
        param_attr=fluid.ParamAttr(
            name="emb",
            initializer=fluid.initializer.XavierInitializer(),
            learning_rate=emb_lr_x))

    emb_label_drop = fluid.layers.dropout(emb_label, dropout_prob=drop_out)

    gru_exp = fluid.layers.expand(
        x=gru_h0_drop, expand_times=[1, (neg_size + 1)])
    gru = fluid.layers.sequence_reshape(input=gru_exp, new_dim=hid_size)

    ele_mul = fluid.layers.elementwise_mul(emb_label_drop, gru)
    red_sum = fluid.layers.reduce_sum(input=ele_mul, dim=1, keep_dim=True)

    pre = fluid.layers.sequence_reshape(input=red_sum, new_dim=(neg_size + 1))

    cost = fluid.layers.bpr_loss(input=pre, label=pos_label)
    cost_sum = fluid.layers.reduce_sum(input=cost)
    return src, pos_label, label, cost_sum

def train_cross_entropy_network(vocab_size, neg_size, hid_size, drop_out=0.2):
    """ network definition """
    emb_lr_x = 1.0
    gru_lr_x = 1.0
    fc_lr_x = 1.0
    # Input data
    src = fluid.layers.data(name="src", shape=[1], dtype="int64", lod_level=1)
    pos_label = fluid.layers.data(
        name="pos_label", shape=[1], dtype="int64", lod_level=1)
    label = fluid.layers.data(
        name="label", shape=[neg_size + 1], dtype="int64", lod_level=1)

    emb_src = fluid.layers.embedding(
        input=src,
        size=[vocab_size, hid_size],
        param_attr=fluid.ParamAttr(
            name="emb",
            initializer=fluid.initializer.XavierInitializer(),
            learning_rate=emb_lr_x))

    emb_src_drop = fluid.layers.dropout(emb_src, dropout_prob=drop_out)

    fc0 = fluid.layers.fc(input=emb_src_drop,
                          size=hid_size * 3,
                          param_attr=fluid.ParamAttr(
                              name="gru_fc",
                              initializer=fluid.initializer.XavierInitializer(),
                              learning_rate=gru_lr_x),
                          bias_attr=False)
    gru_h0 = fluid.layers.dynamic_gru(
        input=fc0,
        size=hid_size,
        param_attr=fluid.ParamAttr(
            name="dy_gru.param",
            initializer=fluid.initializer.XavierInitializer(),
            learning_rate=gru_lr_x),
        bias_attr="dy_gru.bias")
    gru_h0_drop = fluid.layers.dropout(gru_h0, dropout_prob=drop_out)

    label_re = fluid.layers.sequence_reshape(input=label, new_dim=1)
    emb_label = fluid.layers.embedding(
        input=label_re,
        size=[vocab_size, hid_size],
        param_attr=fluid.ParamAttr(
            name="emb",
            initializer=fluid.initializer.XavierInitializer(),
            learning_rate=emb_lr_x))

    emb_label_drop = fluid.layers.dropout(emb_label, dropout_prob=drop_out)

    gru_exp = fluid.layers.expand(
        x=gru_h0_drop, expand_times=[1, (neg_size + 1)])
    gru = fluid.layers.sequence_reshape(input=gru_exp, new_dim=hid_size)

    ele_mul = fluid.layers.elementwise_mul(emb_label_drop, gru)
    red_sum = fluid.layers.reduce_sum(input=ele_mul, dim=1, keep_dim=True)

    pre_ = fluid.layers.sequence_reshape(input=red_sum, new_dim=(neg_size + 1))
    pre = fluid.layers.softmax(input=pre_)

    cost = fluid.layers.cross_entropy(input=pre, label=pos_label)
    cost_sum = fluid.layers.reduce_sum(input=cost)
    return src, pos_label, label, cost_sum

def infer_network(vocab_size, batch_size, hid_size, dropout=0.2):
    src = fluid.layers.data(name="src", shape=[1], dtype="int64", lod_level=1)
    emb_src = fluid.layers.embedding(
        input=src, size=[vocab_size, hid_size], param_attr="emb")
    emb_src_drop = fluid.layers.dropout(
        emb_src, dropout_prob=dropout, is_test=True)

    fc0 = fluid.layers.fc(input=emb_src_drop,
                          size=hid_size * 3,
                          param_attr="gru_fc",
                          bias_attr=False)
    gru_h0 = fluid.layers.dynamic_gru(
        input=fc0,
        size=hid_size,
        param_attr="dy_gru.param",
        bias_attr="dy_gru.bias")
    gru_h0_drop = fluid.layers.dropout(
        gru_h0, dropout_prob=dropout, is_test=True)

    all_label = fluid.layers.data(
        name="all_label",
        shape=[vocab_size, 1],
        dtype="int64",
        append_batch_size=False)
    emb_all_label = fluid.layers.embedding(
        input=all_label, size=[vocab_size, hid_size], param_attr="emb")
    emb_all_label_drop = fluid.layers.dropout(
        emb_all_label, dropout_prob=dropout, is_test=True)

    all_pre = fluid.layers.matmul(
        gru_h0_drop, emb_all_label_drop, transpose_y=True)

    pos_label = fluid.layers.data(
        name="pos_label", shape=[1], dtype="int64", lod_level=1)
    acc = fluid.layers.accuracy(input=all_pre, label=pos_label, k=20)
    return acc


text:
module Diffux
  module SnapshotComparisonImage
    # This subclass of `SnapshotComparisonImage` knows how to draw the
    # representation of the "after" image.
    class After < SnapshotComparisonImage::Base
      # @param y [Integer]
      # @param row [Diff::LCS:ContextChange]
      def render_changed_row(y, row)
        render_added_row(y, row)
      end

      # @param y [Integer]
      # @param row [Diff::LCS:ContextChange]
      def render_added_row(y, row)
        row.new_element.each_with_index do |pixel_after, x|
          render_pixel(x, y, pixel_after)
        end
      end
    end
  end
end


text:
typedef enum {

    ArrangeType_Noum = 0,   //默认  //综合排序
    ArrangeType_Price = 1,    //按价格
    ArrangeType_SalesVolume = 2  //按销量

}ArrangeType;

@interface AFBOrderCommonControlBut : UIControl

@property(nonatomic, strong) UILabel * titleLable;

@property(nonatomic, assign) ArrangeType arrangeType;

@end


text:
import Googlemap from './Googlemap'
export default Googlemap