text:
package redis.clients.jedis;

import java.io.Closeable;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Pattern;

import redis.clients.jedis.commands.JedisCommands;
import redis.clients.jedis.params.GeoRadiusParam;
import redis.clients.jedis.params.SetParams;
import redis.clients.jedis.params.ZAddParams;
import redis.clients.jedis.params.ZIncrByParams;
import redis.clients.jedis.util.Hashing;

public class ShardedJedis extends BinaryShardedJedis implements JedisCommands, Closeable {

  protected ShardedJedisPool dataSource = null;

  public ShardedJedis(List<JedisShardInfo> shards) {
    super(shards);
  }

  public ShardedJedis(List<JedisShardInfo> shards, Hashing algo) {
    super(shards, algo);
  }

  public ShardedJedis(List<JedisShardInfo> shards, Pattern keyTagPattern) {
    super(shards, keyTagPattern);
  }

  public ShardedJedis(List<JedisShardInfo> shards, Hashing algo, Pattern keyTagPattern) {
    super(shards, algo, keyTagPattern);
  }

  @Override
  public String set(final String key, final String value) {
    Jedis j = getShard(key);
    return j.set(key, value);
  }

  @Override
  public String set(final String key, final String value, SetParams params) {
    Jedis j = getShard(key);
    return j.set(key, value, params);
  }

  @Override
  public String get(final String key) {
    Jedis j = getShard(key);
    return j.get(key);
  }

  @Override
  public String echo(final String string) {
    Jedis j = getShard(string);
    return j.echo(string);
  }

  @Override
  public Boolean exists(final String key) {
    Jedis j = getShard(key);
    return j.exists(key);
  }

  @Override
  public String type(final String key) {
    Jedis j = getShard(key);
    return j.type(key);
  }

  @Override
  public byte[] dump(final String key) {
    Jedis j = getShard(key);
    return j.dump(key);
  }

  @Override
  public String restore(final String key, final int ttl, final byte[] serializedValue) {
    Jedis j = getShard(key);
    return j.restore(key, ttl, serializedValue);
  }

  @Override
  public String restoreReplace(final String key, final int ttl, final byte[] serializedValue) {
    Jedis j = getShard(key);
    return j.restoreReplace(key, ttl, serializedValue);
  }

  @Override
  public Long expire(final String key, final int seconds) {
    Jedis j = getShard(key);
    return j.expire(key, seconds);
  }

  @Override
  public Long pexpire(final String key, final long milliseconds) {
    Jedis j = getShard(key);
    return j.pexpire(key, milliseconds);
  }

  @Override
  public Long expireAt(final String key, final long unixTime) {
    Jedis j = getShard(key);
    return j.expireAt(key, unixTime);
  }

  @Override
  public Long pexpireAt(final String key, final long millisecondsTimestamp) {
    Jedis j = getShard(key);
    return j.pexpireAt(key, millisecondsTimestamp);
  }

  @Override
  public Long ttl(final String key) {
    Jedis j = getShard(key);
    return j.ttl(key);
  }

  @Override
  public Long pttl(final String key) {
    Jedis j = getShard(key);
    return j.pttl(key);
  }

  @Override
  public Boolean setbit(final String key, final long offset, boolean value) {
    Jedis j = getShard(key);
    return j.setbit(key, offset, value);
  }

  @Override
  public Boolean setbit(final String key, final long offset, final String value) {
    Jedis j = getShard(key);
    return j.setbit(key, offset, value);
  }

  @Override
  public Boolean getbit(final String key, final long offset) {
    Jedis j = getShard(key);
    return j.getbit(key, offset);
  }

  @Override
  public Long setrange(final String key, final long offset, final String value) {
    Jedis j = getShard(key);
    return j.setrange(key, offset, value);
  }

  @Override
  public String getrange(final String key, final long startOffset, final long endOffset) {
    Jedis j = getShard(key);
    return j.getrange(key, startOffset, endOffset);
  }

  @Override
  public String getSet(final String key, final String value) {
    Jedis j = getShard(key);
    return j.getSet(key, value);
  }

  @Override
  public Long setnx(final String key, final String value) {
    Jedis j = getShard(key);
    return j.setnx(key, value);
  }

  @Override
  public String setex(final String key, final int seconds, final String value) {
    Jedis j = getShard(key);
    return j.setex(key, seconds, value);
  }

  @Override
  public String psetex(final String key, final long milliseconds, final String value) {
    Jedis j = getShard(key);
    return j.psetex(key, milliseconds, value);
  }

  public List<String> blpop(final String arg) {
    Jedis j = getShard(arg);
    return j.blpop(arg);
  }

  @Override
  public List<String> blpop(final int timeout, final String key) {
    Jedis j = getShard(key);
    return j.blpop(timeout, key);
  }

  public List<String> brpop(final String arg) {
    Jedis j = getShard(arg);
    return j.brpop(arg);
  }

  @Override
  public List<String> brpop(final int timeout, final String key) {
    Jedis j = getShard(key);
    return j.brpop(timeout, key);
  }

  @Override
  public Long decrBy(final String key, final long decrement) {
    Jedis j = getShard(key);
    return j.decrBy(key, decrement);
  }

  @Override
  public Long decr(final String key) {
    Jedis j = getShard(key);
    return j.decr(key);
  }

  @Override
  public Long incrBy(final String key, final long increment) {
    Jedis j = getShard(key);
    return j.incrBy(key, increment);
  }

  @Override
  public Double incrByFloat(final String key, final double increment) {
    Jedis j = getShard(key);
    return j.incrByFloat(key, increment);
  }

  @Override
  public Long incr(final String key) {
    Jedis j = getShard(key);
    return j.incr(key);
  }

  @Override
  public Long append(final String key, final String value) {
    Jedis j = getShard(key);
    return j.append(key, value);
  }

  @Override
  public String substr(final String key, final int start, final int end) {
    Jedis j = getShard(key);
    return j.substr(key, start, end);
  }

  @Override
  public Long hset(final String key, final String field, final String value) {
    Jedis j = getShard(key);
    return j.hset(key, field, value);
  }

  @Override
  public Long hset(final String key, final Map<String, String> hash) {
    Jedis j = getShard(key);
    return j.hset(key, hash);
  }

  @Override
  public String hget(final String key, final String field) {
    Jedis j = getShard(key);
    return j.hget(key, field);
  }

  @Override
  public Long hsetnx(final String key, final String field, final String value) {
    Jedis j = getShard(key);
    return j.hsetnx(key, field, value);
  }

  @Override
  public String hmset(final String key, final Map<String, String> hash) {
    Jedis j = getShard(key);
    return j.hmset(key, hash);
  }

  @Override
  public List<String> hmget(final String key, String... fields) {
    Jedis j = getShard(key);
    return j.hmget(key, fields);
  }

  @Override
  public Long hincrBy(final String key, final String field, final long value) {
    Jedis j = getShard(key);
    return j.hincrBy(key, field, value);
  }

  @Override
  public Double hincrByFloat(final String key, final String field, final double value) {
    Jedis j = getShard(key);
    return j.hincrByFloat(key, field, value);
  }

  @Override
  public Boolean hexists(final String key, final String field) {
    Jedis j = getShard(key);
    return j.hexists(key, field);
  }

  @Override
  public Long del(final String key) {
    Jedis j = getShard(key);
    return j.del(key);
  }

  @Override
  public Long unlink(final String key) {
    Jedis j = getShard(key);
    return j.unlink(key);
  }

  @Override
  public Long hdel(final String key, String... fields) {
    Jedis j = getShard(key);
    return j.hdel(key, fields);
  }

  @Override
  public Long hlen(final String key) {
    Jedis j = getShard(key);
    return j.hlen(key);
  }

  @Override
  public Set<String> hkeys(final String key) {
    Jedis j = getShard(key);
    return j.hkeys(key);
  }

  @Override
  public List<String> hvals(final String key) {
    Jedis j = getShard(key);
    return j.hvals(key);
  }

  @Override
  public Map<String, String> hgetAll(final String key) {
    Jedis j = getShard(key);
    return j.hgetAll(key);
  }

  @Override
  public Long rpush(final String key, String... strings) {
    Jedis j = getShard(key);
    return j.rpush(key, strings);
  }

  @Override
  public Long lpush(final String key, String... strings) {
    Jedis j = getShard(key);
    return j.lpush(key, strings);
  }

  @Override
  public Long lpushx(final String key, String... string) {
    Jedis j = getShard(key);
    return j.lpushx(key, string);
  }

  @Override
  public Long strlen(final String key) {
    Jedis j = getShard(key);
    return j.strlen(key);
  }

  @Override
  public Long move(final String key, final int dbIndex) {
    Jedis j = getShard(key);
    return j.move(key, dbIndex);
  }

  @Override
  public Long rpushx(final String key, String... string) {
    Jedis j = getShard(key);
    return j.rpushx(key, string);
  }

  @Override
  public Long persist(final String key) {
    Jedis j = getShard(key);
    return j.persist(key);
  }

  @Override
  public Long llen(final String key) {
    Jedis j = getShard(key);
    return j.llen(key);
  }

  @Override
  public List<String> lrange(final String key, final long start, final long stop) {
    Jedis j = getShard(key);
    return j.lrange(key, start, stop);
  }

  @Override
  public String ltrim(final String key, final long start, final long stop) {
    Jedis j = getShard(key);
    return j.ltrim(key, start, stop);
  }

  @Override
  public String lindex(final String key, final long index) {
    Jedis j = getShard(key);
    return j.lindex(key, index);
  }

  @Override
  public String lset(final String key, final long index, final String value) {
    Jedis j = getShard(key);
    return j.lset(key, index, value);
  }

  @Override
  public Long lrem(final String key, final long count, final String value) {
    Jedis j = getShard(key);
    return j.lrem(key, count, value);
  }

  @Override
  public String lpop(final String key) {
    Jedis j = getShard(key);
    return j.lpop(key);
  }

  @Override
  public String rpop(final String key) {
    Jedis j = getShard(key);
    return j.rpop(key);
  }

  @Override
  public Long sadd(final String key, String... members) {
    Jedis j = getShard(key);
    return j.sadd(key, members);
  }

  @Override
  public Set<String> smembers(final String key) {
    Jedis j = getShard(key);
    return j.smembers(key);
  }

  @Override
  public Long srem(final String key, String... members) {
    Jedis j = getShard(key);
    return j.srem(key, members);
  }

  @Override
  public String spop(final String key) {
    Jedis j = getShard(key);
    return j.spop(key);
  }

  @Override
  public Set<String> spop(final String key, final long count) {
    Jedis j = getShard(key);
    return j.spop(key, count);
  }

  @Override
  public Long scard(final String key) {
    Jedis j = getShard(key);
    return j.scard(key);
  }

  @Override
  public Boolean sismember(final String key, final String member) {
    Jedis j = getShard(key);
    return j.sismember(key, member);
  }

  @Override
  public String srandmember(final String key) {
    Jedis j = getShard(key);
    return j.srandmember(key);
  }

  @Override
  public List<String> srandmember(final String key, final int count) {
    Jedis j = getShard(key);
    return j.srandmember(key, count);
  }

  @Override
  public Long zadd(final String key, final double score, final String member) {
    Jedis j = getShard(key);
    return j.zadd(key, score, member);
  }

  @Override
  public Long zadd(final String key, final double score, final String member, final ZAddParams params) {
    Jedis j = getShard(key);
    return j.zadd(key, score, member, params);
  }

  @Override
  public Long zadd(final String key, final Map<String, Double> scoreMembers) {
    Jedis j = getShard(key);
    return j.zadd(key, scoreMembers);
  }

  @Override
  public Long zadd(final String key, final Map<String, Double> scoreMembers, final ZAddParams params) {
    Jedis j = getShard(key);
    return j.zadd(key, scoreMembers, params);
  }

  @Override
  public Set<String> zrange(final String key, final long start, final long stop) {
    Jedis j = getShard(key);
    return j.zrange(key, start, stop);
  }

  @Override
  public Long zrem(final String key, String... members) {
    Jedis j = getShard(key);
    return j.zrem(key, members);
  }

  @Override
  public Double zincrby(final String key, final double increment, final String member) {
    Jedis j = getShard(key);
    return j.zincrby(key, increment, member);
  }

  @Override
  public Double zincrby(final String key, final double increment, final String member, ZIncrByParams params) {
    Jedis j = getShard(key);
    return j.zincrby(key, increment, member, params);
  }

  @Override
  public Long zrank(final String key, final String member) {
    Jedis j = getShard(key);
    return j.zrank(key, member);
  }

  @Override
  public Long zrevrank(final String key, final String member) {
    Jedis j = getShard(key);
    return j.zrevrank(key, member);
  }

  @Override
  public Set<String> zrevrange(final String key, final long start, final long stop) {
    Jedis j = getShard(key);
    return j.zrevrange(key, start, stop);
  }

  @Override
  public Set<Tuple> zrangeWithScores(final String key, final long start, final long stop) {
    Jedis j = getShard(key);
    return j.zrangeWithScores(key, start, stop);
  }

  @Override
  public Set<Tuple> zrevrangeWithScores(final String key, final long start, final long stop) {
    Jedis j = getShard(key);
    return j.zrevrangeWithScores(key, start, stop);
  }

  @Override
  public Long zcard(final String key) {
    Jedis j = getShard(key);
    return j.zcard(key);
  }

  @Override
  public Double zscore(final String key, final String member) {
    Jedis j = getShard(key);
    return j.zscore(key, member);
  }

  @Override
  public List<String> sort(final String key) {
    Jedis j = getShard(key);
    return j.sort(key);
  }

  @Override
  public List<String> sort(final String key, final SortingParams sortingParameters) {
    Jedis j = getShard(key);
    return j.sort(key, sortingParameters);
  }

  @Override
  public Long zcount(final String key, final double min, final double max) {
    Jedis j = getShard(key);
    return j.zcount(key, min, max);
  }

  @Override
  public Long zcount(final String key, final String min, final String max) {
    Jedis j = getShard(key);
    return j.zcount(key, min, max);
  }

  @Override
  public Set<String> zrangeByScore(final String key, final double min, final double max) {
    Jedis j = getShard(key);
    return j.zrangeByScore(key, min, max);
  }

  @Override
  public Set<String> zrevrangeByScore(final String key, final double max, final double min) {
    Jedis j = getShard(key);
    return j.zrevrangeByScore(key, max, min);
  }

  @Override
  public Set<String> zrangeByScore(final String key, final double min, final double max, final int offset, final int count) {
    Jedis j = getShard(key);
    return j.zrangeByScore(key, min, max, offset, count);
  }

  @Override
  public Set<String> zrevrangeByScore(final String key, final double max, final double min, final int offset, final int count) {
    Jedis j = getShard(key);
    return j.zrevrangeByScore(key, max, min, offset, count);
  }

  @Override
  public Set<Tuple> zrangeByScoreWithScores(final String key, final double min, final double max) {
    Jedis j = getShard(key);
    return j.zrangeByScoreWithScores(key, min, max);
  }

  @Override
  public Set<Tuple> zrevrangeByScoreWithScores(final String key, final double max, final double min) {
    Jedis j = getShard(key);
    return j.zrevrangeByScoreWithScores(key, max, min);
  }

  @Override
  public Set<Tuple> zrangeByScoreWithScores(final String key, final double min, final double max, final int offset,
      final int count) {
    Jedis j = getShard(key);
    return j.zrangeByScoreWithScores(key, min, max, offset, count);
  }

  @Override
  public Set<Tuple> zrevrangeByScoreWithScores(final String key, final double max, final double min, final int offset,
      final int count) {
    Jedis j = getShard(key);
    return j.zrevrangeByScoreWithScores(key, max, min, offset, count);
  }

  @Override
  public Set<String> zrangeByScore(final String key, final String min, final String max) {
    Jedis j = getShard(key);
    return j.zrangeByScore(key, min, max);
  }

  @Override
  public Set<String> zrevrangeByScore(final String key, final String max, final String min) {
    Jedis j = getShard(key);
    return j.zrevrangeByScore(key, max, min);
  }

  @Override
  public Set<String> zrangeByScore(final String key, final String min, final String max, final int offset, final int count) {
    Jedis j = getShard(key);
    return j.zrangeByScore(key, min, max, offset, count);
  }

  @Override
  public Set<String> zrevrangeByScore(final String key, final String max, final String min, final int offset, final int count) {
    Jedis j = getShard(key);
    return j.zrevrangeByScore(key, max, min, offset, count);
  }

  @Override
  public Set<Tuple> zrangeByScoreWithScores(final String key, final String min, final String max) {
    Jedis j = getShard(key);
    return j.zrangeByScoreWithScores(key, min, max);
  }

  @Override
  public Set<Tuple> zrevrangeByScoreWithScores(final String key, final String max, final String min) {
    Jedis j = getShard(key);
    return j.zrevrangeByScoreWithScores(key, max, min);
  }

  @Override
  public Set<Tuple> zrangeByScoreWithScores(final String key, final String min, final String max, final int offset,
      final int count) {
    Jedis j = getShard(key);
    return j.zrangeByScoreWithScores(key, min, max, offset, count);
  }

  @Override
  public Set<Tuple> zrevrangeByScoreWithScores(final String key, final String max, final String min, final int offset,
      final int count) {
    Jedis j = getShard(key);
    return j.zrevrangeByScoreWithScores(key, max, min, offset, count);
  }

  @Override
  public Long zremrangeByRank(final String key, final long start, final long stop) {
    Jedis j = getShard(key);
    return j.zremrangeByRank(key, start, stop);
  }

  @Override
  public Long zremrangeByScore(final String key, final double min, final double max) {
    Jedis j = getShard(key);
    return j.zremrangeByScore(key, min, max);
  }

  @Override
  public Long zremrangeByScore(final String key, final String min, final String max) {
    Jedis j = getShard(key);
    return j.zremrangeByScore(key, min, max);
  }

  @Override
  public Long zlexcount(final String key, final String min, final String max) {
    return getShard(key).zlexcount(key, min, max);
  }

  @Override
  public Set<String> zrangeByLex(final String key, final String min, final String max) {
    return getShard(key).zrangeByLex(key, min, max);
  }

  @Override
  public Set<String> zrangeByLex(final String key, final String min, final String max,
      final int offset, final int count) {
    return getShard(key).zrangeByLex(key, min, max, offset, count);
  }

  @Override
  public Set<String> zrevrangeByLex(final String key, final String max, final String min) {
    return getShard(key).zrevrangeByLex(key, max, min);
  }

  @Override
  public Set<String> zrevrangeByLex(final String key, final String max, final String min, final int offset, final int count) {
    return getShard(key).zrevrangeByLex(key, max, min, offset, count);
  }

  @Override
  public Long zremrangeByLex(final String key, final String min, final String max) {
    return getShard(key).zremrangeByLex(key, min, max);
  }

  @Override
  public Long linsert(final String key, final ListPosition where, final String pivot, final String value) {
    Jedis j = getShard(key);
    return j.linsert(key, where, pivot, value);
  }

  @Override
  public Long bitcount(final String key) {
    Jedis j = getShard(key);
    return j.bitcount(key);
  }

  @Override
  public Long bitcount(final String key, final long start, final long end) {
    Jedis j = getShard(key);
    return j.bitcount(key, start, end);
  }

  @Override
  public Long bitpos(final String key, final boolean value) {
    Jedis j = getShard(key);
    return j.bitpos(key, value);
  }

  @Override
  public Long bitpos(final String key, boolean value, final BitPosParams params) {
    Jedis j = getShard(key);
    return j.bitpos(key, value, params);
  }

  @Override
  public ScanResult<Entry<String, String>> hscan(final String key, final String cursor) {
    Jedis j = getShard(key);
    return j.hscan(key, cursor);
  }

  @Override
  public ScanResult<Entry<String, String>> hscan(final String key, final String cursor, final ScanParams params) {
    Jedis j = getShard(key);
    return j.hscan(key, cursor, params);
  }

  @Override
  public ScanResult<String> sscan(final String key, final String cursor) {
    Jedis j = getShard(key);
    return j.sscan(key, cursor);
  }

  @Override
  public ScanResult<Tuple> zscan(final String key, final String cursor) {
    Jedis j = getShard(key);
    return j.zscan(key, cursor);
  }

  @Override
  public ScanResult<Tuple> zscan(final String key, final String cursor, final ScanParams params) {
    Jedis j = getShard(key);
    return j.zscan(key, cursor, params);
  }

  @Override
  public ScanResult<String> sscan(final String key, final String cursor, final ScanParams params) {
    Jedis j = getShard(key);
    return j.sscan(key, cursor, params);
  }

  @Override
  public void close() {
    if (dataSource != null) {
      boolean broken = false;

      for (Jedis jedis : getAllShards()) {
        if (jedis.getClient().isBroken()) {
          broken = true;
          break;
        }
      }
      ShardedJedisPool pool = this.dataSource;
      this.dataSource = null;
      if (broken) {
        pool.returnBrokenResource(this);
      } else {
        pool.returnResource(this);
      }

    } else {
      disconnect();
    }
  }

  public void setDataSource(ShardedJedisPool shardedJedisPool) {
    this.dataSource = shardedJedisPool;
  }

  public void resetState() {
    for (Jedis jedis : getAllShards()) {
      jedis.resetState();
    }
  }

  @Override
  public Long pfadd(final String key, final String... elements) {
    Jedis j = getShard(key);
    return j.pfadd(key, elements);
  }

  @Override
  public Long pfcount(final String key) {
    Jedis j = getShard(key);
    return j.pfcount(key);
  }

  @Override
  public Long touch(final String key) {
    Jedis j = getShard(key);
    return j.touch(key);
  }

  @Override
  public Long geoadd(final String key, final double longitude, final double latitude, final String member) {
    Jedis j = getShard(key);
    return j.geoadd(key, longitude, latitude, member);
  }

  @Override
  public Long geoadd(final String key, final Map<String, GeoCoordinate> memberCoordinateMap) {
    Jedis j = getShard(key);
    return j.geoadd(key, memberCoordinateMap);
  }

  @Override
  public Double geodist(final String key, final String member1, final String member2) {
    Jedis j = getShard(key);
    return j.geodist(key, member1, member2);
  }

  @Override
  public Double geodist(final String key, final String member1, final String member2, final GeoUnit unit) {
    Jedis j = getShard(key);
    return j.geodist(key, member1, member2, unit);
  }

  @Override
  public List<String> geohash(final String key, final String... members) {
    Jedis j = getShard(key);
    return j.geohash(key, members);
  }

  @Override
  public List<GeoCoordinate> geopos(final String key, final String... members) {
    Jedis j = getShard(key);
    return j.geopos(key, members);
  }

  @Override
  public List<GeoRadiusResponse> georadius(final String key, final double longitude, final double latitude,
      final double radius, final GeoUnit unit) {
    Jedis j = getShard(key);
    return j.georadius(key, longitude, latitude, radius, unit);
  }

  @Override
  public List<GeoRadiusResponse> georadiusReadonly(final String key, final double longitude, final double latitude,
      final double radius, final GeoUnit unit) {
    Jedis j = getShard(key);
    return j.georadiusReadonly(key, longitude, latitude, radius, unit);
  }

  @Override
  public List<GeoRadiusResponse> georadius(final String key, final double longitude, final double latitude,
      final double radius, final GeoUnit unit, final GeoRadiusParam param) {
    Jedis j = getShard(key);
    return j.georadius(key, longitude, latitude, radius, unit, param);
  }

  @Override
  public List<GeoRadiusResponse> georadiusReadonly(final String key, final double longitude, final double latitude,
      final double radius, final GeoUnit unit, final GeoRadiusParam param) {
    Jedis j = getShard(key);
    return j.georadiusReadonly(key, longitude, latitude, radius, unit, param);
  }

  @Override
  public List<GeoRadiusResponse> georadiusByMember(final String key, final String member, final double radius,
      final GeoUnit unit) {
    Jedis j = getShard(key);
    return j.georadiusByMember(key, member, radius, unit);
  }

  @Override
  public List<GeoRadiusResponse> georadiusByMemberReadonly(final String key, final String member, final double radius,
      final GeoUnit unit) {
    Jedis j = getShard(key);
    return j.georadiusByMemberReadonly(key, member, radius, unit);
  }

  @Override
  public List<GeoRadiusResponse> georadiusByMember(final String key, final String member, final double radius,
      final GeoUnit unit, final GeoRadiusParam param) {
    Jedis j = getShard(key);
    return j.georadiusByMember(key, member, radius, unit, param);
  }

  @Override
  public List<GeoRadiusResponse> georadiusByMemberReadonly(final String key, final String member, final double radius,
      final GeoUnit unit, final GeoRadiusParam param) {
    Jedis j = getShard(key);
    return j.georadiusByMemberReadonly(key, member, radius, unit, param);
  }

  @Override
  public List<Long> bitfield(final String key, final String... arguments) {
    Jedis j = getShard(key);
    return j.bitfield(key, arguments);
  }

  @Override
  public Long hstrlen(final String key, final String field) {
    Jedis j = getShard(key);
    return j.hstrlen(key, field);
  }

  @Override
  public StreamEntryID xadd(String key, StreamEntryID id, Map<String, String> hash) {
    Jedis j = getShard(key);
    return j.xadd(key, id, hash);
  }

  @Override
  public StreamEntryID xadd(String key, StreamEntryID id, Map<String, String> hash, long maxLen, boolean approximateLength) {
    Jedis j = getShard(key);
    return j.xadd(key, id, hash, maxLen, approximateLength);
  }

  @Override
  public Long xlen(String key) {
    Jedis j = getShard(key);
    return j.xlen(key);
  }

  @Override
  public List<StreamEntry> xrange(String key, StreamEntryID start, StreamEntryID end, int count) {
    Jedis j = getShard(key);
    return j.xrange(key, start, end, count);
  }

  @Override
  public long xack(String key, String group, StreamEntryID... ids) {
    Jedis j = getShard(key);
    return j.xack(key, group, ids);
  }

  @Override
  public String xgroupCreate(String key, String consumer, StreamEntryID id, boolean makeStream) {
    Jedis j = getShard(key);
    return j.xgroupCreate(key, consumer, id, makeStream);
  }

  @Override
  public String xgroupSetID(String key, String groupname, StreamEntryID id) {
    Jedis j = getShard(key);
    return j.xgroupSetID(key, groupname, id);
  }

  @Override
  public long xgroupDestroy(String key, String groupname) {
    Jedis j = getShard(key);
    return j.xgroupDestroy(key, groupname);
  }

  @Override
  public String xgroupDelConsumer(String key, String groupname, String consumername) {
    Jedis j = getShard(key);
    return j.xgroupDelConsumer(key, groupname, consumername);
  }

  @Override
  public long xdel(String key, StreamEntryID... ids) {
    Jedis j = getShard(key);
    return j.xdel(key, ids);
  }

  @Override
  public long xtrim(String key, long maxLen, boolean approximateLength) {
    Jedis j = getShard(key);
    return j.xtrim(key, maxLen, approximateLength);
  }

  @Override
  public List<StreamEntry> xrevrange(String key, StreamEntryID end, StreamEntryID start, int count) {
    Jedis j = getShard(key);
    return j.xrevrange(key, end, start, count);
  }

  @Override
  public List<StreamPendingEntry> xpending(String key, String groupname, StreamEntryID start, StreamEntryID end,
      int count, String consumername) {
    Jedis j = getShard(key);
    return j.xpending(key, groupname, start, end, count, consumername);
  }

  @Override
  public List<StreamEntry> xclaim(String key, String group, String consumername, long minIdleTime, long newIdleTime,
      int retries, boolean force, StreamEntryID... ids) {
    Jedis j = getShard(key);
    return j.xclaim(key, group, consumername, minIdleTime, newIdleTime, retries, force, ids);
  }
}


text:
@interface TTMFacebookProfile ()
@property (nonatomic, strong) NSString *identifier;
@property (nonatomic, strong) NSString *firstName;
@property (nonatomic, strong) NSString *lastName;
@property (nonatomic, strong) NSString *fullName;
@property (nonatomic, assign) TTMFacebookProfileGenderType gender;
@property (nonatomic, strong) NSString *birthday;
@property (nonatomic, strong) NSString *email;
@property (nonatomic, strong) NSNumber *timeZone;
@property (nonatomic, strong) NSString *link;
@property (nonatomic, strong) NSString *locationId;
@property (nonatomic, strong) NSString *locationName;
@end

@implementation TTMFacebookProfile

- (id)initWithDictionray:(NSDictionary *)profileDic {
    self = [super init];
    if (self) {

        self.identifier = profileDic[@"id"];
        self.firstName = profileDic[@"first_name"];
        self.lastName = profileDic[@"last_name"];
        self.fullName = profileDic[@"name"];

        self.gender = TTMFacebookProfileGenderTypeUnknown;
        NSString *gender = profileDic[@"gender"];
        if ([gender isKindOfClass:[NSString class]]) {
            if ([gender isEqualToString:@"male"]) {
                self.gender = TTMFacebookProfileGenderTypeMale;
            }
            else if ([gender isEqualToString:@"female"]) {
                self.gender = TTMFacebookProfileGenderTypeFemale;
            }
        }

        self.birthday = profileDic[@"birthday"];
        self.email = profileDic[@"email"];
        self.timeZone = profileDic[@"timezone"];
        self.link = profileDic[@"link"];

        NSDictionary *locationDic = profileDic[@"location"];
        self.locationId = locationDic[@"id"];
        self.locationName = locationDic[@"name"];
    }
    return self;
}

- (NSURL *)urlForProfilePictureWithType:(TTMFacebookProfilePictureType)type {

    NSString *typeStr;
    switch (type) {
        case 0:
        default:
            typeStr = @"square";
            break;
        case 1:
            typeStr = @"small";
            break;
        case 2:
            typeStr = @"normal";
            break;
        case 3:
            typeStr = @"large";
            break;
    }
    NSString *urlStr = [NSString stringWithFormat:@"http://graph.facebook.com/%@/picture?type=%@",
                        self.identifier, typeStr];
    return [NSURL URLWithString:urlStr];
}

@end

redpajama_set_name: RedPajamaGithub


text:
package com.ss.editor.plugin.api.editor;

import com.ss.editor.ui.component.editor.state.impl.VoidEditorState;

/**
 * The base implementation of {@link com.ss.editor.ui.component.editor.FileEditor} without
 * {@link com.ss.editor.ui.component.editor.state.EditorState}.
 *
 * @author JavaSaBr
 */
public abstract class BaseFileEditorWithoutState extends BaseFileEditor<VoidEditorState> {
}


text:
/*
 * ctime_ts - A thread-safe wrapper for ctime
 */
#include "csapp.h"

#define MAXSTR 128

static sem_t mutex; /* protects calls to ctime */

static void init_ctime_ts(void) {
    Sem_init(&mutex, 0, 1);
}

/* $begin ctime_ts */
char *ctime_ts(const time_t *timep, char *privatep) {
    char *sharedp;

    P(&mutex);
    sharedp = ctime(timep);
    strcpy(privatep, sharedp); /* Copy string from shared to private */
    V(&mutex);
    return privatep;
}

/* $end ctime_ts */

int main() {
    char timestr[MAXSTR];
    time_t timeval;

    /* Thread-safe code to print the current time string */
    init_ctime_ts();
    timeval = time(NULL);
    ctime_ts(&timeval, timestr);
    printf("%s", timestr);
    exit(0);
}


text:
<!DOCTYPE html>

        <meta charset="UTF-8"/>
        <title>Notepad</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
        <link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.0-rc2/css/bootstrap.min.css" rel="stylesheet"/>
        <link href="stylesheets/examplestyle.css" rel="stylesheet"/>

This page is not designed to work without JavaScript.

Notepad

{{note}}

            Use this code as you wish.


text: from .base import LocalController


text:
.Select-menu-outer {
    color: $dark-grey;
}

.trainForm {
    padding: 20px 0 25px;
    color: #fff;
    background-color: $brand-color;
    margin-bottom: 20px;
}

.trainLine {
    position: absolute;
    display: inline-block;
    top: 7px;
    left: 17px;
    width: calc(100% - 45px);
    height: 5px;
    background-color: $mid-grey;
}

.trainLineTo, .trainLineFrom {
    color: $mid-grey;
}

.trainLineTo {
    position: absolute;
    right: 15px;
    top: 2px;
}
.panel-heading .trainLine {
    background-color: $accent-color;
}
.panel-heading .trainLineTo,.panel-heading  .trainLineFrom {
    color: $accent-color;
}

.journeys small {
    text-transform: uppercase;
    color: $dark-grey;
}

.panel-body .row {
    border-bottom: 1px solid $light-grey;
    padding: 10px 0;
    position: relative;
}

.section {
    position: absolute;
    background: $light-grey;
    color: $mid-grey;
    display: inline-block;
    border-radius: 100px;
    width: 25px;
    height: 25px;
    line-height: 25px;
    text-align: center;
    top: 8px;
    left: -13px;
}

.label {
    padding: 0 5px;
}

.list-inline {
    font-size: 85%;
    margin-top: 0.25em;
    margin-bottom: 0;
}

.map {
    display: inline-block;
    max-width: 1000px;
    width: 100%;
    height: auto;
}


text:
'use strict';

const dimensions = document.querySelector('#dimensions');
const video = document.querySelector('video');
let stream;

const vgaButton = document.querySelector('#vga');
const qvgaButton = document.querySelector('#qvga');
const hdButton = document.querySelector('#hd');
const fullHdButton = document.querySelector('#full-hd');
const fourKButton = document.querySelector('#fourK');
const eightKButton = document.querySelector('#eightK');

const videoblock = document.querySelector('#videoblock');
const messagebox = document.querySelector('#errormessage');

const widthInput = document.querySelector('div#width input');
const widthOutput = document.querySelector('div#width span');
const aspectLock = document.querySelector('#aspectlock');
const sizeLock = document.querySelector('#sizelock');

let currentWidth = 0;
let currentHeight = 0;

vgaButton.onclick = () => {
  getMedia(vgaConstraints);
};

qvgaButton.onclick = () => {
  getMedia(qvgaConstraints);
};

hdButton.onclick = () => {
  getMedia(hdConstraints);
};

fullHdButton.onclick = () => {
  getMedia(fullHdConstraints);
};

fourKButton.onclick = () => {
  getMedia(fourKConstraints);
};

eightKButton.onclick = () => {
  getMedia(eightKConstraints);
};

const qvgaConstraints = {
  video: {width: {exact: 320}, height: {exact: 240}}
};

const vgaConstraints = {
  video: {width: {exact: 640}, height: {exact: 480}}
};

const hdConstraints = {
  video: {width: {exact: 1280}, height: {exact: 720}}
};

const fullHdConstraints = {
  video: {width: {exact: 1920}, height: {exact: 1080}}
};

const fourKConstraints = {
  video: {width: {exact: 4096}, height: {exact: 2160}}
};

const eightKConstraints = {
  video: {width: {exact: 7680}, height: {exact: 4320}}
};

function gotStream(mediaStream) {
  stream = window.stream = mediaStream; // stream available to console
  video.srcObject = mediaStream;
  messagebox.style.display = 'none';
  videoblock.style.display = 'block';
  let track = mediaStream.getVideoTracks()[0];
  let constraints = track.getConstraints();
  console.log('Result constraints: ' + JSON.stringify(constraints));
  if (constraints && constraints.width && constraints.width.exact) {
    widthInput.value = constraints.width.exact;
    widthOutput.textContent = constraints.width.exact;
  } else if (constraints && constraints.width && constraints.width.min) {
    widthInput.value = constraints.width.min;
    widthOutput.textContent = constraints.width.min;
  }
}

function errorMessage(who, what) {
  let message = who + ': ' + what;
  messagebox.innerText = message;
  messagebox.style.display = 'block';
  console.log(message);
}

function clearErrorMessage() {
  messagebox.style.display = 'none';
}

function displayVideoDimensions(whereSeen) {
  if (video.videoWidth) {
    dimensions.innerText = 'Actual video dimensions: ' + video.videoWidth +
      'x' + video.videoHeight + 'px.';
    if (currentWidth !== video.videoWidth
      || currentHeight !== video.videoHeight) {
      console.log(whereSeen + ': ' + dimensions.innerText);
      currentWidth = video.videoWidth;
      currentHeight = video.videoHeight;
    }
  } else {
    dimensions.innerText = 'Video not ready';
  }
}

video.onloadedmetadata = () => {
  displayVideoDimensions('loadedmetadata');
};

video.onresize = () => {
  displayVideoDimensions('resize');
};

function constraintChange(e) {
  widthOutput.textContent = e.target.value;
  let track = window.stream.getVideoTracks()[0];
  let constraints;
  if (aspectLock.checked) {
    constraints = {
      width: {exact: e.target.value},
      aspectRatio: {
        exact: video.videoWidth / video.videoHeight
      }
    };
  } else {
    constraints = {width: {exact: e.target.value}};
  }
  clearErrorMessage();
  console.log('applying ' + JSON.stringify(constraints));
  track.applyConstraints(constraints)
    .then(() => {
      console.log('applyConstraint success');
      displayVideoDimensions('applyConstraints');
    })
    .catch(err => {
      errorMessage('applyConstraints', err.name);
    });
}

widthInput.onchange = constraintChange;

sizeLock.onchange = () => {
  if (sizeLock.checked) {
    console.log('Setting fixed size');
    video.style.width = '100%';
  } else {
    console.log('Setting auto size');
    video.style.width = 'auto';
  }
};

function getMedia(constraints) {
  if (stream) {
    stream.getTracks().forEach(track => {
      track.stop();
    });
  }

  clearErrorMessage();
  videoblock.style.display = 'none';
  navigator.mediaDevices.getUserMedia(constraints)
    .then(gotStream)
    .catch(e => {
      errorMessage('getUserMedia', e.message, e.name);
    });
}


text:
<?php
// +----------------------------------------------------------------------+
// | PHP Version 4                                                        |
// +----------------------------------------------------------------------+
// | Copyright (c) 1998-2004 Manuel Lemos, Tomas V.V.Cox,                 |
// | Stig. S. Bakken, Lukas Smith                                         |
// | All rights reserved.                                                 |
// +----------------------------------------------------------------------+
// | MDB is a merge of PEAR DB and Metabases that provides a unified DB   |
// | API as well as database abstraction for PHP applications.            |
// | This LICENSE is in the BSD license style.                            |
// |                                                                      |
// | Redistribution and use in source and binary forms, with or without   |
// | modification, are permitted provided that the following conditions   |
// | are met:                                                             |
// |                                                                      |
// | Redistributions of source code must retain the above copyright       |
// | notice, this list of conditions and the following disclaimer.        |
// |                                                                      |
// | Redistributions in binary form must reproduce the above copyright    |
// | notice, this list of conditions and the following disclaimer in the  |
// | documentation and/or other materials provided with the distribution. |
// |                                                                      |
// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,    |
// | Lukas Smith nor the names of his contributors may be used to endorse |
// | or promote products derived from this software without specific prior|
// | written permission.                                                  |
// |                                                                      |
// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS  |
// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT    |
// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS    |
// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE      |
// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,          |
// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
// |  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED  |
// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT          |
// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE          |
// | POSSIBILITY OF SUCH DAMAGE.                                          |
// +----------------------------------------------------------------------+
// | Author: Lukas Smith <smith@backendmedia.com>                         |
// +----------------------------------------------------------------------+
//
// $Id: reverse_engineer_xml_schema.php,v 1.17.4.3 2004/03/10 14:43:28 lsmith Exp $
//

/**
 * MDB reverse engineering of xml schemas script.
 *
 * @package MDB
 * @category Database
 * @author  Lukas Smith <smith@backendmedia.com>
 */

echo ('

');

    if(isset($_REQUEST['submit']) && $_REQUEST['file'] != '') {
        // BC hack to define PATH_SEPARATOR for version of PHP prior 4.3
        if(!defined('PATH_SEPARATOR')) {
            if(defined('DIRECTORY_SEPARATOR') && DIRECTORY_SEPARATOR == "\\") {
                define('PATH_SEPARATOR', ';');
            } else {
                define('PATH_SEPARATOR', ':');
            }
        }
        ini_set('include_path', '..'.PATH_SEPARATOR.ini_get('include_path'));
        require_once('MDB.php');
        @include_once('Var_Dump.php');
        MDB::loadFile('Manager');
        $dsn = $_REQUEST['type'].'://'.$_REQUEST['user'].':'.$_REQUEST['pass'].'@'.$_REQUEST['host'].'/'.$_REQUEST['name'];

        $manager =& new MDB_Manager;
        $err = $manager->connect($dsn);
        if(MDB::isError($err)) {
            $error = $err->getMessage();
        } else {
            $manager->captureDebugOutput(TRUE);
            $manager->database->setOption('log_line_break', '
');
            if($_REQUEST['action']) {
                set_time_limit(0);
            }
            if($_REQUEST['action'] == 'dump') {
                switch ($_REQUEST['dump']) {
                    case 'structure':
                        $dump_what = MDB_MANAGER_DUMP_STRUCTURE;
                        break;
                    case 'content':
                        $dump_what = MDB_MANAGER_DUMP_CONTENT;
                        break;
                    default:
                        $dump_what = MDB_MANAGER_DUMP_ALL;
                        break;
                }
                $dump_config = array(
                    'Output_Mode' => 'file',
                    'Output' => $_REQUEST['file']
                );
                if (class_exists('Var_Dump')) {
                    Var_Dump::display($manager->dumpDatabase($dump_config, $dump_what));
                } else {
                    var_dump($manager->dumpDatabase($dump_config, $dump_what));
                }
            } else if($_REQUEST['action'] == 'create') {
                if (class_exists('Var_Dump')) {
                    Var_Dump::display($manager->updateDatabase($_REQUEST['file']));
                } else {
                    var_dump($manager->updateDatabase($_REQUEST['file']));
                }
            } else {
                $error = 'no action selected';
            }
            $warnings = $manager->getWarnings();
            if(count($warnings) > 0) {
                echo('Warnings
');
                if (class_exists('Var_Dump')) {
                    Var_Dump::display($warnings);
                } else {
                    var_dump($warnings);
                }
            }
            if($manager->options['debug']) {
                echo('Debug messages
');
                echo($manager->debugOutput().'
');
            }
            echo('Database structure
');
            if (class_exists('Var_Dump')) {
                Var_Dump::display($manager->database_definition);
            } else {
                var_dump($manager->database_definition);
            }
            $manager->disconnect();
        }
    }

    if (!isset($_REQUEST['submit']) || isset($error)) {
        if (isset($error) && $error) {
            echo($error.'
');
        }
        echo ('
            <form action="reverse_engineer_xml_schema.php">
            Database Type:
            <select name="type">
                <option value="mysql"');
                if(isset($_REQUEST['type']) && $_REQUEST['type'] == 'mysql') {echo ('selected');}
                echo ('>MySQL</option>
                <option value="pgsql"');
                if(isset($_REQUEST['type']) && $_REQUEST['type'] == 'mysql') {echo ('selected');}
                echo ('>Postgres</option>
            </select>

            Username:
            <input type="text" name="user" value="'.(isset($_REQUEST['user']) ? $_REQUEST['user'] : '').'" />

            Password:
            <input type="text" name="pass" value="'.(isset($_REQUEST['pass']) ? $_REQUEST['pass'] : '').'" />

            Host:
            <input type="text" name="host" value="'.(isset($_REQUEST['host']) ? $_REQUEST['host'] : '').'" />

            Databasename:
            <input type="text" name="name" value="'.(isset($_REQUEST['name']) ? $_REQUEST['name'] : '').'" />

            Filename:
            <input type="text" name="file" value="'.(isset($_REQUEST['file']) ? $_REQUEST['file'] : '').'" />

            Dump:
            <input type="radio" name="action" value="dump" />
            <select name="dump">
                <option value="all"');
                if(!isset($_REQUEST['dump']) || $_REQUEST['dump'] == 'all') {echo ('selected');}
                echo ('>All</option>
                <option value="structure"');
                if(isset($_REQUEST['dump']) && $_REQUEST['dump'] == 'structure') {echo ('selected');}
                echo ('>Structure</option>
                <option value="content"');
                if(isset($_REQUEST['dump']) && $_REQUEST['dump'] == 'content') {echo ('selected');}
                echo ('>Content</option>
            </select>

            Create:
            <input type="radio" name="action" value="create" />

            <input type="submit" name="submit" value="ok" />
        ');
    }

    echo ('
</form>

    ');
?>


text:
namespace System.Windows.Forms {
    using System.Runtime.Serialization.Formatters;
    using System.Runtime.Remoting;
    using System.Runtime.InteropServices;

    using System.Diagnostics;

    using System;
    using System.Security.Permissions;
    using System.Globalization;
    using System.Windows.Forms;

    using System.Drawing.Design;
    using System.ComponentModel;
    using System.Windows.Forms.ComponentModel;

    using System.Collections;
    using System.Drawing;
    using Microsoft.Win32;
    using System.Text;

    /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl"]/*' />
    /// <devdoc>
    ///    <para>[To be supplied.]</para>
    /// </devdoc>
    [
    ComVisible(true),
    ClassInterface(ClassInterfaceType.AutoDispatch),
    LookupBindingProperties("DataSource", "DisplayMember", "ValueMember", "SelectedValue")
    ]
    public abstract class ListControl : Control {

        private static readonly object EVENT_DATASOURCECHANGED          = new object();
        private static readonly object EVENT_DISPLAYMEMBERCHANGED       = new object();
        private static readonly object EVENT_VALUEMEMBERCHANGED         = new object();
        private static readonly object EVENT_SELECTEDVALUECHANGED       = new object();
        private static readonly object EVENT_FORMATINFOCHANGED          = new object();
        private static readonly object EVENT_FORMATSTRINGCHANGED        = new object();
        private static readonly object EVENT_FORMATTINGENABLEDCHANGED   = new object();

        private object dataSource;
        private CurrencyManager dataManager;
        private BindingMemberInfo displayMember;
        private BindingMemberInfo valueMember;

        // Formatting stuff
        private string formatString = String.Empty;
        private IFormatProvider formatInfo = null;
        private bool formattingEnabled = false;
        private static readonly object EVENT_FORMAT   = new object();
        private TypeConverter displayMemberConverter = null;
        private static TypeConverter stringTypeConverter = null;

        private bool isDataSourceInitialized;
        private bool isDataSourceInitEventHooked;
        private bool inSetDataConnection = false;

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.DataSource"]/*' />
        /// <devdoc>
        ///     The ListSource to consume as this ListBox's source of data.
        ///     When set, a user can not modify the Items collection.
        /// </devdoc>
        [
        SRCategory(SR.CatData),
        DefaultValue(null),
        RefreshProperties(RefreshProperties.Repaint),
        AttributeProvider(typeof(IListSource)),
        SRDescription(SR.ListControlDataSourceDescr)
        ]
        public object DataSource {
            get {
                return dataSource;
            }
            set {
                if (value != null && !(value is IList || value is IListSource))
                    throw new ArgumentException(SR.GetString(SR.BadDataSourceForComplexBinding));
                if (dataSource == value)
                    return;
                // When we change the dataSource to null, we should reset
                // the displayMember to "". See ASURT 85662.
                try {
                    SetDataConnection(value, displayMember, false);
                } catch {
                    // There are several possibilities why setting the data source throws an exception:
                    // 1. the app throws an exception in the events that fire when we change the data source: DataSourceChanged,
                    // 2. we get an exception when we set the data source and populate the list controls (say,something went wrong while formatting the data)
                    // 3. the DisplayMember does not fit w/ the new data source (this could happen if the user resets the data source but did not reset the DisplayMember)
                    // in all cases ListControl should reset the DisplayMember to String.Empty
                    // the ListControl should also eat the exception - this is the RTM behavior and doing anything else is a breaking change
                    DisplayMember = "";
                }
                if (value == null)
                    DisplayMember = "";
            }
        }

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.DataSourceChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatPropertyChanged), SRDescription(SR.ListControlOnDataSourceChangedDescr)]
        public event EventHandler DataSourceChanged {
            add {
                Events.AddHandler(EVENT_DATASOURCECHANGED, value);
            }
            remove {
                Events.RemoveHandler(EVENT_DATASOURCECHANGED, value);
            }
        }

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.DataManager"]/*' />
        protected CurrencyManager DataManager {
            get {
                return this.dataManager;
            }
        }

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.DisplayMember"]/*' />
        /// <devdoc>
        ///     If the ListBox contains objects that support properties, this indicates
        ///     which property of the object to show.  If "", the object shows it's ToString().
        /// </devdoc>
        [
        SRCategory(SR.CatData),
        DefaultValue(""),
        TypeConverterAttribute("System.Windows.Forms.Design.DataMemberFieldConverter, " + AssemblyRef.SystemDesign),
        Editor("System.Windows.Forms.Design.DataMemberFieldEditor, " + AssemblyRef.SystemDesign, typeof(System.Drawing.Design.UITypeEditor)),
        SRDescription(SR.ListControlDisplayMemberDescr)
        ]
        public string DisplayMember {
            get {
                return displayMember.BindingMember;
            }
            set {
                BindingMemberInfo oldDisplayMember = displayMember;
                try {
                    SetDataConnection(dataSource, new BindingMemberInfo(value), false);
                } catch {
                    displayMember = oldDisplayMember;
                }
            }
        }

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.DisplayMemberChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatPropertyChanged), SRDescription(SR.ListControlOnDisplayMemberChangedDescr)]
        public event EventHandler DisplayMemberChanged {
            add {
                Events.AddHandler(EVENT_DISPLAYMEMBERCHANGED, value);
            }
            remove {
                Events.RemoveHandler(EVENT_DISPLAYMEMBERCHANGED, value);
            }
        }

        // Cached type converter of the property associated with the display member
        private TypeConverter DisplayMemberConverter {
            get {
                if (this.displayMemberConverter == null &&
                    this.DataManager != null &&
                    this.displayMember != null) {
                    PropertyDescriptorCollection props = this.DataManager.GetItemProperties();
                    if (props != null) {
                        PropertyDescriptor displayMemberProperty = props.Find(this.displayMember.BindingField, true);
                        if (displayMemberProperty != null)
                        {
                            this.displayMemberConverter = displayMemberProperty.Converter;
                        }
                    }
                }
                return this.displayMemberConverter;
            }
        }

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.Format"]/*' />
        [SRCategory(SR.CatPropertyChanged), SRDescription(SR.ListControlFormatDescr)]
        public event ListControlConvertEventHandler Format
        {
            add {
                Events.AddHandler(EVENT_FORMAT, value);
                RefreshItems();
            }
            remove {
                Events.RemoveHandler(EVENT_FORMAT, value);
                RefreshItems();
            }
        }

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.FormatInfo"]/*' />
        [
            Browsable(false),
            EditorBrowsable(EditorBrowsableState.Advanced),
            DefaultValue(null)
        ]
        public IFormatProvider FormatInfo {
            get {
                return this.formatInfo;
            }
            set {
                if (value != formatInfo) {
                    formatInfo = value;
                    RefreshItems();
                    OnFormatInfoChanged(EventArgs.Empty);
                }
            }
        }

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.FormatInfoChanged"]/*' />
        [
            Browsable(false),
            EditorBrowsable(EditorBrowsableState.Advanced),
            SRCategory(SR.CatPropertyChanged),
            SRDescription(SR.ListControlFormatInfoChangedDescr)
        ]
        public event EventHandler FormatInfoChanged {
            add {
                Events.AddHandler(EVENT_FORMATINFOCHANGED, value);
            }
            remove {
                Events.RemoveHandler(EVENT_FORMATINFOCHANGED, value);
            }
        }

        [
            DefaultValue(""),
            SRDescription(SR.ListControlFormatStringDescr),
            EditorAttribute("System.Windows.Forms.Design.FormatStringEditor, " + AssemblyRef.SystemDesign, typeof(System.Drawing.Design.UITypeEditor)),
            MergableProperty(false)
        ]
        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.FormatString"]/*' />
        public string FormatString {
            get {
                return formatString;
            }
            set {
                if (value == null)
                    value = String.Empty;
                if (!value.Equals(formatString)) {
                    formatString = value;
                    RefreshItems();
                    OnFormatStringChanged(EventArgs.Empty);
                }
            }
        }

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.FormatStringChanged"]/*' />
        [
            SRCategory(SR.CatPropertyChanged),
            SRDescription(SR.ListControlFormatStringChangedDescr)
        ]
        public event EventHandler FormatStringChanged {
            add {
                Events.AddHandler(EVENT_FORMATSTRINGCHANGED, value);
            }
            remove {
                Events.RemoveHandler(EVENT_FORMATSTRINGCHANGED, value);
            }
        }

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.FormattingEnabled"]/*' />
        [
            DefaultValue(false),
            SRDescription(SR.ListControlFormattingEnabledDescr)
        ]
        public bool FormattingEnabled {
            get {
                return formattingEnabled;
            }
            set {
                if (value != formattingEnabled) {
                    formattingEnabled = value;
                    RefreshItems();
                    OnFormattingEnabledChanged(EventArgs.Empty);
                }
            }
        }

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.FormattingEnabledChanged"]/*' />
        [
            SRCategory(SR.CatPropertyChanged),
            SRDescription(SR.ListControlFormattingEnabledChangedDescr)
        ]
        public event EventHandler FormattingEnabledChanged {
            add {
                Events.AddHandler(EVENT_FORMATTINGENABLEDCHANGED, value);
            }
            remove {
                Events.RemoveHandler(EVENT_FORMATTINGENABLEDCHANGED, value);
            }
        }

        private bool BindingMemberInfoInDataManager(BindingMemberInfo bindingMemberInfo) {
            if (dataManager == null)
                return false;
            PropertyDescriptorCollection props = dataManager.GetItemProperties();
            int propsCount = props.Count;

            for (int i = 0; i < propsCount; i++) {
                if (typeof(IList).IsAssignableFrom(props[i].PropertyType))
                    continue;
                if (props[i].Name.Equals(bindingMemberInfo.BindingField)) {
                    return true;
                }
            }

            for (int i = 0; i < propsCount; i++) {
                if (typeof(IList).IsAssignableFrom(props[i].PropertyType))
                    continue;
                if (String.Compare(props[i].Name, bindingMemberInfo.BindingField, true, CultureInfo.CurrentCulture) == 0) {
                    return true;
                }
            }

            return false;
        }

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.ValueMember"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [
        SRCategory(SR.CatData),
        DefaultValue(""),
        Editor("System.Windows.Forms.Design.DataMemberFieldEditor, " + AssemblyRef.SystemDesign, typeof(System.Drawing.Design.UITypeEditor)),
        SRDescription(SR.ListControlValueMemberDescr)
        ]
        public string ValueMember {
            get {
                return valueMember.BindingMember;
            }
            set {
                if (value == null)
                    value = "";
                BindingMemberInfo newValueMember = new BindingMemberInfo(value);
                BindingMemberInfo oldValueMember = valueMember;
                if (!newValueMember.Equals(valueMember)) {
                    // If the displayMember is set to the EmptyString, then recreate the dataConnection
                    //
                    if (DisplayMember.Length == 0)
                        SetDataConnection(DataSource, newValueMember, false);
                    // See if the valueMember is a member of
                    // the properties in the dataManager
                    if (this.dataManager != null && value != null && value.Length != 0)
                        if (!BindingMemberInfoInDataManager(newValueMember)) {
                            throw new ArgumentException(SR.GetString(SR.ListControlWrongValueMember), "value");
                        }

                    valueMember = newValueMember;
                    OnValueMemberChanged(EventArgs.Empty);
                    OnSelectedValueChanged(EventArgs.Empty);
                }
            }
        }

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.ValueMemberChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatPropertyChanged), SRDescription(SR.ListControlOnValueMemberChangedDescr)]
        public event EventHandler ValueMemberChanged {
            add {
                Events.AddHandler(EVENT_VALUEMEMBERCHANGED, value);
            }
            remove {
                Events.RemoveHandler(EVENT_VALUEMEMBERCHANGED, value);
            }
        }

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.AllowSelection"]/*' />
        /// <devdoc>
        ///    Indicates whether list currently allows selection of list items.
        /// </devdoc>
        protected virtual bool AllowSelection {
            get {
                return true;
            }
        }

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.SelectedIndex"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        public abstract int SelectedIndex {
            get;
            set;
        }

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.SelectedValue"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [
        SRCategory(SR.CatData),
        DefaultValue(null),
        Browsable(false),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden),
        SRDescription(SR.ListControlSelectedValueDescr),
        Bindable(true)
        ]
        public object SelectedValue {
            get {
                if (SelectedIndex != -1 && dataManager != null ) {
                    object currentItem = dataManager[SelectedIndex];
                    object filteredItem = FilterItemOnProperty(currentItem, valueMember.BindingField);
                    return filteredItem;
                }
                return null;
            }
            set {
                if (dataManager != null) {
                    string propertyName = valueMember.BindingField;
                    // we can't set the SelectedValue property when the listManager does not
                    // have a ValueMember set.
                    if (string.IsNullOrEmpty(propertyName))
                        throw new InvalidOperationException(SR.GetString(SR.ListControlEmptyValueMemberInSettingSelectedValue));
                    PropertyDescriptorCollection props = dataManager.GetItemProperties();
                    PropertyDescriptor property = props.Find(propertyName, true);
                    int index = dataManager.Find(property, value, true);
                    this.SelectedIndex = index;
                }
            }
        }

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.SelectedValueChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        [SRCategory(SR.CatPropertyChanged), SRDescription(SR.ListControlOnSelectedValueChangedDescr)]
        public event EventHandler SelectedValueChanged {
            add {
                Events.AddHandler(EVENT_SELECTEDVALUECHANGED, value);
            }
            remove {
                Events.RemoveHandler(EVENT_SELECTEDVALUECHANGED, value);
            }
        }

        private void DataManager_PositionChanged(object sender, EventArgs e) {
            if (this.dataManager != null) {
                if (AllowSelection) {
                    this.SelectedIndex = dataManager.Position;
                }
            }
        }

        private void DataManager_ItemChanged(object sender, ItemChangedEventArgs e) {
            // Note this is being called internally with a null event.
            if (dataManager != null) {
                if (e.Index == -1) {
                    SetItemsCore(dataManager.List);
                    if (AllowSelection) {
                        this.SelectedIndex = this.dataManager.Position;
                    }
                }
                else {
                    SetItemCore(e.Index, dataManager[e.Index]);
                }
            }
        }

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.FilterItemOnProperty"]/*' />
        /// <internalonly/>
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        protected object FilterItemOnProperty(object item) {
            return FilterItemOnProperty(item, displayMember.BindingField);
        }

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.FilterItemOnProperty1"]/*' />
        /// <internalonly/>
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        protected object FilterItemOnProperty(object item, string field) {
            if (item != null && field.Length > 0) {
                try {
                    // if we have a dataSource, then use that to display the string
                    PropertyDescriptor descriptor;
                    if (this.dataManager != null)
                        descriptor = this.dataManager.GetItemProperties().Find(field, true);
                    else
                        descriptor = TypeDescriptor.GetProperties(item).Find(field, true);
                    if (descriptor != null) {
                        item = descriptor.GetValue(item);
                    }
                }
                catch {
                }
            }
            return item;
        }

        //We use  this to prevent getting the selected item when mouse is hovering over the dropdown.
        //
        internal bool BindingFieldEmpty {
            get {
                return (displayMember.BindingField.Length > 0 ? false : true);
            }

        }

        internal int FindStringInternal(string str, IList items, int startIndex, bool exact) {
            return FindStringInternal(str, items, startIndex, exact, true);
        }

        internal int FindStringInternal(string str, IList items, int startIndex, bool exact, bool ignorecase) {

            // Sanity check parameters
            //
            if (str == null || items == null) {
                return -1;
            }
            // VSWhidbey 95158: The last item in the list is still a valid place to start looking!
            if (startIndex < -1 || startIndex >= items.Count) {
                return -1;
            }

            bool found = false;
            int length = str.Length;

            // VSWhidbey 215677: start from the start index and wrap around until we find the string
            // in question.  Use a separate counter to ensure that we arent cycling through the list infinitely.
            int numberOfTimesThroughLoop = 0;

            // this API is really Find NEXT String...
            for (int index = (startIndex+1) % items.Count; numberOfTimesThroughLoop < items.Count; index = (index+1) % items.Count) {
                numberOfTimesThroughLoop++;
                if (exact) {
                    found = String.Compare(str, GetItemText(items[index]), ignorecase, CultureInfo.CurrentCulture) == 0;
                }
                else {
                    found = String.Compare(str, 0, GetItemText(items[index]), 0, length, ignorecase, CultureInfo.CurrentCulture) == 0;
                }

                if (found) {
                    return index;
                }

            }

            return -1;
        }

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.GetItemText"]/*' />
        public string GetItemText(object item)
        {

            // !formattingEnabled == RTM behaviour
            if (!formattingEnabled) {

                // [....] gave his blessing to this RTM breaking change
                if (item == null) {
                    return String.Empty;
                }

                item = FilterItemOnProperty(item, displayMember.BindingField);
                return (item != null) ? Convert.ToString(item, CultureInfo.CurrentCulture) : "";
            }

            //
            // Whidbey formatting features
            //

            object filteredItem = FilterItemOnProperty(item, displayMember.BindingField);

            // first try: the OnFormat event
            ListControlConvertEventArgs e = new ListControlConvertEventArgs(filteredItem, typeof(String), item);
            OnFormat(e);

            // [....]: we need a better check. Should add the Handled property on the ListControlConvertEventArgs?
            if (e.Value != item && e.Value is String) {
                return (string) e.Value;
            }

            // try Formatter::FormatObject
            if (stringTypeConverter == null)
            {
                stringTypeConverter = TypeDescriptor.GetConverter(typeof(String));
            }
            try
            {
                return (string) Formatter.FormatObject(filteredItem, typeof(String), this.DisplayMemberConverter, stringTypeConverter, formatString, formatInfo, null, System.DBNull.Value);
            }
            catch (Exception exception)
            {
                if (ClientUtils.IsSecurityOrCriticalException(exception))
                {
                    throw;
                }
                // if we did not do any work then return the old ItemText
                return (filteredItem != null) ? Convert.ToString(item, CultureInfo.CurrentCulture) : "";
            }
        }

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.IsInputKey"]/*' />
        /// <devdoc>
        ///      Handling special input keys, such as pgup, pgdown, home, end, etc...
        /// </devdoc>
        protected override bool IsInputKey(Keys keyData) {
            if ((keyData & Keys.Alt) == Keys.Alt) return false;
            switch (keyData & Keys.KeyCode) {
                case Keys.PageUp:
                case Keys.PageDown:
                case Keys.Home:
                case Keys.End:
                    return true;
            }
            return base.IsInputKey(keyData);
        }

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.OnBindingContextChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        protected override void OnBindingContextChanged(EventArgs e) {
            SetDataConnection(dataSource, displayMember, true);

            base.OnBindingContextChanged(e);
        }

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.OnDataSourceChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        protected virtual void OnDataSourceChanged(EventArgs e) {
            EventHandler eh = Events[EVENT_DATASOURCECHANGED] as EventHandler;
            if (eh != null) {
                 eh(this, e);
            }
        }

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.OnDisplayMemberChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        protected virtual void OnDisplayMemberChanged(EventArgs e) {
            EventHandler eh = Events[EVENT_DISPLAYMEMBERCHANGED] as EventHandler;
            if (eh != null) {
                 eh(this, e);
            }
        }

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.OnFormat"]/*' />
        protected virtual void OnFormat(ListControlConvertEventArgs e) {
            ListControlConvertEventHandler eh = Events[EVENT_FORMAT] as ListControlConvertEventHandler;
            if (eh != null)
                eh(this, e);
        }

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.OnFormatInfoChanged"]/*' />
        protected virtual void OnFormatInfoChanged(EventArgs e) {
            EventHandler eh = Events[EVENT_FORMATINFOCHANGED] as EventHandler;
            if (eh != null)
                eh(this,e);
        }

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.OnFormatStringChanged"]/*' />
        protected virtual void OnFormatStringChanged(EventArgs e) {
            EventHandler eh = Events[EVENT_FORMATSTRINGCHANGED] as EventHandler;
            if (eh != null)
                eh(this,e);
        }

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.OnFormattingEnabledChanged"]/*' />
        protected virtual void OnFormattingEnabledChanged(EventArgs e) {
            EventHandler eh = Events[EVENT_FORMATTINGENABLEDCHANGED] as EventHandler;
            if (eh != null)
                eh(this,e);
        }

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.OnSelectedIndexChanged"]/*' />
        /// <devdoc>
        ///     Actually goes and fires the selectedIndexChanged event.  Inheriting controls
        ///     should use this to know when the event is fired [this is preferable to
        ///     adding an event handler on yourself for this event].  They should,
        ///     however, remember to call base.OnSelectedIndexChanged(e); to ensure the event is
        ///     still fired to external listeners
        /// </devdoc>
        protected virtual void OnSelectedIndexChanged(EventArgs e) {
            OnSelectedValueChanged(EventArgs.Empty);
        }

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.OnValueMemberChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        protected virtual void OnValueMemberChanged(EventArgs e) {
            EventHandler eh = Events[EVENT_VALUEMEMBERCHANGED] as EventHandler;
            if (eh != null) {
                 eh(this, e);
            }
        }

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.OnSelectedValueChanged"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        protected virtual void OnSelectedValueChanged(EventArgs e) {
            EventHandler eh = Events[EVENT_SELECTEDVALUECHANGED] as EventHandler;
            if (eh != null) {
                 eh(this, e);
            }
        }

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.RefreshItem"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        protected abstract void RefreshItem(int index);

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.RefreshItems"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        protected virtual void RefreshItems() {
        }

        private void DataSourceDisposed(object sender, EventArgs e) {
            Debug.Assert(sender == this.dataSource, "how can we get dispose notification for anything other than our dataSource?");
            SetDataConnection(null, new BindingMemberInfo(""), true);
        }

        private void DataSourceInitialized(object sender, EventArgs e) {
            ISupportInitializeNotification dsInit = (this.dataSource as ISupportInitializeNotification);
            Debug.Assert(dsInit != null, "ListControl: ISupportInitializeNotification.Initialized event received, but current DataSource does not support ISupportInitializeNotification!");
            Debug.Assert(dsInit.IsInitialized, "ListControl: DataSource sent ISupportInitializeNotification.Initialized event but before it had finished initializing.");
            SetDataConnection(this.dataSource, this.displayMember, true);
        }

        private void SetDataConnection(object newDataSource, BindingMemberInfo newDisplayMember, bool force) {
            bool dataSourceChanged = dataSource != newDataSource;
            bool displayMemberChanged = !displayMember.Equals(newDisplayMember);

            // make sure something interesting is happening...
            //
            //force = force && (dataSource != null || newDataSource != null);
            if (inSetDataConnection) {
                return;
            }
            try {
                if (force || dataSourceChanged || displayMemberChanged) {
                    inSetDataConnection = true;
                    IList currentList = this.DataManager != null ? this.DataManager.List : null;
                    bool currentManagerIsNull = this.DataManager == null;

                    UnwireDataSource();

                    dataSource = newDataSource;
                    displayMember = newDisplayMember;

                    WireDataSource();

                    // Provided the data source has been fully initialized, start listening to change events on its
                    // currency manager and refresh our list. If the data source has not yet been initialized, we will
                    // skip this step for now, and try again later (once the data source has fired its Initialized event).
                    //
                    if (isDataSourceInitialized) {

                        CurrencyManager newDataManager = null;
                        if (newDataSource != null && BindingContext != null && !(newDataSource == Convert.DBNull)) {
                            newDataManager = (CurrencyManager)BindingContext[newDataSource, newDisplayMember.BindingPath];
                        }

                        if (dataManager != newDataManager) {
                            if (dataManager != null) {
                                dataManager.ItemChanged -= new ItemChangedEventHandler(DataManager_ItemChanged);
                                dataManager.PositionChanged -= new EventHandler(DataManager_PositionChanged);
                            }

                            dataManager = newDataManager;

                            if (dataManager != null) {
                                dataManager.ItemChanged += new ItemChangedEventHandler(DataManager_ItemChanged);
                                dataManager.PositionChanged += new EventHandler(DataManager_PositionChanged);
                            }
                        }

                        // See if the BindingField in the newDisplayMember is valid
                        // The same thing if dataSource Changed
                        // "" is a good value for displayMember
                        if (dataManager != null && (displayMemberChanged || dataSourceChanged) && displayMember.BindingMember != null && displayMember.BindingMember.Length != 0) {

                            if (!BindingMemberInfoInDataManager(displayMember))
                                throw new ArgumentException(SR.GetString(SR.ListControlWrongDisplayMember), "newDisplayMember");
                        }

                        if (dataManager != null && (dataSourceChanged || displayMemberChanged || force)) {
                            // if we force a new data manager, then change the items in the list control
                            // only if the list changed or if we go from a null dataManager to a full fledged one
                            // or if the DisplayMember changed
                            if (displayMemberChanged || (force && (currentList != this.dataManager.List || currentManagerIsNull))) {
                                DataManager_ItemChanged(dataManager, new ItemChangedEventArgs(-1));
                            }
                        }
                    }
                    this.displayMemberConverter = null;
                }

                if (dataSourceChanged) {
                    OnDataSourceChanged(EventArgs.Empty);
                }

                if (displayMemberChanged) {
                    OnDisplayMemberChanged(EventArgs.Empty);
                }
            }
            finally {
                inSetDataConnection = false;
            }
        }

        private void UnwireDataSource() {
                // If the source is a component, then unhook the Disposed event
                if (this.dataSource is IComponent) {
                    ((IComponent) this.dataSource).Disposed -= new EventHandler(DataSourceDisposed);
                }

                ISupportInitializeNotification dsInit = (this.dataSource as ISupportInitializeNotification);

                if (dsInit != null && isDataSourceInitEventHooked) {
                    // If we previously hooked the data source's ISupportInitializeNotification
                    // Initialized event, then unhook it now (we don't always hook this event,
                    // only if we needed to because the data source was previously uninitialized)
                    dsInit.Initialized -= new EventHandler(DataSourceInitialized);
                    isDataSourceInitEventHooked = false;
                }
        }

        private void WireDataSource() {
                // If the source is a component, then hook the Disposed event,
                // so we know when the component is deleted from the form
                if (this.dataSource is IComponent) {
                    ((IComponent) this.dataSource).Disposed += new EventHandler(DataSourceDisposed);
                }

                ISupportInitializeNotification dsInit = (this.dataSource as ISupportInitializeNotification);

                if (dsInit != null && !dsInit.IsInitialized) {
                    // If the source provides initialization notification, and is not yet
                    // fully initialized, then hook the Initialized event, so that we can
                    // delay connecting to it until it *is* initialized.
                    dsInit.Initialized += new EventHandler(DataSourceInitialized);
                    isDataSourceInitEventHooked = true;
                    isDataSourceInitialized = false;
                }
                else {
                    // Otherwise either the data source says it *is* initialized, or it
                    // does not support the capability to report whether its initialized,
                    // in which case we have to just assume it that is initialized.
                    isDataSourceInitialized = true;
                }
        }

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.SetItemsCore"]/*' />
        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        protected abstract void SetItemsCore(IList items);

        /// <include file='doc\ListControl.uex' path='docs/doc[@for="ListControl.SetItemCore"]/*' />
        protected virtual void SetItemCore(int index, object value) {}
    }
}


text:
package studio.xmatrix.qqpvp.assistant.ui.activity.collection;

import android.annotation.SuppressLint;
import android.databinding.DataBindingUtil;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import com.daimajia.swipe.SwipeLayout;
import com.daimajia.swipe.adapters.RecyclerSwipeAdapter;

import java.util.ArrayList;
import java.util.List;

import studio.xmatrix.qqpvp.assistant.R;
import studio.xmatrix.qqpvp.assistant.data.common.Resource;
import studio.xmatrix.qqpvp.assistant.data.model.CollectionItem;
import studio.xmatrix.qqpvp.assistant.data.model.HeroListItem;
import studio.xmatrix.qqpvp.assistant.data.model.ItemItem;
import studio.xmatrix.qqpvp.assistant.data.model.ListItem;
import studio.xmatrix.qqpvp.assistant.data.model.SummonerItem;
import studio.xmatrix.qqpvp.assistant.databinding.CollectionItemBinding;
import studio.xmatrix.qqpvp.assistant.ui.activity.herodetail.HeroDetailActivity;
import studio.xmatrix.qqpvp.assistant.ui.activity.list.ListItemHandler;
import studio.xmatrix.qqpvp.assistant.ui.activity.list.ListSkillHandler;
import studio.xmatrix.qqpvp.assistant.ui.common.ViewModel;
import studio.xmatrix.qqpvp.assistant.ui.fragment.note.NoteFragment;

public class CollectionAdapter extends RecyclerSwipeAdapter<CollectionAdapter.MyViewHolder> {
    private ViewModel viewModel;
    private CollectionActivity activity;
    private List<Pair<CollectionItem, ? extends ListItem>> data;

    @Override
    public int getSwipeLayoutResourceId(int position) {
        return R.id.collection_swipe;
    }

    CollectionAdapter(CollectionActivity activity, ViewModel viewModel) {
        this.viewModel = viewModel;
        this.activity = activity;
        this.data = new ArrayList<>();
    }

    // 刷新数据
    void refreshData(List<Pair<CollectionItem, ? extends ListItem>> data) {
        if (data == null) return;
        this.notifyItemRangeRemoved(0, this.data.size());
        this.data = data;
        this.notifyItemRangeInserted(0, this.data.size());
    }

    void observeData(List<Pair<CollectionItem, ? extends ListItem>> newData) {
        if (newData == null) return;
        List<Pair<CollectionItem, ? extends ListItem>> oldData = this.data;
        this.data = newData;
        if (newData.size() > oldData.size()) {
            this.notifyItemInserted(newData.size() - 1);
        } else if (newData.size() < oldData.size()) {
            for (int i = 0; i < oldData.size(); i++) {
                if (i >= newData.size()) {
                    notifyItemRemoved(i);
                    break;
                }
                if (oldData.get(i).first.getId() != newData.get(i).first.getId()) {
                    notifyItemRemoved(i);
                    break;
                }
            }
        } else {
            this.notifyDataSetChanged();
        }
    }

    @NonNull
    @Override
    public CollectionAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        CollectionItemBinding binding = DataBindingUtil.inflate(LayoutInflater.from(activity), R.layout.collection_item, viewGroup, false);
        return new CollectionAdapter.MyViewHolder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull CollectionAdapter.MyViewHolder viewHolder, int i) {
        viewHolder.bind(this.data.get(i));
        mItemManger.bindView(viewHolder.itemView, i);
    }

    @Override
    public int getItemCount() {
        if (this.data == null) return 0;
        return this.data.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder {
        private CollectionItemBinding binding;

        MyViewHolder(CollectionItemBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }

        @SuppressLint("SetTextI18n")
        void bind(final Pair<CollectionItem, ? extends ListItem> item) {
            binding.collectionSwipe.setShowMode(SwipeLayout.ShowMode.PullOut);
            binding.collectionSwipe.addDrag(SwipeLayout.DragEdge.Left, binding.collectionBottomLeft.collectionLayoutLeft);
            binding.collectionSwipe.addDrag(SwipeLayout.DragEdge.Right, binding.collectionBottomRight.collectionLayoutRight);
            switch (item.first.getType()) {
                case Hero:
                    HeroListItem hero = (HeroListItem) item.second;
                    binding.collectionSurface.cardName.setText(hero.getName());
                    binding.collectionSurface.cardTitle.setText(hero.getTypes() + " · " + hero.getDefaultSkin());
                    viewModel.getHeroIcon(hero.getId()).observe(activity, res -> {
                        if (res == null || res.data == null || res.status != Resource.Status.SUCCESS) return;
                        binding.collectionSurface.listItemIcon.setImageBitmap(res.data);
                    });
                    binding.collectionSurface.cardTypeName.setText("英雄");
                    binding.collectionSurface.cardLayoutClick.setOnClickListener(v -> HeroDetailActivity.startActivity(activity, hero.getId()));
                    break;
                case Item:
                    ItemItem itemItem = (ItemItem) item.second;
                    binding.collectionSurface.cardName.setText(itemItem.getName());
                    binding.collectionSurface.cardTitle.setText("常规装备");
                    viewModel.getItemIcon(itemItem.getId()).observe(activity, res -> {
                        if (res == null || res.data == null || res.status != Resource.Status.SUCCESS) return;
                        binding.collectionSurface.listItemIcon.setImageBitmap(res.data);
                    });
                    binding.collectionSurface.cardTypeName.setText("装备");
                    binding.collectionSurface.cardLayoutClick.setOnClickListener(v -> ListItemHandler.showCard(activity, viewModel, itemItem, false));
                    break;
                case SpecialItem:
                    ItemItem specialItem = (ItemItem) item.second;
                    binding.collectionSurface.cardName.setText(specialItem.getName());
                    binding.collectionSurface.cardTitle.setText("常规装备");
                    viewModel.getItemIcon(specialItem.getId()).observe(activity, res -> {
                        if (res == null || res.data == null || res.status != Resource.Status.SUCCESS) return;
                        binding.collectionSurface.listItemIcon.setImageBitmap(res.data);
                    });
                    binding.collectionSurface.cardTypeName.setText("装备");
                    binding.collectionSurface.cardLayoutClick.setOnClickListener(v -> ListItemHandler.showCard(activity, viewModel, specialItem, true));
                    break;

                case Summoner:
                    SummonerItem summoner = (SummonerItem) item.second;
                    binding.collectionSurface.cardName.setText(summoner.getName());
                    binding.collectionSurface.cardTitle.setText(summoner.getRank());
                    viewModel.getSummonerIcon(summoner.getId()).observe(activity, res -> {
                        if (res == null || res.data == null || res.status != Resource.Status.SUCCESS) return;
                        binding.collectionSurface.listItemIcon.setImageBitmap(res.data);
                    });
                    binding.collectionSurface.cardTypeName.setText("技能");
                    binding.collectionSurface.cardLayoutClick.setOnClickListener(v -> ListSkillHandler.showCard(activity, viewModel, summoner));
                    break;
            }
            if (!item.first.getRemark().equals("")) {
                binding.collectionSurface.cardName.setText(binding.collectionSurface.cardName.getText() + "("+item.first.getRemark()+")");
                binding.collectionBottomLeft.collectionNoteText.setText("修改备注");
            } else {
                binding.collectionBottomLeft.collectionNoteText.setText("添加备注");
            }
            binding.collectionBottomLeft.collectionLayoutLeft.setOnClickListener(v -> {
                for (int i = 0; i < data.size(); i++) {
                    if (data.get(i).first.getId() == item.first.getId()) {
                        NoteFragment noteFragment = new NoteFragment(activity);
                        if (!item.first.getRemark().equals("")) noteFragment.setText(item.first.getRemark());
                        noteFragment.setOnEditNote(s -> {
                            item.first.setRemark(s);
                            viewModel.updateCollection(item.first);
                            mItemManger.closeAllItems();
                        });
                        noteFragment.show(activity.getSupportFragmentManager(), "note");
                        break;
                    }
                }
            });
            binding.collectionBottomRight.collectionLayoutRight.setOnClickListener(v -> {
                for (int i = 0; i < data.size(); i++) {
                    if (data.get(i).first.getId() == item.first.getId()) {
                        viewModel.removeCollection(item.first.getId());
                        mItemManger.closeAllItems();
                        break;
                    }
                }
            });
        }
    }
}


text:
describe :socket_addrinfo_to_sockaddr, :shared => true do

  describe "for an ipv4 socket" do
    before :each do
      @addrinfo = Addrinfo.tcp("127.0.0.1", 80)
    end

    it "returns a sockaddr packed structure" do
      @addrinfo.send(@method).should == Socket.sockaddr_in(80, '127.0.0.1')
    end
  end

  describe "for an ipv6 socket" do
    before :each do
      @addrinfo = Addrinfo.tcp("::1", 80)
    end

    it "returns a sockaddr packed structure" do
      @addrinfo.send(@method).should == Socket.sockaddr_in(80, '::1')
    end
  end

  with_feature :unix_socket do
    describe "for a unix socket" do
      before :each do
        @addrinfo = Addrinfo.unix("/tmp/sock")
      end

      it "returns a sockaddr packed structure" do
        @addrinfo.send(@method).should == Socket.sockaddr_un('/tmp/sock')
      end
    end
  end

  describe 'using a Addrinfo with just an IP address' do
    it 'returns a String' do
      addr = Addrinfo.ip('127.0.0.1')

      addr.send(@method).should == Socket.sockaddr_in(0, '127.0.0.1')
    end
  end

  describe 'using a Addrinfo without an IP and port' do
    it 'returns a String' do
      addr = Addrinfo.new(['AF_INET', 0, '', ''])

      addr.send(@method).should == Socket.sockaddr_in(0, '')
    end
  end

end


text:
import { IBreakableTypes } from './IBreakableTypes';
import { ISIGeneralContent } from './ISIGeneralContent';
import { ISymbolBase } from './ISymbolBase';

export interface IBreakable<T extends IBreakableTypes> extends ISymbolBase<T> {
  has: ISIGeneralContent[];
}