text:
import {
  targetStore,
  transformValueOut,
  PropMetadata,
  PoClassPropertyMap,
  PropertyContainer,
  DeserializeMapper,
  SerializeMapper,
  MapperFactory,
  PlainObjectMapper
} from '@tdm/core/tdm';

import { TopLevel, ResourceObject, ResourceIdentifierObject } from './json-api';
import * as japiUtils from './json-api-utils';

/**
 * A mapper that has no mapping effect.
 * Maps every property on the source to the same property on the target.
 *
 */
export class JSONAPIDeserializeMapper extends DeserializeMapper {
  setRef(value: any): void {
    if (this.current) {
      this.existing.set(this.uuid(this.current.type, this.current.id), value);
    }
  }

  readonly isCollection: boolean;

  protected idx: number = -1;
  protected current: ResourceObject;
  protected keys: { att: string[]; rel: string[] };
  protected existing: Map<string, any>;

  private get ref(): any | undefined {
    if (this.current) {
      return this.existing.get(this.uuid(this.current.type, this.current.id));
    }
  }

  constructor(
    public source: TopLevel,
    sourceType: any,
    plainMapper?: PlainObjectMapper
  ) {
    super(source, sourceType, plainMapper);

    if (!(this instanceof JSONAPIChildDeserializeMapper)) {
      this.existing = new Map<string, any>();
    }

    this.isCollection = Array.isArray(source.data);
    if (!this.isCollection) {
      this.current = this.source.data as any;
      this.keys = japiUtils.getResourceKeys(this.current);
    }
  }

  getIdentity(): string {
    return this.current.id;
  }

  next(): boolean {
    if (this.isCollection) {
      this.current = this.source.data[++this.idx];
      if (this.current) {
        this.keys = japiUtils.getResourceKeys(this.current);
        return true;
      }
    }
    return false;
  }

  getKeys(): string[] {
    return this.keys.att.concat(this.keys.rel);
  }

  getValue(key: string, prop?: PropMetadata): any | undefined {
    if (this.keys.att.indexOf(key) > -1) {
      return this.getAttrValue(key, prop);
    } else if (this.keys.rel.indexOf(key) > -1) {
      return this.getRelatedValue(key, prop);
    }
  }

  protected uuid(type: string, id: string): string {
    return `${type}-${id}`;
  }

  protected getAttrValue(key: string, prop?: PropMetadata): any {
    return this.current.attributes[key];
  }

  protected getRelatedValue(key: string, prop?: PropMetadata): any | undefined {
    const relObject = this.current.relationships[key];

    if (relObject && relObject.data) {
      if (Array.isArray(relObject.data)) {
        return relObject.data.map(rel => this.getIncluded(rel, prop));
      } else {
        return this.getIncluded(relObject.data, prop);
      }
    }
  }

  protected getIncluded(
    rel: ResourceIdentifierObject,
    prop?: PropMetadata
  ): any {
    const uuid = this.uuid(rel.type, rel.id);

    if (this.existing.has(uuid)) {
      return this.existing.get(uuid);
    }

    const included =
      japiUtils.findIncluded(this.source.included, rel) || (rel as any);

    if (included) {
      const target: any =
        prop && targetStore.hasTarget(prop.type)
          ? prop.type
          : targetStore.findTarget(rel.type);

      const mapper = this.ref // event if no target we use ChildDes because the type can be found be "type" keys of child resources.
        ? new JSONAPIChildDeserializeMapper(
            {
              data: included,
              included: this.source.included
            },
            target,
            this.existing,
            this.plainMapper
          )
        : jsonAPIMapper.deserializer({ data: included }, target);

      // if target is none, a plain deserializer is used.
      return targetStore.deserialize(mapper);
    }
  }
}

export class JSONAPIChildDeserializeMapper extends JSONAPIDeserializeMapper {
  constructor(
    public source: TopLevel,
    sourceType: any,
    protected existing: Map<string, any>,
    plainMapper: PlainObjectMapper
  ) {
    super(source, sourceType, plainMapper);
  }
}

export class JSONAPISerializeMapper extends SerializeMapper {
  protected cache: Map<string, ResourceObject>;
  private doc: TopLevel;

  serialize(container: PropertyContainer): TopLevel {
    if (!this.cache) {
      this.cache = new Map<string, ResourceObject>();
    }

    if (Array.isArray(this.source)) {
      this.doc = { data: [] as any, included: [] };
      this.doc.data = this.serializeCollection(
        this.source,
        this.doc,
        container
      );
    } else {
      this.doc = { data: {} as any, included: [] };
      this.doc.data = this.serializeObject(this.source, this.doc, container);
    }

    if (!(this instanceof JSONAPIChildSerializeMapper) && this.cache.size > 0) {
      const includedArr = (this.doc.included = []);
      const data: any = this.doc.data;
      const canInclude = Array.isArray(data)
        ? item => data.indexOf(item) === -1
        : item => item !== this.doc.data;

      Array.from(this.cache.values()).forEach(toInclude => {
        if (!japiUtils.isIdentObject(toInclude) && canInclude(toInclude)) {
          includedArr.push(toInclude);
        }
      });
    }

    this.cleanDoc(this.doc, container);

    return this.doc;
  }

  private cleanDoc(doc: TopLevel, container: PropertyContainer): void {
    if (Array.isArray(doc.data)) {
      for (let i = 0, len = doc.data.length; i < len; i++) {
        this.cleanResourceObject(doc.data[i], container);
      }
    } else if (doc.data && Object.keys(doc.data).length === 0) {
      delete doc.data;
    } else {
      this.cleanResourceObject(doc.data, container);
    }

    if (doc.included && doc.included.length === 0) {
      delete doc.included;
    }
  }

  private cleanResourceObject(obj: ResourceObject, container): void {
    if (obj) {
      if (obj.attributes) {
        delete obj.attributes[
          targetStore.getIdentityKey(container.target, 'outgoing')
        ];
        if (Object.keys(obj.attributes).length === 0) {
          delete obj.attributes;
        }
      }

      if (obj.relationships && Object.keys(obj.relationships).length === 0) {
        delete obj.relationships;
      }
    }
  }

  private serializeObject(
    obj: any,
    doc: TopLevel,
    container: PropertyContainer
  ): ResourceObject | ResourceIdentifierObject {
    const id = obj[targetStore.getIdentityKey(container.target)];
    const type = targetStore.getTargetName(container.target);

    const uuid = this.uuid(type, id);

    if (this.cache.has(uuid)) {
      return this.cache.get(uuid);
    }

    const data: ResourceObject = {
      id,
      type,
      attributes: {},
      relationships: {}
    };

    this.cache.set(uuid, data);

    const cb = (pMap: PoClassPropertyMap) => {
      const p = pMap.prop;
      if (p && p.relation) {
        const type = p.type.ref;
        const name = targetStore.getTargetName(type as any);

        if (!type || !name) {
          // TODO: handle without error
          throw new Error(
            'Property Relation without type or name, try setting typeGetter in prop'
          );
        }

        const isArray =
          p.relation && p.type.isArray && Array.isArray(obj[pMap.cls]);
        const idKey = targetStore.getIdentityKey(type as any);
        const createRel = (id: string) => ({ id, type: name });

        if (isArray) {
          const relList = [];
          data.relationships[pMap.cls] = { data: relList };
          obj[pMap.cls].forEach(item => {
            relList.push(createRel(item[idKey]));
            this.serializeChild(item, type);
          });
        } else {
          data.relationships[pMap.cls] = {
            data: createRel(obj[pMap.cls][idKey])
          };
          this.serializeChild(obj[pMap.cls], type);
        }
      } else {
        const value = transformValueOut(obj[pMap.cls], p);
        data.attributes[pMap.obj] = this.plainMapper.serialize(value);
      }
    };

    container.forEach(Object.keys(obj), cb);

    return data;
  }

  private uuid(type: string, id: string): string {
    return `${type}-${id}`;
  }

  private serializeChild(obj: any, type: any): void {
    targetStore.serialize(
      type,
      new JSONAPIChildSerializeMapper(obj, this.cache, this.plainMapper)
    );
  }

  private serializeCollection(
    arr: any[],
    doc: TopLevel,
    container: PropertyContainer
  ): Array<ResourceObject | ResourceIdentifierObject> {
    return arr.map(s => this.serializeObject(s, doc, container));
  }
}

export class JSONAPIChildSerializeMapper extends JSONAPISerializeMapper {
  constructor(
    source: any,
    protected cache: Map<string, ResourceObject>,
    plainMapper: PlainObjectMapper
  ) {
    super(source, plainMapper);
  }
}

export const jsonAPIMapper: MapperFactory = {
  serializer(
    source: any,
    plainMapper?: PlainObjectMapper
  ): JSONAPISerializeMapper {
    return new JSONAPISerializeMapper(source, plainMapper);
  },
  deserializer(
    source: any,
    sourceType: any,
    plainMapper?: PlainObjectMapper
  ): JSONAPIDeserializeMapper {
    return new JSONAPIDeserializeMapper(source, sourceType, plainMapper);
  }
};


text:
<?xml version="1.0"?>
<assembly>
    <id>targz</id>
    <formats>
        <format>tar.gz</format>
    </formats>

    <includeBaseDirectory>true</includeBaseDirectory>

    <fileSets>
        <fileSet>
            <directory>bin</directory>
            <outputDirectory>bin</outputDirectory>
            <fileMode>0755</fileMode>
            <directoryMode>0755</directoryMode>
            <lineEnding>unix</lineEnding>
            <filtered>true</filtered>
            <includes>
                <include>elasticsearch.in.sh</include>
                <include>elasticsearch</include>
                <include>plugin</include>
            </includes>
        </fileSet>

        <fileSet>
            <directory>lib/sigar</directory>
            <outputDirectory>lib/sigar</outputDirectory>
            <excludes>
                <exclude>*.dll</exclude>
                <exclude>**winnt**</exclude>
            </excludes>
        </fileSet>
    </fileSets>

    <componentDescriptors>
        <componentDescriptor>src/main/assemblies/common-bin.xml</componentDescriptor>
    </componentDescriptors>
</assembly>

redpajama_set_name: RedPajamaGithub


text:
        Vendor

 Vendors

Vendor

{{vendor.name}}

               Address

                {{vendor.primary.addressline1}}
                {{vendor.primary.addressline2}}
                {{vendor.primary.city}}
                , California

               Location

{{vendor.primary.city}}, California

               Contact

{{vendor.primary.phone}}

              <button class="btn btn-primary btn-block" ng-show="showNewProductForm==false" ng-click="addNewProductForm()">Add Product</button>

New Product

				<form class="form-horizontal" ng-submit="addProduct(newproduct)" >

					     Name

					       <input type="text" class="form-control" ng-model="newproduct.name" required/>

					     Category

					       <input type="text" class="form-control" ng-model="newproduct.type" required/>

					     Sub Category

					       <input type="text" class="form-control" ng-model="newproduct.subcategory" required/>

					     Measure Unit

					       <input type="text" class="form-control" ng-model="newproduct.model" required/>

<button type="submit" class="btn btn-success btn-block">Save</button>

<button type="button" class="btn btn-warning btn-block" ng-click="cancelNewProductForm()">Cancel</button>

				</form>

Products

Orders

Settings

                <form class="form-horizontal">

     					     Name

     					       <input type="text" class="form-control" ng-model="vendor.primary.name" required/>

     					     Contact Name

     					       <input type="text" class="form-control" ng-model="vendor.primary.contactname" required/>

     					     Street

     					       <input type="text" class="form-control" ng-model="vendor.primary.addressline1" required/>

     					     Apt, Suite, etc

     					       <input type="text" class="form-control" ng-model="vendor.primary.addressline2" />

     					     City

     					       <input type="text" class="form-control" ng-model="vendor.primary.city" required/>

     					     State

     					       <input type="text" class="form-control" ng-model="vendor.primary.state" required/>

     					     Zipcode

     					       <input type="text" class="form-control" ng-model="vendor.primary.zipcode" required/>

     					     Email

     					       <input type="email" class="form-control" ng-model="vendor.primary.email" required/>

     					     Phone Number

     					       <input type="text" class="form-control" ng-model="vendor.primary.phone" required/>

<button type="submit" class="btn btn-success btn-block">Update</button>

<button type="button" class="btn btn-warning btn-block" ng-click="cancelNewVendor()">Cancel</button>

                </form>


text:
package com.itsdamiya.legendary.cache

import play.api._

import reflect.ClassTag
import org.apache.commons.lang3.reflect.TypeUtils

import scala.concurrent.duration.Duration

/**
 * API for a Cache plugin.
 */
trait CacheAPI {

  /**
   * Set a value into the cache.
   *
   * @param key Item key.
   * @param value Item value.
   * @param timeToIdle Expiration time in seconds (0 second means eternity).
   */
  def set(key: String, value: Any, timeToIdle: Int)

  def set(key: String, value: Any, timeToLive: Int, timeToIdle: Int)

  /**
   * Retrieve a value from the cache.
   *
   * @param key Item key.
   */
  def get(key: String): Option[Any]

  /**
   * Remove a value from the cache
   */
  def remove(key: String)
}

/**
 * Public Cache API.
 *
 * The underlying Cache implementation is received from plugin.
 */
object Cache {

  private def cacheAPI(implicit app: Application): CacheAPI = {
    app.plugin[CachePlugin] match {
      case Some(plugin) => plugin.api
      case None => throw new Exception("There is no cache plugin registered. Make sure at least one CachePlugin implementation is enabled.")
    }
  }

  /**
   * Set a value into the cache.
   *
   * @param key Item key.
   * @param value Item value.
   * @param timeToIdle Expiration time in seconds (0 second means eternity).
   */
  def set(key: String, value: Any, timeToIdle: Int)(implicit app: Application): Unit = {
    cacheAPI.set(key, value, timeToIdle)
  }

  /**
   * Set a value into the cache.
   *
   * @param key Item key.
   * @param value Item value.
   * @param timeToIdle Expiration time as a [[scala.concurrent.duration.Duration]].
   */
  def set(key: String, value: Any, timeToIdle: Duration)(implicit app: Application): Unit = {
    set(key, value, timeToIdle.toSeconds.toInt)
  }

  def set(key: String, value: Any, timeToIdle: Int, timeToLive: Int)(implicit app: Application): Unit = {
    cacheAPI.set(key, value, timeToIdle, timeToLive)
  }

  def set(key: String, value: Any, timeToIdle: Duration, timeToLive: Duration)(implicit app: Application): Unit = {
    set(key, value, timeToIdle.toSeconds.toInt, timeToLive.toSeconds.toInt)
  }

  /**
   * Retrieve a value from the cache.
   *
   * @param key Item key.
   */
  def get(key: String)(implicit app: Application): Option[Any] = {
    cacheAPI.get(key)
  }

  /**
   * Retrieve a value from the cache, or set it from a default function.
   *
   * @param key Item key.
   * @param timeToIdle timeToIdle period in seconds.
   * @param orElse The default function to invoke if the value was found in cache.
   */
  def getOrElse[A](key: String, timeToIdle: Int)(orElse: => A)(implicit app: Application, ct: ClassTag[A]): A = {
    getAs[A](key).getOrElse {
      val value = orElse
      set(key, value, timeToIdle)
      value
    }
  }

  def getOrElse[A](key: String, timeToIdle: Int, timeToLive: Int)(orElse: => A)(implicit app: Application, ct: ClassTag[A]): A = {
    getAs[A](key).getOrElse {
      val value = orElse
      set(key, value, timeToIdle, timeToLive)
      value
    }
  }

  /**
   * Retrieve a value from the cache for the given objectType
   *
   * @param key Item key.
   * @return result as Option[T]
   */
  def getAs[T](key: String)(implicit app: Application, ct: ClassTag[T]): Option[T] = {
    get(key)(app).map { item =>
      if (TypeUtils.isInstance(item, ct.runtimeClass)) Some(item.asInstanceOf[T]) else None
    }.getOrElse(None)
  }

  def remove(key: String)(implicit app: Application) {
    cacheAPI.remove(key)
  }
}

/**
 * A Cache Plugin provides an implementation of the Cache API.
 */
abstract class CachePlugin extends Plugin {

  /**
   * Implementation of the the Cache plugin
   * provided by this plugin.
   */
  def api: CacheAPI

}

import net.sf.ehcache._

/**
 * EhCache implementation.
 */
class EhCachePlugin(app: Application) extends CachePlugin {

  @volatile var loaded = false

  lazy val manager = {
    loaded = true
    // See if there's an ehcache.xml, or fall back to the built in ehcache-default.xml
    val ehcacheXml = Option(app.classloader.getResource("ehcache.xml"))
      .getOrElse(app.classloader.getResource("ehcache-default.xml"))
    CacheManager.create(ehcacheXml)
  }

  lazy val cache: Ehcache = {
    manager.addCache("legendary")
    manager.getEhcache("legendary")
  }

  /**
   * Is this plugin enabled.
   *
   * {{{
   * ehcacheplugin=disabled
   * }}}
   */
  override lazy val enabled = {
    !app.configuration.getString("ehcacheplugin").filter(_ == "disabled").isDefined
  }

  override def onStart() {
    cache
  }

  override def onStop() {
    if (loaded) {
      manager.shutdown()
    }
  }

  lazy val api = new EhCacheImpl(cache)

}

class EhCacheImpl(private val cache: Ehcache) extends CacheAPI {
  private def createElement(key: String, value: Any, timeToIdle: Int): Element = {
    val element = new Element(key, value)
    if (timeToIdle == 0) element.setEternal(true)
    element.setTimeToIdle(timeToIdle)
    element
  }

  def set(key: String, value: Any, timeToIdle: Int) {
    cache.put(createElement(key, value, timeToIdle))
  }

  def get(key: String): Option[Any] = {
    Option(cache.get(key)).map(_.getObjectValue)
  }

  def remove(key: String) {
    cache.remove(key)
  }

  def set(key: String, value: Any, timeToLive: Int, timeToIdle: Int) {
    val element = createElement(key, value, timeToIdle)
    element.setTimeToLive(timeToLive)
    cache.put(element)
  }
}


text:
user="docker"
password="docker"

/etc/init.d/mysql start

# Give it time to start
sleep 5

# Set up initial user
mysql <<EOF
  CREATE USER '$user'@'%' IDENTIFIED by '$password' ;
  GRANT ALL PRIVILEGES ON *.* to '$user'@'%' WITH GRANT OPTION ;
  FLUSH PRIVILEGES ;
EOF

# Set up broker DB and its tables
mysql < /setup.sql

/etc/init.d/mysql stop


text:
<?php

final class AlmanacInterfaceDeleteController
  extends AlmanacDeviceController {

  public function handleRequest(AphrontRequest $request) {
    $viewer = $request->getViewer();

    $id = $request->getURIData('id');
    $interface = id(new AlmanacInterfaceQuery())
      ->setViewer($viewer)
      ->withIDs(array($id))
      ->requireCapabilities(
        array(
          PhabricatorPolicyCapability::CAN_VIEW,
          PhabricatorPolicyCapability::CAN_EDIT,
        ))
      ->executeOne();
    if (!$interface) {
      return new Aphront404Response();
    }

    $device = $interface->getDevice();
    $device_uri = $device->getURI();

    if ($interface->loadIsInUse()) {
      return $this->newDialog()
        ->setTitle(pht('Interface In Use'))
        ->appendParagraph(
          pht(
            'You can not delete this interface because it is currently in '.
            'use. One or more services are bound to it.'))
        ->addCancelButton($device_uri);
    }

    if ($request->isFormPost()) {
      $type_interface = AlmanacDeviceTransaction::TYPE_INTERFACE;

      $xactions = array();

      $v_old = array(
        'id' => $interface->getID(),
      ) + $interface->toAddress()->toDictionary();

      $xactions[] = id(new AlmanacDeviceTransaction())
        ->setTransactionType($type_interface)
        ->setOldValue($v_old)
        ->setNewValue(null);

      $editor = id(new AlmanacDeviceEditor())
        ->setActor($viewer)
        ->setContentSourceFromRequest($request)
        ->setContinueOnNoEffect(true)
        ->setContinueOnMissingFields(true);

      $editor->applyTransactions($device, $xactions);

      return id(new AphrontRedirectResponse())->setURI($device_uri);
    }

    return $this->newDialog()
      ->setTitle(pht('Delete Interface'))
      ->appendParagraph(
        pht(
          'Remove interface %s on device %s?',
          phutil_tag('strong', array(), $interface->renderDisplayAddress()),
          phutil_tag('strong', array(), $device->getName())))
      ->addCancelButton($device_uri)
      ->addSubmitButton(pht('Delete Interface'));
  }

}


text:
package org.asynchttpclient.providers.netty;

import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.AsyncHttpClientConfig;
import org.asynchttpclient.async.FilterTest;

public class NettyFilterTest extends FilterTest {
    @Override
    public AsyncHttpClient getAsyncHttpClient(AsyncHttpClientConfig config) {
        return NettyProviderUtil.nettyProvider(config);
    }
}


text:
package com.lightcrafts.media.jai.opimage;
import java.awt.RenderingHints;
import java.awt.image.RenderedImage;
import java.awt.image.renderable.ParameterBlock;
import java.awt.image.renderable.RenderedImageFactory;

/**
 * @since EA2
 */
public class PNGRIF implements RenderedImageFactory {

    /** Constructor. */
    public PNGRIF() {}

    /**
     * Creates a RenderedImage representing the contents
     * of a PNM-encoded image.
     *
     * @param paramBlock A ParameterBlock containing the PNM
     *        SeekableStream to read.
     * @param renderHints An instance of RenderingHints,
     *        or null.
     */
    public RenderedImage create(ParameterBlock paramBlock,
                                RenderingHints renderHints) {
        return CodecRIFUtil.create("png", paramBlock, renderHints);
    }
}


text: Rails.application.config.session_store :cookie_store, key: '_mallard_session'


text:
<?php
namespace App;
use Lucid\Lucid, Lucid\Html\html;

class App extends \Lucid\App
{

}


text:
package com.justwayward.reader.view.chmview;

import java.io.IOException;

public class LZXTree {

    public static final int LZX_LENTABLE_SAFETY = 64; // allow length table decoding overruns
    public static final int LZX_PRETREE_NUM_ELEMENTS = 20;

    int bits;
    int max_symbol;

    int[] symbols;
    byte[] lens;

    LZXTree(int bits, int max) {
        this.bits = bits;
        this.max_symbol = max;

        symbols = new int[(1 << bits) + (max << 1)];
        lens = new byte[max + LZX_LENTABLE_SAFETY];
    }

    /**
     * This function was coded by David Tritscher. It builds a fast huffman
     * decoding table out of just a canonical huffman code lengths table.
     */
    void makeSymbolTable() throws DataFormatException {
        int bit_num = 1;
        int pos = 0; // the current position in the decode table
        int table_mask = 1 << bits;
        int bit_mask = table_mask >> 1; // don't do 0 length codes
        int next_symbol = bit_mask; // base of allocation for long codes

        // fill entries for codes short enough for a direct mapping
        while (bit_num <= bits) {
            for (int symbol = 0; symbol < max_symbol; symbol++) {
                if (lens[symbol] == bit_num) {
                    int leaf = pos;

                    if ((pos += bit_mask) > table_mask)    // ensure capacity
                        throw new DataFormatException("symbol table overruns");
                    // fill all possible lookups of this symbol with the symbol itself
                    while (leaf < pos) symbols[leaf++] = symbol;
                }
            }
            bit_mask >>= 1;
            bit_num++;
        }

        // if there are any codes longer than table.bits
        if (pos != table_mask) {
            // clear the remainder of the table
            for (int i = pos; i < table_mask; i++) symbols[i] = 0;

            // give ourselves room for codes to grow by up to 16 more bits
            pos <<= 16;
            table_mask <<= 16;
            bit_mask = 1 << 15;

            while (bit_num <= 16) {
                for (int symbol = 0; symbol < max_symbol; symbol++) {
                    if (lens[symbol] == bit_num) {
                        int leaf = pos >> 16;
                        for (int fill = 0; fill < bit_num - bits; fill++) {
                            // if this path hasn't been taken yet, 'allocate' two entries
                            if (symbols[leaf] == 0) {
                                symbols[next_symbol << 1] = 0;
                                symbols[(next_symbol << 1) + 1] = 0;
                                symbols[leaf] = (next_symbol++);
                            }
                            // follow the path and select either left or right for next bit
                            leaf = symbols[leaf] << 1;
                            if (((pos >> (15 - fill)) & 1) > 0) // odd
                                leaf++;
                        }
                        symbols[leaf] = symbol;

                        if ((pos += bit_mask) > table_mask)
                            throw new DataFormatException("symbol table overflow");
                    }
                }
                bit_mask >>= 1;
                bit_num++;
            }
        }

        // full table?
        if (pos == table_mask)
            return;

        // either erroneous table, or all elements are 0 - let's find out.
        for (short sym = 0; sym < max_symbol; sym++)
            if (lens[sym] != 0)
                throw new DataFormatException("erroneous symbol table");
    }

    /**
     * reads in code lengths for symbols
     * first to last in the given table. The code lengths are stored in their
     * own special LZX way.
     */
    void readLengthTable(BitsInputStream bin, int first, int last) throws DataFormatException, IOException {
        LZXTree preTree = new LZXTree(6, LZX_PRETREE_NUM_ELEMENTS);
        for (int i = 0; i < preTree.max_symbol; i++)
            preTree.lens[i] = (byte) bin.readLE(4);
        preTree.makeSymbolTable();

        for (int pos = first; pos < last; ) {
            int symbol = preTree.readHuffmanSymbol(bin);
            if (symbol == 0x11) {
                int pos2 = pos + bin.readLE(4) + 4;
                while (pos < pos2) lens[pos++] = (byte) 0;
            } else if (symbol == 0x12) {
                int pos2 = pos + bin.readLE(5) + 20;
                while (pos < pos2) lens[pos++] = (byte) 0;
            } else if (symbol == 0x13) {
                int pos2 = pos + bin.readLE(1) + 4;
                symbol = lens[pos] - preTree.readHuffmanSymbol(bin);
                if (symbol < 0)
                    symbol += 0x11;
                while (pos < pos2) lens[pos++] = (byte) symbol;
            } else {
                symbol = lens[pos] - symbol;
                if (symbol < 0)
                    symbol += 0x11;
                lens[pos++] = (byte) symbol;
            }
        }
    }

    /**
     * decodes one huffman symbol from the bitstream using the
     * stated table and return it.
     * @throws IOException
     */
    int readHuffmanSymbol(BitsInputStream bin) throws IOException {
        int next = bin.peekUnder(16);

		/* TODO: it's very strange that bin.peek(bits) will raise EOFException,
		 * we have to use peekUnder(bits) here, but how should it happen like this?
		 */
        int symbol = symbols[bin.peekUnder(bits)];
        if (symbol >= max_symbol) {
            int j = 1 << (16 - bits);
            do {
                j >>= 1;
                symbol <<= 1;
                symbol |= (next & j) > 0 ? 1 : 0;
                symbol = symbols[symbol];
            } while (symbol >= max_symbol);
        }
        bin.readLE(lens[symbol]);
        return symbol;
    }

    public void clear() {
        for (int i = 0; i < lens.length; i++)
            lens[i] = 0;
    }
}


text:
#include "OgreBspSceneManagerPlugin.h"
#include "OgreRoot.h"

namespace Ogre
{
	const String sPluginName = "BSP Scene Manager";
	//---------------------------------------------------------------------
	BspSceneManagerPlugin::BspSceneManagerPlugin()
		:mBspFactory(0), mBspResourceManager(0)
	{

	}
	//---------------------------------------------------------------------
	const String& BspSceneManagerPlugin::getName() const
	{
		return sPluginName;
	}
	//---------------------------------------------------------------------
	void BspSceneManagerPlugin::install()
	{
		// Create new scene manager
		mBspFactory = OGRE_NEW BspSceneManagerFactory();

	}
	//---------------------------------------------------------------------
	void BspSceneManagerPlugin::initialise()
	{
		// Register (factory not dependent on rsys resources)
		Root::getSingleton().addSceneManagerFactory(mBspFactory);
		// Create resource manager (registers itself)
		mBspResourceManager = OGRE_NEW BspResourceManager();
	}
	//---------------------------------------------------------------------
	void BspSceneManagerPlugin::shutdown()
	{
		// Unregister SM factory
		Root::getSingleton().removeSceneManagerFactory(mBspFactory);

		// delete resource manager, will unregister itself
		OGRE_DELETE mBspResourceManager;
		mBspResourceManager = 0;

	}
	//---------------------------------------------------------------------
	void BspSceneManagerPlugin::uninstall()
	{

		OGRE_DELETE mBspFactory;
		mBspFactory = 0;

	}

}


text:
using System;
using JetBrains.Annotations;

namespace ByrneLabs.Commons.MetadataDom
{
    [PublicAPI]
    public abstract class ConstantInfo
    {
        public abstract Type ConstantType { get; }

        public abstract object Value { get; }

        public FieldInfo ParentField => Parent as FieldInfo;

        public ParameterInfo ParentParameter => Parent as ParameterInfo;

        public PropertyInfo ParentProperty => Parent as PropertyInfo;

        protected abstract object Parent { get; }

        public override string ToString() => (Parent as IMemberInfo).FullName;
    }
}


text:
// MusicXML Class Library
// Copyright (c) by Matthew James Briggs
// Distributed under the MIT License

#include "mxtest/control/CompileControl.h"
#ifdef MX_COMPILE_CORE_TESTS

#include "cpul/cpulTestHarness.h"
#include "mx/core/Elements.h"
#include <sstream>

using namespace mx::core;

TEST( Test01, BarStyle )
{
	std::string indentString( INDENT );
	BarStyleEnum value1 = BarStyleEnum::heavy;
	BarStyleEnum value2 = BarStyleEnum::lightHeavy;
	BarStyle object1;
	BarStyle object2( value2 );
	BarStyleAttributesPtr attributes1 = std::make_shared<BarStyleAttributes>();
	BarStyleAttributesPtr attributesNull;
	/* set some attribute1 values here */
	object2.setAttributes( attributes1 );
    attributes1->hasColor = true;
    attributes1->color = Color{ 100, 101, 102, 103 };
	std::stringstream default_constructed;
	object1.toStream( default_constructed, 0 );
	std::stringstream object2_stream;
	object2.toStream( object2_stream, 2 );
	std::string expected = R"(<bar-style>regular</bar-style>)";
	std::string actual = default_constructed.str();
	CHECK_EQUAL( expected, actual )
	expected = indentString+indentString+R"(<bar-style color="#64656667">light-heavy</bar-style>)";
	actual = object2_stream.str();
	CHECK_EQUAL( expected, actual )
	value1 = object2.getValue();
	object1.setValue( value1 );
	std::stringstream o1;	std::stringstream o2;	bool isOneLineOnly = false;
	object1.streamContents( o1, 0, isOneLineOnly );
	object2.streamContents( o2, 0, isOneLineOnly );
	CHECK( isOneLineOnly )
	CHECK_EQUAL( o1.str(), o2.str() )
}

#endif


text:
package com.dremio.exec.planner.sql.handlers;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rex.RexBuilder;
import org.apache.calcite.rex.RexCall;
import org.apache.calcite.rex.RexLiteral;
import org.apache.calcite.rex.RexNode;
import org.apache.calcite.rex.RexShuttle;
import org.apache.calcite.sql.SqlKind;
import org.apache.calcite.sql.fun.SqlStdOperatorTable;
import org.apache.calcite.sql.type.SqlTypeName;

import com.dremio.exec.planner.StatelessRelShuttleImpl;
import com.dremio.exec.planner.physical.FilterPrel;
import com.google.common.collect.ImmutableSet;

/**
 * A shuttle designed to convert
 * AND(exp_1<>literal_1, exp1<>literal_2, exp_2<>literal_3, exp_2<>literal_4,...) pattern to
 * AND(NOT(OR(exp_1=literal_1,exp_1=literal_2)),NOT(OR(exp_2=literal_3,exp_2=literal_4)),...).
 */
class AndToOrConverter extends StatelessRelShuttleImpl {

  @Override
  public RelNode visit(RelNode other) {
    if (other instanceof FilterPrel) {
      FilterPrel filter = (FilterPrel) other;
      AndToOrRexShuttle converter = new AndToOrRexShuttle(filter.getCluster().getRexBuilder());
      RexNode newCondition = converter.convert(filter.getCondition());
      if (converter.converted()) {
        return super.visit(filter.copy(filter.getTraitSet(), filter.getInput(), newCondition));
      }
    }
    return super.visit(other);
  }

  public static class AndToOrRexShuttle extends RexShuttle {

    private final RexBuilder rexBuilder;
    private boolean converted;
    private final Set<SqlTypeName> SUPPORTED_TYPES =
      ImmutableSet.of(SqlTypeName.INTEGER, SqlTypeName.BIGINT, SqlTypeName.DATE, SqlTypeName.TIME, SqlTypeName.TIMESTAMP, SqlTypeName.VARCHAR, SqlTypeName.VARBINARY);

    public AndToOrRexShuttle(RexBuilder rexBuilder) {
      this.rexBuilder = rexBuilder;
      this.converted = false;
    }

    private boolean isTypeSuppored(SqlTypeName type) {
      return SUPPORTED_TYPES.contains(type);
    }

    public RexNode convert(RexNode rexNode) {
      converted = false;
      return rexNode.accept(this);
    }

    @Override
    public RexNode visitCall(RexCall call) {
      if (call.getKind() == SqlKind.AND) {
        final List<RexNode> operands = call.getOperands();
        Map<String, List<RexNode>> operandsByExpr = new HashMap<>();
        List<RexNode> extras = new ArrayList<>();
        for (RexNode rexNode : operands) {
          if (!(rexNode instanceof RexCall) || (rexNode.getKind() != SqlKind.NOT_EQUALS)) {
            extras.add(rexNode);
            continue;
          }

          RexCall opCall = (RexCall) rexNode;
          if (opCall.getOperands().size() != 2) {
            extras.add(rexNode);
            continue;
          }

          RexNode first = opCall.getOperands().get(0);
          RexNode second = opCall.getOperands().get(1);

          if ((first.getType().getSqlTypeName() != second.getType().getSqlTypeName()) || !isTypeSuppored(first.getType().getSqlTypeName())) {
            extras.add(rexNode);
            continue;
          }

          RexLiteral literal = null;
          RexNode other = null;

          if (first instanceof RexLiteral && !(second instanceof RexLiteral)) {
            literal = (RexLiteral) first;
            other = second;
          }

          if (second instanceof RexLiteral && !(first instanceof RexLiteral)) {
            literal = (RexLiteral) second;
            other = first;
          }

          if (literal == null) {
            extras.add(rexNode);
            continue;
          }

          String stringExpr = other.toString();

          RexNode newOperand = rexBuilder.makeCall(SqlStdOperatorTable.EQUALS, other, literal);
          if (!operandsByExpr.containsKey(stringExpr)) {
            operandsByExpr.put(stringExpr, new ArrayList<>());
            if (other.getType().isNullable()) {
              extras.add(rexBuilder.makeCall(SqlStdOperatorTable.IS_NOT_NULL, other));
            }
          }
          operandsByExpr.get(stringExpr).add(newOperand);
        }

        if (extras.size() != operands.size()) {
          converted = true;
          List<RexNode> operandList = new ArrayList<>();
          for (String expr : operandsByExpr.keySet()) {
            if (operandsByExpr.get(expr).size() > 1) {
              operandList.add(rexBuilder.makeCall(SqlStdOperatorTable.NOT, rexBuilder.makeCall(SqlStdOperatorTable.OR, operandsByExpr.get(expr))));
            } else {
              operandList.add(rexBuilder.makeCall(SqlStdOperatorTable.NOT, operandsByExpr.get(expr)));
            }
          }
          operandList.addAll(extras);
          if (operandList.size() == 1) {
            return operandList.get(0);
          } else {
            return rexBuilder.makeCall(SqlStdOperatorTable.AND, operandList);
          }
        }
      }
      return call;
    }

    public boolean converted() {
      return converted;
    }
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Persoonia 20: 45 (2008)

#### Original name
Jattaea prunicola Damm & Crous

### Remarks
null


text:
package cz.jiripinkas.example.eshop.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import cz.jiripinkas.example.eshop.domain.Basket;
import cz.jiripinkas.example.eshop.service.ItemService;

@Controller
@RequestMapping("/basket")
@SessionAttributes("basket")
public class BasketController {

	@Autowired
	private ItemService itemService;

	@ModelAttribute("basket")
	public Basket construct() {
		return new Basket();
	}

	@RequestMapping
	public String show(Model model, HttpSession session) {
		return "basket";
	}

	@RequestMapping("/add")
	public String add(@RequestParam int id, @RequestParam int quantity,
			@ModelAttribute Basket basket) {
		basket.add(itemService.findOne(id), quantity);
		return "redirect:/items.html";
	}

	@RequestMapping("/remove")
	public String remove(@RequestParam int id, @ModelAttribute Basket basket) {
		basket.remove(id);
		return "redirect:/basket.html";
	}

}


text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview A TTS engine that writes to window.console.
 */

goog.provide('cvox.ConsoleTts');

goog.require('cvox.AbstractTts');
goog.require('cvox.TtsInterface');

/**
 * @constructor
 * @implements {cvox.TtsInterface}
 */
cvox.ConsoleTts = function() {
  /**
   * True if the console TTS is enabled by the user.
   * @type {boolean}
   * @private
   */
  this.enabled_ = false;
};
goog.addSingletonGetter(cvox.ConsoleTts);

/** @override */
cvox.ConsoleTts.prototype.speak = function(textString, queueMode, properties) {
  if (this.enabled_ && window['console']) {
    var logStr = 'Speak';
    if (queueMode == cvox.QueueMode.FLUSH) {
      logStr += ' (I)';
    } else if (queueMode == cvox.QueueMode.CATEGORY_FLUSH) {
      logStr += ' (C)';
    } else {
      logStr += ' (Q)';
    }
    if (properties && properties.category) {
      logStr += ' category=' + properties.category;
    }
    logStr += ' "' + textString + '"';
    console.log(logStr);
  }
  return this;
};

/** @override */
cvox.ConsoleTts.prototype.isSpeaking = function() { return false; };

/** @override */
cvox.ConsoleTts.prototype.stop = function() {
  if (this.enabled_) {
    console.log('Stop');
  }
};

/** @override */
cvox.ConsoleTts.prototype.addCapturingEventListener = function(listener) { };

/** @override */
cvox.ConsoleTts.prototype.increaseOrDecreaseProperty = function() { };

/** @override */
cvox.ConsoleTts.prototype.propertyToPercentage = function() { };

/**
 * Sets the enabled bit.
 * @param {boolean} enabled The new enabled bit.
 */
cvox.ConsoleTts.prototype.setEnabled = function(enabled) {
  this.enabled_ = enabled;
};

/** @override */
cvox.ConsoleTts.prototype.getDefaultProperty = function(property) { };


text:
<?php

/**
 * @file
 * Contains \Drupal\Core\Executable\ExecutablePluginBase.
 */

namespace Drupal\Core\Executable;

use Drupal\Core\Plugin\ContextAwarePluginBase;
use Symfony\Component\Validator\Validation;
use Drupal\Component\Plugin\Exception\PluginException;

/**
 * Provides the basic architecture for executable plugins.
 */
abstract class ExecutablePluginBase extends ContextAwarePluginBase implements ExecutableInterface {

  /**
   * The condition manager to proxy execute calls through.
   *
   * @var \Drupal\Component\Plugin\PluginManagerInterface
   */
  protected $executableManager;

  /**
   * {@inheritdoc}
   */
  public function setExecutableManager(ExecutableManagerInterface $executableManager) {
    $this->executableManager = $executableManager;
    return $this;
  }

  /**
   * Gets an array of definitions of available configuration options.
   *
   * @todo: This needs to go into an interface.
   *
   * @return array
   *   An array of typed data definitions describing available configuration
   *   options, keyed by option name.
   */
  public function getConfigDefinitions() {
    $definition = $this->getPluginDefinition();
    if (!empty($definition['configuration'])) {
      return $definition['configuration'];
    }
    return array();
  }

  /**
   * Gets the definition of a configuration option.
   *
   * @todo: This needs to go into an interface.
   *
   * @return array
   *   The typed data definition describing the configuration option, or FALSE
   *   if the option does not exist.
   */
  public function getConfigDefinition($key) {
    $definition = $this->getPluginDefinition();
    if (!empty($definition['configuration'][$key])) {
      return $definition['configuration'][$key];
    }
    return FALSE;
  }

  /**
   * Gets all configuration values.
   *
   * @todo: This needs to go into an interface.
   *
   * @return array
   *   The array of all configuration values, keyed by configuration option
   *   name.
   */
  public function getConfig() {
    return $this->configuration;
  }

  /**
   * Sets the value of a particular configuration option.
   *
   * @param string $name
   *   The name of the configuration option to set.
   * @param mixed $value
   *   The value to set.
   *
   * @todo This doesn't belong here. Move this into a new base class in
   *   http://drupal.org/node/1764380.
   * @todo This does not set a value in \Drupal::config(), so the name is confusing.
   *
   * @return \Drupal\Core\Executable\ExecutablePluginBase.
   *   The executable object for chaining.
   */
  public function setConfig($key, $value) {
    if ($definition = $this->getConfigDefinition($key)) {
      $typed_data = \Drupal::typedDataManager()->create($definition, $value);

      if ($typed_data->validate()->count() > 0) {
        throw new PluginException("The provided configuration value does not pass validation.");
      }
    }
    $this->configuration[$key] = $value;
    return $this;
  }
}


text:
export const getUserInfo = (state) => {
  return state.user.data;
};

export const getUserAuth = (state) => {
  return state.user.auth;
};

export const getLists = (state) => {
  return state.lists.all;
};

export const getTasks = (state) => {
  return state.tasks.all;
};

export const isShowDetail = (state) => {
  return state.tasks.showDetail;
};

export const getTaskDetail = (state) => {
  return state.tasks.taskDetail;
};

// ajax 加载相关
export const isRequestingTaskDetail = (state) => {
	return state.tasks.isRequestingTaskDetail;
}
export const isRequestingTasks = (state) => {
	return state.tasks.isRequestingTasks;
}


text:
local uuid      = require("kong.tools.utils").uuid
local helpers   = require "spec.helpers"
local timestamp = require "kong.tools.timestamp"

local get_local_key = function(conf, identifier, period, period_date)
  return string.format("ratelimit:%s:%s:%s:%s:%s",
    conf.route_id, conf.service_id, identifier, period_date, period)
end

describe("Plugin: rate-limiting (policies)", function()

  local policies

  lazy_setup(function()
    package.loaded["kong.plugins.rate-limiting.policies"] = nil
    policies = require "kong.plugins.rate-limiting.policies"
  end)

  describe("local", function()
    local identifier = uuid()
    local conf       = { route_id = uuid(), service_id = uuid() }

    local shm = ngx.shared.kong_rate_limiting_counters

    before_each(function()
      shm:flush_all()
      shm:flush_expired()
    end)

    it("sets the TTL equal to one period when incrementing", function()
      local current_timestamp = 1553263548
      local periods = timestamp.get_timestamps(current_timestamp)

      local limits = {
        minute = 100,
        hour   = 100
      }

      assert(policies["local"].increment(conf, limits, identifier, current_timestamp, 1))

      local minute_key_ttl = shm:ttl(get_local_key(conf, identifier, "minute", periods.minute))
      local hour_key_ttl = shm:ttl(get_local_key(conf, identifier, "hour", periods.hour))

      assert(minute_key_ttl > 55 and minute_key_ttl <= 60)
      assert(hour_key_ttl > 3555 and hour_key_ttl <= 3600)
    end)

    it("expires after due time", function ()
      local timestamp = 569000048000

      assert(policies['local'].increment(conf, {second=100}, identifier, timestamp+20, 1))
      local v = shm:ttl(get_local_key(conf, identifier, 'second', timestamp))
      assert(v and v > 0, "wrong value")
      ngx.sleep(1.020)

      v = shm:ttl(get_local_key(conf, identifier, 'second', timestamp))
      assert(v == nil, "still there")
    end)
  end)

  for _, strategy in helpers.each_strategy() do
    describe("cluster [#" .. strategy .. "]", function()
      local identifier = uuid()
      local conf       = { route = { id = uuid() }, service = { id = uuid() } }

      local db

      lazy_setup(function()
        local _
        _, db = helpers.get_db_utils(strategy, {})

        if _G.kong then
          _G.kong.db = db
        else
          _G.kong = { db = db }
        end
      end)

      before_each(function()
        assert(db:truncate("ratelimiting_metrics"))
      end)

      it("returns 0 when rate-limiting metrics don't exist yet", function()
        local current_timestamp = 1424217600
        local periods = timestamp.get_timestamps(current_timestamp)

        for period in pairs(periods) do
          local metric = assert(policies.cluster.usage(conf, identifier, period, current_timestamp))
          assert.equal(0, metric)
        end
      end)

      it("increments rate-limiting metrics with the given period", function()
        local current_timestamp = 1424217600
        local periods = timestamp.get_timestamps(current_timestamp)

        local limits = {
          second = 100,
          minute = 100,
          hour   = 100,
          day    = 100,
          month  = 100,
          year   = 100
        }

        -- First increment
        assert(policies.cluster.increment(conf, limits, identifier, current_timestamp, 1))

        -- First select
        for period in pairs(periods) do
          local metric = assert(policies.cluster.usage(conf, identifier, period, current_timestamp))
          assert.equal(1, metric)
        end

        -- Second increment
        assert(policies.cluster.increment(conf, limits, identifier, current_timestamp, 1))

        -- Second select
        for period in pairs(periods) do
          local metric = assert(policies.cluster.usage(conf, identifier, period, current_timestamp))
          assert.equal(2, metric)
        end

        -- 1 second delay
        current_timestamp = 1424217601
        periods = timestamp.get_timestamps(current_timestamp)

        -- Third increment
        assert(policies.cluster.increment(conf, limits, identifier, current_timestamp, 1))

        -- Third select with 1 second delay
        for period in pairs(periods) do
          local expected_value = 3
          if period == "second" then
            expected_value = 1
          end

          local metric = assert(policies.cluster.usage(conf, identifier, period, current_timestamp))
          assert.equal(expected_value, metric)
        end
      end)
    end)
  end

end)


text:
Only delegate-ch meta tags in the original HTML sent from the server
are respected. Any injected via javascript (or other means) are ignored.


text:
package priv.valueyouth.rhymemusic.lrc_view;

import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint.Align;
import android.graphics.Paint.FontMetrics;
import android.text.Layout.Alignment;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import java.util.List;

import priv.valueyouth.rhymemusic.R;
import priv.valueyouth.rhymemusic.util.Lyric;
import priv.valueyouth.rhymemusic.util.LyricUtils;

/**
 * <p>
 * 自定义View,滚动播放LRC歌词
 * </p>
 */
public class LyricView extends View
{

    private static final String TAG = "RhymeMusic";
    private static final String SUB = "[LyricView]#";

    private static final int DEFAULT_TEXT_SIZE = 40;
    private static final int DEFAULT_TEXT_COLOR = 0xFFFFFFFF;
    private static final int DEFAULT_CURRENT_TEXT_COLOR = 0xFF0E8DC4;
    private static final int DEFAULT_MAX_LINES = 10;
    private static final int DEFAULT_LINE_SPACE = 15;
    private static final int DEFAULT_ANIM_DURATION = 400;

    private int mTextSize = DEFAULT_TEXT_SIZE; // 字体大小
    private int mTextColor = DEFAULT_TEXT_COLOR; // 字体颜色
    private int mCurrentTextColor = DEFAULT_CURRENT_TEXT_COLOR; // 当前播放字体颜色

    // 字体透明度,用于渐变
    private int mMaxTextAlpha = 0xFF;
    private int mMinTextAlpha = 0x00;

    private int mMaxLines = DEFAULT_MAX_LINES; // 最大行数
    private int mLineSpace = DEFAULT_LINE_SPACE; // 行距

    private List<Lyric> mLyrics = null;
    private int mCurrentIndex = 0; // 当前歌词对应索引

    private TextPaint mPaint;
    private int mTextHeight = 0; // 字体高度

    // View 宽高
    private int mWidth = 0, mHeight = 0;

    private ValueAnimator mLineAnimator;
    private long mLineAnimDuration = DEFAULT_ANIM_DURATION; // 歌词滚动动画时间长度
    private int mLineOffset = 0; // 动画当前偏移
    private int mAnimOffset = 0; // 动画总偏移,偏移的总动画

    public LyricView(Context context)
    {
        this(context, null);
    }

    public LyricView(Context context, AttributeSet attrs)
    {
        this(context, attrs, 0);
    }

    public LyricView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        initAttribute(context, attrs);
        initView();
    }

    /**
     * onSizeChanged()在onDraw()之前调用,可以在这里获取View的宽高
     */
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh)
    {
        super.onSizeChanged(w, h, oldw, oldh);
        mWidth = w;
        mHeight = h;
    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        super.onDraw(canvas);
        if ( mLyrics == null || 0 == mLyrics.size())
        {
            mPaint.setColor(mTextColor);
            String noLyrics = getContext().getString(R.string.no_lyrics);
            String tips = "Tips:将歌词文件放于歌曲目录,使命名一致";

            canvas.drawText(noLyrics, mWidth / 2, mHeight / 2, mPaint);
            canvas.drawText(tips, mWidth / 2, 2 * mHeight / 3, mPaint);

            return;
        }

        // 绘制当前播放歌词行
        mPaint.setColor(mCurrentTextColor);
        mPaint.setAlpha(mMaxTextAlpha);
        String currentLine = mLyrics.get(mCurrentIndex).getContent();
        float drawY = mHeight / 2;
        drawText(currentLine, canvas, drawY + mLineOffset);

        // 需要绘制已播放行数
        int alreadyPlayedCount = (int) Math.ceil((double) (mMaxLines - 1) / 2);
        // 需要绘制即将播放行数
        int soonPlayCount = (int) Math.floor((double) (mMaxLines - 1) / 2);

        // 绘制已播放歌词
        mPaint.setColor(mTextColor);
        for (int i = 1; i <= alreadyPlayedCount; i++)
        {
            int index = mCurrentIndex - i;
            if (index < 0)
            {
                break;
            }
            int alpha = mMaxTextAlpha -
                    (mMaxTextAlpha - mMinTextAlpha) / (alreadyPlayedCount + 1) * i;
            mPaint.setAlpha(alpha);
            String line = mLyrics.get(index).getContent();
            drawY = drawY - getNumberOfRows(line) * mTextHeight - mLineSpace;
            drawText(line, canvas, drawY + mLineOffset);
        }

        // 绘制即将播放歌词
        drawY = mHeight / 2 + getNumberOfRows(currentLine) * mTextHeight + mLineSpace;
        for (int i = 1; i <= soonPlayCount; i++)
        {
            int index = mCurrentIndex + i;
            if (index > mLyrics.size() - 1)
            {
                break;
            }
            int alpha = mMaxTextAlpha - (mMaxTextAlpha - mMinTextAlpha) /
                    (soonPlayCount + 1) * i;
            mPaint.setAlpha(alpha);
            String line = mLyrics.get(index).getContent();
            drawText(line, canvas, drawY + mLineOffset);
            drawY = drawY + getNumberOfRows(line) * mTextHeight + mLineSpace;
        }
    }

    private void initAttribute(Context context, AttributeSet attrs)
    {
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.lyric);
        mTextSize = ta.getDimensionPixelOffset(R.styleable.lyric_textSize, DEFAULT_TEXT_SIZE);
        mTextColor = ta.getColor(R.styleable.lyric_textColor, DEFAULT_TEXT_COLOR);
        mCurrentTextColor = ta.getColor(R.styleable.lyric_currentTextColor, DEFAULT_CURRENT_TEXT_COLOR);
        mMaxLines = ta.getInt(R.styleable.lyric_maxLine, DEFAULT_MAX_LINES);
        mLineSpace = ta.getDimensionPixelOffset(R.styleable.lyric_lineSpace, DEFAULT_LINE_SPACE);
        mLineAnimDuration = ta.getInt(R.styleable.lyric_animDuration, DEFAULT_ANIM_DURATION);
        ta.recycle();
    }

    private void initView()
    {
        mPaint = new TextPaint();
        mPaint.setTextSize(mTextSize);
        mPaint.setTextAlign(Align.CENTER);
        mPaint.setAntiAlias(true);

        // 计算字体高度
        FontMetrics fm = mPaint.getFontMetrics();
        mTextHeight = (int) (fm.bottom - fm.top);

        // 滚动动画
        mLineAnimator = new ValueAnimator();
        mLineAnimator.setIntValues(0, 100);
        mLineAnimator.setDuration(mLineAnimDuration);
        mLineAnimator.addUpdateListener(new AnimatorUpdateListener()
        {
            @Override
            public void onAnimationUpdate(ValueAnimator animation)
            {
                int value = (Integer) animation.getAnimatedValue();
                float percent = 1 - (float) value / 100;
                mLineOffset = (int) (mAnimOffset * percent); // 更新偏移值,重绘View
                invalidate();
            }
        });
    }

    /**
     * 设置歌词内容
     * @param lyrics
     */
    public void setLyricContent(List<Lyric> lyrics)
    {
        Log.d(TAG, SUB + "setLyricContent");
        mLyrics = lyrics;
        invalidate();
    }

    /**
     * 指定当前播放时间,刷新歌词
     *
     * @param time
     * @param animation 是否动画滚动
     */
    public void setCurrentTime(long time, boolean animation)
    {
        if (mLyrics == null)
        {
            return;
        }
        int index = getIndexByPositionTime(time);
        if (index < 0 || index > mLyrics.size() - 1)
        {
            return;
        }
        if (index == mCurrentIndex)
        {
            return;
        }
        mCurrentIndex = index;
        mLineAnimator.cancel();
        if (animation)
        {
            if (mCurrentIndex == 0)
            {
                mLineOffset = 0;
                invalidate();
            }
            else
            {
                String lastLine = mLyrics.get(mCurrentIndex - 1).getContent();
                mAnimOffset = getNumberOfRows(lastLine) * mTextHeight + mLineSpace;
                mLineAnimator.start();
            }
        }
        else
        {
            mLineOffset = 0;
            invalidate();
        }
    }

    /**
     * 当前播放时间对应的歌词索引值
     *
     * @param time
     * @return
     */
    private int getIndexByPositionTime(long time)
    {
        int index = 0;
        if (mLyrics != null)
        {
            for (int i = 0; i < mLyrics.size(); i++)
            {
                long t = mLyrics.get(i).getTime();
                if (t > time)
                {
                    break;
                }
                index = i;
            }
        }
        return index;
    }

    /**
     * 一句歌词需要显示的行数(换行次数)
     *
     * @param lrc
     * @return
     */
    private int getNumberOfRows(String lrc)
    {
        float width = mPaint.measureText(lrc);
        float maxWidth = mWidth - getPaddingLeft() - getPaddingRight();
        int num = (int) Math.ceil(width / maxWidth);
        return num;
    }

    /**
     * 绘制文本,可自动换行
     * @param text
     * @param canvas
     * @param y
     */
    private void drawText(String text, Canvas canvas, float y)
    {
        int status = canvas.save();
        canvas.translate(mWidth / 2, y);
        int w = mWidth - getPaddingLeft() - getPaddingRight();
        StaticLayout layout = new StaticLayout(text, mPaint, w,
                Alignment.ALIGN_NORMAL, 1.0f, 0, false);
        layout.draw(canvas);
        canvas.restoreToCount(status);
    }
}


text:
define('mods/main',function(require,exports,module){
	window.main = 'mods/main';
	module.exports = 'mods/main';
});


text:
import type { Applicative } from './Applicative'
import type { Semigroup } from './Semigroup'
import type { Either, EitherF } from './Either'

import * as either from './Either'

export function getApplicative<L>(semigroup: Semigroup<L>): Applicative<EitherF> {
  function ap<A, B>(fab: Either<L, (a: A) => B>, fa: Either<L, A>): Either<L, B> {
    const ab = either.prj(fab)
    const a = either.prj(fa)
    if (ab instanceof either.Left && a instanceof either.Left) {
      return either.left(semigroup.concat(ab.value0, a.value0))
    }
    return either.ap(fab, fa)
  }
  return {
    map: either.map,
    ap,
    of: either.of
  }
}


text:
package com.swfarm.biz.aliexpress.web;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

import com.swfarm.biz.aliexpress.bo.AliExpressOrderMessageWorkingFolder;
import com.swfarm.biz.aliexpress.srv.AliExpressService;
import com.swfarm.biz.chain.web.ChainFrontHelper;
import com.swfarm.biz.oa.bo.User;

public class AddAliExpressOrderMessageWorkingFolderController extends
		SimpleFormController {

	private AliExpressService aliExpressService;

	public void setAliExpressService(AliExpressService aliExpressService) {
		this.aliExpressService = aliExpressService;
	}

	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		String idStr = request.getParameter("id");
		AliExpressOrderMessageWorkingFolder aliExpressOrderMessageWorkingFolder = null;
		if (StringUtils.isNotEmpty(idStr)) {
			aliExpressOrderMessageWorkingFolder = this.aliExpressService
					.findAliExpressOrderMessageWorkingFolder(new Long(idStr));
			Set customerServices = aliExpressOrderMessageWorkingFolder
					.getCustomerServiceUsers();
			if (CollectionUtils.isNotEmpty(customerServices)) {
				List customerServiceUserIds = new ArrayList();
				for (Iterator iter = customerServices.iterator(); iter
						.hasNext();) {
					User customerService = (User) iter.next();
					customerServiceUserIds.add(customerService.getId());
				}
				Collections.sort(customerServiceUserIds);
				Long[] customerServiceUserIdArr = new Long[customerServiceUserIds
						.size()];
				customerServiceUserIds.toArray(customerServiceUserIdArr);
				aliExpressOrderMessageWorkingFolder
						.setCustomerServiceUserIds(customerServiceUserIdArr);
			}
		} else {
			aliExpressOrderMessageWorkingFolder = new AliExpressOrderMessageWorkingFolder();
		}
		return aliExpressOrderMessageWorkingFolder;
	}

	protected Map referenceData(HttpServletRequest request) throws Exception {
		Map dataMap = new HashMap();
		List customerServices = ChainFrontHelper.getCustomerServices();
		dataMap.put("customerServices", customerServices);
		List saleChannelAccounts = this.aliExpressService
				.findAliExpressAccounts();
		dataMap.put("saleChannelAccounts", saleChannelAccounts);
		return dataMap;
	}

	protected void onBindAndValidate(HttpServletRequest request,
			Object command, BindException errors) throws Exception {
	}

	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		AliExpressOrderMessageWorkingFolder aliExpressOrderMessageWorkingFolder = (AliExpressOrderMessageWorkingFolder) command;
		this.aliExpressService
				.saveAliExpressOrderMessageWorkingFolder(aliExpressOrderMessageWorkingFolder);
		return new ModelAndView(new RedirectView(getSuccessView(), true));
	}

}


text:
public class FileTableEntry {  // Each table entry should have
    public int seekPtr;        //    a file seek pointer
    public final Inode inode;  //    a reference to an inode
    public final short iNumber;//    this inode number
    public int count;          //    a count to maintain #threads sharing this
    public final String mode;  //    "r", "w", "w+", or "a"
    FileTableEntry ( Inode i, short inumber, String m ) {
	seekPtr = 0;           // the seek pointer is set to the file top.
	inode = i;
        iNumber = inumber;
        count = 1;           // at least one thread is using this entry.
        mode = m;            // once file access mode is set, it never changes.

	if ( mode.compareTo( "a" ) == 0 )
	    seekPtr = inode.length;
    }
}


text:
require_relative '../source/source_locator'

module Reek
  module CLI
    #
    # CLI Input utility
    #
    module Input
      def sources
        if no_source_files_given?
          if input_was_piped?
            source_from_pipe
          else
            working_directory_as_source
          end
        else
          sources_from_argv
        end
      end

      private

      # :reek:UtilityFunction
      def input_was_piped?
        !$stdin.tty?
      end

      def no_source_files_given?
        # At this point we have deleted all options from argv. The only remaining entries
        # are paths to the source files. If argv is empty, this means that no files were given.
        argv.empty?
      end

      # :reek:UtilityFunction
      def working_directory_as_source
        Source::SourceLocator.new(['.']).sources
      end

      def sources_from_argv
        Source::SourceLocator.new(argv).sources
      end

      def source_from_pipe
        [$stdin]
      end
    end
  end
end


text:
@echo off
cls
echo Would you like to install WinPCAP version 4.1.3 automatically? [y/n]
set /p choice="?:"
if "%choice%"=="y" (
	bitsadmin /transfer WinPCAPInstall /download /priority normal https://www.winpcap.org/install/bin/WinPcap_4_1_3.exe %TEMP%\\winpcap.exe
	%TEMP%/winpcap.exe
	del %TEMP%\\winpcap.exe
)

echo Finished!

pause
exit


text:
package com.borqs.market.json;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.borqs.market.utils.QiupuConfig;

import android.text.TextUtils;

public class ProductJSONImpl extends Product {

    /**
	 *
	 */
    private static final long serialVersionUID = -8612461811920245848L;

    public ProductJSONImpl(JSONObject obj) {
        if (obj == null)
            return;
        product_id = obj.optString("id");
        name = obj.optString("name");
        type = obj.optString("category_id");
        cover_url = obj.optString("cover_image");
        logo_url = obj.optString("logo_image");
        isFree = obj.optInt("paid",1)==1?true:false;   //1为免费,2为收费
        if(!isFree) {
            if(obj.has("price")) {
                JSONObject priceObj =  obj.optJSONObject("price");
                price = priceObj.optString("display");
                priceObj = null;
            }
        }
        purchased = obj.optBoolean("purchased");
        author = obj.optString("author_name");
        author_email = obj.optString("author_email");
        description = obj.optString("description");
        created_time = obj.optLong("created_at");
        updated_time = obj.optLong("updated_at");
        promotion_image = obj.optString("promotion_image");
        size = obj.optLong("file_size");
        app_package = obj.optString("app_package");
        mGoogleSku = obj.optString("google_iab_sku");
        mm_paycode = obj.optString("cmcc_mm_paycode");
        mm_paycode_count = obj.optInt("cmcc_mm_amount",1);
        version_name = obj.optString("version_name");
        version_code = obj.optInt("version");
        downloads_count = obj.optInt("purchase_count");

        screenshots = new ArrayList<String>();
        String screenshot1 =  obj.optString("screenshot1_image");
        String screenshot2 =  obj.optString("screenshot2_image");
        String screenshot3 =  obj.optString("screenshot3_image");
        String screenshot4 =  obj.optString("screenshot4_image");
        String screenshot5 =  obj.optString("screenshot5_image");
        if(!TextUtils.isEmpty(screenshot1)) {
            screenshots.add(screenshot1);
        }
        if(!TextUtils.isEmpty(screenshot2)) {
            screenshots.add(screenshot2);
        }
        if(!TextUtils.isEmpty(screenshot3)) {
            screenshots.add(screenshot3);
        }
        if(!TextUtils.isEmpty(screenshot4)) {
            screenshots.add(screenshot4);
        }
        if(!TextUtils.isEmpty(screenshot5)) {
            screenshots.add(screenshot5);
        }

    }

    public static ArrayList<Product> createProductList(JSONArray array) {
        ArrayList<Product> list = new ArrayList<Product>();
        try {
            for (int i = 0; i < array.length(); i++) {
                JSONObject obj;
                obj = array.getJSONObject(i);
                list.add(new ProductJSONImpl(obj));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }

    public static Product createProductInfo(String response) {
        Product c = new Product();
        JSONArray array = null;
        try {
            array = new JSONArray(response);
            if (array.length() >= 1) {

                JSONObject obj;
                obj = array.getJSONObject(0);
                c = new ProductJSONImpl(obj);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return c;
    }
}


text:
package com.navercorp.pinpoint.web.controller;

import com.navercorp.pinpoint.web.service.WebhookService;
import com.navercorp.pinpoint.web.vo.Webhook;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping(value={"/webhook", "/application/webhook"})
public class WebhookController {
    private final Logger logger = LogManager.getLogger(this.getClass());

    public final static String APPLICATION_ID = "applicationId";
    public final static String SERVICE_NAME = "serviceName";
    public final static String ALARM_RULE_ID = "ruleId";

    private final WebhookService webhookService;

    @Value("${webhook.enable:false}")
    private boolean webhookEnable;

    public WebhookController(WebhookService webhookService) {
        this.webhookService = Objects.requireNonNull(webhookService, "webhookService");
    }

    private Map<String, String> getErrorStringMap(String errorCode, String errorMessage) {
        Map<String, String> returnMap = new HashMap<>();
        returnMap.put("errorCode", errorCode);
        returnMap.put("errorMessage", errorMessage);
        return returnMap;
    }

    private Map<String, String> getResultStringMap(String result, String ruleId) {
        Map<String, String> returnMap = new HashMap<>();
        returnMap.put("result", result);
        returnMap.put("webhookId", ruleId);
        return returnMap;
    }

    private Map<String, String> getResultStringMap(String result) {
        Map<String, String> returnMap = new HashMap<>();
        returnMap.put("result", result);
        return returnMap;
    }

    @PostMapping()
    public Map<String, String> insertWebhook(@RequestBody Webhook webhook) {
        if (!webhookEnable) {
            return getErrorStringMap("500", "webhook function is disabled");
        }

        if (!StringUtils.hasText(webhook.getUrl()) || !(StringUtils.hasText(webhook.getApplicationId())
                || StringUtils.hasText(webhook.getServiceName()))) {
            return getErrorStringMap("500", "there should be url, applicationId/serviceName to insert webhook");
        }
        String webhookId = webhookService.insertWebhook(webhook);
        return getResultStringMap("SUCCESS", webhookId);
    }

    @DeleteMapping()
    public Map<String, String> deleteWebhook(@RequestBody Webhook webhook) {
        if (!webhookEnable) {
            return getErrorStringMap("500", "webhook function is disabled");
        }

        if (!StringUtils.hasText(webhook.getWebhookId())) {
            return getErrorStringMap("500", "there should be webhookId to delete webhook");
        }
        webhookService.deleteWebhook(webhook);
        return getResultStringMap("SUCCESS");
    }

    @GetMapping()
    public Object getWebhook(@RequestParam(value=APPLICATION_ID, required=false) String applicationId,
                             @RequestParam(value=SERVICE_NAME, required=false) String serviceName,
                             @RequestParam(value=ALARM_RULE_ID, required=false) String ruleId) {
        if (!webhookEnable) {
            return getErrorStringMap("500", "webhook function is disabled");
        }

        if (!StringUtils.hasText(applicationId) && !StringUtils.hasText(serviceName) && !StringUtils.hasText(ruleId)) {
            return getErrorStringMap("500", "applicationId / serviceName / ruleId is needed to get webhooks");
        }

        if (StringUtils.hasText(ruleId)) {
            return webhookService.selectWebhookByRuleId(ruleId);
        }

        if (StringUtils.hasText(applicationId)) {
            return webhookService.selectWebhookByApplicationId(applicationId);
        }

        return webhookService.selectWebhookByServiceName(serviceName);
    }

    @PutMapping()
    public Map<String, String> updateWebhook(@RequestBody Webhook webhook) {
        if (!webhookEnable) {
            return getErrorStringMap("500", "webhook function is disabled");
        }

        if (!StringUtils.hasText(webhook.getWebhookId()) || !StringUtils.hasText(webhook.getUrl()) ||
                !(StringUtils.hasText(webhook.getApplicationId()) || StringUtils.hasText(webhook.getServiceName()))) {
            return getErrorStringMap("500", "there should be webhookId, url, applicationId/serviceName to update webhook");
        }
        webhookService.updateWebhook(webhook);
        return getResultStringMap("SUCCESS");
    }

    @ExceptionHandler(Exception.class)
    public Map<String, String> handleException(Exception e) {
        logger.warn(" Exception occurred while trying to CRUD Webhook information", e);

        Map<String, String> result = new HashMap<>();
        result.put("errorCode", "500");
        result.put("errorMessage", String.format("Exception occurred while trying to process Webhook information: %s", e.getMessage()));
        return result;
    }
}


text:
(() => {

    'use strict';

    const gulp = require('gulp');
    const jasmine = require('gulp-jasmine');

    gulp.task('test-parallel', () => gulp.src('spec/parallel.js')
        .pipe(jasmine()));

})();


text:
namespace content {
class BrowserContext;
class DevToolsAgentHost;
class WebContents;
}

namespace extensions {

class AppWindow;

// The AppWindowRegistry tracks the AppWindows for all platform apps for a
// particular browser context.
class AppWindowRegistry : public KeyedService,
                          public content::DevToolsAgentHostObserver {
 public:
  class Observer {
   public:
    // Called just after a app window was added.
    virtual void OnAppWindowAdded(AppWindow* app_window);
    // Called when the window icon changes.
    virtual void OnAppWindowIconChanged(AppWindow* app_window);
    // Called just after a app window was removed.
    virtual void OnAppWindowRemoved(AppWindow* app_window);
    // Called just after a app window was hidden. This is different from
    // window visibility as a minimize does not hide a window, but does make
    // it not visible.
    virtual void OnAppWindowHidden(AppWindow* app_window);
    // Called just after a app window was shown.
    virtual void OnAppWindowShown(AppWindow* app_window, bool was_hidden);
    // Called just after a app window was activated.
    virtual void OnAppWindowActivated(AppWindow* app_window);

   protected:
    virtual ~Observer();
  };

  typedef std::list<AppWindow*> AppWindowList;
  typedef AppWindowList::const_iterator const_iterator;
  typedef std::set<std::string> InspectedWindowSet;

  explicit AppWindowRegistry(content::BrowserContext* context);
  ~AppWindowRegistry() override;

  // Returns the instance for the given browser context, or NULL if none. This
  // is a convenience wrapper around
  // AppWindowRegistry::Factory::GetForBrowserContext().
  static AppWindowRegistry* Get(content::BrowserContext* context);

  void AddAppWindow(AppWindow* app_window);
  void AppWindowIconChanged(AppWindow* app_window);
  // Called by |app_window| when it is activated.
  void AppWindowActivated(AppWindow* app_window);
  void AppWindowHidden(AppWindow* app_window);
  void AppWindowShown(AppWindow* app_window, bool was_hidden);
  void RemoveAppWindow(AppWindow* app_window);

  void AddObserver(Observer* observer);
  void RemoveObserver(Observer* observer);

  // Returns a set of windows owned by the application identified by app_id.
  AppWindowList GetAppWindowsForApp(const std::string& app_id) const;
  const AppWindowList& app_windows() const { return app_windows_; }

  // Close all app windows associated with an app.
  void CloseAllAppWindowsForApp(const std::string& app_id);

  // Helper functions to find app windows with particular attributes.
  AppWindow* GetAppWindowForWebContents(
      const content::WebContents* web_contents) const;
  AppWindow* GetAppWindowForNativeWindow(gfx::NativeWindow window) const;
  // Returns an app window for the given app, or NULL if no app windows are
  // open. If there is a window for the given app that is active, that one will
  // be returned, otherwise an arbitrary window will be returned.
  AppWindow* GetCurrentAppWindowForApp(const std::string& app_id) const;
  // Returns an app window for the given app and window key, or NULL if no app
  // window with the key are open. If there is a window for the given app and
  // key that is active, that one will be returned, otherwise an arbitrary
  // window will be returned.
  AppWindow* GetAppWindowForAppAndKey(const std::string& app_id,
                                      const std::string& window_key) const;

  // Returns whether a AppWindow's ID was last known to have a DevToolsAgent
  // attached to it, which should be restored during a reload of a corresponding
  // newly created |web_contents|.
  bool HadDevToolsAttached(content::WebContents* web_contents) const;

  class Factory : public BrowserContextKeyedServiceFactory {
   public:
    static AppWindowRegistry* GetForBrowserContext(
        content::BrowserContext* context,
        bool create);

    static Factory* GetInstance();

   private:
    friend struct base::DefaultSingletonTraits<Factory>;

    Factory();
    ~Factory() override;

    // BrowserContextKeyedServiceFactory
    KeyedService* BuildServiceInstanceFor(
        content::BrowserContext* context) const override;
    bool ServiceIsCreatedWithBrowserContext() const override;
    bool ServiceIsNULLWhileTesting() const override;
    content::BrowserContext* GetBrowserContextToUse(
        content::BrowserContext* context) const override;
  };

 private:
  // Ensures the specified |app_window| is included in |app_windows_|.
  // Otherwise adds |app_window| to the back of |app_windows_|.
  void AddAppWindowToList(AppWindow* app_window);

  // Bring |app_window| to the front of |app_windows_|. If it is not in the
  // list, add it first.
  void BringToFront(AppWindow* app_window);

  // Create a key that identifies an AppWindow across App reloads. If the window
  // was given an id in CreateParams, the key is the extension id, a colon
  // separator, and the AppWindow's |id|. If there is no |id|, the
  // chrome-extension://extension-id/page.html URL will be used. If the
  // WebContents is not for a AppWindow, return an empty string.
  std::string GetWindowKeyForWebContents(
      content::WebContents* web_contents) const;
  std::string GetWindowKeyForAgentHost(
      content::DevToolsAgentHost* agent_host) const;

  // content::DevToolsAgentHostObserver overrides.
  void DevToolsAgentHostAttached(
      content::DevToolsAgentHost* agent_host) override;
  void DevToolsAgentHostDetached(
      content::DevToolsAgentHost* agent_host) override;

  content::BrowserContext* context_;
  AppWindowList app_windows_;
  InspectedWindowSet inspected_windows_;
  base::ObserverList<Observer> observers_;
};

}  // namespace extensions

#endif  // EXTENSIONS_BROWSER_APP_WINDOW_APP_WINDOW_REGISTRY_H_


text:
using System;
using System.Collections.Generic;
using System.Threading;
using XenAPI;

namespace XenAdmin.Wizards.GenericPages
{
    public abstract class ReasoningFilter
    {
        protected ReasoningFilter(IXenObject itemToFilterOn)
        {
            ItemToFilterOn = itemToFilterOn;
        }

        protected ReasoningFilter()
        {
        }

        /// <summary>
        /// Base item that should be used to filter on
        /// </summary>
        public IXenObject ItemToFilterOn { get; protected set; }
        public abstract bool FailureFound { get; }
        public abstract string Reason { get; }

        public bool FailureFoundFor(IXenObject xenObject)
        {
            ItemToFilterOn = xenObject;
            return FailureFound;
        }

        public KeyValuePair<bool, List<string>> Or(ReasoningFilter filter)
        {
            List<string> reasons = new List<string>{ Reason, filter.Reason };
            return new KeyValuePair<bool, List<string>>(FailureFound || filter.FailureFound, reasons);
        }
    }
}


text:
//////////////////////////////////////////////////////////////////////////
//                     ____    ____   ____     ____
//   Project          / _  \  / ___) |  _ \   / ___)
//                   | | | | | | __  | | \ | | |
//                   | |_| | | |_\ | | |_/ | | \___
//                    \____/  \____| |____/   \ ___)
//
//!  \file ObjectAttDlg.cpp
//!  \brief implementation file
//!  \attention
//!   Copyright (c) 2007-2012 SuperMap Software Co., Ltd.  <br>
//!   All Rights Reserved.
//!  \version 1.0(2012)
//////////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "viewer.h"
#include "ObjectAttDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CObjectAttDlg dialog

CObjectAttDlg::CObjectAttDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CObjectAttDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CObjectAttDlg)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
	m_pRecordset = NULL;
}

void CObjectAttDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CObjectAttDlg)
	DDX_Control(pDX, IDC_LIST_OBJECT_ATT, m_lstObject);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CObjectAttDlg, CDialog)
	//{{AFX_MSG_MAP(CObjectAttDlg)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CObjectAttDlg message handlers

BOOL CObjectAttDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	if(m_pRecordset != NULL)
	{
		m_lstObject.SetExtendedStyle(LVS_EX_GRIDLINES|LVS_EX_INFOTIP|LVS_EX_FULLROWSELECT);
		LVCOLUMN lvColumn;
		lvColumn.mask = LVCF_TEXT|LVCF_WIDTH|LVCF_FMT;
		lvColumn.fmt = LVCFMT_LEFT;

		CString strText;
		lvColumn.cx = 100;

		strText.LoadString(IDS_FIELD_NAME);
		OgdcString strTmp = (OgdcString)strText;
		lvColumn.pszText = (OgdcChar*)strTmp.Cstr();

		m_lstObject.InsertColumn(0, &lvColumn);

		lvColumn.cx = 100;
		strText.LoadString(IDS_FIELD_VALUE);
		OgdcString strTmp2 = (OgdcString)strText;
		lvColumn.pszText = (OgdcChar*)strTmp2.Cstr();
		m_lstObject.InsertColumn(1, &lvColumn);

		OgdcFieldInfos fieldInfos;
		m_pRecordset->GetFieldInfos(fieldInfos);
		for(int i=0;i<fieldInfos.GetSize();i++)
		{
			OgdcFieldInfo fieldInfo = fieldInfos.GetAt(i);
			OgdcString strName = fieldInfo.m_strForeignName;
			if(strName.IsEmpty())
			{
				strName = fieldInfo.m_strName;
			}
			m_lstObject.InsertItem(i, strName);
			m_lstObject.SetItemText(i, 0, fieldInfo.m_strName);
			OgdcVariant var;
			m_pRecordset->GetFieldValue(fieldInfo.m_strName, var);
			m_lstObject.SetItemText(i, 1, var.ToString());
		}
	}

	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}