text:
import { build, fs, IParameters, http, install, logger, strings, semver, inquirer } from '../index'
import { parseParams } from '../toolbox/parameter-tools'
import { machineIdSync } from 'node-machine-id'
import * as path from 'path'

const debug = require('debug')('weex:core')

export enum ModType {
  PLUGIN,
  EXTENSION,
}

export enum ErrorType {
  PACKAGE_VERSION_NOT_FOUND = 101,
  PACKAGE_NOT_FOUND,
}
export interface ModData {
  mods: {
    [key: string]: ModItem
  }
  last_update_time: number
}

export interface Command {
  name?: string
  alias?: string
  dashed?: boolean
  description?: string
}

export interface ModItem {
  type: ModType
  version: string
  description: string
  dependencies?: {
    [key: string]: string
  }
  next_version?: string
  is_next?: boolean
  changelog?: string
  local: string
  commands?: string[]
}
export interface PluginItem {
  value?: string
  options?: any
  commands?: {
    name: string
    alias: string
    description: string
    showed: boolean
  }[]
  name?: string
}

export interface CliConfiguration {
  cliVersion: string
  corePath: string
  coreName: string
  coreRoot: string
  moduleRoot: string
  moduleConfigFileName: string
  home: string
  registry: string
  argv: string
  trash: string
  modules: ModData
  globalConfigFileName: string
  force?: boolean
  configs?: {
    [key: string]: any
  }
  ENVS?: any
}

export interface CoreOptions {
  brand?: string
  help?: any
  defaultCommand?: any
  version?: any
  plugin?: {
    value?: string
    options?: any
  }
  plugins?: {
    value?: string
    options?: any
  }
  exclude?: string[]
}
// use for analyzer function
let cliConfiguration: CliConfiguration

export default class Cli {
  private cli: any
  private updateTime: number
  private rawArgv: string[] | string
  private argv: IParameters
  private plugins: PluginItem[] = []
  private cliConfiguration: CliConfiguration
  constructor(data: CliConfiguration, options: CoreOptions = {}) {
    debug('Init Cli instance on <%s>', __filename)
    this.rawArgv = data.argv

    this.updateTime = data.configs.update_time || 7

    this.argv = parseParams(data.argv)

    this.cliConfiguration = cliConfiguration = {
      ...data,
      force: this.argv.options.f || this.argv.options.force,
    }
    // create a CLI runtime
    this.cli = build(options.brand || 'weex')
      .src(__dirname)
      .help(options.help)
      .version(options.version)
      .exclude(options.exclude)
      .defaultCommand(options.defaultCommand)

    if (options.plugins && options.plugins.value) {
      this.cli = this.cli.plugins(options.plugins.value, options.plugins.options)
    }

    if (!this.cliConfiguration.modules.mods) {
      this.cliConfiguration.modules['mods'] = {}
      this.cliConfiguration.modules['last_update_time'] = new Date().getTime()
    }

    if (options.plugin) {
      if (Array.isArray(options.plugin)) {
        options.plugin.forEach(p => {
          this.cli = this.cli.plugin(p.value, p.options)
        })
      } else {
        this.cli = this.cli.plugin(options.plugin.value, options.plugin.options)
      }
    }
  }

  async start() {
    const command = this.argv.array[0]
    const moduleConfigFilePath = path.join(this.cliConfiguration.moduleRoot, this.cliConfiguration.moduleConfigFileName)
    const pkg = require('../../package.json')

    const traceData = {
      cmd: command || '',
      argv: this.argv.array.join('+'),
      mid: machineIdSync(),
      node: process.version,
      core: pkg.version,
    }
    usertrack('usage', traceData, this.cliConfiguration.configs.telemetry)

    if (this.cliConfiguration.modules) {
      this.plugins = pickPlugins(this.cliConfiguration.modules)
    } else {
      fs.write(moduleConfigFilePath, {
        mods: {},
        last_update_time: new Date().getTime(),
      })
    }
    if (command === 'repair') {
      debug(`Do repair`)
    } else if (command === 'config') {
      debug('Do config')
    } else if (command === 'install') {
      debug('Do install')
    } else if (command === 'uninstall') {
      debug('Do uninstall')
    } else if (command) {
      const plugin = searchPlugin(command, this.plugins)
      let commands = []
      let type = ModType.EXTENSION
      // If the module has been instll, skip
      if (!plugin || !plugin.name) {
        let packageSubName = command
        if (command === 'create' || command === 'platform') {
          packageSubName = 'generator'
        }
        const res: { error?: string; [key: string]: any } = await suggestPackage(
          packageSubName,
          this.cliConfiguration.configs.registry,
        )
        if (res && !res.error) {
          const packages: any = await installPackage(this.cliConfiguration, `@weex-cli/${packageSubName}`, 'latest', {
            root: this.cliConfiguration.moduleRoot,
            registry: this.cliConfiguration.configs.registry,
            force: this.cliConfiguration.force,
            ENVS: this.cliConfiguration.configs.ENVS,
          })
          for (let i = 0; i < packages.length; i++) {
            const commandBasePath = path.join(packages[i].root, 'commands')
            const extensionBasePath = path.join(packages[i].root, 'extensions')
            const commandFiles: string[] = fs.list(commandBasePath) || []
            commands = []
            // continue next package while the package has not commands and extensions folder
            if (!fs.existsAsync(commandBasePath) && !fs.existsAsync(extensionBasePath)) {
              continue
            }
            commandFiles.forEach(file => {
              let content: Command = {}
              try {
                content = require(path.join(commandBasePath, file))
              } catch (e) {
                debug(`Check module error with: ${e.stack}`)
                // try prev version
              }
              if (content.name) {
                commands.push({
                  name: content.name || '',
                  alias: content.alias || '',
                  showed: typeof content.dashed === 'boolean' ? !content.dashed : true,
                  description: content.description || '',
                })
                type = ModType.PLUGIN
              } else {
                type = ModType.EXTENSION
              }
            })

            this.cliConfiguration.modules.mods[packages[i].package.name] = {
              type: type,
              version: packages[i].package.version,
              description: packages[i].package.description || '',
              dependencies: packages[i].package.pluginDependencies,
              next_version: '',
              is_next: true,
              changelog: packages[i].package.changelog || '',
              local: packages[i].root,
              commands: commands,
            }
            this.plugins.push({
              value: packages[i].root,
              options: {},
              commands: commands,
              name: packages[i].package.name,
            })
          }
          // update module file
          fs.write(moduleConfigFilePath, {
            mods: this.cliConfiguration.modules.mods,
            last_update_time: new Date().getTime(),
          })
        }
      } else {
        // check if there has some module need to be upgraded
        // check last_update_time
        const info: any = await updateNpmPackageInfo(
          this.cliConfiguration.modules,
          this.cliConfiguration.configs.registry,
          this.updateTime,
        )
        if (info) {
          let upgradeList = {}
          for (let mod in info.mods) {
            if (!info.mods[mod].is_next) {
              upgradeList[mod] = info.mods[mod]
            }
          }
          const generateChangelog = (changelog: any[] | string): string => {
            if (!changelog) {
              return ''
            }
            if (typeof changelog === 'string') {
              changelog = [changelog]
            }
            changelog = changelog.map(log => `\n    • ${log}`)
            return `\n  changelog:${changelog.join('')}`
          }

          let lists = Object.keys(upgradeList).map(key => {
            return {
              name: `${key} ${logger.colors.grey(
                `${upgradeList[key].version} -> ${upgradeList[key].next_version}${generateChangelog(
                  upgradeList[key].changelog,
                )}`,
              )}`,
              value: key,
            }
          })
          let yes = 'Yes, update all'
          let no = 'No, next time'
          let choices = [yes, no, new inquirer.Separator('Or choose update package')].concat(lists)
          if (lists.length > 0) {
            let res = await inquirer.prompt({
              name: 'choose',
              type: 'list',
              choices: choices,
              default: yes,
              message: 'New update detected, update now?',
            })
            if (yes === res.choose) {
              for (let item in upgradeList) {
                await repairPackage(this.cliConfiguration, item, upgradeList[item].next_version)
                logger.success(
                  `[${logger.checkmark}] Upgrade ${item} ${upgradeList[item].version} -> ${
                    upgradeList[item].next_version
                  } success`,
                )
              }
              logger.success(`All task completed.`)
            } else if (no !== res.choose) {
              await repairPackage(this.cliConfiguration, res.choose, upgradeList[res.choose].next_version)
              logger.success(
                `[${logger.checkmark}] Upgrade ${res.choose} ${upgradeList[res.choose].version} -> ${
                  upgradeList[res.choose].next_version
                } success`,
              )
            }
          }
          fs.write(moduleConfigFilePath, info)
        }
      }
      if (this.plugins.length > 0) {
        this.plugins.forEach(p => {
          this.cli = this.cli.plugin(p.value, p.options)
        })
      }
    }
    // run the cli
    const toolbox = await this.cli.create().run(this.rawArgv, { __config: this.cliConfiguration, __analyzer: analyzer })
    // send it back (for testing, mostly)
    return toolbox
  }
}

/**
 * Repair npm package
 *
 * @param name npm package name
 * @param version npm package version
 */
export async function repairPackage(config: CliConfiguration, name: string, version: string) {
  let commands = []
  let type = ModType.EXTENSION
  const moduleConfigFilePath = path.join(config.moduleRoot, config.moduleConfigFileName)
  const packages: any = await installPackage(config, name, version, {
    root: config.moduleRoot,
    registry: config && config.configs && config.configs.registry,
    force: config.force,
    ENVS: config.ENVS,
  })
  for (let i = 0; i < packages.length; i++) {
    let commandBasePath = path.join(packages[i].root, 'commands')
    let commandFiles: string[] = fs.list(commandBasePath) || []
    commandFiles.forEach(file => {
      let content
      try {
        content = require(path.join(commandBasePath, file))
      } catch (e) {
        debug(`Check module error with: ${e.stack}`)
        // try prev version
      }
      commands.push({
        name: (content && content.name) || '',
        alias: (content && content.alias) || '',
        showed: content && typeof content.dashed === 'boolean' ? !content.dashed : true,
        description: (content && content.description) || '',
      })
      type = ModType.PLUGIN
    })
    if (commands.length > 0) {
      config.modules.mods[packages[i].package.name] = {
        type: type,
        version: packages[i].package.version,
        description: packages[i].package.description || '',
        dependencies: packages[i].package.pluginDependencies,
        next_version: '',
        is_next: true,
        changelog: packages[i].package.changelog || '',
        local: packages[i].root,
        commands: commands,
      }
      commands = []
    } else {
      config.modules.mods[packages[i].package.name] = {
        type: type,
        version: packages[i].package.version,
        description: packages[i].package.description || '',
        dependencies: packages[i].package.pluginDependencies,
        next_version: '',
        is_next: true,
        changelog: packages[i].package.changelog || '',
        local: packages[i].root,
      }
    }
  }
  debug(`save modjson: ${JSON.stringify(config.modules.mods)}`)
  // update module file
  fs.write(moduleConfigFilePath, {
    mods: config.modules.mods,
    last_update_time: new Date().getTime(),
  })
}

/**
 * Install packages
 *
 * @param name package name
 * @param version package version
 * @param options install options
 * @param result data from reduce
 */
export async function installPackage(
  config: CliConfiguration,
  name: string,
  version: string,
  options: any,
  result: any = [],
) {
  const info: any = await install(name, version || 'latest', options)
  let res = result.concat(info)
  if (info.package.pluginDependencies) {
    for (let name in info.package.pluginDependencies) {
      res = await installPackage(config, name, info.package.pluginDependencies[name], options, res)
    }
  }
  return res
}

/**
 * Suggest if there has a official module for the command.
 *
 * @param command command name
 * @param registry npm registry
 */
export async function suggestPackage(command: string, registry: string = 'https://registry.npm.taobao.org/') {
  const npmApi = http.create({
    baseURL: `${registry}${registry.slice(-1) === '/' ? '' : '/'}-/package/@weex-cli/`,
    timeout: 30000,
    headers: {
      Accept: '*/*',
    },
  })
  const res: any = await npmApi.get(`${command}/dist-tags`)
  if (res.problem) {
    debug('suggest package error:', res.problem)
    await analyzer('request', res.problem, { registry })
  }
  return res.data
}

/**
 * Checking if there has the package on the specified registry with specified version
 *
 * @param name package name
 * @param version package version
 * @param registry npm registry
 */
export async function checkNpmPackageExist(name: string, version: string, registry: string) {
  const npmApi = http.create({
    baseURL: `${registry}`,
  })
  const res: any = await npmApi.get(`${name}`)
  if (res && res.data.error) {
    if (/not_found/.test(res.data.error)) {
      res.data.error = ErrorType.PACKAGE_NOT_FOUND
    }
  } else if (version && version !== 'latest') {
    if (res && !res.data.versions[version]) {
      res.data.error = ErrorType.PACKAGE_VERSION_NOT_FOUND
      res.data.versions = Object.keys(res.data.versions)
    }
  }
  return res.data
}

/**
 * Check if there has some modules need to be upgraded.
 *
 * @param modules module item
 * @param registry npm registry
 * @param time update checking times, day
 */
export async function updateNpmPackageInfo(modules: ModData, registry: string, time: number = 1) {
  const modData = Object.assign({}, modules)
  const date = new Date()
  if (date.getTime() - modData.last_update_time <= 24 * 3600 * 1000 * time) {
    return false
  }
  logger.info(`Time: ${formateTime(date)}, verify if there is an update`)
  for (let mod in modData.mods) {
    let spinner = logger.spin(`Checking ${mod} ... ${logger.colors.grey('this may take a few seconds')}`)
    spinner.text = ``
    let res = await getLatestNpmPackageInfo(mod, registry)
    if (res && !res.error) {
      spinner.stopAndPersist({
        symbol: `${logger.colors.green(`[${logger.checkmark}]`)}`,
        text: `sync module [${mod}]`,
      })
      if (semver.gt(res.latest, modData.mods[mod].version)) {
        modData.mods[mod].is_next = false
        modData.mods[mod].next_version = res.latest
        modData.mods[mod].changelog = res.package.changelog || ''
      } else {
        modData.mods[mod].is_next = true
        modData.mods[mod].next_version = res.latest
        modData.mods[mod].changelog = res.package.changelog || ''
      }
    } else {
      if (res.error === ErrorType.PACKAGE_NOT_FOUND) {
        spinner.stopAndPersist({
          symbol: `${logger.colors.red(`[${logger.xmark}]`)}`,
          text: `Package [${mod}] not found on registry ${registry}`,
        })
      } else {
        spinner.stopAndPersist({
          symbol: `${logger.colors.red(`[${logger.xmark}]`)}`,
          text: `Unkonw error with checking [${mod}], ${res.error}`,
        })
      }
    }
  }
  modData.last_update_time = date.getTime()
  return modData
}

/**
 * Get the latest version of a package.
 *
 * @param name package name
 * @param registry npm registry
 * @returns {error?:string, latest?:string}
 */
export async function getLatestNpmPackageInfo(name: string, registry: string = 'https://registry.npm.taobao.org/') {
  const npmApi = http.create({
    baseURL: `${registry}`,
    timeout: 30000,
    headers: {
      Accept: '*/*',
    },
  })
  const res: any = await npmApi.get(`${registry}${registry.slice(-1) === '/' ? '' : '/'}${name}/latest`)
  let error
  if (res && res.data) {
    debug('Get latest npm package info: ', JSON.stringify(res.data))
    if (res.data.error) {
      if (/not_found/.test(res.data.error)) {
        error = ErrorType.PACKAGE_NOT_FOUND
      }
    } else if (res.data['version']) {
      const latest = res.data['version']
      return {
        latest: latest,
        package: res.data,
      }
    }
  } else {
    error = `can't found ${name} latest version`
  }
  return {
    error: error,
  }
}

/**
 * Pick suitable search from stack
 * @param stack error stack
 */
export function pickSearchKey(stack: string) {
  let res = /error:/gi.exec(stack)
  let errorIndex
  if (res) {
    errorIndex = res.index
  } else {
    errorIndex = -6
  }
  if (errorIndex) {
    return stack
      .slice(errorIndex + 6)
      .split('\n')[0]
      .split(' ')
      .join('+')
  } else {
    return stack
      .split('\n')[0]
      .split(' ')
      .join('+')
  }
}

/**
 * Show help message while catch an unknow issue
 * @param stack
 */
export function showUnknowErrorsHelp(stack: string) {
  logger.error(stack)
  logger.log(logger.colors.grey(`Search for existing GitHub issues similar to yours:`))
  let searchKey = pickSearchKey(stack)
  logger.log(`https://github.com/weexteam/weex-toolkit/issues?q=${searchKey}&type=issue`)

  logger.log(logger.colors.grey(`\nIf none exists, create a ticket, with the template displayed above, on:`))
  logger.log(`https://github.com/weexteam/weex-toolkit/issues/new`)

  logger.log(
    logger.colors.grey(
      `\nBe sure to first read the contributing guide for details on how to properly submit a ticket:`,
    ),
  )
  logger.log(`https://github.com/weexteam/weex-toolkit/master/CONTRIBUTING.md`)

  logger.log(logger.colors.grey(`\nDon't forget to anonymize any private data!`))

  logger.log(logger.colors.grey(`\nLooking for related issues on:`))
  logger.log('https://github.com/weexteam/weex-toolkit/issues?q=is%3Aclosed')
}

/**
 * Analyzer error stack and give some solution.
 *
 * @param type command type
 * @param stack error stack
 * @param options data from error stack
 */
export async function analyzer(type: string, stack: any, options?: any) {
  if (type === 'repair') {
    if (ErrorType.PACKAGE_NOT_FOUND === stack) {
      const innerMods = [
        '@weex-cli/debug',
        '@weex-cli/generator',
        '@weex-cli/build',
        '@weex-cli/preview',
        '@weex-cli/run',
        '@weex-cli/doctor',
        '@weex-cli/lint',
        '@weex-cli/device',
      ]
      let score
      let tempScore
      let suggestName
      innerMods.forEach(mod => {
        tempScore = strings.strSimilarity2Number(mod, options.name)
        if (!score) {
          score = tempScore
          suggestName = mod
        } else if (tempScore < score) {
          score = tempScore
          suggestName = mod
        }
      })
      logger.warn(`Module "${options.name}" not found, do you mean "${suggestName}"?`)
    } else if (ErrorType.PACKAGE_VERSION_NOT_FOUND === stack) {
      logger.warn(`Module "${options.name}@${options.version}" not found`)
      if (Array.isArray(options.versions) && options.versions.length > 0) {
        logger.info('Chose one of the versions:')
        options.versions.forEach(version => {
          logger.info(`- ${version}`)
        })
      }
    } else if (typeof stack === 'string') {
      if (/module is locked/.test(stack)) {
        logger.log(`The module is locked now, please be patient and wait for other installation processes to complete.`)
        logger.warn(`You can also enforce it by adding \`-f\` or \`--force\` flag.`)
      }
      showUnknowErrorsHelp(stack)
    }
  } else if (type === 'request') {
    if (stack === 'CONNECTION_ERROR') {
      logger.log(`Please check if your network can access ${logger.colors.yellow(options.registry)} normally`)
      logger.log(`Or you can use \`weex config set registry [registry-url]\` command to use other npm registry`)
    } else if (stack === 'TIMEOUT_ERROR') {
      logger.log(`Please check if your network can access ${logger.colors.yellow(options.registry)} normally`)
      logger.info(`Or you can use the \`install\` command to install the plugin.`)
    }
  } else if (type === 'compile') {
    let vueMismatchReg = /Vue packages version mismatch/gi
    if (vueMismatchReg.test(stack)) {
      logger.error(stack)
      logger.warn('\n Try `weex doctor` command to fix this problem.')
    } else {
      showUnknowErrorsHelp(stack)
    }
  } else if (typeof stack === 'string') {
    showUnknowErrorsHelp(stack)
    usertrack('error_track', { type, stack }, cliConfiguration.configs.telemetry)
  }
}

/**
 * usertrack
 * @param stage usertrack usage
 * @param track data
 * @param telemetry can report data or not
 */
export function usertrack(stage: string, track: any, telemetry: boolean) {
  if (!telemetry) {
    return
  }
  // usertrack
  const usertrackapi = http.create({
    baseURL: `http://gm.mmstat.com/`,
  })
  let trackQuery = `weex-cli-2.0.tool_usage.${stage}?`
  for (let key in track) {
    trackQuery += `${key}=${track[key]}&`
  }
  trackQuery += `t=${new Date().getTime()}`
  try {
    /* tslint-disabled */
    usertrackapi.get(trackQuery)
  } catch (error) {
    debug('Http request error', error)
  }
}

/**
 * Formate time to hh:mm:ss
 * @param date
 */
export function formateTime(date: Date) {
  let hourse = date.getHours() > 9 ? date.getHours() : '0' + date.getHours()
  let min = date.getHours() > 9 ? date.getMinutes() : '0' + date.getMinutes()
  let seconds = date.getSeconds() > 9 ? date.getSeconds() : '0' + date.getSeconds()
  return `${hourse}:${min}:${seconds}`
}

/**
 * Pick plugin items for cli toolbox.
 *
 * @param modules data from module.json
 */
export function pickPlugins(modules: ModData): PluginItem[] {
  if (!modules) return []
  let plugins = []
  for (let item in modules.mods) {
    let mod: ModItem = modules.mods[item]
    plugins.push({
      value: mod.local,
      options: {},
      commands: mod.commands,
      name: item,
    })
  }
  return plugins
}

/**
 * Map command to a package module.
 *
 * @param command
 * @param mods
 */
export function searchPlugin(command: string, mods: PluginItem[]): PluginItem {
  if (mods.length > 0) {
    let result
    mods.forEach((mod: PluginItem) => {
      if (mod.commands && Array.isArray(mod.commands)) {
        mod.commands.forEach(cmd => {
          if (cmd.name === command || cmd.alias === command) {
            result = mod
          }
        })
      }
    })
    return result
  } else {
    return {}
  }
}


text:
package hu.akarnokd.reactive4javaflow.impl.consumers;

import hu.akarnokd.reactive4javaflow.FolyamSubscriber;
import hu.akarnokd.reactive4javaflow.impl.*;

import java.lang.invoke.*;
import java.util.concurrent.*;

public final class CompletionStageConsumer<T> extends CompletableFuture<T> implements FolyamSubscriber<T> {

    T item;

    Flow.Subscription upstream;
    static final VarHandle UPSTREAM = VH.find(MethodHandles.lookup(), CompletionStageConsumer.class, "upstream", Flow.Subscription.class);

    @Override
    public void onSubscribe(Flow.Subscription subscription) {
        if (SubscriptionHelper.replace(this, UPSTREAM, subscription)) {
            whenComplete(this::cancel);
            subscription.request(Long.MAX_VALUE);
        }
    }

    void cancel(T t, Throwable e) {
        SubscriptionHelper.cancel(this, UPSTREAM);
        item = null;
    }

    @Override
    public void onNext(T item) {
        this.item = item;
    }

    @Override
    public void onError(Throwable throwable) {
        item = null;
        super.completeExceptionally(throwable);
    }

    @Override
    public void onComplete() {
        super.complete(item);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.jackrabbit.oak.segment.tool;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.Lists.newArrayList;
import static org.apache.jackrabbit.oak.segment.file.FileStoreBuilder.fileStoreBuilder;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.jackrabbit.oak.segment.file.InvalidFileStoreVersionException;
import org.apache.jackrabbit.oak.segment.file.JournalReader;
import org.apache.jackrabbit.oak.segment.file.ReadOnlyFileStore;
import org.apache.jackrabbit.oak.segment.file.tooling.BasicReadOnlyBlobStore;
import org.apache.jackrabbit.oak.spi.blob.BlobStore;

class Utils {

    private static final boolean TAR_STORAGE_MEMORY_MAPPED = Boolean.getBoolean("tar.memoryMapped");

    private static final int TAR_SEGMENT_CACHE_SIZE = Integer.getInteger("cache", 256);

    static ReadOnlyFileStore openReadOnlyFileStore(File path, BlobStore blobStore) throws IOException, InvalidFileStoreVersionException {
        return fileStoreBuilder(isValidFileStoreOrFail(path))
                .withSegmentCacheSize(TAR_SEGMENT_CACHE_SIZE)
                .withMemoryMapping(TAR_STORAGE_MEMORY_MAPPED)
                .withBlobStore(blobStore)
                .buildReadOnly();
    }

    static ReadOnlyFileStore openReadOnlyFileStore(File path) throws IOException, InvalidFileStoreVersionException {
        return fileStoreBuilder(isValidFileStoreOrFail(path))
                .withSegmentCacheSize(TAR_SEGMENT_CACHE_SIZE)
                .withMemoryMapping(TAR_STORAGE_MEMORY_MAPPED)
                .buildReadOnly();
    }

    static BlobStore newBasicReadOnlyBlobStore() {
        return new BasicReadOnlyBlobStore();
    }

    static List<String> readRevisions(File store) {
        File journal = new File(store, "journal.log");

        if (journal.exists()) {
            try (JournalReader journalReader = new JournalReader(journal)) {
                return newArrayList(journalReader);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return newArrayList();
    }

    private static File isValidFileStoreOrFail(File store) {
        checkArgument(isValidFileStore(store), "Invalid FileStore directory " + store);
        return store;
    }

    private static boolean isValidFileStore(File store) {
        if (!store.exists()) {
            return false;
        }

        if (!store.isDirectory()) {
            return false;
        }

        for (String f : store.list()) {
            if ("journal.log".equals(f)) {
                return true;
            }
        }

        return false;
    }

}


text:
layout: post
date: '2016-10-04'
title: "Casablanca Bridal 2090 Fit and Flare Wedding Dress"
category: Casablanca Bridal
tags: [Casablanca Bridal]
---
### Casablanca Bridal 2090 Fit and Flare Wedding Dress
Just **$337.99**
###

Special Order Only, NOT AVAILABLE IN STORE FOR TRY ON.

Glamorous trumpet shaped silhouette with flowers delicately placed throughout the skirt. This strapless gown has an asymmetric ruched dropped waist and deep

Buy it: [https://www.eudances.com/en/casablanca-bridal/523-casablanca-bridal-2090-fit-and-flare-wedding-dress.html](https://www.eudances.com/en/casablanca-bridal/523-casablanca-bridal-2090-fit-and-flare-wedding-dress.html)


text:
namespace net {

class QuicStreamSequencer;

namespace test {

class QuicStreamSequencerPeer {
 public:
  static size_t GetNumBufferedFrames(QuicStreamSequencer* sequencer);

  static bool FrameOverlapsBufferedData(QuicStreamSequencer* sequencer,
                                        const QuicStreamFrame& frame);

  static QuicStreamOffset GetCloseOffset(QuicStreamSequencer* sequencer);

 private:
  DISALLOW_COPY_AND_ASSIGN(QuicStreamSequencerPeer);
};

}  // namespace test
}  // namespace net

#endif  // NET_QUIC_TEST_TOOLS_QUIC_STREAM_SEQUENCER_PEER_H_


text:
/**
 * Open Payments Cloud Application API
 * Open Payments Cloud API
 *
 * OpenAPI spec version: 1.0.0
 *
 *
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen.git
 * Do not edit the class manually.
 *
 */

(function(root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['ApiClient', 'model/Withdrawal'], factory);
  } else if (typeof module === 'object' && module.exports) {
    // CommonJS-like environments that support module.exports, like Node.
    module.exports = factory(require('../ApiClient'), require('./Withdrawal'));
  } else {
    // Browser globals (root is window)
    if (!root.OpenPaymentsCloudApplicationApi) {
      root.OpenPaymentsCloudApplicationApi = {};
    }
    root.OpenPaymentsCloudApplicationApi.Withdrawals = factory(root.OpenPaymentsCloudApplicationApi.ApiClient, root.OpenPaymentsCloudApplicationApi.Withdrawal);
  }
}(this, function(ApiClient, Withdrawal) {
  'use strict';

  /**
   * The Withdrawals model module.
   * @module model/Withdrawals
   * @version 1.1.0
   */

  /**
   * Constructs a new Withdrawals.
   * @alias module:model/Withdrawals
   * @class
   */
  var exports = function() {
    var _this = this;

  };

  /**
   * Constructs a Withdrawals from a plain JavaScript object, optionally creating a new instance.
   * Copies all relevant properties from data to obj if supplied or a new instance if not.
   * @param {Object} data The plain JavaScript object bearing properties of interest.
   * @param {module:model/Withdrawals} obj Optional instance to populate.
   * @return {module:model/Withdrawals} The populated Withdrawals instance.
   */
  exports.constructFromObject = function(data, obj) {
    if (data) {
      obj = obj || new exports();

      if (data.hasOwnProperty('withdrawals')) {
        obj['withdrawals'] = ApiClient.convertToType(data['withdrawals'], [Withdrawal]);
      }
      if (data.hasOwnProperty('count')) {
        obj['count'] = ApiClient.convertToType(data['count'], 'Number');
      }
      if (data.hasOwnProperty('actions')) {
        obj['actions'] = ApiClient.convertToType(data['actions'], ['String']);
      }
    }
    return obj;
  }

  /**
   * @member {Array.<module:model/Withdrawal>} withdrawals
   */
  exports.prototype['withdrawals'] = undefined;
  /**
   * The total number of entries that match the given filter, including any entries which were not returned due to paging constraints.
   * @member {Number} count
   */
  exports.prototype['count'] = undefined;
  /**
   * The actions that can be performed on this particular resource instance.
   * @member {Array.<module:model/Withdrawals.ActionsEnum>} actions
   */
  exports.prototype['actions'] = undefined;

  /**
   * Allowed values for the actions property.
   * @enum {String}
   * @readonly
   */
  exports.ActionsEnum = {
    /**
     * value: "CREATE"
     * @const
     */
    "CREATE": "CREATE"  };

  return exports;
}));


text:
package org.wso2.carbon.identity.query.saml.validation;

import org.opensaml.saml.saml2.core.AssertionIDRequest;
import org.opensaml.saml.saml2.core.AttributeQuery;
import org.opensaml.saml.saml2.core.AuthnQuery;
import org.opensaml.saml.saml2.core.RequestAbstractType;
import org.opensaml.saml.saml2.core.SubjectQuery;
import org.opensaml.saml.saml2.core.impl.AuthzDecisionQueryImpl;
import org.wso2.carbon.identity.query.saml.dto.InvalidItemDTO;
import org.wso2.carbon.identity.query.saml.util.SAMLQueryRequestConstants;

import java.util.List;

/**
 * This factory class is used to select relevant validation class dynamically
 */
public class SAMLValidatorFactory {

    /**
     * This method is used to select validation class using factory pattern
     *
     * @param request any type of request message
     * @return SAMLQueryValidator selected validation class
     */
    public static SAMLQueryValidator getValidator(List<InvalidItemDTO> invalidItems, RequestAbstractType request) {
        SAMLQueryValidator samlQueryValidator = null;
        if (request instanceof AssertionIDRequest) {
            samlQueryValidator = new SAMLIDRequestValidator();
        } else if (request instanceof AttributeQuery) {
            samlQueryValidator = new SAMLAttributeQueryValidator();
        } else if (request instanceof AuthnQuery) {
            samlQueryValidator = new SAMLAuthQueryValidator();
        } else if (request instanceof AuthzDecisionQueryImpl) {
            samlQueryValidator = new SAMLAuthzDecisionValidator();
        } else if (request instanceof SubjectQuery) {
            samlQueryValidator = new SAMLSubjectQueryValidator();
        } else {
            invalidItems.add(new InvalidItemDTO(SAMLQueryRequestConstants.ValidationType.VAL_MESSAGE_TYPE,
                    SAMLQueryRequestConstants.ValidationMessage.VAL_MESSAGE_TYPE_ERROR));
        }
        return samlQueryValidator;
    }
}


text:
\chapter{Frequently Asked Questions}

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "kulemt"
%%% End:


text:
package org.teavm.jso.dom.xml;

import org.teavm.jso.JSProperty;

public interface Element extends Node {
    String getAttribute(String name);

    void setAttribute(String name, String value);

    void removeAttribute(String name);

    Attr getAttributeNode(String name);

    Attr setAttributeNode(Attr newAttr);

    Attr removeAttributeNode(Attr oldAttr);

    NodeList<? extends Element> getElementsByTagName(String name);

    String getAttributeNS(String namespaceURI, String localName);

    void setAttributeNS(String namespaceURI, String qualifiedName, String value);

    void removeAttributeNS(String namespaceURI, String localName);

    Attr getAttributeNodeNS(String namespaceURI, String localName);

    Attr setAttributeNodeNS(Attr newAttr);

    NodeList<? extends Element> getElementsByTagNameNS(String namespaceURI, String localName);

    boolean hasAttribute(String name);

    boolean hasAttributeNS(String namespaceURI, String localName);

    Element querySelector(String selectors);

    NodeList<? extends Element> querySelectorAll(String selectors);

    @JSProperty
    String getId();

    @JSProperty
    void setId(String id);

    @JSProperty
    String getTagName();

    void scrollIntoView();
}


text:
                    #
                    {$this->lang->words['Words']['Free']}
                    {const="VIP_NAME_1"}
                    <if syntax="VIP_NUMBER >= 2">
                    {const="VIP_NAME_2"}
                    </if>
                    <if syntax="VIP_NUMBER >= 3">
                    {const="VIP_NAME_3"}
                    </if>
                    <if syntax="VIP_NUMBER >= 4">
                    {const="VIP_NAME_4"}
                    </if>
                    <if syntax="VIP_NUMBER == 5">
                    {const="VIP_NAME_5"}
                    </if>

            	<if syntax="$this->settings['USERPANEL']['CHARACTER']['MASTER_RESET'][0xFF]['MODE'] < 3">

                    {$this->lang->words['Infos']['MResetTable']['ResetsRequire']}
                    {$informations['masterResetTable']['resets_require'][0]}
                    {$informations['masterResetTable']['resets_require'][1]}
                    <if syntax="VIP_NUMBER >= 2">
                    {$informations['masterResetTable']['resets_require'][2]}
                    </if>
                    <if syntax="VIP_NUMBER >= 3">
                    {$informations['masterResetTable']['resets_require'][3]}
                    </if>
                    <if syntax="VIP_NUMBER >= 4">
                    {$informations['masterResetTable']['resets_require'][4]}
                    </if>
                    <if syntax="VIP_NUMBER == 5">
                    {$informations['masterResetTable']['resets_require'][5]}
                    </if>

                </if>

                	{$this->lang->words['Infos']['MResetTable']['LevelReset']}
                    {$informations['masterResetTable']['level_reset'][0]}
                    {$informations['masterResetTable']['level_reset'][1]}
                    <if syntax="VIP_NUMBER >= 2">
                    {$informations['masterResetTable']['level_reset'][2]}
                    </if>
                    <if syntax="VIP_NUMBER >= 3">
                    {$informations['masterResetTable']['level_reset'][3]}
                    </if>
                    <if syntax="VIP_NUMBER >= 4">
                    {$informations['masterResetTable']['level_reset'][4]}
                    </if>
                    <if syntax="VIP_NUMBER == 5">
                    {$informations['masterResetTable']['level_reset'][5]}
                    </if>

                    {$this->lang->words['Infos']['MResetTable']['StrengthRequire']}
                    {$informations['masterResetTable']['strength_require']}
                    {$informations['masterResetTable']['strength_require']}
                    <if syntax="VIP_NUMBER >= 2">
                    {$informations['masterResetTable']['strength_require']}
                    </if>
                    <if syntax="VIP_NUMBER >= 3">
                    {$informations['masterResetTable']['strength_require']}
                    </if>
                    <if syntax="VIP_NUMBER >= 4">
                    {$informations['masterResetTable']['strength_require']}
                    </if>
                    <if syntax="VIP_NUMBER == 5">
                    {$informations['masterResetTable']['strength_require']}
                    </if>

                    {$this->lang->words['Infos']['MResetTable']['DexterityRequire']}
                    {$informations['masterResetTable']['dexterity_require']}
                    {$informations['masterResetTable']['dexterity_require']}
                    <if syntax="VIP_NUMBER >= 2">
                    {$informations['masterResetTable']['dexterity_require']}
                    </if>
                    <if syntax="VIP_NUMBER >= 3">
                    {$informations['masterResetTable']['dexterity_require']}
                    </if>
                    <if syntax="VIP_NUMBER >= 4">
                    {$informations['masterResetTable']['dexterity_require']}
                    </if>
                    <if syntax="VIP_NUMBER == 5">
                    {$informations['masterResetTable']['dexterity_require']}
                    </if>

                    {$this->lang->words['Infos']['MResetTable']['VitalityRequire']}
                    {$informations['masterResetTable']['vitality_require']}
                    {$informations['masterResetTable']['vitality_require']}
                    <if syntax="VIP_NUMBER >= 2">
                    {$informations['masterResetTable']['vitality_require']}
                    </if>
                    <if syntax="VIP_NUMBER >= 3">
                    {$informations['masterResetTable']['vitality_require']}
                    </if>
                    <if syntax="VIP_NUMBER >= 4">
                    {$informations['masterResetTable']['vitality_require']}
                    </if>
                    <if syntax="VIP_NUMBER == 5">
                    {$informations['masterResetTable']['vitality_require']}
                    </if>

                    {$this->lang->words['Infos']['MResetTable']['EnergyRequire']}
                    {$informations['masterResetTable']['energy_require']}
                    {$informations['masterResetTable']['energy_require']}
                    <if syntax="VIP_NUMBER >= 2">
                    {$informations['masterResetTable']['energy_require']}
                    </if>
                    <if syntax="VIP_NUMBER >= 3">
                    {$informations['masterResetTable']['energy_require']}
                    </if>
                    <if syntax="VIP_NUMBER >= 4">
                    {$informations['masterResetTable']['energy_require']}
                    </if>
                    <if syntax="VIP_NUMBER == 5">
                    {$informations['masterResetTable']['energy_require']}
                    </if>

                <if syntax="MUSERVER_VERSION >= 1">

                    {$this->lang->words['Infos']['MResetTable']['CommandRequire']}
                    {$informations['masterResetTable']['command_require']}
                    {$informations['masterResetTable']['command_require']}
                    <if syntax="VIP_NUMBER >= 2">
                    {$informations['masterResetTable']['command_require']}
                    </if>
                    <if syntax="VIP_NUMBER >= 3">
                    {$informations['masterResetTable']['command_require']}
                    </if>
                    <if syntax="VIP_NUMBER >= 4">
                    {$informations['masterResetTable']['command_require']}
                    </if>
                    <if syntax="VIP_NUMBER == 5">
                    {$informations['masterResetTable']['command_require']}
                    </if>

                </if>

                    {$this->lang->words['Infos']['MResetTable']['MoneyReset']}
                    {$informations['masterResetTable']['money_require'][0]}
                    {$informations['masterResetTable']['money_require'][1]}
                    <if syntax="VIP_NUMBER >= 2">
                    {$informations['masterResetTable']['money_require'][2]}
                    </if>
                    <if syntax="VIP_NUMBER >= 3">
                    {$informations['masterResetTable']['money_require'][3]}
                    </if>
                    <if syntax="VIP_NUMBER >= 4">
                    {$informations['masterResetTable']['money_require'][4]}
                    </if>
                    <if syntax="VIP_NUMBER == 5">
                    {$informations['masterResetTable']['money_require'][5]}
                    </if>

                <if syntax="$this->settings['USERPANEL']['CHARACTER']['MASTER_RESET'][0xFF]['MODE'] == 1">

                    {$this->lang->words['Infos']['MResetTable']['ResetsRemove']}
                    {$informations['masterResetTable']['resets_remove'][0]}
                    {$informations['masterResetTable']['resets_remove'][1]}
                    <if syntax="VIP_NUMBER >= 2">
                    {$informations['masterResetTable']['resets_remove'][2]}
                    </if>
                    <if syntax="VIP_NUMBER >= 3">
                    {$informations['masterResetTable']['resets_remove'][3]}
                    </if>
                    <if syntax="VIP_NUMBER >= 4">
                    {$informations['masterResetTable']['resets_remove'][4]}
                    </if>
                    <if syntax="VIP_NUMBER == 5">
                    {$informations['masterResetTable']['resets_remove'][5]}
                    </if>

                </if>

                    {$this->lang->words['Infos']['MResetTable']['ResetPoints']}
                    {$informations['masterResetTable']['reset_points'][0]}
                    {$informations['masterResetTable']['reset_points'][1]}
                    <if syntax="VIP_NUMBER >= 2">
                    {$informations['masterResetTable']['reset_points'][2]}
                    </if>
                    <if syntax="VIP_NUMBER >= 3">
                    {$informations['masterResetTable']['reset_points'][3]}
                    </if>
                    <if syntax="VIP_NUMBER >= 4">
                    {$informations['masterResetTable']['reset_points'][4]}
                    </if>
                    <if syntax="VIP_NUMBER == 5">
                    {$informations['masterResetTable']['reset_points'][5]}
                    </if>

                    {$this->lang->words['Infos']['MResetTable']['ClearInvent']}
                    {$informations['masterResetTable']['clear_invent'][0]}
                    {$informations['masterResetTable']['clear_invent'][1]}
                    <if syntax="VIP_NUMBER >= 2">
                    {$informations['masterResetTable']['clear_invent'][2]}
                    </if>
                    <if syntax="VIP_NUMBER >= 3">
                    {$informations['masterResetTable']['clear_invent'][3]}
                    </if>
                    <if syntax="VIP_NUMBER >= 4">
                    {$informations['masterResetTable']['clear_invent'][4]}
                    </if>
                    <if syntax="VIP_NUMBER == 5">
                    {$informations['masterResetTable']['clear_invent'][5]}
                    </if>

                    {$this->lang->words['Infos']['MResetTable']['ClearSkill']}
                    {$informations['masterResetTable']['clear_skill'][0]}
                    {$informations['masterResetTable']['clear_skill'][1]}
                    <if syntax="VIP_NUMBER >= 2">
                    {$informations['masterResetTable']['clear_skill'][2]}
                    </if>
                    <if syntax="VIP_NUMBER >= 3">
                    {$informations['masterResetTable']['clear_skill'][3]}
                    </if>
                    <if syntax="VIP_NUMBER >= 4">
                    {$informations['masterResetTable']['clear_skill'][4]}
                    </if>
                    <if syntax="VIP_NUMBER == 5">
                    {$informations['masterResetTable']['clear_skill'][5]}
                    </if>

                    {$this->lang->words['Infos']['MResetTable']['ClearQuest']}
                    {$informations['masterResetTable']['clear_quest'][0]}
                    {$informations['masterResetTable']['clear_quest'][1]}
                    <if syntax="VIP_NUMBER >= 2">
                    {$informations['masterResetTable']['clear_quest'][2]}
                    </if>
                    <if syntax="VIP_NUMBER >= 3">
                    {$informations['masterResetTable']['clear_quest'][3]}
                    </if>
                    <if syntax="VIP_NUMBER >= 4">
                    {$informations['masterResetTable']['clear_quest'][4]}
                    </if>
                    <if syntax="VIP_NUMBER == 5">
                    {$informations['masterResetTable']['clear_quest'][5]}
                    </if>

                    {$this->lang->words['Infos']['MResetTable']['CoinAward']}
                    {$informations['masterResetTable']['coin_award'][0]}
                    {$informations['masterResetTable']['coin_award'][1]}
                    <if syntax="VIP_NUMBER >= 2">
                    {$informations['masterResetTable']['coin_award'][2]}
                    </if>
                    <if syntax="VIP_NUMBER >= 3">
                    {$informations['masterResetTable']['coin_award'][3]}
                    </if>
                    <if syntax="VIP_NUMBER >= 4">
                    {$informations['masterResetTable']['coin_award'][4]}
                    </if>
                    <if syntax="VIP_NUMBER == 5">
                    {$informations['masterResetTable']['coin_award'][5]}
                    </if>


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:id="@+id/rl_date_picker_item"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="@dimen/date_card_width"
    android:layout_height="match_parent"
    android:background="@android:color/black"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_date_picker_day"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textColor="@color/date_item_day"
        android:textSize="25sp"
        tools:text="12"/>

    <TextView
        android:id="@+id/tv_date_picker_day_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@id/tv_date_picker_day"
        android:layout_centerHorizontal="true"
        android:textColor="@color/date_item_day_name"
        tools:text="Monday"/>

    <TextView
        android:id="@+id/tv_date_picker_month_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv_date_picker_day"
        android:layout_centerHorizontal="true"
        android:textColor="@color/date_item_month_name"
        tools:text="January"/>

    <View
        android:id="@+id/view_date_indicator"
        android:layout_width="wrap_content"
        android:layout_height="1dp"
        android:layout_alignParentBottom="true"
        android:background="@color/date_item_unselected_indicator"/>

</RelativeLayout>


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingTop="0dp"
    android:paddingBottom="0dp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp" >

    <!-- Name Label -->

    <TextView
        android:id="@+id/player_name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="0dip"
        android:paddingTop="5dip"
        android:textColor="#acacac"
        android:textSize="20sp"
        android:textStyle="bold" />

</LinearLayout>


text:
package com.drop.spper.mvp.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.drop.spper.R;
import com.drop.spper.di.component.DaggerForgetPasswordComponent;
import com.drop.spper.di.module.ForgetPasswordModule;
import com.drop.spper.mvp.contract.ForgetPasswordContract;
import com.drop.spper.mvp.presenter.ForgetPasswordPresenter;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.UiUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;

public class ForgetPasswordActivity extends BaseActivity<ForgetPasswordPresenter> implements ForgetPasswordContract.View {

    @BindView(R.id.toolbar_back_tv)
    TextView toolbarBackTv;
    @BindView(R.id.toolbar_back)
    LinearLayout toolbarBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.my)
    TextView my;
    @BindView(R.id.phone)
    EditText phone;
    @BindView(R.id.Pi)
    EditText Pi;
    @BindView(R.id.password)
    EditText password;
    @BindView(R.id.Cpassword)
    EditText Cpassword;

    @Override
    public void setupActivityComponent(AppComponent appComponent) {
        DaggerForgetPasswordComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .forgetPasswordModule(new ForgetPasswordModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(Bundle savedInstanceState) {
        return R.layout.activity_forget_password; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        toolbarBackTv.setText("返回");
        toolbarTitle.setText("忘记密码");
        my.setVisibility(View.INVISIBLE);
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        UiUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        UiUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @OnClick({R.id.toolbar_back, R.id.get, R.id.login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.toolbar_back:
                finish();
                break;
            case R.id.get:
                break;
            case R.id.login:
                break;
        }
    }
}


text:
LOGIN

{{message}}

  <button (click)="login()"  *ngIf="!authService.isLoggedIn">Login</button>
  <button (click)="logout()" *ngIf="authService.isLoggedIn">Logout</button>


text:
package com.linchaolong.apktoolplus.utils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class LogUtils {

	/** 日志级别 **/
	public static final int VERBOSE = 0;
	public static final int INFO = 1;
	public static final int DEBUG = 2;
	public static final int WARN= 3;
	public static final int ERROR = 4;

	/** 当前日志级别 **/
	private static int mLogLevel = VERBOSE;
	public static void setLogLevel(int logLevel){
		mLogLevel = logLevel;
	}
	public static int getLogLevel(){
		return mLogLevel;
	}

    // 得到日期时间的DateFormat对象
    private static DateFormat localDateFromat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	/**
	 * 获取当前堆栈元素
	 *
	 * @return
	 */
	private static StackTraceElement getCurrentStackTraceElement() {
        return Thread.currentThread().getStackTrace()[6]; // 0是调用的栈顶元素,也就是当前方法,索引0-5都是Debug里的方法,6是调用Logger的所在方法
	}

    /**
     * 日期Log
     *
     * @return
     */
    public static String getDateLog(){
        StringBuilder sBuff = new StringBuilder();
        StackTraceElement s = getCurrentStackTraceElement();
        sBuff.append(localDateFromat.format(new Date()))
                .append(format(s));
        return sBuff.toString();
    }

    public static String format(StackTraceElement s){
        //return String.format("%s.%s(%s:%s)%n", s.getClassName(), s.getMethodName(),s.getFileName(), s.getLineNumber());
        return String.format(".(%s:%s)",s.getFileName(), s.getLineNumber());
    }

	/**
	 * 格式化log
	 *
	 * @param logLevel		log级别
	 * @param log				log
	 * @return
	 */
	private static String format(int logLevel, String log) {

//		四月 08, 2016 10:35:04 下午 com.sun.javafx.css.StyleManager loadStylesheetUnPrivileged
//		INFO: Could not find stylesheet: jar:file:/C:/Users/Administrator/AppData/Local/Temp/e4jA5CD.tmp_dir1460126084/ApkToolPlus_release_1.0.6.jar!/css/jiagu.css

        StringBuilder sBuff = new StringBuilder();
        // 日志级别
        switch (logLevel){
            case VERBOSE:
                sBuff.append("VERBOSE");
            break;
            case INFO:
                sBuff.append("INFO");
                break;
            case DEBUG:
                sBuff.append("DEBUG");
                break;
            case WARN:
                sBuff.append("WARN");
                break;
            case ERROR:
                sBuff.append("ERROR");
                break;
        }
        sBuff.append(":");
        sBuff.append(getDateLog()).append(": ");
        // log
        if (log != null){
            sBuff.append(log);
        }else{
            sBuff.append("null");
        }
		return sBuff.toString();
	}

	/**
	 * 日志输出
	 *
	 * @param log
	 */
	private static void stdOutput(String log){
		System.out.println(log);
	}

	/**
	 * 输出错误日志(红色)
	 *
	 * @param log
	 */
	private static void errOutput(String log){
		System.err.println(log);
	}

	/**
	 * 格式化并输出
	 *
	 * @param logLevel		log级别
	 * @param log				log
	 */
	private static void formatOutput(int logLevel, String log) {
        if(logLevel < WARN){
            stdOutput(format(logLevel, log));
        }else{
            errOutput(format(logLevel, log));
        }
	}

	// 不同级别的日志输出函数
    public static void v(String msg){
        if (VERBOSE >= mLogLevel) {
            formatOutput(VERBOSE, msg);
        }
    }

    public static void i(String msg){
        if (INFO >= mLogLevel) {
            formatOutput(INFO, msg);
        }
    }

	public static void d(String msg){
		if (DEBUG >= mLogLevel) {
            formatOutput(DEBUG, msg);
		}
	}

    public static void w(String msg){
        if (WARN >= mLogLevel) {
            formatOutput(WARN, msg);
        }
    }

	public static void e(String msg){
		if (ERROR >= mLogLevel) {
            formatOutput(ERROR, msg);
		}
	}

    public static void d(Throwable e){
        if(DEBUG >= mLogLevel && e != null ){
            stdOutput(getDateLog());
            e.printStackTrace();
        }
    }

    public static void e(Throwable e){
        if(ERROR >= mLogLevel && e != null ){
            errOutput(getDateLog());
            e.printStackTrace();
        }
    }
}


text:
//----------------------------------------------------------------------------------
#ifndef SKILLGROUPMANAGER_H
#define SKILLGROUPMANAGER_H
//----------------------------------------------------------------------------------
//!Класс менеджера групп навыков
class CSkillGroupManager
{
    int Count = 0;

private:
    //!Выставление значение по-умолчанию для стандартных групп
    void MakeDefaultMiscellaneous();
    void MakeDefaultCombat();
    void MakeDefaultTradeSkills();
    void MakeDefaultMagic();
    void MakeDefaultWilderness();
    void MakeDefaultThieving();
    void MakeDefaultBard();

public:
    //!Указатель на список групп
    CSkillGroupObject *m_Groups{ NULL };

    CSkillGroupManager();
    ~CSkillGroupManager();

    /*!
	Выставить группы по-умолчанию
	@return
	*/
    void MakeDefault();

    /*!
	Очистить список групп
	@return
	*/
    void Clear();

    /*!
	Добавить группу
	@param [__in] group Ссылка на группу
	@return
	*/
    void Add(CSkillGroupObject *group);

    /*!
	Удалить группу
	@param [__in] group Ссылка на группу
	@return
	*/
    bool Remove(CSkillGroupObject *group);

    /*!
	Загрузка групп из файла конфига
	@param [__in] path Путь к файлу конфига
	@return
	*/
    bool Load(const os_path &path);

    /*!
	Сохранение групп в файл конфиг
	@param [__in] path Путьк  файлу конфига
	@return
	*/
    void Save(const os_path &path);
};
//----------------------------------------------------------------------------------
//!Менеджер групп навыков
extern CSkillGroupManager g_SkillGroupManager;
//----------------------------------------------------------------------------------
#endif
//----------------------------------------------------------------------------------


text:
/**
 * buildsys/data/pages
 * Build property data for each page.
 * @author Keenan Staffieri
 */

export default [
{
  ref: 'index',
  name: 'Index',
  dirPath: '',
  scssPath: 'index',
  scriptPath: 'index',
},
// PAGE AUTOMATION !! DON'T TOUCH
]


text:
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * The simplest PHPUnit test case customised for Moodle
 *
 * It is intended for isolated tests that do not modify database or any globals.
 *
 * @package    core
 * @category   phpunit
 * @copyright  2012 Petr Skoda {@link http://skodak.org}
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
abstract class basic_testcase extends base_testcase {

    /**
     * Constructs a test case with the given name.
     *
     * Note: use setUp() or setUpBeforeClass() in your test cases.
     *
     * @param string $name
     * @param array  $data
     * @param string $dataName
     */
    final public function __construct($name = null, array $data = array(), $dataName = '') {
        parent::__construct($name, $data, $dataName);

        $this->setBackupGlobals(false);
        $this->setBackupStaticAttributes(false);
        $this->setRunTestInSeparateProcess(false);
    }

    /**
     * Runs the bare test sequence and log any changes in global state or database.
     * @return void
     */
    final public function runBare() {
        global $DB;

        try {
            parent::runBare();

        } catch (Exception $ex) {
            $e = $ex;
        } catch (Throwable $ex) {
            // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
            $e = $ex;
        }

        if (isset($e)) {
            // cleanup after failed expectation
            phpunit_util::reset_all_data();
            throw $e;
        }

        if ($DB->is_transaction_started()) {
            phpunit_util::reset_all_data();
            throw new coding_exception('basic_testcase '.$this->getName().' is not supposed to use database transactions!');
        }

        phpunit_util::reset_all_data(true);
    }
}


text:
Integrates the [tslint](https://github.com/palantir/tslint) linter for the TypeScript language into VS Code.

Please refer to the tslint [documentation](https://github.com/palantir/tslint) for how to configure the linting rules.

# Prerequisites
The extension requires that tslint is installed either locally or globally.

>Tip: if you get the error that "failed to load tslint", but you have tslint installed locally,
then try to install tslint and its typescript dependency globally using `npm install -g tslint typescript`.

The recommended version of tslint is 3.2.1.

# Configuration options

- `tslint.enable` - enable/disable tslint.
- `tslint.rulesDirectory` - an additional rules directory, for user-created rules.
- `tslint.configFile` - the configuration file that tslint should use instead of the default `tslint.json`.
- `tslint.ignoreDefinitionFiles` - control if TypeScript definition files should be ignored.
- `tslint.exclude` - configure glob patterns of file paths to exclude from linting.
- `tslint.validateWithDefaultConfig` - validate a file for which there was no custom tslint confguration found. The default is `false`.

# Quick fixes

The extension supports some quick fixing of warnings. For warnings which support a quick fix a light bulp is shown when the cursor is positioned inside the warning's range. You can apply the quick fix by either clicking the light bulp or by executing the `Quick Fix` command. The following quick fixes are currently supported:
- missing whitespace
- missing semicolon
- missing trailing comma
- ' should be "
- " sould be '
- trailing whitespace
- file should end with a newline
- forbidden 'var' keyword

# Release Notes
## 0.5.33
- Only prompt for installing tslint, when the workspace root includes a `tslint.json` file.

## 0.5.32
- Clear errors when document is closed.

## 0.5.30
- More quick fixes.

## 0.5.25
- Add support for quick fixing some warnings.

## 0.5.23
- Updated to version 2.0 of the vscode language protocol.

## 0.5.21
- Added the setting `tslint.validateWithDefaultConfig`.

# Release Notes
## 0.5.17
- Added setting `tslint.validateWithDefaultConfig`.
- Added setting `tslint.ignoreDefinitionFiles`.

## 0.5.15
- Watch for changes in the tslint.json when the file is located outside of the workspace.

## 0.5.13
- Handle the case where a user edits a `tslint.json` configuration file and it is in an intermediate inconsistent state gracefully.

## 0.5.8
- protect against exceptions thrown by tslint.

## 0.5.5
- `tslint.json` is now validated using a JSON schema.
- Diagnostic messages produced by tslint are now tagged with `tslint`.

## 0.5.4
- Added the `tslint.configFile` option.


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center">
    <ImageView
            android:id="@+id/mImageNoData"
            android:layout_width="120dp"
            android:layout_height="120dp"
            android:src="@mipmap/no_data"
            />

    <TextView
            android:id="@+id/mTextNoData"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="6dp"
            android:gravity="center"
            android:textColor="@color/gray_80"
            android:text="@string/error_text"
            android:textSize="15sp"
            />
</LinearLayout>


text:
The keys.txt contains the public keys of Gitian builders and active developers.

The keys are mainly used to sign git commits or the build results of Gitian
builds.

The most recent version of each pgp key can be found on most pgp key servers.

Fetch the latest version from the key server to see if any key was revoked in
the meantime.
To fetch the latest version of all pgp keys in your gpg homedir,

```sh
gpg --refresh-keys
```

To fetch keys of Gitian builders and active developers, feed the list of
fingerprints of the primary keys into gpg:

```sh
while read fingerprint keyholder_name; do gpg --keyserver hkp://pool.sks-keyservers.net --recv-keys ${fingerprint}; done < ./keys.txt
```


text:
package ua.com.fielden.platform.web.centre.api.crit;

import ua.com.fielden.platform.entity.AbstractEntity;
import ua.com.fielden.platform.web.centre.api.crit.defaults.IMultiBooleanDefaultValueAssigner;
import ua.com.fielden.platform.web.centre.api.crit.defaults.IMultiStringDefaultValueAssigner;

/**
 * A contract for selecting multi-valued criteria.
 *
 * @author TG Team
 *
 * @param <T>
 */
public interface IMultiValueCritSelector<T extends AbstractEntity<?>> {

    /**
     * Specifies the need to add a multi-valued autocompleter as a selection criterion, which supports wile card values.
     *
     * @return
     */
    <V extends AbstractEntity<?>> IMutliValueAutocompleterBuilder<T, V> autocompleter(final Class<V> type);

    /**
     * Specified the need to add a multi-valued text-based selection criterion, which support wild card values.
     * It is applicable for many different property types, including phone, colour (expressed in hex codes), email and of course short or long strings.
     *
     * @return
     */
    IMultiStringDefaultValueAssigner<T> text();

    /**
     * Specifies the need to add a multi-valued boolean selection criterion.
     * For boolean criterion this is the most ordinary case, supporting alternation between false/true, neither or both.
     *
     * @return
     */
    IMultiBooleanDefaultValueAssigner<T> bool();
}


text:
/*
 * Copyright (C) 2000,
 *
 * Arjuna Solutions Limited,
 * Newcastle upon Tyne,
 * Tyne and Wear,
 * UK.
 *
 * $Id: ContextORBInitializerImpl.java 2342 2006-03-30 13:06:17Z  $
 */

package com.arjuna.ats.jts.orbspecific.ibmorb.interceptors.context;

import org.omg.CORBA.LocalObject;
import org.omg.IOP.Codec;
import org.omg.IOP.ENCODING_CDR_ENCAPS;
import org.omg.IOP.Encoding;
import org.omg.IOP.CodecFactoryPackage.UnknownEncoding;
import org.omg.PortableInterceptor.ClientRequestInterceptor;
import org.omg.PortableInterceptor.ORBInitInfo;
import org.omg.PortableInterceptor.ORBInitializer;
import org.omg.PortableInterceptor.ServerRequestInterceptor;
import org.omg.PortableInterceptor.ORBInitInfoPackage.DuplicateName;

import com.arjuna.ats.arjuna.exceptions.FatalError;
import com.arjuna.ats.internal.arjuna.thread.ThreadActionData;
import com.arjuna.ats.jts.OTSManager;
import com.arjuna.ats.jts.logging.jtsLogger;

public class ContextORBInitializerImpl extends LocalObject implements ORBInitializer
{

    public ContextORBInitializerImpl ()
    {
	if (jtsLogger.logger.isTraceEnabled())
	{
	    jtsLogger.logger.trace("ContextORBInitializerImpl ()");
	}

	/*
	 * Register the thread-setup object so that ArjunaCore can be
	 * used raw.
	 */

	ThreadActionData.addSetup(new ContextThreadSetup());
    }

    public void pre_init (ORBInitInfo init_info)
    {
	if (jtsLogger.logger.isTraceEnabled())
	{
	    jtsLogger.logger.trace("ContextORBInitializer.pre_init ()");
	}

	/*
	 * These value should be part of the standard.
	 */

	int localSlot = init_info.allocate_slot_id();
	int receivedSlot = init_info.allocate_slot_id();

	OTSManager.setLocalSlotId(localSlot);
	OTSManager.setReceivedSlotId(receivedSlot);

	/*
	 * Get the CDR codec; used for encoding/decoding the service
	 * context and IOR components.
	 */

	Codec cdr_codec = null;

	try
	{
	    if (jtsLogger.logger.isTraceEnabled())
	    {
		jtsLogger.logger.trace("ContextORBInitializerImpl - getting reference to ENCODING_CDR_ENCAPS codec");
	    }

	    Encoding cdr_encoding = new Encoding(ENCODING_CDR_ENCAPS.value, (byte)1, (byte)2);

	    cdr_codec = init_info.codec_factory().create_codec(cdr_encoding);
	}
	catch (UnknownEncoding ex)
	{
        jtsLogger.i18NLogger.warn_orbspecific_javaidl_interceptors_context_codecerror(
                "ContextORBInitializerImpl", "ENCODING_CDR_ENCAPS", ex);

	    throw new FatalError(jtsLogger.i18NLogger.get_orbspecific_javaidl_interceptors_context_codeccreate(), ex);
	}

	/*
	 * Register client interceptor to propogate the context.
	 */

	try
	{
	    if (jtsLogger.logger.isTraceEnabled())
	    {
		jtsLogger.logger.trace("ContextORBInitializerImpl - registering ClientRequestInterceptor");
	    }

	    ClientRequestInterceptor client_interceptor = new ContextClientRequestInterceptorImpl(localSlot, cdr_codec);

	    init_info.add_client_request_interceptor(client_interceptor);
	}
	catch (DuplicateName ex)
	{
        jtsLogger.i18NLogger.warn_orbspecific_javaidl_interceptors_context_duplicatename(
                "ContextORBInitializerImpl", "ClientRequestInterceptor", ex);

	    throw new FatalError(jtsLogger.i18NLogger.get_orbspecific_javaidl_interceptors_context_cie(), ex);
	}

	/*
	 * Register a server interceptor to receive the context.
	 */

	try
	{
	    if (jtsLogger.logger.isTraceEnabled())
	    {
		jtsLogger.logger.trace("ContextORBInitializerImpl - registering ServerRequestInterceptor");
	    }

	    ServerRequestInterceptor server_interceptor = new ContextServerRequestInterceptorImpl(receivedSlot, cdr_codec);

	    init_info.add_server_request_interceptor(server_interceptor);
	}
	catch (DuplicateName ex)
	{
        jtsLogger.i18NLogger.warn_orbspecific_javaidl_interceptors_context_duplicatename(
                 "ContextORBInitializerImpl", "ServerRequestInterceptor", ex);

	    throw new FatalError(jtsLogger.i18NLogger.get_orbspecific_javaidl_interceptors_context_sie(), ex);
	}
    }

    public void post_init (ORBInitInfo init_info)
    {
	if (jtsLogger.logger.isTraceEnabled())
	{
	    jtsLogger.logger.trace("ContextORBInitializerImpl.post_init ()");
	}

	// nothing to do
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="14dp"
    android:paddingBottom="12dp"
    >

</RelativeLayout>


text:
using Microsoft.Phone.Controls;

namespace YesEquality.Views
{
    public partial class MainView : PhoneApplicationPage
    {
        public MainView()
        {
            InitializeComponent();
        }
    }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Enumeration of the lichens found in New Bedford, Mass. , and its vicinity from 1862 to 1892 38 (1892)

#### Original name
Pyrenula staurospora Tuck. ex Willey

### Remarks
null


text:
from oslo_serialization import jsonutils
from oslo_utils.fixture import uuidsentinel as uuids
from oslo_versionedobjects import base as ovo_base

from nova import exception
from nova.network import model as network_model
from nova import objects
from nova.objects import migrate_data
from nova import test
from nova.tests.unit.objects import test_objects

class _TestLiveMigrateData(object):
    def test_obj_make_compatible(self):
        props = {
            'serial_listen_addr': '127.0.0.1',
            'serial_listen_ports': [1000, 10001, 10002, 10003],
            'wait_for_vif_plugged': True
        }

        obj = migrate_data.LibvirtLiveMigrateData(**props)
        primitive = obj.obj_to_primitive()
        self.assertIn('serial_listen_ports', primitive['nova_object.data'])
        self.assertIn('wait_for_vif_plugged', primitive['nova_object.data'])
        obj.obj_make_compatible(primitive['nova_object.data'], '1.5')
        self.assertNotIn('wait_for_vif_plugged', primitive['nova_object.data'])
        obj.obj_make_compatible(primitive['nova_object.data'], '1.1')
        self.assertNotIn('serial_listen_ports', primitive['nova_object.data'])

class TestLiveMigrateData(test_objects._LocalTest,
                          _TestLiveMigrateData):
    pass

class TestRemoteLiveMigrateData(test_objects._RemoteTest,
                                _TestLiveMigrateData):
    pass

class _TestLibvirtLiveMigrateData(object):
    def test_bdm_to_disk_info(self):
        obj = migrate_data.LibvirtLiveMigrateBDMInfo(
            serial='foo', bus='scsi', dev='sda', type='disk')
        expected_info = {
            'dev': 'sda',
            'bus': 'scsi',
            'type': 'disk',
        }
        self.assertEqual(expected_info, obj.as_disk_info())
        obj.format = 'raw'
        obj.boot_index = 1
        expected_info['format'] = 'raw'
        expected_info['boot_index'] = '1'
        self.assertEqual(expected_info, obj.as_disk_info())

    def test_numa_migrate_data(self):
        data = lambda x: x['nova_object.data']
        obj = migrate_data.LibvirtLiveMigrateNUMAInfo(
            cpu_pins={'0': set([1])},
            cell_pins={'2': set([3])},
            emulator_pins=set([4]),
            sched_vcpus=set([5]),
            sched_priority=6)
        manifest = ovo_base.obj_tree_get_versions(obj.obj_name())
        primitive = data(obj.obj_to_primitive(target_version='1.0',
                                              version_manifest=manifest))
        self.assertEqual({'0': (1,)}, primitive['cpu_pins'])
        self.assertEqual({'2': (3,)}, primitive['cell_pins'])
        self.assertEqual((4,), primitive['emulator_pins'])
        self.assertEqual((5,), primitive['sched_vcpus'])
        self.assertEqual(6, primitive['sched_priority'])

    def test_obj_make_compatible(self):
        obj = migrate_data.LibvirtLiveMigrateData(
            src_supports_native_luks=True,
            old_vol_attachment_ids={uuids.volume: uuids.attachment},
            supported_perf_events=[],
            serial_listen_addr='127.0.0.1',
            target_connect_addr='127.0.0.1',
            dst_wants_file_backed_memory=False,
            file_backed_memory_discard=False,
            src_supports_numa_live_migration=True,
            dst_supports_numa_live_migration=True,
            dst_numa_info=migrate_data.LibvirtLiveMigrateNUMAInfo())
        manifest = ovo_base.obj_tree_get_versions(obj.obj_name())

        data = lambda x: x['nova_object.data']

        primitive = data(obj.obj_to_primitive())
        self.assertIn('file_backed_memory_discard', primitive)
        primitive = data(obj.obj_to_primitive(target_version='1.0',
                                              version_manifest=manifest))
        self.assertNotIn('target_connect_addr', primitive)
        self.assertNotIn('supported_perf_events', primitive)
        self.assertNotIn('old_vol_attachment_ids', primitive)
        self.assertNotIn('src_supports_native_luks', primitive)
        self.assertNotIn('dst_wants_file_backed_memory', primitive)
        primitive = data(obj.obj_to_primitive(target_version='1.1',
                                              version_manifest=manifest))
        self.assertNotIn('serial_listen_ports', primitive)
        primitive = data(obj.obj_to_primitive(target_version='1.2',
                                              version_manifest=manifest))
        self.assertNotIn('supported_perf_events', primitive)
        primitive = data(obj.obj_to_primitive(target_version='1.3',
                                              version_manifest=manifest))
        self.assertNotIn('old_vol_attachment_ids', primitive)
        primitive = data(obj.obj_to_primitive(target_version='1.4',
                                              version_manifest=manifest))
        self.assertNotIn('src_supports_native_luks', primitive)
        primitive = data(obj.obj_to_primitive(target_version='1.6',
                                              version_manifest=manifest))
        self.assertNotIn('dst_wants_file_backed_memory', primitive)
        primitive = data(obj.obj_to_primitive(target_version='1.7',
                                              version_manifest=manifest))
        self.assertNotIn('file_backed_memory_discard', primitive)
        primitive = data(obj.obj_to_primitive(target_version='1.9',
                                              version_manifest=manifest))
        self.assertNotIn('dst_numa_info', primitive)
        self.assertNotIn('src_supports_numa_live_migration', primitive)
        self.assertNotIn('dst_supports_numa_live_migration', primitive)

    def test_bdm_obj_make_compatible(self):
        obj = migrate_data.LibvirtLiveMigrateBDMInfo(
            encryption_secret_uuid=uuids.encryption_secret_uuid)
        primitive = obj.obj_to_primitive(target_version='1.0')
        self.assertNotIn(
            'encryption_secret_uuid', primitive['nova_object.data'])

        primitive = obj.obj_to_primitive(target_version='1.1')
        self.assertIn(
            'encryption_secret_uuid', primitive['nova_object.data'])

    def test_vif_migrate_data(self):
        source_vif = network_model.VIF(
            id=uuids.port_id,
            network=network_model.Network(id=uuids.network_id),
            type=network_model.VIF_TYPE_OVS,
            vnic_type=network_model.VNIC_TYPE_NORMAL,
            active=True,
            profile={'migrating_to': 'dest-host'})
        vif_details_dict = {'port_filter': True}
        profile_dict = {'trusted': False}
        vif_data = objects.VIFMigrateData(
            port_id=uuids.port_id,
            vnic_type=network_model.VNIC_TYPE_NORMAL,
            vif_type=network_model.VIF_TYPE_BRIDGE,
            vif_details=vif_details_dict, profile=profile_dict,
            host='dest-host', source_vif=source_vif)
        # Make sure the vif_details and profile fields are converted and
        # stored properly.
        self.assertEqual(
            jsonutils.dumps(vif_details_dict), vif_data.vif_details_json)
        self.assertEqual(
            jsonutils.dumps(profile_dict), vif_data.profile_json)
        self.assertDictEqual(vif_details_dict, vif_data.vif_details)
        self.assertDictEqual(profile_dict, vif_data.profile)
        obj = migrate_data.LibvirtLiveMigrateData(
            file_backed_memory_discard=False)
        obj.vifs = [vif_data]
        manifest = ovo_base.obj_tree_get_versions(obj.obj_name())
        primitive = obj.obj_to_primitive(target_version='1.8',
                                         version_manifest=manifest)
        self.assertIn(
            'file_backed_memory_discard', primitive['nova_object.data'])
        self.assertNotIn('vifs', primitive['nova_object.data'])

class TestLibvirtLiveMigrateData(test_objects._LocalTest,
                                 _TestLibvirtLiveMigrateData):
    pass

class TestRemoteLibvirtLiveMigrateData(test_objects._RemoteTest,
                                       _TestLibvirtLiveMigrateData):
    pass

class _TestHyperVLiveMigrateData(object):
    def test_obj_make_compatible(self):
        obj = migrate_data.HyperVLiveMigrateData(
            is_shared_instance_path=True,
            old_vol_attachment_ids={'yes': 'no'},
            wait_for_vif_plugged=True)

        data = lambda x: x['nova_object.data']

        primitive = data(obj.obj_to_primitive())
        self.assertIn('is_shared_instance_path', primitive)
        primitive = data(obj.obj_to_primitive(target_version='1.0'))
        self.assertNotIn('is_shared_instance_path', primitive)
        primitive = data(obj.obj_to_primitive(target_version='1.1'))
        self.assertNotIn('old_vol_attachment_ids', primitive)
        primitive = data(obj.obj_to_primitive(target_version='1.2'))
        self.assertNotIn('wait_for_vif_plugged', primitive)

class TestHyperVLiveMigrateData(test_objects._LocalTest,
                                _TestHyperVLiveMigrateData):
    pass

class TestRemoteHyperVLiveMigrateData(test_objects._RemoteTest,
                                      _TestHyperVLiveMigrateData):
    pass

class TestVIFMigrateData(test.NoDBTestCase):

    def test_get_dest_vif_source_vif_not_set(self):
        migrate_vif = objects.VIFMigrateData(
            port_id=uuids.port_id, vnic_type=network_model.VNIC_TYPE_NORMAL,
            vif_type=network_model.VIF_TYPE_OVS, vif_details={},
            profile={}, host='fake-dest-host')
        self.assertRaises(
            exception.ObjectActionError, migrate_vif.get_dest_vif)

    def test_get_dest_vif(self):
        source_vif = network_model.VIF(
            id=uuids.port_id, type=network_model.VIF_TYPE_OVS, details={},
            vnic_type=network_model.VNIC_TYPE_DIRECT, profile={'foo': 'bar'},
            ovs_interfaceid=uuids.ovs_interfaceid)
        migrate_vif = objects.VIFMigrateData(
            port_id=uuids.port_id, vnic_type=network_model.VNIC_TYPE_NORMAL,
            vif_type=network_model.VIF_TYPE_BRIDGE, vif_details={'bar': 'baz'},
            profile={}, host='fake-dest-host', source_vif=source_vif)
        dest_vif = migrate_vif.get_dest_vif()
        self.assertEqual(migrate_vif.port_id, dest_vif['id'])
        self.assertEqual(migrate_vif.vnic_type, dest_vif['vnic_type'])
        self.assertEqual(migrate_vif.vif_type, dest_vif['type'])
        self.assertEqual(migrate_vif.vif_details, dest_vif['details'])
        self.assertEqual(migrate_vif.profile, dest_vif['profile'])
        self.assertEqual(uuids.ovs_interfaceid, dest_vif['ovs_interfaceid'])

    def test_create_skeleton_migrate_vifs(self):
        vifs = [
            network_model.VIF(id=uuids.port1),
            network_model.VIF(id=uuids.port2)]
        mig_vifs = migrate_data.VIFMigrateData.create_skeleton_migrate_vifs(
            vifs)
        self.assertEqual(len(vifs), len(mig_vifs))
        self.assertEqual([vif['id'] for vif in vifs],
                         [mig_vif.port_id for mig_vif in mig_vifs])

    def test_supports_os_vif_delegation(self):
        # first try setting on a object without 'profile' defined
        migrate_vif = objects.VIFMigrateData(
            port_id=uuids.port_id, vnic_type=network_model.VNIC_TYPE_NORMAL,
            vif_type=network_model.VIF_TYPE_OVS, vif_details={},
            host='fake-dest-host')
        migrate_vif.supports_os_vif_delegation = True
        self.assertTrue(migrate_vif.supports_os_vif_delegation)
        self.assertEqual(migrate_vif.profile, {'os_vif_delegation': True})

        # now do the same but with profile defined
        migrate_vif = objects.VIFMigrateData(
            port_id=uuids.port_id, vnic_type=network_model.VNIC_TYPE_NORMAL,
            vif_type=network_model.VIF_TYPE_OVS, vif_details={},
            host='fake-dest-host', profile={'interface_name': 'eth0'})
        migrate_vif.supports_os_vif_delegation = True
        self.assertTrue(migrate_vif.supports_os_vif_delegation)
        self.assertEqual(
            migrate_vif.profile,
            {'os_vif_delegation': True, 'interface_name': 'eth0'})