text:
Changelog
=========

## v.2.3.1 - xx Nov, 2015

Bugfixes

-  Fixed saving buffers with charsets other than utf-8 while using multi ([@BridgeAR](https://github.com/BridgeAR))
-  Fixed js parser handling big values very slow ([@BridgeAR](https://github.com/BridgeAR))
 -  The speed is up to ~500% faster than before but still up to ~50% slower than the hiredis parser.

## v.2.3.0 - 30 Oct, 2015

Features

-  Improve speed further for: ([@BridgeAR](https://github.com/BridgeAR))
 -  saving big strings (up to +300%)
 -  using .multi / .batch (up to +50% / on Node.js 0.10.x +300%)
 -  saving small buffers
-  Increased coverage to 99% ([@BridgeAR](https://github.com/BridgeAR))
-  Refactored manual backpressure control ([@BridgeAR](https://github.com/BridgeAR))
 -  Removed the high water mark and low water mark. Such a mechanism should be implemented by a user instead
 -  The `drain` event is from now on only emitted if the stream really had to buffer
-  Reduced the default connect_timeout to be one hour instead of 24h ([@BridgeAR](https://github.com/BridgeAR))
-  Added .path to redis.createClient(options); ([@BridgeAR](https://github.com/BridgeAR))
-  Ignore info command, if not available on server ([@ivanB1975](https://github.com/ivanB1975))

Bugfixes

-  Fixed a js parser error that could result in a timeout ([@BridgeAR](https://github.com/BridgeAR))
-  Fixed .multi / .batch used with Node.js 0.10.x not working properly after a reconnect ([@BridgeAR](https://github.com/BridgeAR))
-  Fixed fired but not yet returned commands not being rejected after a connection loss ([@BridgeAR](https://github.com/BridgeAR))
-  Fixed connect_timeout not respected if no connection has ever been established ([@gagle](https://github.com/gagle) & [@benjie](https://github.com/benjie))
-  Fixed return_buffers in pub sub mode ([@komachi](https://github.com/komachi))

## v.2.2.5 - 18 Oct, 2015

Bugfixes

-  Fixed undefined options passed to a new instance not accepted (possible with individual .createClient functions) ([@BridgeAR](https://github.com/BridgeAR))

## v.2.2.4 - 17 Oct, 2015

Bugfixes

-  Fixed unspecific error message for unresolvable commands ([@BridgeAR](https://github.com/BridgeAR))
-  Fixed not allowed command error in pubsub mode not being returned in a provided callback ([@BridgeAR](https://github.com/BridgeAR))
-  Fixed to many commands forbidden in pub sub mode ([@BridgeAR](https://github.com/BridgeAR))
-  Fixed mutation of the arguments array passed to .multi / .batch constructor ([@BridgeAR](https://github.com/BridgeAR))
-  Fixed mutation of the options object passed to createClient ([@BridgeAR](https://github.com/BridgeAR))
-  Fixed error callback in .multi not called if connection in broken mode ([@BridgeAR](https://github.com/BridgeAR))

## v.2.2.3 - 14 Oct, 2015

Bugfixes

-  Fixed multi not being executed on Node 0.10.x if node_redis not yet ready ([@BridgeAR](https://github.com/BridgeAR))

## v.2.2.2 - 14 Oct, 2015

Bugfixes

-  Fixed regular commands not being executed after a .multi until .exec was called ([@BridgeAR](https://github.com/BridgeAR))

## v.2.2.1 - 12 Oct, 2015

No code change

## v.2.2.0 - 12 Oct, 2015 - The peregrino falcon

The peregrino falcon is the fasted bird on earth and this is what this release is all about: Increased performance for heavy usage by up to **400%** [sic!] and increased overall performance for any command as well. Please check the benchmarks in the [README.md](README.md) for further details.

Features

-  Added rename_commands options to handle renamed commands from the redis config ([@digmxl](https://github.com/digmxl) & [@BridgeAR](https://github.com/BridgeAR))
-  Added disable_resubscribing option to prevent a client from resubscribing after reconnecting ([@BridgeAR](https://github.com/BridgeAR))
-  Increased performance ([@BridgeAR](https://github.com/BridgeAR))
 -  exchanging built in queue with [@petkaantonov](https://github.com/petkaantonov)'s [double-ended queue](https://github.com/petkaantonov/deque)
 -  prevent polymorphism
 -  optimize statements
-  Added *.batch* command, similar to .multi but without transaction ([@BridgeAR](https://github.com/BridgeAR))
-  Improved pipelining to minimize the [RTT](http://redis.io/topics/pipelining) further ([@BridgeAR](https://github.com/BridgeAR))

Bugfixes

-  Fixed a javascript parser regression introduced in 2.0 that could result in timeouts on high load. ([@BridgeAR](https://github.com/BridgeAR))
  - I was not able to write a regression test for this, since the error seems to only occur under heavy load with special conditions. So please have a look for timeouts with the js parser, if you use it and report all issues and switch to the hiredis parser in the meanwhile. If you're able to come up with a reproducable test case, this would be even better :)
-  Fixed should_buffer boolean for .exec, .select and .auth commands not being returned and fix a couple special conditions ([@BridgeAR](https://github.com/BridgeAR))

If you do not rely on transactions but want to reduce the RTT you can use .batch from now on. It'll behave just the same as .multi but it does not have any transaction and therefor won't roll back any failed commands.

Both .multi and .batch are from now on going to cache the commands and release them while calling .exec.

Please consider using .batch instead of looping through a lot of commands one by one. This will significantly improve your performance.

Here are some stats compared to ioredis 1.9.1 (Lenovo T450s i7-5600U):

                      simple set
          82,496 op/s » ioredis
         112,617 op/s » node_redis

                      simple get
          82,015 op/s » ioredis
         105,701 op/s » node_redis

                      simple get with pipeline
          10,233 op/s » ioredis
          26,541 op/s » node_redis (using .batch)

                      lrange 100
           7,321 op/s » ioredis
          26,155 op/s » node_redis

                      publish
          90,524 op/s » ioredis
         112,823 op/s » node_redis

                      subscribe
          43,783 op/s » ioredis
          61,889 op/s » node_redis

To conclude: we can proudly say that node_redis is very likely outperforming any other node redis client.

Known issues

-  The pub sub system has some flaws and those will be addressed in the next minor release

## v2.1.0 - Oct 02, 2015

Features:

-  Addded optional flush parameter to `.end`. If set to true, commands fired after using .end are going to be rejected instead of being ignored. (@crispy1989)
-  Addded: host and port can now be provided in a single options object. E.g. redis.createClient({ host: 'localhost', port: 1337, max_attempts: 5 }); (@BridgeAR)
-  Speedup common cases (@BridgeAR)

Bugfixes:

-  Fix argument mutation while using the array notation with the multi constructor (@BridgeAR)
-  Fix multi.hmset key not being type converted if used with an object and key not being a string (@BridgeAR)
-  Fix parser errors not being catched properly (@BridgeAR)
-  Fix a crash that could occur if a redis server does not return the info command as usual #541 (@BridgeAR)
-  Explicitly passing undefined as a callback statement will work again. E.g. client.publish('channel', 'message', undefined); (@BridgeAR)

## v2.0.1 - Sep 24, 2015

Bugfixes:

-  Fix argument mutation while using the array notation in combination with keys / callbacks ([#866](.)). (@BridgeAR)

## v2.0.0 - Sep 21, 2015

This is the biggest release that node_redis had since it was released in 2010. A long list of outstanding bugs has been fixed, so we are very happy to present you redis 2.0 and we highly recommend updating as soon as possible.

# What's new in 2.0

- Implemented a "connection is broken" mode if no connection could be established
- node_redis no longer throws under any circumstances, preventing it from terminating applications.
- Multi error handling is now working properly
- Consistent command behavior including multi
- Windows support
- Improved performance
- A lot of code cleanup
- Many bug fixes
- Better user support!

## Features:

- Added a "redis connection is broken" mode after reaching max connection attempts / exceeding connection timeout. (@BridgeAR)
- Added NODE_DEBUG=redis env to activate the debug_mode (@BridgeAR)
- Added a default connection timeout of 24h instead of never timing out as a default (@BridgeAR)
- Added: Network errors and other stream errors will from now on include the error code as `err.code` property (@BridgeAR)
- Added: Errors thrown by redis will now include the redis error code as `err.code` property. (@skeggse & @BridgeAR)
- Added: Errors thrown by node_redis will now include a `err.command` property for the command used (@BridgeAR)
- Added new commands and drop support for deprecated *substr* (@BridgeAR)
- Added new possibilities how to provide the command arguments (@BridgeAR)
- The entries in the keyspace of the server_info is now an object instead of a string. (@SinisterLight & @BridgeAR)
- Small speedup here and there (e.g. by not using .toLowerCase() anymore) (@BridgeAR)
- Full windows support (@bcoe)
- Increased coverage by 10% and add a lot of tests to make sure everything works as it should. We now reached 97% :-) (@BridgeAR)
- Remove dead code, clean up and refactor very old chunks (@BridgeAR)
- Don't flush the offline queue if reconnecting (@BridgeAR)
- Emit all errors insteaf of throwing sometimes and sometimes emitting them (@BridgeAR)
- *auth_pass* passwords are now checked to be a valid password (@jcppman & @BridgeAR)

## Bug fixes:

- Don't kill the app anymore by randomly throwing errors sync instead of emitting them (@BridgeAR)
- Don't catch user errors anymore occuring in callbacks (no try callback anymore & more fixes for the parser) (@BridgeAR)
- Early garbage collection of queued items (@dohse)
- Fix js parser returning errors as strings (@BridgeAR)
- Do not wrap errors into other errors (@BridgeAR)
- Authentication failures are now returned in the callback instead of being emitted (@BridgeAR)
- Fix a memory leak on reconnect (@rahar)
- Using `send_command` directly may now also be called without the args as stated in the [README.md](./README.md) (@BridgeAR)
- Fix the multi.exec error handling (@BridgeAR)
- Fix commands being inconsistent and behaving wrong (@BridgeAR)
- Channel names with spaces are now properly resubscribed after a reconnection (@pbihler)
- Do not try to reconnect after the connection timeout has been exceeded (@BridgeAR)
- Ensure the execution order is observed if using .eval (@BridgeAR)
- Fix commands not being rejected after calling .quit (@BridgeAR)
- Fix .auth calling the callback twice if already connected (@BridgeAR)
- Fix detect_buffers not working in pub sub mode and while monitoring (@BridgeAR)
- Fix channel names always being strings instead of buffers while return_buffers is true (@BridgeAR)
- Don't print any debug statements if not asked for (@BridgeAR)
- Fix a couple small other bugs

## Breaking changes:

1. redis.send_command commands have to be lower case from now on. This does only apply if you use `.send_command` directly instead of the convenient methods like `redis.command`.
2. Error messages have changed quite a bit. If you depend on a specific wording please check your application carfully.
3. Errors are from now on always either returned if a callback is present or emitted. They won't be thrown (neither sync, nor async).
4. The Multi error handling has changed a lot!
 - All errors are from now on errors instead of strings (this only applied to the js parser).
 - If an error occurs while queueing the commands an EXECABORT error will be returned including the failed commands as `.errors` property instead of an array with errors.
 - If an error occurs while executing the commands and that command has a callback it'll return the error as first parameter (`err, undefined` instead of `null, undefined`).
 - All the errors occuring while executing the commands will stay in the result value as error instance (if you used the js parser before they would have been strings). Be aware that the transaction won't be aborted if those error occurr!
 - If `multi.exec` does not have a callback and an EXECABORT error occurrs, it'll emit that error instead.
5. If redis can't connect to your redis server it'll give up after a certain point of failures (either max connection attempts or connection timeout exceeded). If that is the case it'll emit an CONNECTION_BROKEN error. You'll have to initiate a new client to try again afterwards.
6. The offline queue is not flushed anymore on a reconnect. It'll stay until node_redis gives up trying to reach the server or until you close the connection.
7. Before this release node_redis catched user errors and threw them async back. This is not the case anymore! No user behavior of what so ever will be tracked or catched.
8. The keyspace of `redis.server_info` (db0...) is from now on an object instead of an string.

NodeRedis also thanks @qdb, @tobek, @cvibhagool, @frewsxcv, @davidbanham, @serv, @vitaliylag, @chrishamant, @GamingCoder and all other contributors that I may have missed for their contributions!

From now on we'll push new releases more frequently out and fix further long outstanding things and implement new features.

## v1.0.0 - Aug 30, 2015

* Huge issue and pull-request cleanup. Thanks Blain! (@blainsmith)
* [#658](https://github.com/NodeRedis/node_redis/pull/658) Client now parses URL-format connection strings (e.g., redis://foo:pass@127.0.0.1:8080) (@kuwabarahiroshi)
* [#749](https://github.com/NodeRedis/node_redis/pull/749) Fix reconnection bug when client is in monitoring mode (@danielbprice)
* [#786](https://github.com/NodeRedis/node_redis/pull/786) Refactor createClient. Fixes #651 (@BridgeAR)
* [#793](https://github.com/NodeRedis/node_redis/pull/793) Refactor tests and improve test coverage (@erinspice, @bcoe)
* [#733](https://github.com/NodeRedis/node_redis/pull/733) Fixes detect_buffers functionality in the context of exec. Fixes #732, #263 (@raydog)
* [#785](https://github.com/NodeRedis/node_redis/pull/785) Tiny speedup by using 'use strict' (@BridgeAR)
* Fix extraneous error output due to pubsub tests (Mikael Kohlmyr)

## v0.12.1 - Aug 10, 2014
* Fix IPv6/IPv4 family selection in node 0.11+ (Various)

## v0.12.0 - Aug 9, 2014
* Fix unix socket support (Jack Tang)
* Improve createClient argument handling (Jack Tang)

## v0.11.0 - Jul 10, 2014

* IPv6 Support. (Yann Stephan)
* Revert error emitting and go back to throwing errors. (Bryce Baril)
* Set socket_keepalive to prevent long-lived client timeouts. (mohit)
* Correctly reset retry timer. (ouotuo)
* Domains protection from bad user exit. (Jake Verbaten)
* Fix reconnection socket logic to prevent misqueued entries. (Iain Proctor)

## v0.10.3 - May 22, 2014

* Update command list to match Redis 2.8.9 (Charles Feng)

## v0.10.2 - May 18, 2014

* Better binary key handling for HGETALL. (Nick Apperson)
* Fix test not resetting `error` handler. (CrypticSwarm)
* Fix SELECT error semantics. (Bryan English)

## v0.10.1 - February 17, 2014

* Skip plucking redis version from the INFO stream if INFO results weren't provided. (Robert Sköld)

## v0.10.0 - December 21, 2013

* Instead of throwing errors asynchronously, emit errors on client. (Bryce Baril)

## v0.9.2 - December 15, 2013

* Regenerate commands for new 2.8.x Redis commands. (Marek Ventur)
* Correctly time reconnect counts when using 'auth'. (William Hockey)

## v0.9.1 - November 23, 2013

* Allow hmset to accept numeric keys. (Alex Stokes)
* Fix TypeError for multiple MULTI/EXEC errors. (Kwangsu Kim)

## v0.9.0 - October 17, 2013

* Domains support. (Forrest L Norvell)

## v0.8.6 - October 2, 2013

* If error is already an Error, don't wrap it in another Error. (Mathieu M-Gosselin)
* Fix retry delay logic (Ian Babrou)
* Return Errors instead of strings where Errors are expected (Ian Babrou)
* Add experimental `.unref()` method to RedisClient (Bryce Baril / Olivier Lalonde)
* Strengthen checking of reply to prevent conflating "message" or "pmessage" fields with pub_sub replies. (Bryce Baril)

## v0.8.5 - September 26, 2013

* Add `auth_pass` option to connect and immediately authenticate (Henrik Peinar)

## v0.8.4 - June 24, 2013

Many contributed features and fixes, including:
* Ignore password set if not needed. (jbergknoff)
* Improved compatibility with 0.10.X for tests and client.end() (Bryce Baril)
* Protect connection retries from application exceptions. (Amos Barreto)
* Better exception handling for Multi/Exec (Thanasis Polychronakis)
* Renamed pubsub mode to subscriber mode (Luke Plaster)
* Treat SREM like SADD when passed an array (Martin Ciparelli)
* Fix empty unsub/punsub TypeError (Jeff Barczewski)
* Only attempt to run a callback if it one was provided (jifeng)

## v0.8.3 - April 09, 2013

Many contributed features and fixes, including:
* Fix some tests for Node.js version 0.9.x+ changes (Roman Ivanilov)
* Fix error when commands submitted after idle event handler (roamm)
* Bypass Redis for no-op SET/SETEX commands (jifeng)
* Fix HMGET + detect_buffers (Joffrey F)
* Fix CLIENT LOAD functionality (Jonas Dohse)
* Add percentage outputs to diff_multi_bench_output.js (Bryce Baril)
* Add retry_max_delay option (Tomasz Durka)
* Fix parser off-by-one errors with nested multi-bulk replies (Bryce Baril)
* Prevent parser from sinking application-side exceptions (Bryce Baril)
* Fix parser incorrect buffer skip when parsing multi-bulk errors (Bryce Baril)
* Reverted previous change with throwing on non-string values with HMSET (David Trejo)
* Fix command queue sync issue when using pubsub (Tom Leach)
* Fix compatibility with two-word Redis commands (Jonas Dohse)
* Add EVAL with array syntax (dmoena)
* Fix tests due to Redis reply order changes in 2.6.5+ (Bryce Baril)
* Added a test for the SLOWLOG command (Nitesh Sinha)
* Fix SMEMBERS order dependency in test broken by Redis changes (Garrett Johnson)
* Update commands for new Redis commands (David Trejo)
* Prevent exception from SELECT on subscriber reconnection (roamm)

## v0.8.2 - November 11, 2012

Another version bump because 0.8.1 didn't get applied properly for some mysterious reason.
Sorry about that.

Changed name of "faster" parser to "javascript".

## v0.8.1 - September 11, 2012

Important bug fix for null responses (Jerry Sievert)

## v0.8.0 - September 10, 2012

Many contributed features and fixes, including:

* Pure JavaScript reply parser that is usually faster than hiredis (Jerry Sievert)
* Remove hiredis as optionalDependency from package.json. It still works if you want it.
* Restore client state on reconnect, including select, subscribe, and monitor. (Ignacio Burgueño)
* Fix idle event (Trae Robrock)
* Many documentation improvements and bug fixes (David Trejo)

## v0.7.2 - April 29, 2012

Many contributed fixes. Thank you, contributors.

* [GH-190] - pub/sub mode fix (Brian Noguchi)
* [GH-165] - parser selection fix (TEHEK)
* numerous documentation and examples updates
* auth errors emit Errors instead of Strings (David Trejo)

## v0.7.1 - November 15, 2011

Fix regression in reconnect logic.

Very much need automated tests for reconnection and queue logic.

## v0.7.0 - November 14, 2011

Many contributed fixes. Thanks everybody.

* [GH-127] - properly re-initialize parser on reconnect
* [GH-136] - handle passing undefined as callback (Ian Babrou)
* [GH-139] - properly handle exceptions thrown in pub/sub event handlers (Felix Geisendörfer)
* [GH-141] - detect closing state on stream error (Felix Geisendörfer)
* [GH-142] - re-select database on reconnection (Jean-Hugues Pinson)
* [GH-146] - add sort example (Maksim Lin)

Some more goodies:

* Fix bugs with node 0.6
* Performance improvements
* New version of `multi_bench.js` that tests more realistic scenarios
* [GH-140] - support optional callback for subscribe commands
* Properly flush and error out command queue when connection fails
* Initial work on reconnection thresholds

## v0.6.7 - July 30, 2011

(accidentally skipped v0.6.6)

Fix and test for [GH-123]

Passing an Array as as the last argument should expand as users
expect.  The old behavior was to coerce the arguments into Strings,
which did surprising things with Arrays.

## v0.6.5 - July 6, 2011

Contributed changes:

*  Support SlowBuffers (Umair Siddique)
*  Add Multi to exports (Louis-Philippe Perron)
*  Fix for drain event calculation (Vladimir Dronnikov)

Thanks!

## v0.6.4 - June 30, 2011

Fix bug with optional callbacks for hmset.

## v0.6.2 - June 30, 2011

Bugs fixed:

*  authentication retry while server is loading db (danmaz74) [GH-101]
*  command arguments processing issue with arrays

New features:

*  Auto update of new commands from redis.io (Dave Hoover)
*  Performance improvements and backpressure controls.
*  Commands now return the true/false value from the underlying socket write(s).
*  Implement command_queue high water and low water for more better control of queueing.

See `examples/backpressure_drain.js` for more information.

## v0.6.1 - June 29, 2011

Add support and tests for Redis scripting through EXEC command.

Bug fix for monitor mode.  (forddg)

Auto update of new commands from redis.io (Dave Hoover)

## v0.6.0 - April 21, 2011

Lots of bugs fixed.

*  connection error did not properly trigger reconnection logic [GH-85]
*  client.hmget(key, [val1, val2]) was not expanding properly [GH-66]
*  client.quit() while in pub/sub mode would throw an error [GH-87]
*  client.multi(['hmset', 'key', {foo: 'bar'}]) fails [GH-92]
*  unsubscribe before subscribe would make things very confused [GH-88]
*  Add BRPOPLPUSH [GH-79]

## v0.5.11 - April 7, 2011

Added DISCARD

I originally didn't think DISCARD would do anything here because of the clever MULTI interface, but somebody
pointed out to me that DISCARD can be used to flush the WATCH set.

## v0.5.10 - April 6, 2011

Added HVALS

## v0.5.9 - March 14, 2011

Fix bug with empty Array arguments - Andy Ray

## v0.5.8 - March 14, 2011

Add `MONITOR` command and special monitor command reply parsing.

## v0.5.7 - February 27, 2011

Add magical auth command.

Authentication is now remembered by the client and will be automatically sent to the server
on every connection, including any reconnections.

## v0.5.6 - February 22, 2011

Fix bug in ready check with `return_buffers` set to `true`.

Thanks to Dean Mao and Austin Chau.

## v0.5.5 - February 16, 2011

Add probe for server readiness.

When a Redis server starts up, it might take a while to load the dataset into memory.
During this time, the server will accept connections, but will return errors for all non-INFO
commands.  Now node_redis will send an INFO command whenever it connects to a server.
If the info command indicates that the server is not ready, the client will keep trying until
the server is ready.  Once it is ready, the client will emit a "ready" event as well as the
"connect" event.  The client will queue up all commands sent before the server is ready, just
like it did before.  When the server is ready, all offline/non-ready commands will be replayed.
This should be backward compatible with previous versions.

To disable this ready check behavior, set `options.no_ready_check` when creating the client.

As a side effect of this change, the key/val params from the info command are available as
`client.server_options`.  Further, the version string is decomposed into individual elements
in `client.server_options.versions`.

## v0.5.4 - February 11, 2011

Fix excess memory consumption from Queue backing store.

Thanks to Gustaf Sjöberg.

## v0.5.3 - February 5, 2011

Fix multi/exec error reply callback logic.

Thanks to Stella Laurenzo.

## v0.5.2 - January 18, 2011

Fix bug where unhandled error replies confuse the parser.

## v0.5.1 - January 18, 2011

Fix bug where subscribe commands would not handle redis-server startup error properly.

## v0.5.0 - December 29, 2010

Some bug fixes:

* An important bug fix in reconnection logic.  Previously, reply callbacks would be invoked twice after
  a reconnect.
* Changed error callback argument to be an actual Error object.

New feature:

* Add friendly syntax for HMSET using an object.

## v0.4.1 - December 8, 2010

Remove warning about missing hiredis.  You probably do want it though.

## v0.4.0 - December 5, 2010

Support for multiple response parsers and hiredis C library from Pieter Noordhuis.
Return Strings instead of Buffers by default.
Empty nested mb reply bug fix.

## v0.3.9 - November 30, 2010

Fix parser bug on failed EXECs.

## v0.3.8 - November 10, 2010

Fix for null MULTI response when WATCH condition fails.

## v0.3.7 - November 9, 2010

Add "drain" and "idle" events.

## v0.3.6 - November 3, 2010

Add all known Redis commands from Redis master, even ones that are coming in 2.2 and beyond.

Send a friendlier "error" event message on stream errors like connection refused / reset.

## v0.3.5 - October 21, 2010

A few bug fixes.

* Fixed bug with `nil` multi-bulk reply lengths that showed up with `BLPOP` timeouts.
* Only emit `end` once when connection goes away.
* Fixed bug in `test.js` where driver finished before all tests completed.

## unversioned wasteland

See the git history for what happened before.


text:
package info.bitrich.xchangestream.ftx;

import com.fasterxml.jackson.databind.JsonNode;
import info.bitrich.xchangestream.core.StreamingTradeService;
import io.reactivex.Observable;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.dto.Order;
import org.knowm.xchange.dto.trade.UserTrade;

public class FtxStreamingTradeService implements StreamingTradeService {

  private final Observable<JsonNode> fills;
  private final Observable<JsonNode> orders;

  public FtxStreamingTradeService(FtxStreamingService service) {
    this.fills = service.subscribeChannel("fills");
    this.orders = service.subscribeChannel("orders");
  }

  @Override
  public Observable<UserTrade> getUserTrades(CurrencyPair currencyPair, Object... args) {

    return fills
        .filter(jsonNode -> jsonNode.hasNonNull("data"))
        .filter(
            jsonNode ->
                new CurrencyPair(jsonNode.get("data").get("market").asText()).equals(currencyPair))
        .map(FtxStreamingAdapters::adaptUserTrade);
  }

  @Override
  public Observable<Order> getOrderChanges(CurrencyPair currencyPair, Object... args) {

    return orders
        .filter(jsonNode -> jsonNode.hasNonNull("data"))
        .filter(
            jsonNode ->
                new CurrencyPair(jsonNode.get("data").get("market").asText()).equals(currencyPair))
        .map(FtxStreamingAdapters::adaptOrders);
  }
}

redpajama_set_name: RedPajamaGithub


text:
package main

import (
	"bufio"
	"context"
	"crypto/rand"
	"flag"
	"fmt"
	"io"
	"log"
	mrand "math/rand"
	"os"

	"github.com/libp2p/go-libp2p"
	"github.com/libp2p/go-libp2p/core/crypto"
	"github.com/libp2p/go-libp2p/core/host"
	"github.com/libp2p/go-libp2p/core/network"
	"github.com/libp2p/go-libp2p/core/peer"
	"github.com/libp2p/go-libp2p/core/peerstore"

	"github.com/multiformats/go-multiaddr"
)

func handleStream(s network.Stream) {
	log.Println("Got a new stream!")

	// Create a buffer stream for non blocking read and write.
	rw := bufio.NewReadWriter(bufio.NewReader(s), bufio.NewWriter(s))

	go readData(rw)
	go writeData(rw)

	// stream 's' will stay open until you close it (or the other side closes it).
}

func readData(rw *bufio.ReadWriter) {
	for {
		str, _ := rw.ReadString('\n')

		if str == "" {
			return
		}
		if str != "\n" {
			// Green console colour: 	\x1b[32m
			// Reset console colour: 	\x1b[0m
			fmt.Printf("\x1b[32m%s\x1b[0m> ", str)
		}

	}
}

func writeData(rw *bufio.ReadWriter) {
	stdReader := bufio.NewReader(os.Stdin)

	for {
		fmt.Print("> ")
		sendData, err := stdReader.ReadString('\n')
		if err != nil {
			log.Println(err)
			return
		}

		rw.WriteString(fmt.Sprintf("%s\n", sendData))
		rw.Flush()
	}
}

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	sourcePort := flag.Int("sp", 0, "Source port number")
	dest := flag.String("d", "", "Destination multiaddr string")
	help := flag.Bool("help", false, "Display help")
	debug := flag.Bool("debug", false, "Debug generates the same node ID on every execution")

	flag.Parse()

	if *help {
		fmt.Printf("This program demonstrates a simple p2p chat application using libp2p\n\n")
		fmt.Println("Usage: Run './chat -sp <SOURCE_PORT>' where <SOURCE_PORT> can be any port number.")
		fmt.Println("Now run './chat -d <MULTIADDR>' where <MULTIADDR> is multiaddress of previous listener host.")

		os.Exit(0)
	}

	// If debug is enabled, use a constant random source to generate the peer ID. Only useful for debugging,
	// off by default. Otherwise, it uses rand.Reader.
	var r io.Reader
	if *debug {
		// Use the port number as the randomness source.
		// This will always generate the same host ID on multiple executions, if the same port number is used.
		// Never do this in production code.
		r = mrand.New(mrand.NewSource(int64(*sourcePort)))
	} else {
		r = rand.Reader
	}

	h, err := makeHost(*sourcePort, r)
	if err != nil {
		log.Println(err)
		return
	}

	if *dest == "" {
		startPeer(ctx, h, handleStream)
	} else {
		rw, err := startPeerAndConnect(ctx, h, *dest)
		if err != nil {
			log.Println(err)
			return
		}

		// Create a thread to read and write data.
		go writeData(rw)
		go readData(rw)

	}

	// Wait forever
	select {}
}

func makeHost(port int, randomness io.Reader) (host.Host, error) {
	// Creates a new RSA key pair for this host.
	prvKey, _, err := crypto.GenerateKeyPairWithReader(crypto.RSA, 2048, randomness)
	if err != nil {
		log.Println(err)
		return nil, err
	}

	// 0.0.0.0 will listen on any interface device.
	sourceMultiAddr, _ := multiaddr.NewMultiaddr(fmt.Sprintf("/ip4/0.0.0.0/tcp/%d", port))

	// libp2p.New constructs a new libp2p Host.
	// Other options can be added here.
	return libp2p.New(
		libp2p.ListenAddrs(sourceMultiAddr),
		libp2p.Identity(prvKey),
	)
}

func startPeer(ctx context.Context, h host.Host, streamHandler network.StreamHandler) {
	// Set a function as stream handler.
	// This function is called when a peer connects, and starts a stream with this protocol.
	// Only applies on the receiving side.
	h.SetStreamHandler("/chat/1.0.0", streamHandler)

	// Let's get the actual TCP port from our listen multiaddr, in case we're using 0 (default; random available port).
	var port string
	for _, la := range h.Network().ListenAddresses() {
		if p, err := la.ValueForProtocol(multiaddr.P_TCP); err == nil {
			port = p
			break
		}
	}

	if port == "" {
		log.Println("was not able to find actual local port")
		return
	}

	log.Printf("Run './chat -d /ip4/127.0.0.1/tcp/%v/p2p/%s' on another console.\n", port, h.ID().Pretty())
	log.Println("You can replace 127.0.0.1 with public IP as well.")
	log.Println("Waiting for incoming connection")
	log.Println()
}

func startPeerAndConnect(ctx context.Context, h host.Host, destination string) (*bufio.ReadWriter, error) {
	log.Println("This node's multiaddresses:")
	for _, la := range h.Addrs() {
		log.Printf(" - %v\n", la)
	}
	log.Println()

	// Turn the destination into a multiaddr.
	maddr, err := multiaddr.NewMultiaddr(destination)
	if err != nil {
		log.Println(err)
		return nil, err
	}

	// Extract the peer ID from the multiaddr.
	info, err := peer.AddrInfoFromP2pAddr(maddr)
	if err != nil {
		log.Println(err)
		return nil, err
	}

	// Add the destination's peer multiaddress in the peerstore.
	// This will be used during connection and stream creation by libp2p.
	h.Peerstore().AddAddrs(info.ID, info.Addrs, peerstore.PermanentAddrTTL)

	// Start a stream with the destination.
	// Multiaddress of the destination peer is fetched from the peerstore using 'peerId'.
	s, err := h.NewStream(context.Background(), info.ID, "/chat/1.0.0")
	if err != nil {
		log.Println(err)
		return nil, err
	}
	log.Println("Established connection to destination")

	// Create a buffered stream so that read and writes are non blocking.
	rw := bufio.NewReadWriter(bufio.NewReader(s), bufio.NewWriter(s))

	return rw, nil
}


text:
package com.hive_unit;

import com.google.common.io.Files;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.mapred.HadoopTestCase;
import org.apache.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class HiveTestBase extends HadoopTestCase {

    protected final static Logger LOGGER = Logger.getLogger(HiveTestBase.class.getName());
    protected static final Path ROOT_DIR = new Path("testing");
    protected List<File> toCleanUp = new ArrayList<File>();

    public HiveTestBase() throws IOException {
        super(HadoopTestCase.LOCAL_MR, HadoopTestCase.LOCAL_FS, 1, 1);
        Map<String, String> env = new HashMap<String, String>();
        env.putAll(System.getenv());

        if (System.getenv("HADOOP_HOME") == null) {
            String shome = System.getProperty("user.home");
            if (shome != null) {
                File hadoopHome = new File(new File(shome, "hadoop"), "hadoop-1.2.1_local");
                if (hadoopHome.exists()) {
                    env.put("HADOOP_HOME", hadoopHome.getAbsolutePath());
                    EnvironmentHack.setEnv(env);
                    LOGGER.info(String.format("HADOOP_HOME was set by hiveunit to %1$s.", System.getenv("HADOOP_HOME")));
                }
                File target = new File("target/hadoop-1.2.1");
                if (target.exists()) {
                    env.put("HADOOP_HOME", target.getAbsolutePath());
                    EnvironmentHack.setEnv(env);
                    LOGGER.info(String.format("HADOOP_HOME was set by hiveunit to %1$s.", System.getenv("HADOOP_HOME")));
                }
            } else {
                LOGGER.info(String.format("HADOOP_HOME was found in environment as %1$s. Using that for hiveunit.", System.getenv("HADOOP_HOME")));
            }
            //detect variable or hadoop in path and throw exception here?
        }
    }

    protected Path getDir(Path dir) {
        if (isLocalFS()) {
            String localPathRoot = System.getProperty("test.build.data", "/tmp").replace(' ', '+');
            dir = new Path(localPathRoot, dir);
        }
        return dir;
    }

    /**
     * Hive InputFormats and Serdes may require some classes to exist in the auxlib or lib folder. This method
     * finds the jar file for a given class and copies that jar to the hadoop lib directory. (this only works with a writable
     * hadoop_home) the teardown method of this class should automatically remove this file.
     *
     * @param cl
     */
    public void addJarFileToLib(Class cl) {
        try {
            File source = new File(cl.getProtectionDomain().getCodeSource().getLocation().toURI());
            File destination = new File(System.getenv("HADOOP_HOME"), "lib");
            if (destination.exists() && destination.isDirectory() && destination.canWrite()) {
                LOGGER.info("copy " + source.getPath() + "destination " + destination.getPath());
                File destinationFile = new File(destination, source.getName());
                Files.copy(source, destinationFile);
                toCleanUp.add(destinationFile);
            } else {
                throw new RuntimeException("Did not add jar file to " + destination + " Permissions?");
            }
        } catch (IOException e) {
            throw new RuntimeException("unable to copy to hadoop_home" + e);
        } catch (URISyntaxException e) {
            throw new RuntimeException("unable to copy to hadoop_home" + e);
        }
    }

    public void setUp() throws Exception {
        super.setUp();
        String jarFile = org.apache.hadoop.hive.ql.exec.CopyTask.class.getProtectionDomain().getCodeSource().getLocation().getFile();
        System.setProperty(HiveConf.ConfVars.HIVEJAR.toString(), jarFile);
        Path rootDir = getDir(ROOT_DIR);
        Configuration conf = createJobConf();
        FileSystem fs = FileSystem.get(conf);
        fs.delete(rootDir, true);
        Path metastorePath = new Path("/tmp/metastore_db");
        fs.delete(metastorePath, true);
        Path warehouse = new Path("/tmp/warehouse");
        fs.delete(warehouse, true);
        fs.mkdirs(warehouse);
    }

    public void tearDown() throws Exception {
        super.tearDown();
        for (File f : this.toCleanUp) {
            boolean result = f.delete();
            if (!result) {
                LOGGER.warn("count not delete " + f);
            }
        }
    }
}


text:
VERSION >= v"0.4.0-dev+6521" && __precompile__()

module ColorTypes

using FixedPointNumbers, Compat
if VERSION < v"0.4.0-dev"
    using Docile
end

typealias Fractional Union(FloatingPoint, FixedPoint)
typealias U8 Ufixed8

if VERSION >= v"0.4.0-dev"
    @doc "`U8` is an abbreviation for the Ufixed8 type from FixedPointNumbers" -> U8
end

import Base: ==, convert, eltype, length, show, showcompact, one, zero

## Types
export Fractional, U8

export Colorant
export Color, TransparentColor, AlphaColor, ColorAlpha, AbstractRGB

export RGB, BGR, RGB1, RGB4
export HSV, HSB, HSL, HSI
export XYZ, xyY, LMS, Lab, LCHab, Luv, LCHuv
export DIN99, DIN99d, DIN99o
export YIQ, YCbCr

export Gray

export RGB24, ARGB32, Gray24, AGray32

# Note: the parametric TransparentColorColors are exported
# algorithmically, see `@make_alpha` in types.jl.

## Functions
export base_color_type, base_colorant_type, ccolor, color, color_type
export alphacolor, coloralpha
export alpha, red, green, blue, gray   # accessor functions that generalize to RGB24, etc.
export comp1, comp2, comp3

include("types.jl")
include("traits.jl")
include("conversions.jl")
include("show.jl")

end # module

if VERSION < v"0.4.0-dev"
    using Docile
end

@doc """
ColorTypes summary:

Type hierarchy:
```
                          Colorant{T,N}
             Color{T,N}                    TransparentColor{C,T,N}
     AbstractRGB{T}                  AlphaColor{C,T,N}  ColorAlpha{C,T,N}
```

Concrete types:
- `RGB`, `BGR`, `RGB1`, `RGB4`, `RGB24` are all subtypes of `AbstractRGB`

- `HSV`, `HSL`, `HSI`, `XYZ`, `xyY`, `Lab`, `LCHab`, `Luv`, `LCHuv`,
  `DIN99`, `DIN99d`, `DIN99o`, `LMS`, `YIQ`, `YCbCR` are subtypes of
  `Color{T,3}`

- Alpha-channel analogs in such as `ARGB` and `RGBA` for most of those
  types (with a few exceptions like `RGB24`, which has `ARGB32`)

- Grayscale types `Gray` and `Gray24` (subtypes of `Color{T,1}`), and
  the corresponding transparent types `AGray`, `GrayA`, and `AGray32`

- Trait functions `eltype`, `length`, `alphacolor`, `coloralpha`,
  `color_type`, `base_color_type`, `base_colorant_type`, `ccolor`

- Getters `red`, `green`, `blue`, `alpha`, `gray`, `comp1`, `comp2`, `comp3`

Use `?` to get more information about specific types or functions.
""" -> ColorTypes


text:
#include "hpdf_conf.h"
#include "hpdf_utils.h"
#include "hpdf.h"
#include "hpdf_image.h"

static HPDF_Image
LoadPngImageFromStream (HPDF_Doc      pdf,
                        HPDF_Stream   imagedata,
                        HPDF_BOOL     delayed_loading);

HPDF_EXPORT(HPDF_Image)
HPDF_LoadPngImageFromFile  (HPDF_Doc     pdf,
                            const char  *filename)
{
    HPDF_Stream imagedata;
    HPDF_Image image;

    HPDF_PTRACE ((" HPDF_LoadPngImageFromFile\n"));

    if (!HPDF_HasDoc (pdf))
        return NULL;

    /* create file stream */
    imagedata = HPDF_FileReader_New (pdf->mmgr, filename);

    if (HPDF_Stream_Validate (imagedata))
        image = LoadPngImageFromStream (pdf, imagedata, HPDF_FALSE);
    else
        image = NULL;

    /* destroy file stream */
    if (imagedata)
        HPDF_Stream_Free (imagedata);

    if (!image)
        HPDF_CheckError (&pdf->error);

    return image;
}

/* delaied loading version of HPDF_LoadPngImageFromFile */
HPDF_EXPORT(HPDF_Image)
HPDF_LoadPngImageFromFile2  (HPDF_Doc     pdf,
                             const char  *filename)
{
    HPDF_Stream imagedata;
    HPDF_Image image;
    HPDF_String fname;

    HPDF_PTRACE ((" HPDF_LoadPngImageFromFile\n"));

    if (!HPDF_HasDoc (pdf))
        return NULL;

    /* check whether file name is valid or not. */
    imagedata = HPDF_FileReader_New (pdf->mmgr, filename);

    if (HPDF_Stream_Validate (imagedata))
        image = LoadPngImageFromStream (pdf, imagedata, HPDF_TRUE);
    else
        image = NULL;

    /* destroy file stream */
    if (imagedata)
        HPDF_Stream_Free (imagedata);

    if (!image)
        HPDF_CheckError (&pdf->error);

    /* add file-name to image dictionary as a hidden entry.
     * it is used when the image data is needed.
     */
    fname = HPDF_String_New (pdf->mmgr, filename, NULL);
    if (!fname) {
        HPDF_CheckError (&pdf->error);
        return NULL;
    }

    fname->header.obj_id |= HPDF_OTYPE_HIDDEN;

    if ((HPDF_Dict_Add (image, "_FILE_NAME", fname)) != HPDF_OK) {
        HPDF_CheckError (&pdf->error);
        return NULL;
    }

    return image;
}

#ifndef HPDF_NOPNGLIB
static HPDF_Image
LoadPngImageFromStream (HPDF_Doc      pdf,
                        HPDF_Stream   imagedata,
                        HPDF_BOOL     delayed_loading)
{
    HPDF_Image image;

    HPDF_PTRACE ((" HPDF_LoadPngImageFromStream\n"));

    image = HPDF_Image_LoadPngImage (pdf->mmgr, imagedata, pdf->xref,
                delayed_loading);

    if (image && (pdf->compression_mode & HPDF_COMP_IMAGE))
        image->filter = HPDF_STREAM_FILTER_FLATE_DECODE;

    return image;
}

#else
static HPDF_Image
LoadPngImageFromStream (HPDF_Doc      pdf,
                        HPDF_Stream   imagedata,
                        HPDF_BOOL     delayed_loading)
{
    HPDF_SetError (&pdf->error, HPDF_UNSUPPORTED_FUNC, 0);

    return NULL;
}

#endif /* HPDF_NOPNGLIB */


text:
CKEDITOR.editorConfig = function(config) {
    // Define changes to default configuration here. For example:
    // config.language = 'fr';
    // config.uiColor = '#AADC6E';
};


text:
package com.amazonaws.services.emrserverless.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.emrserverless.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * InitialCapacityConfig JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class InitialCapacityConfigJsonUnmarshaller implements Unmarshaller<InitialCapacityConfig, JsonUnmarshallerContext> {

    public InitialCapacityConfig unmarshall(JsonUnmarshallerContext context) throws Exception {
        InitialCapacityConfig initialCapacityConfig = new InitialCapacityConfig();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return null;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("workerCount", targetDepth)) {
                    context.nextToken();
                    initialCapacityConfig.setWorkerCount(context.getUnmarshaller(Long.class).unmarshall(context));
                }
                if (context.testExpression("workerConfiguration", targetDepth)) {
                    context.nextToken();
                    initialCapacityConfig.setWorkerConfiguration(WorkerResourceConfigJsonUnmarshaller.getInstance().unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return initialCapacityConfig;
    }

    private static InitialCapacityConfigJsonUnmarshaller instance;

    public static InitialCapacityConfigJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new InitialCapacityConfigJsonUnmarshaller();
        return instance;
    }
}


text:
@interface Stack()
@property (nonatomic, strong) NSMutableArray *objects;
@end

@implementation Stack

@synthesize objects = _objects;

#pragma mark -

- (id)init {
    if ((self = [self initWithArray:nil])) {
    }
    return self;
}

- (id)initWithArray:(NSArray*)array {
    if ((self = [super init])) {
        _objects = [[NSMutableArray alloc] initWithArray:array];
    }
    return self;
}

#pragma mark - Custom accessors

- (NSUInteger)count {
    return _objects.count;
}

#pragma mark -

- (void)pushObject:(id)object {
    if (object) {
        [_objects addObject:object];
    }
}

- (void)pushObjects:(NSArray*)objects {
    for (id object in objects) {
        [self pushObject:object];
    }
}

- (id)popObject {
    if (_objects.count > 0) {
        id object = [_objects objectAtIndex:(_objects.count - 1)];
        [_objects removeLastObject];
        return object;
    }
    return nil;
}

- (id)peekObject {
    if (_objects.count > 0) {
        id object = [_objects objectAtIndex:(_objects.count - 1)];
        return object;
    }
    return nil;
}

#pragma mark - NSFastEnumeration

- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(__unsafe_unretained id [])buffer count:(NSUInteger)len {
    return [_objects countByEnumeratingWithState:state objects:buffer count:len];
}

@end


text:
    <form>

            Name
                    <input type="text" placeholder="Name Contains" ng-model="searchName">

            School
                    <input type="text" placeholder="School Contains" ng-model="searchSchool">

            Descriptor
                    <input type="text" placeholder="Descriptor Contains" ng-model="searchDescriptor">

            <input type="submit" class="button" value="Search" ng-click="search()">

    </form>

{{s.name}}

                    School: {{s.school}} [{{s.descriptor}}]

Level: {{s.spell_level}}

            <button class="close-button" aria-label="Close alert" type="button" ng-click="clearSpell()">
                ×
            </button>

        There are no results matching your search criteria.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace WindowsGame1
{
    class BackgroundElement : GameObject
    {
        protected float deltaX;
        protected float locX;

        public BackgroundElement(Rectangle sourceRect, Rectangle destRect, float dX)
            : base()
        {
            SourceRect = sourceRect;
            DestinationRect = destRect;
            deltaX = dX;
            locX = destRect.X;
        }

        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);
            locX += deltaX;
            if (locX < -DestinationRect.Width)
            {
                locX += DestinationRect.Width;
            }
            DestinationRect.X = (int)locX;
        }

    }
}


text:
using Elasticsearch.Net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Nest
{
	public partial interface IClusterPendingTasksRequest { }

	public partial class ClusterPendingTasksRequest { }

	public partial class ClusterPendingTasksDescriptor { }
}


text:
package org.robolectric.annotation.processing.validator;

import org.robolectric.annotation.processing.RobolectricModel;

import java.util.List;

import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.type.TypeMirror;
import javax.tools.Diagnostic.Kind;

/**
 * Validator that checks usages of {@link org.robolectric.annotation.Implements}.
 */
public class ImplementsValidator extends Validator {

  public static final String IMPLEMENTS_CLASS = "org.robolectric.annotation.Implements";

  public ImplementsValidator(RobolectricModel model, ProcessingEnvironment env) {
    super(model, env, IMPLEMENTS_CLASS);
  }

  private TypeElement getClassNameTypeElement(AnnotationValue cv) {
    String className = RobolectricModel.classNameVisitor.visit(cv);
    TypeElement type = elements.getTypeElement(className.replace('$', '.'));

    if (type == null) {
      error("@Implements: could not resolve class <" + className + '>', cv);
      return null;
    }
    return type;
  }

  @Override
  public Void visitType(TypeElement elem, Element parent) {
    // Don't import nested classes because some of them have the same name.
    AnnotationMirror am = getCurrentAnnotation();
    AnnotationValue av = RobolectricModel.getAnnotationValue(am, "value");
    AnnotationValue cv = RobolectricModel.getAnnotationValue(am, "className");
    TypeElement type = null;
    if (av == null) {
      if (cv == null) {
        error("@Implements: must specify <value> or <className>");
        return null;
      }
      type = getClassNameTypeElement(cv);
    } else {
      TypeMirror value = RobolectricModel.valueVisitor.visit(av);
      if (value == null) {
        return null;
      }

      boolean isAnything = model.ANYTHING_MIRROR != null && types.isSameType(value, model.ANYTHING_MIRROR);

      if (isAnything) {

        if (cv == null) {
          error("@Implements: Anything class specified but no <className> attribute");
          return null;
        }

        type = getClassNameTypeElement(cv);
      } else if (cv != null) {
        error("@Implements: cannot specify both <value> and <className> attributes");
      } else {
        type = RobolectricModel.typeVisitor.visit(types.asElement(value));
      }
    }
    if (type == null) {
      return null;
    }
    final List<? extends TypeParameterElement> typeTP = type.getTypeParameters();
    final List<? extends TypeParameterElement> elemTP = elem.getTypeParameters();
    if (!model.isSameParameterList(typeTP, elemTP)) {
      StringBuilder message = new StringBuilder();
      if (elemTP.isEmpty()) {
        message.append("Shadow type is missing type parameters, expected <");
        model.appendParameterList(message, type.getTypeParameters());
        message.append('>');
      } else if (typeTP.isEmpty()) {
        message.append("Shadow type has type parameters but real type does not");
      } else {
        message.append("Shadow type must have same type parameters as its real counterpart: expected <");
        model.appendParameterList(message, type.getTypeParameters());
        message.append(">, was <");
        model.appendParameterList(message, elem.getTypeParameters());
        message.append('>');
      }
      messager.printMessage(Kind.ERROR, message, elem);
      return null;
    }
    model.addShadowType(elem, type);
    return null;
  }
}


text:
package com.thoughtworks.go.plugin.configrepo.contract;

import com.thoughtworks.go.plugin.configrepo.contract.tasks.CRBuildTask;
import com.thoughtworks.go.plugin.configrepo.contract.tasks.CRTask;
import org.junit.Test;

import java.util.Map;

import static org.junit.Assert.assertThat;
import static org.hamcrest.Matchers.is;

public class CRJobTest extends AbstractCRTest<CRJob> {

    private final CRBuildTask rakeTask = CRBuildTask.rake();
    private final CRBuildTask antTask = CRBuildTask.ant();

    private final CRJob buildRake;
    private final CRJob build2Rakes;
    private final CRJob jobWithVar;
    private final CRJob jobWithResource;
    private final CRJob jobWithTab;
    private final CRJob jobWithProp;
    private final CRJob invalidJobNoName;
    private final CRJob invalidJobResourcesAndElasticProfile;

    public CRJobTest()
    {
        buildRake = new CRJob("build", rakeTask);
        build2Rakes = new CRJob("build", rakeTask,CRBuildTask.rake("Rakefile.rb","compile"));

        jobWithVar = new CRJob("build", rakeTask);
        jobWithVar.addEnvironmentVariable("key1","value1");

        jobWithResource = new CRJob("test",antTask);
        jobWithResource.addResource("linux");

        jobWithTab = new CRJob("test",antTask);
        jobWithTab.addTab(new CRTab("test","results.xml"));

        jobWithProp = new CRJob("perfTest",rakeTask);
        jobWithProp.addProperty(new CRPropertyGenerator("perf","test.xml","substring-before(//report/data/all/coverage[starts-with(@type,'class')]/@value, '%')"));

        invalidJobNoName = new CRJob();

        invalidJobResourcesAndElasticProfile = new CRJob("build",rakeTask);
        invalidJobResourcesAndElasticProfile.addResource("linux");
        invalidJobResourcesAndElasticProfile.setElasticProfileId("profile");
    }

    @Override
    public void addGoodExamples(Map<String, CRJob> examples) {
        examples.put("buildRake",buildRake);
        examples.put("build2Rakes",build2Rakes);
        examples.put("jobWithVar",jobWithVar);
        examples.put("jobWithResource",jobWithResource);
        examples.put("jobWithTab",jobWithTab);
        examples.put("jobWithProp",jobWithProp);
    }

    @Override
    public void addBadExamples(Map<String, CRJob> examples) {
        examples.put("invalidJobNoName",invalidJobNoName);
        examples.put("invalidJobResourcesAndElasticProfile",invalidJobResourcesAndElasticProfile);
    }

    @Test
    public void shouldHandlePolymorphismWhenDeserializingTasks()
    {
        String json = gson.toJson(build2Rakes);

        CRJob deserializedValue = gson.fromJson(json,CRJob.class);

        CRTask task1 = deserializedValue.getTasks().get(1);
        assertThat(task1 instanceof CRBuildTask,is(true));
        assertThat(((CRBuildTask)task1).getBuildFile(),is("Rakefile.rb"));
    }
}


text:
<?php

namespace Meinhof\Composer;

use Meinhof\Command\UpdateCommand;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Helper\HelperSet;
use Symfony\Component\Console\Helper\DialogHelper;
use Symfony\Component\Console\Helper\FormatterHelper;

/**
 * The methods of this class are called
 * by the composer package manager
 *
 * @author Miguel Ibero <miguel@ibero.me>
 */
class ScriptHandler
{
    public static function onInstall($event)
    {
        try {
            self::executeUpdate($event);
        } catch (\Exception $e) {
            echo $e->getMessage().PHP_EOL;
        }
    }

    public static function onUpdate($event)
    {
        try {
            self::executeUpdate($event);
        } catch (\Exception $e) {
            echo $e->getMessage().PHP_EOL;
        }
    }

    protected static function executeUpdate($event)
    {
        $options = self::getOptions($event);
        $siteDir = $options['meinhof-site-dir'];

        $command = new UpdateCommand();
        self::executeCommand($command, $siteDir);
    }

    protected static function executeCommand(Command $command, $siteDir)
    {
        if (!is_dir($siteDir)) {
            throw new \RuntimeException('The meinhof-site-dir ('.$siteDir.') specified in composer.json was not found in '.getcwd());
        }

        $helpers = new HelperSet(array(
            new FormatterHelper(),
            new DialogHelper(),
        ));

        $command->setHelperSet($helpers);
        $input = new ArrayInput(array('dir'=>$siteDir));
        $output = new ConsoleOutput();
        $command->run($input, $output);
    }

    protected static function getOptions($event)
    {
        $options = array_merge(array(
            'meinhof-site-dir' => '.',
        ), $event->getComposer()->getPackage()->getExtra());

        return $options;
    }

}


text:
namespace GatewayService.Tests
{
	using MassTransit;
	using MassTransit.Configuration;
	using MassTransit.Transports;
	using NUnit.Framework;

	[TestFixture]
	public class LoopbackTestFixture :
		EndpointTestFixture<LoopbackEndpoint>
	{
		public IServiceBus LocalBus { get; private set; }

		protected override void EstablishContext()
		{
			base.EstablishContext();

			LocalBus = ServiceBusConfigurator.New(x => { x.ReceiveFrom("loopback://localhost/mt_client"); });
		}

		protected override void TeardownContext()
		{
			LocalBus.Dispose();
			LocalBus = null;

			base.TeardownContext();
		}
	}
}


text:
<?php

namespace Elastica;
use Elastica\Cluster\Health;
use Elastica\Cluster\Settings;
use Elastica\Exception\NotImplementedException;

/**
 * Cluster informations for elasticsearch
 *
 * @category Xodoa
 * @package Elastica
 * @author Nicolas Ruflin <spam@ruflin.com>
 * @link http://www.elasticsearch.org/guide/reference/api/
 */
class Cluster
{
    /**
     * Client
     *
     * @var \Elastica\Client Client object
     */
    protected $_client = null;

    /**
     * Cluster state response.
     *
     * @var \Elastica\Response
     */
    protected $_response;

    /**
     * Cluster state data.
     *
     * @var array
     */
    protected $_data;

    /**
     * Creates a cluster object
     *
     * @param \Elastica\Client $client Connection client object
     */
    public function __construct(Client $client)
    {
        $this->_client = $client;
        $this->refresh();
    }

    /**
     * Refreshes all cluster information (state)
     */
    public function refresh()
    {
        $path = '_cluster/state';
        $this->_response = $this->_client->request($path, Request::GET);
        $this->_data = $this->getResponse()->getData();
    }

    /**
     * Returns the response object
     *
     * @return \Elastica\Response Response object
     */
    public function getResponse()
    {
        return $this->_response;
    }

    /**
     * Return list of index names
     *
     * @return array List of index names
     */
    public function getIndexNames()
    {
        $metaData = $this->_data['metadata']['indices'];

        $indices = array();
        foreach ($metaData as $key => $value) {
            $indices[] = $key;
        }

        return $indices;
    }

    /**
     * Returns the full state of the cluster
     *
     * @return array State array
     * @link http://www.elasticsearch.org/guide/reference/api/admin-cluster-state.html
     */
    public function getState()
    {
        return $this->_data;
    }

    /**
     * Returns a list of existing node names
     *
     * @return array List of node names
     */
    public function getNodeNames()
    {
        $data = $this->getState();

        return array_keys($data['routing_nodes']['nodes']);
    }

    /**
     * Returns all nodes of the cluster
     *
     * @return \Elastica\Node[]
     */
    public function getNodes()
    {
        $nodes = array();
        foreach ($this->getNodeNames() as $name) {
            $nodes[] = new Node($name, $this->getClient());
        }

        return $nodes;
    }

    /**
     * Returns the client object
     *
     * @return \Elastica\Client Client object
     */
    public function getClient()
    {
        return $this->_client;
    }

    /**
     * Returns the cluster information (not implemented yet)
     *
     * @param  array                                      $args Additional arguments
     * @throws \Elastica\Exception\NotImplementedException
     * @link http://www.elasticsearch.org/guide/reference/api/admin-cluster-nodes-info.html
     */
    public function getInfo(array $args)
    {
        throw new NotImplementedException('not implemented yet');
    }

    /**
     * Return Cluster health
     *
     * @return \Elastica\Cluster\Health
     * @link http://www.elasticsearch.org/guide/reference/api/admin-cluster-health.html
     */
    public function getHealth()
    {
        return new Health($this->getClient());
    }

    /**
     * Return Cluster settings
     *
     * @return \Elastica\Cluster\Settings
     */
    public function getSettings()
    {
        return new Settings($this->getClient());
    }

    /**
     * Shuts down the complete cluster
     *
     * @param  string            $delay OPTIONAL Seconds to shutdown cluster after (default = 1s)
     * @return \Elastica\Response
     * @link http://www.elasticsearch.org/guide/reference/api/admin-cluster-nodes-shutdown.html
     */
    public function shutdown($delay = '1s')
    {
        $path = '_shutdown?delay=' . $delay;

        return $this->_client->request($path, Request::POST);
    }
}


text:
<TITLE>Review for Tale of the Three Lost Jewels, The (1994)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Tale of the Three Lost Jewels, The (1994)

reviewed by
James Berardinelli

                              TALE OF THREE JEWELS
                       A film review by James Berardinelli
                        Copyright 1996 James Berardinelli

RATING (0 TO 10): 7.0
Alternative Scale: *** out of ****

UK/Belgium/Palestine, 1995
Running Length: 1:47
MPAA Classification: No MPAA Rating (Violence, mature themes)
Theatrical Aspect Ratio: 1.66:1
Shown at the Philadelphia Festival of World Cinema, 5/3/96, 5/5/96,
      5/9/96

Cast: Mohammad Nahlal, Hana Ne'meh, Ghassan Abu Libda, Makram Khouri,
      Bushra Qaraman
Director: Michel Khleifi
Producers: Michel Khleifi and Omar Al-Qattan
Screenplay: Michel Khleifi
Cinematography: Raymond Fromont
Music: Abed Azarieh
In Arabic with subtitles

     Twelve-year old Yusef (Mohammad Nahlal) has a problem that's common
to adolescent boys:  he's in love with an older girl.  The object of his
affection is Aida (Hana Ne'meh), the daughter of a Gypsy family, and,
while she likes him too, she's not above playing games and seeing how
far she can manipulate him.  When she mentions that the one who will
marry her must find the lost three jewels on her grandmother's necklace,
Yusef is determined to travel to South America to look for them.  His
chosen method of transportation is, to say the least, unusual.

     There's a serious side to this mostly-lighthearted, magical romp.
Filmed entirely in Gaza, TALE OF THE THREE JEWELS uses the uneasy
political backdrop as a story element.  Yusef's father is in prison for
an unspecified act against the Israelis, and his brother is a member of
an illegal guerrilla organization.  Curfews are imposed every night, and
traveling after dark becomes a dangerous prospect.

     One of the things that TALE OF THE THREE JEWELS does exceptionally
well is to illustrate that even in a land torn by strife, life and
childhood go on.  Yusef's environment hasn't warped him -- he's
basically a well-adjusted young boy with many of the same hopes and
fears as other children all around the world.  Occasionally, violence
erupts suddenly, but Yusef is able to shrug it off.  It's part of his
everyday life, and, beyond the initial shock caused by the first shots,
he has learned to cope with it.

     Director Michel Khleifi, who directed 1987's WEDDING IN GALILEE,
shows a deft hand at incorporating the divergent elements of stark
violence and magic realism into this coming-of-age tale.  The ending is
ambiguous, and we're left unsure whether the final scene reflects a
dream or reality.  As a result, those who want a happy ending can have
it; those who crave something more tragic can use that interpretation.
In the final analysis, TALE OF THREE JEWELS is about the resilience and
boundless optimism of children -- qualities that the nonstop brutality
of Gaza have sucked out of many adults.

- James Berardinelli
e-mail: berardin@bc.cybernex.net
web: http://www.cybernex.net/~berardin

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
package pluginactionfakes

import (
	sync "sync"

	pluginaction "code.cloudfoundry.org/cli/actor/pluginaction"
)

type FakePluginUninstaller struct {
	RunStub        func(string, string) error
	runMutex       sync.RWMutex
	runArgsForCall []struct {
		arg1 string
		arg2 string
	}
	runReturns struct {
		result1 error
	}
	runReturnsOnCall map[int]struct {
		result1 error
	}
	invocations      map[string][][]interface{}
	invocationsMutex sync.RWMutex
}

func (fake *FakePluginUninstaller) Run(arg1 string, arg2 string) error {
	fake.runMutex.Lock()
	ret, specificReturn := fake.runReturnsOnCall[len(fake.runArgsForCall)]
	fake.runArgsForCall = append(fake.runArgsForCall, struct {
		arg1 string
		arg2 string
	}{arg1, arg2})
	fake.recordInvocation("Run", []interface{}{arg1, arg2})
	fake.runMutex.Unlock()
	if fake.RunStub != nil {
		return fake.RunStub(arg1, arg2)
	}
	if specificReturn {
		return ret.result1
	}
	fakeReturns := fake.runReturns
	return fakeReturns.result1
}

func (fake *FakePluginUninstaller) RunCallCount() int {
	fake.runMutex.RLock()
	defer fake.runMutex.RUnlock()
	return len(fake.runArgsForCall)
}

func (fake *FakePluginUninstaller) RunCalls(stub func(string, string) error) {
	fake.runMutex.Lock()
	defer fake.runMutex.Unlock()
	fake.RunStub = stub
}

func (fake *FakePluginUninstaller) RunArgsForCall(i int) (string, string) {
	fake.runMutex.RLock()
	defer fake.runMutex.RUnlock()
	argsForCall := fake.runArgsForCall[i]
	return argsForCall.arg1, argsForCall.arg2
}

func (fake *FakePluginUninstaller) RunReturns(result1 error) {
	fake.runMutex.Lock()
	defer fake.runMutex.Unlock()
	fake.RunStub = nil
	fake.runReturns = struct {
		result1 error
	}{result1}
}

func (fake *FakePluginUninstaller) RunReturnsOnCall(i int, result1 error) {
	fake.runMutex.Lock()
	defer fake.runMutex.Unlock()
	fake.RunStub = nil
	if fake.runReturnsOnCall == nil {
		fake.runReturnsOnCall = make(map[int]struct {
			result1 error
		})
	}
	fake.runReturnsOnCall[i] = struct {
		result1 error
	}{result1}
}

func (fake *FakePluginUninstaller) Invocations() map[string][][]interface{} {
	fake.invocationsMutex.RLock()
	defer fake.invocationsMutex.RUnlock()
	fake.runMutex.RLock()
	defer fake.runMutex.RUnlock()
	copiedInvocations := map[string][][]interface{}{}
	for key, value := range fake.invocations {
		copiedInvocations[key] = value
	}
	return copiedInvocations
}

func (fake *FakePluginUninstaller) recordInvocation(key string, args []interface{}) {
	fake.invocationsMutex.Lock()
	defer fake.invocationsMutex.Unlock()
	if fake.invocations == nil {
		fake.invocations = map[string][][]interface{}{}
	}
	if fake.invocations[key] == nil {
		fake.invocations[key] = [][]interface{}{}
	}
	fake.invocations[key] = append(fake.invocations[key], args)
}

var _ pluginaction.PluginUninstaller = new(FakePluginUninstaller)


text: Generates nice, shareable visual statements that almost make sense.


text:
package skadistats.clarity.model.s1;

import skadistats.clarity.model.FieldPath;

public class S1FieldPath implements FieldPath<S1FieldPath> {

    private final int idx;

    public S1FieldPath(int idx) {
        this.idx = idx;
    }

    public int idx() {
        return idx;
    }

    @Override
    public String toString() {
        return String.valueOf(idx);
    }

    @Override
    public boolean equals(Object o) {
        if (o instanceof S1FieldPath) {
            return idx == ((S1FieldPath) o).idx;
        }
        return false;
    }

    @Override
    public int hashCode() {
        return Integer.hashCode(idx);
    }

    @Override
    public int compareTo(S1FieldPath o) {
        return Integer.compare(idx, o.idx);
    }

}


text:
<?php

namespace Nosto\Model\Signup;

use Nosto\AbstractObject;
use Nosto\Helper\ValidationHelper;
use Nosto\NostoException;
use Nosto\Request\Api\Token;
use Nosto\Types\Signup\AccountInterface;
use Nosto\Types\ValidatableInterface;

/**
 * Nosto account class for handling account related actions like, creation, OAuth2 syncing and SSO to Nosto.
 */
class Account extends AbstractObject implements AccountInterface, ValidatableInterface
{
    /**
     * @var string the name of the Nosto account.
     */
    private $name;

    /**
     * @var Token[] the Nosto API tokens associated with this account.
     */
    private $tokens = [];

    /**
     * Constructor.
     * Create a new account object with given name.
     *
     * @param $name
     * @throws NostoException
     */
    public function __construct($name)
    {
        $this->name = $name;
        $this->validate();
    }

    /**
     * Validates the account attributes.
     *
     * @throws NostoException if any attribute is invalid.
     */
    protected function validate()
    {
        $validator = new ValidationHelper($this);
        if (!$validator->validate()) {
            foreach ($validator->getErrors() as $errors) {
                throw new NostoException(sprintf('Invalid Nosto account. %s', $errors[0]));
            }
        }
    }

    /**
     * @inheritdoc
     */
    public function isConnectedToNosto()
    {
        if (empty($this->tokens)) {
            return false;
        }
        foreach (Token::getMandatoryApiTokenNames() as $name) {
            if ($this->getApiToken($name) === null) {
                return false;
            }
        }
        return true;
    }

    /**
     * @inheritdoc
     */
    public function getApiToken($name)
    {
        foreach ($this->tokens as $token) {
            if ($token->getName() === $name) {
                return $token;
            }
        }
        return null;
    }

    /**
     * @inheritdoc
     */
    public function validationRules()
    {
        return [
            [['name'], 'required']
        ];
    }

    /**
     * Returns the account name.
     *
     * @return string the name.
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param string $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }

    /**
     * Returns the account tokens.
     *
     * @return Token[] the tokens.
     */
    public function getTokens()
    {
        return $this->tokens;
    }

    /**
     * @param Token[] $tokens
     */
    public function setTokens($tokens)
    {
        $this->tokens = $tokens;
    }

    /**
     * @inheritdoc
     */
    public function hasMissingTokens()
    {
        if (empty($this->tokens)) {
            return true;
        }
        foreach (Token::getApiTokenNames() as $name) {
            if ($this->getApiToken($name) === null) {
                return true;
            }
        }
        return false;
    }

    /**
     * Adds an API token to the account.
     *
     * @param Token $token the token.
     */
    public function addApiToken(Token $token)
    {
        $this->tokens[] = $token;
    }

    /**
     * @inheritdoc
     */
    public function getMissingTokens()
    {
        $allTokens = Token::getApiTokenNames();
        $missingTokens = [];
        foreach ($allTokens as $token) {
            if (!$this->getApiToken($token)) {
                $missingTokens[] = $token;
            }
        }

        return $missingTokens;
    }
}


text:
package db

import com.bryzek.apidoc.api.v0.models.UserForm
import lib.Role
import org.scalatest.{FunSpec, Matchers}
import org.junit.Assert._
import java.util.UUID

class EmailVerificationsDaoSpec extends FunSpec with Matchers with util.TestApplication {

  def emailVerificationConfirmationsDao = play.api.Play.current.injector.instanceOf[db.EmailVerificationConfirmationsDao]

  it("create") {
    val user = Util.createRandomUser()
    val verification = emailVerificationsDao.create(Util.createdBy, user, user.email)
    verification.userGuid should be(user.guid)
    verification.email should be(user.email)
  }

  it("upsert") {
    val user = Util.createRandomUser()
    val verification1 = emailVerificationsDao.upsert(Util.createdBy, user, user.email)
    val verification2 = emailVerificationsDao.upsert(Util.createdBy, user, user.email)
    verification2.guid should be(verification1.guid)

    emailVerificationsDao.softDelete(Util.createdBy, verification1)
    val verification3 = emailVerificationsDao.upsert(Util.createdBy, user, user.email)
    verification3.guid should not be(verification1.guid)

    val verificationWithDifferentEmail = emailVerificationsDao.upsert(Util.createdBy, user, "other-" + user.email)
    verificationWithDifferentEmail.guid should not be(verification3.guid)
  }

  it("isExpired") {
    val user = Util.createRandomUser()
    val verification = emailVerificationsDao.create(Util.createdBy, user, user.email)
    emailVerificationsDao.isExpired(verification) should be(false)
  }

  it("confirm") {
    val user = Util.createRandomUser()
    val verification = emailVerificationsDao.create(Util.createdBy, user, user.email)
    emailVerificationConfirmationsDao.findAll(emailVerificationGuid = Some(verification.guid)) should be(Seq.empty)

    emailVerificationsDao.confirm(None, verification)
    emailVerificationConfirmationsDao.findAll(emailVerificationGuid = Some(verification.guid)).map(_.emailVerificationGuid) should be(Seq(verification.guid))
  }

  it("findByGuid") {
    val user = Util.createRandomUser()
    val verification = emailVerificationsDao.create(Util.createdBy, user, user.email)

    emailVerificationsDao.findByGuid(verification.guid).map(_.userGuid) should be(Some(user.guid))
    emailVerificationsDao.findByGuid(UUID.randomUUID) should be(None)
  }

  it("findByToken") {
    val user = Util.createRandomUser()
    val verification = emailVerificationsDao.create(Util.createdBy, user, user.email)

    emailVerificationsDao.findByToken(verification.token).map(_.userGuid) should be(Some(user.guid))
    emailVerificationsDao.findByToken(UUID.randomUUID.toString) should be(None)
  }

  it("findAll") {
    val user1 = Util.createRandomUser()
    val verification1 = emailVerificationsDao.create(Util.createdBy, user1, user1.email)

    val user2 = Util.createRandomUser()
    val verification2 = emailVerificationsDao.create(Util.createdBy, user2, user2.email)

    emailVerificationsDao.findAll(userGuid = Some(user1.guid)).map(_.userGuid).distinct should be(Seq(user1.guid))
    emailVerificationsDao.findAll(userGuid = Some(user2.guid)).map(_.userGuid).distinct should be(Seq(user2.guid))
    emailVerificationsDao.findAll(userGuid = Some(UUID.randomUUID)).map(_.userGuid).distinct should be(Seq.empty)

    emailVerificationsDao.findAll(isExpired = Some(false), userGuid = Some(user1.guid)).map(_.userGuid).distinct should be(Seq(user1.guid))
    emailVerificationsDao.findAll(isExpired = Some(true), userGuid = Some(user1.guid)).map(_.userGuid).distinct should be(Seq.empty)

    emailVerificationsDao.findAll(email = Some(user1.email)).map(_.userGuid).distinct should be(Seq(user1.guid))
    emailVerificationsDao.findAll(email = Some(user1.email.toUpperCase)).map(_.userGuid).distinct should be(Seq(user1.guid))
    emailVerificationsDao.findAll(email = Some(user2.email)).map(_.userGuid).distinct should be(Seq(user2.guid))
    emailVerificationsDao.findAll(email = Some(UUID.randomUUID.toString)).map(_.userGuid).distinct should be(Seq.empty)

    emailVerificationsDao.findAll(guid = Some(verification1.guid)).map(_.userGuid).distinct should be(Seq(user1.guid))
    emailVerificationsDao.findAll(guid = Some(verification2.guid)).map(_.userGuid).distinct should be(Seq(user2.guid))
    emailVerificationsDao.findAll(guid = Some(UUID.randomUUID)).map(_.userGuid).distinct should be(Seq.empty)

    emailVerificationsDao.findAll(token = Some(verification1.token)).map(_.userGuid).distinct should be(Seq(user1.guid))
    emailVerificationsDao.findAll(token = Some(verification2.token)).map(_.userGuid).distinct should be(Seq(user2.guid))
    emailVerificationsDao.findAll(token = Some("bad")).map(_.userGuid).distinct should be(Seq.empty)
  }

  describe("membership requests") {

    it("confirm auto approves pending membership requests based on org email domain") {
      val org = Util.createOrganization()
      val domain = UUID.randomUUID.toString + ".com"

      organizationDomainsDao.create(Util.createdBy, org, domain)

      val prefix = "test-user-" + UUID.randomUUID.toString

      val user = usersDao.create(UserForm(
        email = prefix + "@" + domain,
        password = "testing"
      ))

      val nonMatchingUser = usersDao.create(UserForm(
        email = prefix + "@other." + domain,
        password = "testing"
      ))

      usersDao.processUserCreated(user.guid)
      usersDao.processUserCreated(nonMatchingUser.guid)

      membershipsDao.isUserMember(user, org) should be(false)
      membershipsDao.isUserMember(nonMatchingUser, org) should be(false)

      val verification = emailVerificationsDao.upsert(Util.createdBy, user, user.email)
      emailVerificationsDao.confirm(Some(Util.createdBy), verification)

      membershipsDao.isUserMember(user, org) should be(true)
      membershipsDao.isUserMember(nonMatchingUser, org) should be(false)
    }

  }

}


text:
$(document).ready(function () {
    "use strict";
    $("#search").on("keyup", function() {
        // Filter logic
        var search_val = $("#search").val().toLowerCase();
        $(".host_box").each(function() {
            var host = $(this);
            var text = host.children(".host_info").text().toLowerCase();
            if (!text.includes(search_val)) {
                host.hide();
            } else {
                host.show();
            }
        });
    });
});


text:
<!DOCTYPE html>

    <title>$$(Title_feature-chooser)</title>

    <link href="%%ignite-ui%%/css/themes/infragistics/infragistics.theme.css" rel="stylesheet">
    <link href="%%ignite-ui%%/css/structure/infragistics.css" rel="stylesheet">


text:
package org.apache.logging.log4j.core.util;

import java.lang.reflect.UndeclaredThrowableException;

import org.junit.Test;

public class ThrowablesTest {

    @Test(expected = NullPointerException.class)
    public void testRethrowRuntimeException() throws Exception {
        Throwables.rethrow(new NullPointerException());
    }

    @Test(expected = UnknownError.class)
    public void testRethrowError() throws Exception {
        Throwables.rethrow(new UnknownError());
    }

    @Test(expected = UndeclaredThrowableException.class)
    public void testRethrowCheckedException() throws Exception {
        Throwables.rethrow(new NoSuchMethodException());
    }
}


text:
namespace ApplicationStore.Web.Areas.Developer.ViewModels
{
    using System.Web;

    public class AppImageModel
    {
        public HttpPostedFileBase UploadedImage { get; set; }
    }
}


text:
/* global expect */

import {
  mount
} from 'enzyme';
import React from 'react';
import Home from '../../components/Home.jsx';

let wrapper;

describe('<Home />', () => {
  wrapper = mount(<Home />);

  it('renders divs with class names', () => {
    expect(wrapper.find('.app-name').length).toBe(1);
    expect(wrapper.find('.docify-signup').length).toBe(1);
    expect(wrapper.find('.material-icons').length).toBe(2);
    expect(wrapper.find('.desc-middle').children().length).toBe(2);
    expect(wrapper.find('.desc-right').html())
      .toEqual("

Sign Up, It's Free

Sign up for a free account, Create your own group or Join one.

");
    expect(wrapper.find('.desc-left').length).toBe(1);

  });

});


text:
using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Text;

namespace BrimboriumSPCopy
{
    /// <summary>
    /// BrimboriumSPCopy.Implementation.SPCopyService
    /// </summary>
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class SPCopyService : ISPCopyService
    {
#if DEBUG
        /// <summary>
        /// Ping-pong the specified text. (for testing only)
        /// </summary>
        /// <param name="text">The text.</param>
        /// <returns></returns>
        public string Ping(string text)
        {
            return string.Format("{0} : {1}", text ?? "", System.DateTime.Now.ToLongTimeString());
        }
#endif
        /// <summary>
        /// Copies the file.
        /// </summary>
        /// <param name="sourceUrl">The source URL.</param>
        /// <param name="destinationUrl">The destination URL.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">
        /// sourceUrl
        /// or
        /// destinationUrl
        /// </exception>
        /// <exception cref="System.ArgumentException">
        /// sourceUrl must be absolute
        /// or
        /// destinationUrl must be absolute
        /// </exception>
        /// <exception cref="System.IO.FileNotFoundException"></exception>
        public string CopyFile(string sourceUrl, string destinationUrl)
        {
            if (string.IsNullOrEmpty(sourceUrl)) { throw new ArgumentNullException("sourceUrl"); }
            if (string.IsNullOrEmpty(destinationUrl)) { throw new ArgumentNullException("destinationUrl"); }
            if (!(new Uri(sourceUrl, UriKind.RelativeOrAbsolute)).IsAbsoluteUri) { throw new ArgumentException("sourceUrl must be absolute"); }
            if (!(new Uri(destinationUrl, UriKind.RelativeOrAbsolute)).IsAbsoluteUri) { throw new ArgumentException("destinationUrl must be absolute"); }
            //
            try
            {
                using (SPSite sourceSite = new SPSite(sourceUrl))
                {
                    using (SPSite destinationSite = new SPSite(destinationUrl))
                    {
                        using (SPWeb sourceWeb = sourceSite.OpenWeb())
                        {
                            using (SPWeb destinationWeb = destinationSite.OpenWeb())
                            {
                                destinationWeb.AllowUnsafeUpdates = true;
                                SPFile sourceFile = sourceWeb.GetFile(sourceUrl);
                                if (sourceFile.Exists)
                                {
                                    SPFile destinationFile = destinationWeb.GetFile(destinationUrl);
                                    using (var sourceStream = sourceFile.OpenBinaryStream())
                                    {
                                        destinationFile.SaveBinary(sourceStream);
                                    }
                                    return "OK";
                                }
                                else
                                {
                                    throw new System.IO.FileNotFoundException(sourceUrl);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception exc)
            {
#if DEBUG
                return exc.ToString();
#else
                return exc.Message;
#endif
            }
        }

        /// <summary>
        /// Gets the content of the file as an base64 encoded string.
        /// </summary>
        /// <param name="sourceUrl">The source URL.</param>
        /// <returns>
        /// the file content as a BASE64 json string
        /// </returns>
        /// <exception cref="System.ArgumentNullException">sourceUrl</exception>
        /// <exception cref="System.ArgumentException">sourceUrl must be absolute</exception>
        /// <exception cref="System.IO.FileNotFoundException"></exception>
        public string GetFileContentAsBase64(string sourceUrl)
        {
            if (string.IsNullOrEmpty(sourceUrl)) { throw new ArgumentNullException("sourceUrl"); }
            if (!(new Uri(sourceUrl, UriKind.RelativeOrAbsolute)).IsAbsoluteUri) { throw new ArgumentException("sourceUrl must be absolute"); }
            //
            using (SPSite sourceSite = new SPSite(sourceUrl))
            {
                using (SPWeb sourceWeb = sourceSite.OpenWeb())
                {
                    SPFile sourceFile = sourceWeb.GetFile(sourceUrl);
                    if (sourceFile.Exists)
                    {
                        byte[] content;
                        using (var sourceStream = sourceFile.OpenBinaryStream())
                        {
                            using (var memoryStream = new System.IO.MemoryStream())
                            {
                                sourceStream.CopyTo(memoryStream);
                                memoryStream.Position = 0;
                                content = memoryStream.ToArray();
                            }
                            return Convert.ToBase64String(content);
                        }
                    }
                    else
                    {
                        throw new System.IO.FileNotFoundException(sourceUrl);
                    }
                }
            }
        }

        /// <summary>
        /// Sets the file content from base64.
        /// </summary>
        /// <param name="destinationUrl">The destination URL.</param>
        /// <param name="content">The content.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">destinationUrl</exception>
        /// <exception cref="System.ArgumentException">destinationUrl must be absolute</exception>
        public string SetFileContentFromBase64(string destinationUrl, string content)
        {
            if (string.IsNullOrEmpty(destinationUrl)) { throw new ArgumentNullException("destinationUrl"); }
            if (!(new Uri(destinationUrl, UriKind.RelativeOrAbsolute)).IsAbsoluteUri) { throw new ArgumentException("destinationUrl must be absolute"); }
            //
            try
            {
                using (SPSite destinationSite = new SPSite(destinationUrl))
                {
                    using (SPWeb destinationWeb = destinationSite.OpenWeb())
                    {
                        destinationWeb.AllowUnsafeUpdates = true;
                        SPFile destinationFile = destinationWeb.GetFile(destinationUrl);
                        byte[] arrContent = Convert.FromBase64String(content);
                        destinationFile.SaveBinary(arrContent);
                        return "OK";
                    }
                }
            }
            catch (Exception exc)
            {
#if DEBUG
                return exc.ToString();
#else
                return exc.Message;
#endif
            }
        }

    }
}


text:
/**
*--- start---系统参数配置信息----v_1.0.0
*/

DROP TABLE IF EXISTS `tb_sys_config`;
CREATE TABLE `tb_sys_config` (
`id`  int NOT NULL AUTO_INCREMENT ,
`param_key`  varchar(255) NULL COMMENT '参数键' ,
`param_value`  varchar(255) NULL COMMENT '参数值' ,
`param_mark`  varchar(255) NULL COMMENT '参数描述信息' ,
PRIMARY KEY (`id`)
)
COMMENT='系统参数配置信息'
;

ALTER TABLE `tb_sys_config` ADD UNIQUE INDEX `index_unique_param_key` (`param_key`) ;

INSERT INTO `tb_sys_config` (`param_key`, `param_value`, `param_mark`) VALUES ('DBVersion', 'v_1.0.0', '数据库版本信息');

/**
*--- end---系统参数配置信息----v_1.0.0
*/

/**
*--- start---增加主键----v_1.0.1
*/

ALTER TABLE `tb_role_permission` ADD COLUMN `id` INT NOT NULL AUTO_INCREMENT FIRST,
 ADD PRIMARY KEY (`id`);

ALTER TABLE `tb_user_role` ADD COLUMN `id` INT NOT NULL AUTO_INCREMENT FIRST,
 ADD PRIMARY KEY (`id`);

 UPDATE `tb_sys_config` SET `param_value`='v_1.0.1' WHERE `param_key`='DBVersion';

/**
*--- end---增加主键----v_1.0.1
*/

/**
*--- start---修改字段名称----v_1.0.2
*/

ALTER TABLE `tb_notification`
CHANGE COLUMN `read` `is_read` TINYINT (1) NOT NULL COMMENT '是否已读:0默认 1已读' AFTER `id`;

ALTER TABLE `tb_topic`
CHANGE COLUMN `view` `view_count` INT (11) NOT NULL COMMENT '1置顶 0默认' AFTER `last_reply_author`,
CHANGE COLUMN `top` `is_top` TINYINT (1) NOT NULL COMMENT '1置顶 0默认' AFTER `author`,
CHANGE COLUMN `good` `is_good` TINYINT (1) NOT NULL COMMENT '1精华 0默认' AFTER `is_top`;

UPDATE `tb_sys_config` SET `param_value`='v_1.0.2' WHERE `param_key`='DBVersion';

/**
*--- end---修改字段名称----v_1.0.2
*/

/**
*--- start---重建权限信息----v_1.0.3
*/
-- ----------------------------
-- Table structure for tb_permission
-- ----------------------------
DROP TABLE IF EXISTS `tb_permission`;
CREATE TABLE `tb_permission` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) NOT NULL DEFAULT '' COMMENT '权限名称',
  `url` varchar(255) DEFAULT NULL COMMENT '授权路径',
  `description` varchar(255) NOT NULL COMMENT '权限描述',
  `pid` int(11) NOT NULL COMMENT '父节点0',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=89 DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT;

-- ----------------------------
-- Records of tb_permission
-- ----------------------------
INSERT INTO `tb_permission` VALUES ('55', 'section', '', '板块节点', '0');
INSERT INTO `tb_permission` VALUES ('56', 'system', '', '系统设置', '0');
INSERT INTO `tb_permission` VALUES ('57', 'topic', '', '话题节点', '0');
INSERT INTO `tb_permission` VALUES ('58', 'reply', '', '回复节点', '0');
INSERT INTO `tb_permission` VALUES ('59', 'system:users', '/manage/users', '用户列表', '56');
INSERT INTO `tb_permission` VALUES ('60', 'system:roles', '/manage/roles', '角色列表', '56');
INSERT INTO `tb_permission` VALUES ('61', 'system:permissions', '/manage/permissions', '权限列表', '56');
INSERT INTO `tb_permission` VALUES ('62', 'system:user:role', '/manage/user-role', '用户角色关联', '56');
INSERT INTO `tb_permission` VALUES ('63', 'system:role:permission', '/manage/role-permission', '角色权限关联', '56');
INSERT INTO `tb_permission` VALUES ('64', 'system:add:permission', '/manage/add-permission', '添加权限', '56');
INSERT INTO `tb_permission` VALUES ('65', 'system:edit:permission', '/manage/edit-permission', '编辑权限', '56');
INSERT INTO `tb_permission` VALUES ('66', 'system:add:role', '/manage/add-role', '添加角色', '56');
INSERT INTO `tb_permission` VALUES ('68', 'system:delete:user', '/manage/delete-user', '删除用户', '56');
INSERT INTO `tb_permission` VALUES ('69', 'system:delete:role', '/manage/delete-role', '删除角色', '56');
INSERT INTO `tb_permission` VALUES ('70', 'system:delete:permission', '/manage/delete-permission', '删除权限', '56');
INSERT INTO `tb_permission` VALUES ('71', 'topic:delete', '/topic/delete', '删除话题', '57');
INSERT INTO `tb_permission` VALUES ('73', 'reply:delete', '/reply/delete', '删除回复', '58');
INSERT INTO `tb_permission` VALUES ('74', 'reply:edit', '/reply/edit', '编辑回复', '58');
INSERT INTO `tb_permission` VALUES ('75', 'topic:edit', '/topic/edit', '话题编辑', '57');
INSERT INTO `tb_permission` VALUES ('76', 'topic:append:edit', '/topic/append-edit', '追加编辑', '57');
INSERT INTO `tb_permission` VALUES ('77', 'topic:top', '/topic/top', '话题置顶', '57');
INSERT INTO `tb_permission` VALUES ('78', 'topic:good', '/topic/good', '话题加精', '57');
INSERT INTO `tb_permission` VALUES ('79', 'system:clear:cache', '/clear', '删除所有缓存', '56');
INSERT INTO `tb_permission` VALUES ('80', 'system:user:block', '/manage/user-block', '禁用用户', '56');
INSERT INTO `tb_permission` VALUES ('81', 'section:list', '/section/list', '板块列表', '55');
INSERT INTO `tb_permission` VALUES ('82', 'section:change:show:status', '/section/change-show-status', '改变板块显示状态', '55');
INSERT INTO `tb_permission` VALUES ('83', 'section:delete', '/section/delete', '删除板块', '55');
INSERT INTO `tb_permission` VALUES ('84', 'section:add', '/section/add', '添加板块', '55');
INSERT INTO `tb_permission` VALUES ('85', 'section:edit', '/section/edit', '编辑板块', '55');
INSERT INTO `tb_permission` VALUES ('86', 'reply:list', '/reply/list', '回复列表', '58');
INSERT INTO `tb_permission` VALUES ('87', 'system:solr', '/solr', '索引所有话题(慎用)', '56');
INSERT INTO `tb_permission` VALUES ('88', 'system:delete:all:index', '/delete-all-index', '删除所有索引', '56');

-- ----------------------------
-- Table structure for tb_role_permission
-- ----------------------------
DROP TABLE IF EXISTS `tb_role_permission`;
CREATE TABLE `tb_role_permission` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `rid` int(11) NOT NULL,
  `pid` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `fk_role_permission` (`rid`),
  KEY `fk_permission_role` (`pid`)
) ENGINE=InnoDB AUTO_INCREMENT=37 DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT;

-- ----------------------------
-- Records of tb_role_permission
-- ----------------------------
INSERT INTO `tb_role_permission` VALUES ('1', '2', '71');
INSERT INTO `tb_role_permission` VALUES ('2', '2', '75');
INSERT INTO `tb_role_permission` VALUES ('3', '2', '76');
INSERT INTO `tb_role_permission` VALUES ('4', '2', '77');
INSERT INTO `tb_role_permission` VALUES ('5', '2', '78');
INSERT INTO `tb_role_permission` VALUES ('6', '2', '73');
INSERT INTO `tb_role_permission` VALUES ('7', '2', '74');
INSERT INTO `tb_role_permission` VALUES ('8', '1', '59');
INSERT INTO `tb_role_permission` VALUES ('9', '1', '60');
INSERT INTO `tb_role_permission` VALUES ('10', '1', '61');
INSERT INTO `tb_role_permission` VALUES ('11', '1', '62');
INSERT INTO `tb_role_permission` VALUES ('12', '1', '63');
INSERT INTO `tb_role_permission` VALUES ('13', '1', '64');
INSERT INTO `tb_role_permission` VALUES ('14', '1', '65');
INSERT INTO `tb_role_permission` VALUES ('15', '1', '66');
INSERT INTO `tb_role_permission` VALUES ('17', '1', '68');
INSERT INTO `tb_role_permission` VALUES ('18', '1', '69');
INSERT INTO `tb_role_permission` VALUES ('19', '1', '70');
INSERT INTO `tb_role_permission` VALUES ('20', '1', '79');
INSERT INTO `tb_role_permission` VALUES ('21', '1', '87');
INSERT INTO `tb_role_permission` VALUES ('22', '1', '88');
INSERT INTO `tb_role_permission` VALUES ('23', '1', '89');
INSERT INTO `tb_role_permission` VALUES ('24', '1', '71');
INSERT INTO `tb_role_permission` VALUES ('25', '1', '75');
INSERT INTO `tb_role_permission` VALUES ('26', '1', '76');
INSERT INTO `tb_role_permission` VALUES ('27', '1', '77');
INSERT INTO `tb_role_permission` VALUES ('28', '1', '78');
INSERT INTO `tb_role_permission` VALUES ('29', '1', '73');
INSERT INTO `tb_role_permission` VALUES ('30', '1', '74');
INSERT INTO `tb_role_permission` VALUES ('31', '1', '86');
INSERT INTO `tb_role_permission` VALUES ('32', '1', '81');
INSERT INTO `tb_role_permission` VALUES ('33', '1', '82');
INSERT INTO `tb_role_permission` VALUES ('34', '1', '83');
INSERT INTO `tb_role_permission` VALUES ('35', '1', '84');
INSERT INTO `tb_role_permission` VALUES ('36', '1', '85');

UPDATE `tb_sys_config` SET `param_value`='v_1.0.3' WHERE `param_key`='DBVersion';

/**
*--- end---重建权限信息----v_1.0.3
*/

/**
*--- start---修改用户信息表----v_1.0.4
*/

ALTER TABLE `tb_user`
MODIFY COLUMN `score` int(11) NULL COMMENT '积分' AFTER `nickname`,
MODIFY COLUMN `avatar` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT '头像' AFTER `score`,
MODIFY COLUMN `email` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '邮箱' AFTER `avatar`,
MODIFY COLUMN `third_id` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT '第三方账户id' AFTER `signature`,
MODIFY COLUMN `access_token` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL AFTER `third_id`,
MODIFY COLUMN `receive_msg` tinyint(1) NULL DEFAULT 1 COMMENT '邮箱是否接收社区消息' AFTER `access_token`,
MODIFY COLUMN `expire_time` datetime NULL AFTER `in_time`,
MODIFY COLUMN `channel` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL AFTER `expire_time`,
MODIFY COLUMN `is_block` tinyint(1) NULL DEFAULT 0 COMMENT '禁用0默认 1禁用' AFTER `channel`;

ALTER TABLE `tb_user`
ADD COLUMN `password` varchar(125) NULL AFTER `nickname`;

UPDATE `tb_sys_config` SET `param_value`='v_1.0.4' WHERE `param_key`='DBVersion';

/**
*--- end---修改用户信息表----v_1.0.4
*/

/**
*--- start---用户单点登录信息表----v_1.0.5
*/

ALTER TABLE `tb_user`
DROP COLUMN `third_id`,
DROP COLUMN `channel`,
DROP COLUMN `third_access_token`;

DROP TABLE IF EXISTS `tb_user_oauth`;
CREATE TABLE `tb_user_oauth` (
`id`  int NOT NULL AUTO_INCREMENT ,
`channel`  varchar(64) NULL ,
`third_id`  int NULL ,
`third_access_token`  varchar(255) NULL ,
`uid`  int NULL ,
PRIMARY KEY (`id`)
)
COMMENT='用户单点登录'
;

UPDATE `tb_sys_config` SET `param_value`='v_1.0.5' WHERE `param_key`='DBVersion';

/**
*--- end---用户单点登录信息表----v_1.0.5
*/

/**
*--- start---表名称增加描述信息----v_1.0.6
*/

ALTER TABLE `tb_collect` COMMENT='话题收藏';
ALTER TABLE `tb_notification` COMMENT='用户通知信息';
ALTER TABLE `tb_permission` COMMENT='权限信息字典';
ALTER TABLE `tb_reply` COMMENT='话题回复';
ALTER TABLE `tb_role` COMMENT='角色信息';
ALTER TABLE `tb_role_permission` COMMENT='角色权限信息关联';
ALTER TABLE `tb_section` COMMENT='模板信息';
ALTER TABLE `tb_topic` COMMENT='话题信息表';
ALTER TABLE `tb_topic_append` COMMENT='话题信息追加';
ALTER TABLE `tb_user` COMMENT='用户信息';
ALTER TABLE `tb_user_role` COMMENT='用户与角色关联信息';

UPDATE `tb_sys_config` SET `param_value`='v_1.0.6' WHERE `param_key`='DBVersion';

/**
*--- end---表名称增加描述信息----v_1.0.6
*/


text:
@implementation UIView (SGPagingView)
- (void)setSG_x:(CGFloat)SG_x {
    CGRect frame = self.frame;
    frame.origin.x = SG_x;
    self.frame = frame;
}
- (CGFloat)SG_x {
    return self.frame.origin.x;
}

- (void)setSG_y:(CGFloat)SG_y {
    CGRect frame = self.frame;
    frame.origin.y = SG_y;
    self.frame = frame;
}
- (CGFloat)SG_y {
    return self.frame.origin.y;
}

- (void)setSG_width:(CGFloat)SG_width {
    CGRect frame = self.frame;
    frame.size.width = SG_width;
    self.frame = frame;
}
- (CGFloat)SG_width {
    return self.frame.size.width;
}

- (void)setSG_height:(CGFloat)SG_height {
    CGRect frame = self.frame;
    frame.size.height = SG_height;
    self.frame = frame;
}
- (CGFloat)SG_height {
    return self.frame.size.height;
}

- (CGFloat)SG_centerX {
    return self.center.x;
}
- (void)setSG_centerX:(CGFloat)SG_centerX {
    CGPoint center = self.center;
    center.x = SG_centerX;
    self.center = center;
}

- (CGFloat)SG_centerY {
    return self.center.y;
}
- (void)setSG_centerY:(CGFloat)SG_centerY {
    CGPoint center = self.center;
    center.y = SG_centerY;
    self.center = center;
}

- (void)setSG_origin:(CGPoint)SG_origin {
    CGRect frame = self.frame;
    frame.origin = SG_origin;
    self.frame = frame;
}
- (CGPoint)SG_origin {
    return self.frame.origin;
}

- (void)setSG_size:(CGSize)SG_size {
    CGRect frame = self.frame;
    frame.size = SG_size;
    self.frame = frame;
}
- (CGSize)SG_size {
    return self.frame.size;
}

/// 从 XIB 中加载视图
+ (instancetype)SG_loadViewFromXib {
    return [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self) owner:nil options:nil].lastObject;
}

@end