text:
[![Build Status](https://travis-ci.org/Acornsgrow/hitnmiss.svg?branch=master)](https://travis-ci.org/Acornsgrow/hitnmiss)
[![Code Climate](https://codeclimate.com/github/Acornsgrow/hitnmiss/badges/gpa.svg)](https://codeclimate.com/github/Acornsgrow/hitnmiss)
[![Test Coverage](https://codeclimate.com/github/Acornsgrow/hitnmiss/badges/coverage.svg)](https://codeclimate.com/github/Acornsgrow/hitnmiss/coverage)
[![Issue Count](https://codeclimate.com/github/Acornsgrow/hitnmiss/badges/issue_count.svg)](https://codeclimate.com/github/Acornsgrow/hitnmiss)

# Hitnmiss

Hitnmiss is a Ruby gem that provides support for using the Repository
pattern for read-through, write-behind caching in a thread-safe way. It
is built heavily around using POROs (Plain Old Ruby Objects). This means
it is intended to be used with all kinds of Ruby applications from plain
Ruby command line tools, to framework (Rails, Sinatra, Rack, Hanami,
etc.) based web apps, etc.

Having defined repositories for accessing your caches aids in a number of ways.
First, it centralizes cache key generation.  Secondly, it centralizes &
standardizes access to the cache rather than having code spread across your app
duplicating key generation and access. Third, it provides clean separation
between the cache persistence layer and the business representation.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'hitnmiss'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install hitnmiss

## Define/Mixin a Repository

Before you can use Hitnmiss to manage cache you first need to define a
cache repository. This is done by defining a class for your repository
and mixing the appropriate repository module in using `include`.

Below, are explanations of the **Standard Repository** and the **Background
Refresh Repository** so that you can decide which one fits your needs as well as
learn how to use them.

### Standard Repository

The standard repository module, `Hitnmiss::Repository`, fits the most common
caching use case, the "Expiration Model". The "Expiration Model" is a caching
model where a value gets cached with an associated expiration and when that
expiration is reached that value is no longer cached. This affects the app
behavior by having it pay the caching cost when it tries to get a value and it
has expired. The following is an example of creating a `MostRecentPrice` cache
repository for the "Expiration Model".

```ruby
class MostRecentPrice
  include Hitnmiss::Repository

  default_expiration 134 # expiration in seconds from when value cached
end
```

More often than not your caching use case will have a static/known
expiration that you want to use for all values that get cached. This is handled
for you by setting the `default_expiration` as seen in the example above.
**Note:** Hitnmiss also supports being able to have different expirations for
each cached value. You can learn more about this in the "Set Cache Source based
Expiration" section.

### Background Refresh Repository

Sometimes you don't have an expiration value and don't want cached values to
disappear. In these scenarios you want something to update the cache for you
based on some defined interval. When you use the
`Hitnmiss::BackgroundRefreshRepository` module and set the `refresh_interval`
as seen below, it prepares your repository to handle this scenario. This changes
the behavior where the app never experiences the caching cost as it is
continually managed for the app in the background based on the
`refresh_interval`.

```ruby
class MostRecentPrice
  include Hitnmiss::BackgroundRefreshRepository

  refresh_interval 60*5 # refresh interval in seconds
end
```

Once you have defined your Background Refresh Repository in order to get the
background process to update your cache you have to kick it off using the
`background_refresh(*args, swallow_exceptions: [])` method as seen in the
example below. The optional keyword argument `swallow_exceptions` defaults to
`[]`. If enabled it will prevent the specified exceptions, raised in the
`fetch(*args)` or `stale?(*args)` methods you defined, from killing the
background thread, and prevent the exceptions from making their way up to the
application. This is useful in scenarios where you want it to absorb say timeout
exceptions, etc. and continue trucking along. **Note:** Any other exceptions not
covered by the exceptions listed in the `swallow_exceptions` array will still be
raised up into the application.

```ruby
repository = MostRecentPrice.new
repository.background_refresh(store_id)
```

This model also has the added benefit that the priming of the cache in the
background refresh process is non-blocking. This means if you use this model the
consumer will not experience the priming of the cache like they would with the
Standard Repository's Expiration Model.

#### Staleness Checking

The Background Refresh Repository model introduces a new concept, Staleness
Checking. Staleness is checked during the background refresh process. The way it
works is if the cache is identified to be stale, then it primes the cache in the
background, if the cache is identified to NOT be stale, then it sleeps for
another `refresh_interval`.

The stale checker, `stale?(*args)`, defaults to an always stale value of `true`.
This causes the background refresh process to prime the cache every
`refresh_interval`.

If you want your cache implementation to be smarter and say validate a
fingerprint or last modified value against the source, you can do it simply by
overwriting the `stale?(*args)` method with your own staleness checking logic.
The following is an example of this.

```ruby
class MostRecentPrice
  include Hitnmiss::BackgroundRefreshRepository

  refresh_interval 60*5 # refresh interval in seconds

  def initialize
    @client = HTTPClient.new
  end

  def stale?(*args)
    hit_or_miss = get_from_cache(*args)
    if hit_or_miss.is_a?(Hitnmiss::Driver::Miss)
      return true
    elsif hit_or_miss.is_a?(Hitnmiss::Driver::Hit)
      url = "https://someresource.example.com/#{args[0]}/#{args[1]}/digest.json"
      res = @client.head(url)
      fingerprint = res.header['ETag'].first
      return false if fingerprint == hit_or_miss.fingerprint
      return true
    else
      raise Hitnmiss::Repository::UnsupportedDriverResponse.new("Driver '#{self.class.driver.inspect}' did not return an object of the support types (Hitnmiss::Driver::Hit, Hitnmiss::Driver::Miss)")
    end
  end
end
```

### Set a Repositories Cache Driver

Hitnmiss defaults to the provided `Hitnmiss::InMemoryDriver`, but if an alternate
driver is needed a new driver can be registered as seen below.

```ruby
# config/hitnmiss.rb
Hitnmiss.register_driver(:my_driver, SomeAlternativeDriver.new)
```

Once you have registered the new driver you can tell `Hitnmiss` what
driver to use for this particular repository. The following is an example
of how one would accomplish setting the repository driver to the driver
that was just registered.

```ruby
class MostRecentPrice
  include Hitnmiss::Repository

  driver :my_driver
end
```

This works exactly the same with the `Hitnmiss::BackgroundRefreshRepository`.

### Set a Logger

Hitnmiss defaults to not logging. However, if you would like to get detailed
logging from Hitnmiss you can do so by passing your application controlled
logger instance to the Hitnmiss repository. An example of this can be seen
below.

```ruby
class MostRecentPrice
  include Hitnmiss::Repository

  logger Logger.new(STDOUT)
end
```

**Note:** The above works exactly the same way for `Hitnmiss::Repository` and
`Hitnmiss::BackgroundRefreshRepository`.

### Use the File Driver

Hitnmiss ships with an alternate file based driver that can be used to write
cache values to individual files in a folder.

```ruby
class MostRecentPrice
  include Hitnmiss::Repository

  driver Hitnmiss::FileDriver.new("some_cache_folder")
end
```

### Define Fetcher Methods

You may be asking yourself, "How does the cache value get set?" Well,
the answer is one of two ways.

* Fetching an individual cacheable entity
* Fetching all of the repository's cacheable entities

Both of these scenarios are supported by defining the `fetch(*args)`
method or the `fetch_all(keyspace)` method respectively in your cache
repository class. See the following example.

```ruby
class MostRecentPrice
  include Hitnmiss::Repository

  default_expiration 134

  private

  def fetch(*args)
    # - do whatever to get the value you want to cache
    # - construct a Hitnmiss::Entity with the value
    Hitnmiss::Entity.new('some value')
  end

  def fetch_all(keyspace)
    # - do whatever to get the values you want to cache
    # - construct a collection of arguments and Hitnmiss entities
    [
      { args: ['a', 'b'], entity: Hitnmiss::Entity.new('some value') },
      { args: ['x', 'y'], entity: Hitnmiss::Entity.new('other value') }
    ]
  end
end
```

The `fetch(*args)` method is responsible for obtaining the value that you want
to cache by whatever means necessary and returning a `Hitnmiss::Entity`
containing the value, and optionally an `expiration`, `fingerprint`, and
`last_modified`. **Note:** The `*args` passed into the `fetch(*args)` method
originate as the arguments that are passed into `prime` and `get` methods when
they are called. For more context on `prime` and `get` please so [Priming an
Entity](#priming-an-entity) and [Getting a Value](#getting-a-value)
respectively. Defining the `fetch(*args)` method is **required** if you want to
be able to cache values or get cached values using the `prime` or `get` methods.

If you wish to support [priming the cache for an entire
repository](#priming-the-entire-repository) using the `prime_all` method, you
**must** define the `fetch_all(keyspace)` method on the repository class. This
method **must** return a collection of hashes describing the `args` that would
be used to get an entity and the corresponding `Hitnmiss::Entity`. See example
above.

#### Set Cache Source based Expiration

In some cases you might need to set the expiration to be a different
value for each cached value. This is generally needed when you get
information back from a remote entity in the `fetch(*args)` method and you
use it to compute the expiration. This for example could be via the `Expiration`
header in an HTTP response. Once you have the expiration for that
value you can set it by passing the expiration into the
`Hitnmiss::Entity` constructor as seen below. **Note:** The expiration
in the `Hitnmiss::Entity` will take precedence over the
`default_expiration`.

```ruby
class MostRecentPrice
  include Hitnmiss::Repository

  default_expiration 134

  private

  def fetch(*args)
    # - do whatever to get the value you want to cache
    # - construct a Hitnmiss::Entity with the value and optionally a
    #   result based expiration. If no result based expiration is
    #   provided it will use the default_expiration.
    Hitnmiss::Entity.new('some value', expiration: 235)
  end
end
```

#### Set Cache Source based Fingerprint

In some cases you might want to set the fingerprint for the cached value. Doing
so provides more flexibility to `Hitnmiss` in terms of determining staleness of
cache. A very common example of this would be if you are fetching something over
HTTP from the remote and the remote includes the `ETag` header. If you take the
value of the `ETag` header (a fingerprint) and you set it in the
`Hitnmiss::Entity` it can be used later on by `Hitnmiss` to aid in identifying
staleness. Once you have obtained the fingerprint by whatever means you can set
it by passing the fingerprint into the `Hitnmiss::Entity` constructor as seen
below.

```ruby
class MostRecentPrice
  include Hitnmiss::Repository

  default_expiration 134

  private

  def fetch(*args)
    # - do whatever to get the value you want to cache
    # - do whatever to get the fingerprint of the value you want to cache
    # - construct a Hitnmiss::Entity with the value and optionally a
    #   fingerprint.
    Hitnmiss::Entity.new('some value',
                         fingerprint: "63478adce0dd0fbc82ef4bb1f1d64193")
  end
end
```

#### Set Cache Source based Last Modified

In some cases you might want to set the `last_modified` value for a cached
value. Doing this provides more felxibility to `Hitnmiss` when trying to
determine staleness of a cached item. A common example of this would be if you
are fetching somthing over HTTP from a remote server and it includes the
`Last-Modified` entity header in the response. If you took the value of the
`Last-Modified` header and you set it in the `Hitnmiss::Entity` it can be used
later on by `Hitnmiss` to aid in identifying staleness. Once you have obtained
the `Last-Modified` value by whatever means you can set it by passing the
`last_modified` option into the `Hitnmiss::Entity` constructor as seen below.

```ruby
class MostRecentPrice
  include Hitnmiss::Repository

  default_expiration 134

  private

  def fetch(*args)
    # - do whatever to get the value you want to cache
    # - do whatever to get the last modified of the value you want to cache
    # - construct a Hitnmiss::Entity with the value and optionally a
    #   last_modified value.
    Hitnmiss::Entity.new('some value',
                         last_modified: "2016-04-15T13:00:00Z")
  end
end
```

## Usage

The following is a light breakdown of the various pieces of Hitnmiss and
how to get going with them after defining your cache repository.

### Priming an entity

Once you have defined the `fetch(*args)` method you can construct an
instance of your cache repository and use it. One way you might want to
use it is to force the repository to cache a value. This can be done
using the `prime` method as seen below.

```ruby
repository = MostRecentPrice.new
repository.prime(current_user.id) # => cached_value
```

### Priming the entire repository

You can use the `prime_all` method to prime the entire repository. **Note:**
The repository class must define the `fetch_all(keyspace)` method for this
to work. See the "Define Fetcher Methods" section above for details.

```ruby
repository = MostRecentPrice.new
repository.prime_all # => [cached values, ...]
```

### Getting a value

You can also use your cache repository to get a particular cached
value by doing the following.

```ruby
repository = MostRecentPrice.new
repository.get(current_user.id) # => cached_value
```

### Deleting a cached value

You can delete a cached value by calling the `delete` method with the
same arguments used to get it.

```ruby
repository = MostRecentPrice.new
# cache some values ex: repository.prime(current_user.id)
repository.delete(current_user.id)
```

### Clearing a repository

You can clear the entire repository of cached values by calling the
`clear` method.

```ruby
repository = MostRecentPrice.new
# cache some values ex: repository.prime(current_user.id)
repository.clear
```

## Contributing

If you are interested in contributing to Hitnmiss. There is a guide (both code
and general help) over in
[CONTRIBUTING](https://github.com/Acornsgrow/hitnmiss/blob/master/CONTRIBUTING.md).

## License

The gem is available as open source under the terms of the [MIT
License](http://opensource.org/licenses/MIT).


text:
//This test was useful during implementation, but introduces an unwanted depedency
//using System.Web;
//using Dlbr.CommonLogin.IdentityModel.WebApi;
//using NUnit.Framework;
//using Seges.IdentityModel;
//using Seges.IdentityModel.DeflatedSaml;

//namespace Dlbr.CommonLogin.IdentityModel.Tests.Unit.Seges.IdentityModel
//{
//    [TestFixture]
//    [Category("BuildVerification")]
//    public class DeflatedSamlEncoderTests
//    {

//        [Test]
//        public void Encode_OutputMatchOldImplementation()
//        {
//            DeflatedSamlEncoder encoder = new DeflatedSamlEncoder();
//            var input = Token;
//            var actual = encoder.Encode(input);
//            var expected = new DeflatedSamlTokenHeaderEncoder().Encode(input);
//            AssertAreEqualIgnoringUrlEncodeCase(expected, actual);
//        }

//        private void AssertAreEqualIgnoringUrlEncodeCase(string expected, string actual)
//        {
//            var actualCanonical = HttpUtility.UrlEncode(HttpUtility.UrlDecode(actual));
//            var expectedCanonical = HttpUtility.UrlEncode(HttpUtility.UrlDecode(expected));
//            Assert.AreEqual(expectedCanonical, actualCanonical);
//        }

//        private const string Token = "<saml:Assertion MajorVersion=\"1\" MinorVersion=\"1\" AssertionID=\"_b6f31526-cafa-4dc" +
//            "2-abac-cca3f56e8a3f\" Issuer=\"http://si-idp.vfltest.dk/adfs/services/trust\" Issue" +
//            "Instant=\"2017-10-12T13:04:43.961Z\" xmlns:saml=\"urn:oasis:names:tc:SAML:1.0:asser" +
//            "tion\"><saml:Conditions NotBefore=\"2017-10-12T13:04:43.961Z\" NotOnOrAfter=\"2017-1" +
//            "0-12T14:04:43.961Z\"><saml:AudienceRestrictionCondition><saml:Audience>https://lo" +
//            "calhost.vfltest.dk/CustomerSampleTier1Service/</saml:Audience></saml:AudienceRes" +
//            "trictionCondition></saml:Conditions><saml:AttributeStatement><saml:Subject><saml" +
//            ":SubjectConfirmation><saml:ConfirmationMethod>urn:oasis:names:tc:SAML:1.0:cm:bea" +
//            "rer</saml:ConfirmationMethod></saml:SubjectConfirmation></saml:Subject><saml:Att" +
//            "ribute AttributeName=\"name\" AttributeNamespace=\"http://schemas.xmlsoap.org/ws/20" +
//            "05/05/identity/claims\"><saml:AttributeValue>PROD\\cvr01</saml:AttributeValue></sa" +
//            "ml:Attribute><saml:Attribute AttributeName=\"emailaddress\" AttributeNamespace=\"ht" +
//            "tp://schemas.xmlsoap.org/ws/2005/05/identity/claims\"><saml:AttributeValue>mac@vf" +
//            "l.dk</saml:AttributeValue></saml:Attribute><saml:Attribute AttributeName=\"upn\" A" +
//            "ttributeNamespace=\"http://schemas.xmlsoap.org/ws/2005/05/identity/claims\"><saml:" +
//            "AttributeValue>cvr01@PROD.DLI</saml:AttributeValue></saml:Attribute><saml:Attrib" +
//            "ute AttributeName=\"givenname\" AttributeNamespace=\"http://schemas.xmlsoap.org/ws/" +
//            "2005/05/identity/claims\"><saml:AttributeValue> </saml:AttributeValue></saml:Attr" +
//            "ibute><saml:Attribute AttributeName=\"surname\" AttributeNamespace=\"http://schemas" +
//            ".xmlsoap.org/ws/2005/05/identity/claims\"><saml:AttributeValue>cvr01 (89999995)</" +
//            "saml:AttributeValue></saml:Attribute><saml:Attribute AttributeName=\"actor\" Attri" +
//            "buteNamespace=\"http://schemas.xmlsoap.org/ws/2009/09/identity/claims\"><saml:Attr" +
//            "ibuteValue><Actor><saml:Attribute AttributeName=\"name\" AttributeNamespa" +
//            "ce=\"http://schemas.xmlsoap.org/ws/2005/05/identity/claims\" xmlns:saml=\"urn:oasis" +
//            ":names:tc:SAML:1.0:assertion\"><saml:AttributeValue>PROD\\customersamplea" +
//            "ctas</saml:AttributeValue></saml:Attribute><saml:Attribute Attrib" +
//            "uteName=\"upn\" AttributeNamespace=\"http://schemas.xmlsoap.org/ws/2005/05/identity" +
//            "/claims\" xmlns:saml=\"urn:oasis:names:tc:SAML:1.0:assertion\"><saml:Attribut" +
//            "eValue>customersampleactas@PROD.DLI</saml:AttributeValue></saml:Attr" +
//            "ibute><saml:Attribute AttributeName=\"emailaddress\" AttributeNamespace=\"htt" +
//            "p://schemas.xmlsoap.org/ws/2005/05/identity/claims\" xmlns:saml=\"urn:oasis:names:" +
//            "tc:SAML:1.0:assertion\"><saml:AttributeValue>test@example.com</saml:A" +
//            "ttributeValue></saml:Attribute><saml:Attribute AttributeName=\"givenn" +
//            "ame\" AttributeNamespace=\"http://schemas.xmlsoap.org/ws/2005/05/identity/claims\" " +
//            "xmlns:saml=\"urn:oasis:names:tc:SAML:1.0:assertion\"><saml:AttributeValue&gt" +
//            "; </saml:AttributeValue></saml:Attribute><saml:Attribute Attribut" +
//            "eName=\"surname\" AttributeNamespace=\"http://schemas.xmlsoap.org/ws/2005/05/identi" +
//            "ty/claims\" xmlns:saml=\"urn:oasis:names:tc:SAML:1.0:assertion\"><saml:Attrib" +
//            "uteValue>customersampleactas</saml:AttributeValue></saml:Attribute&g" +
//            "t;<saml:Attribute AttributeName=\"authenticationmethod\" AttributeNamespace=\"ht" +
//            "tp://schemas.microsoft.com/ws/2008/06/identity/claims\" xmlns:saml=\"urn:oasis:nam" +
//            "es:tc:SAML:1.0:assertion\"><saml:AttributeValue>http://schemas.microsoft" +
//            ".com/ws/2008/06/identity/authenticationmethod/password</saml:AttributeValue&g" +
//            "t;</saml:Attribute><saml:Attribute AttributeName=\"authenticationinstant" +
//            "\" AttributeNamespace=\"http://schemas.microsoft.com/ws/2008/06/identity/claims\" x" +
//            "mlns:saml=\"urn:oasis:names:tc:SAML:1.0:assertion\"><saml:AttributeValue a:t" +
//            "ype=\"tn:dateTime\" xmlns:tn=\"http://www.w3.org/2001/XMLSchema\" xmlns:a=\"http://ww" +
//            "w.w3.org/2001/XMLSchema-instance\">2017-10-12T13:04:43.946Z</saml:Attribute" +
//            "Value></saml:Attribute></Actor></saml:AttributeValue></saml:Attri" +
//            "bute></saml:AttributeStatement><saml:AuthenticationStatement AuthenticationMetho" +
//            "d=\"urn:oasis:names:tc:SAML:1.0:am:password\" AuthenticationInstant=\"2017-10-12T13" +
//            ":04:43.524Z\"><saml:Subject><saml:SubjectConfirmation><saml:ConfirmationMethod>ur" +
//            "n:oasis:names:tc:SAML:1.0:cm:bearer</saml:ConfirmationMethod></saml:SubjectConfi" +
//            "rmation></saml:Subject></saml:AuthenticationStatement><ds:Signature xmlns:ds=\"ht" +
//            "tp://www.w3.org/2000/09/xmldsig#\"><ds:SignedInfo><ds:CanonicalizationMethod Algo" +
//            "rithm=\"http://www.w3.org/2001/10/xml-exc-c14n#\" /><ds:SignatureMethod Algorithm=" +
//            "\"http://www.w3.org/2001/04/xmldsig-more#rsa-sha256\" /><ds:Reference URI=\"#_b6f31" +
//            "526-cafa-4dc2-abac-cca3f56e8a3f\"><ds:Transforms><ds:Transform Algorithm=\"http://" +
//            "www.w3.org/2000/09/xmldsig#enveloped-signature\" /><ds:Transform Algorithm=\"http:" +
//            "//www.w3.org/2001/10/xml-exc-c14n#\" /></ds:Transforms><ds:DigestMethod Algorithm" +
//            "=\"http://www.w3.org/2001/04/xmlenc#sha256\" /><ds:DigestValue>h5vM3c1hsbwUJ7daOK2" +
//            "5ODvIsIu59kW7J7p0avMRBI8=</ds:DigestValue></ds:Reference></ds:SignedInfo><ds:Sig" +
//            "natureValue>VPavX82SqyETqzuFUA0UGToJPQc9RIPoiNY4dKoWUUzTXeKiXScGmIcCYWJVL5Bby/aJ" +
//            "oT20jKb81VJl+OHxlu0ctb0Ytr4eoZzoGczWCwZYl5w7h5vRwxRc/pR6umCSgdy3d1NVt0s5CsycjQQY" +
//            "lgHRsQMWk7G2FL2P1rc1zuArATNade9okAP7CmO7i7aw7UPsTglEiCWY8nLFfUiy5e1HyTab/Vw05ETH" +
//            "A+/ZqT7N5POYHkynogf9todX11NDB/4Xh8Y4WETb6sBioKbOoZlQYe//DHxu3AxDZseDg/nLURO7P3sV" +
//            "9qO/uKVhElXWNIgAhjlL+LVV/SMcOnEALw==</ds:SignatureValue><KeyInfo xmlns=\"http://w" +
//            "ww.w3.org/2000/09/xmldsig#\"><X509Data><X509Certificate>MIIDQjCCAiqgAwIBAgIQGuO/V" +
//            "sFEcJ1BS46QHMNn9DANBgkqhkiG9w0BAQsFADArMSkwJwYDVQQDEyBBREZTIFNpZ25pbmcgLSBzaS1pZ" +
//            "HAudmZsdGVzdC5kazAgFw0xNTEyMzEyMjAwMDBaGA8zOTk5MTIzMTIyMDAwMFowKzEpMCcGA1UEAxMgQ" +
//            "URGUyBTaWduaW5nIC0gc2ktaWRwLnZmbHRlc3QuZGswggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKA" +
//            "oIBAQC4MsHOghdlzNfQXZrLFq+oL1oqcEi0vPplGOWqCj9boRaKyzJ4oNnFcvZQvKIYv+w46mADxYd0R" +
//            "XVK/dzinSZ3Qb7jnYdGAC1OxfSeTzWd+usNzIm/HvYgw6UjfEhwao0mWQYlELHSb88kzMTPrPRYyu+kr" +
//            "vpAmVysGzeVRU6nt2tQk5xx8aTh3x+Kfqcr405OSul7uzgogz+R+hOhhImvt/i6msituw+RpmgyReEy7" +
//            "qZE12yZKLCbKeVf821uud+fkJzGsqsJ54sgpgbanQWB5eUDWLDV0wKoW8bCMpuFWWanCpw3nHQeZzZr9" +
//            "vb2Y5iq0RcMzsK/CVzBeIeCIQBBAgMBAAGjYDBeMFwGA1UdAQRVMFOAEJaBJFyizaDteaBULprNsymhL" +
//            "TArMSkwJwYDVQQDEyBBREZTIFNpZ25pbmcgLSBzaS1pZHAudmZsdGVzdC5ka4IQGuO/VsFEcJ1BS46QH" +
//            "MNn9DANBgkqhkiG9w0BAQsFAAOCAQEATe4nVccZXgJlohDTNQeDfDrvOoiagsLA739oVVWqQG4qIY9yg" +
//            "Rzy8XTPbtTfxNIRU4uXnwzcdhqEUykNBo0V6HcCR7WuQ/4xMuhKvHW4fcjds7Ezrvz9y+ij0hmiAinW8" +
//            "K7UXjH3FmlwevOlrIbKKLS3DdSC1PkYBMp4qnPz8zT0zsQEo3ZpnBnxzKnQXhXV/rTvrUUwjFoRJeILk" +
//            "xvqg6+A/IJMD8seXs5Y1kq2Igr1QRn/sxi0EapVltLLcVRHfP2TIqn+2jFQLQ4vbU7KLL3BWJJjXFGFL" +
//            "e90f4wmJHs82Ru1Znxxn/YptFDeYOxsJyeRa2msijBkJn911ue2sA==</X509Certificate></X509D" +
//            "ata></KeyInfo></ds:Signature></saml:Assertion>";

//    }
//}

redpajama_set_name: RedPajamaGithub


text:
var xmldom = require('xmldom');

var Variable = function(id, name, type) {
    this.id = id;
    this.name = name;
    this.type = type;
    this.value = '0';
    this.ts = new Date();
}

Variable.prototype.setValue = function(value) {
    this.value = value;
    this.ts = new Date();
}

Variable.prototype.getValue = function() {
    return this.value;
}

Variable.prototype.getId = function() {
    return this.id;
}

Variable.prototype.getType = function() {
    return this.type;
}

Variable.prototype.getTs = function() {
    return this.ts;
}

Variable.prototype.getName = function() {
    return this.name;
}

Variable.prototype.getStateXml = function(doc) {
    var varNode = doc.createElement('var');
    varNode.setAttribute('type', this.getType());
    varNode.setAttribute('id', this.getId());

    var initNode = doc.createElement('init');
    initNode.appendChild(doc.createTextNode(this.getValue()));
    varNode.appendChild(initNode);

    var valNode = doc.createElement('val');
    valNode.appendChild(doc.createTextNode(this.getValue()));
    varNode.appendChild(valNode);

    var tsNode = doc.createElement('ts');
    tsNode.appendChild(doc.createTextNode(this.getTs().toString()));
    varNode.appendChild(tsNode);

    return varNode;
}

exports.Variable = Variable;


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

import java.util.List;
import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.textract.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * RelationshipMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class RelationshipMarshaller {

    private static final MarshallingInfo<String> TYPE_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Type").build();
    private static final MarshallingInfo<List> IDS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Ids").build();

    private static final RelationshipMarshaller instance = new RelationshipMarshaller();

    public static RelationshipMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(Relationship relationship, ProtocolMarshaller protocolMarshaller) {

        if (relationship == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(relationship.getType(), TYPE_BINDING);
            protocolMarshaller.marshall(relationship.getIds(), IDS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
package nodefs

// This file contains FileSystemConnector's implementation of
// RawFileSystem

import (
	"bytes"
	"fmt"
	"log"
	"strings"
	"time"

	"github.com/hanwen/go-fuse/fuse"
)

// Returns the RawFileSystem so it can be mounted.
func (c *FileSystemConnector) RawFS() fuse.RawFileSystem {
	return (*rawBridge)(c)
}

type rawBridge FileSystemConnector

func (c *rawBridge) Fsync(input *fuse.FsyncIn) fuse.Status {
	return fuse.ENOSYS
}

func (c *rawBridge) SetDebug(debug bool) {
	c.fsConn().SetDebug(debug)
}

func (c *rawBridge) FsyncDir(input *fuse.FsyncIn) fuse.Status {
	return fuse.ENOSYS
}

func (c *rawBridge) fsConn() *FileSystemConnector {
	return (*FileSystemConnector)(c)
}

func (c *rawBridge) String() string {
	if c.rootNode == nil || c.rootNode.mount == nil {
		return "go-fuse:unmounted"
	}

	name := fmt.Sprintf("%T", c.rootNode.Node())
	name = strings.TrimLeft(name, "*")
	return name
}

func (c *rawBridge) Init(s *fuse.Server) {
	c.server = s
}

func (c *FileSystemConnector) lookupMountUpdate(out *fuse.Attr, mount *fileSystemMount) (node *Inode, code fuse.Status) {
	code = mount.mountInode.Node().GetAttr(out, nil, nil)
	if !code.Ok() {
		log.Println("Root getattr should not return error", code)
		out.Mode = fuse.S_IFDIR | 0755
		return mount.mountInode, fuse.OK
	}

	return mount.mountInode, fuse.OK
}

func (c *FileSystemConnector) internalLookup(out *fuse.Attr, parent *Inode, name string, header *fuse.InHeader) (node *Inode, code fuse.Status) {
	child := parent.GetChild(name)
	if child != nil && child.mountPoint != nil {
		return c.lookupMountUpdate(out, child.mountPoint)
	}

	if child != nil {
		parent = nil
	}
	if child != nil {
		code = child.fsInode.GetAttr(out, nil, &header.Context)
	} else {
		child, code = parent.fsInode.Lookup(out, name, &header.Context)
	}

	return child, code
}

func (c *rawBridge) Lookup(header *fuse.InHeader, name string, out *fuse.EntryOut) (code fuse.Status) {
	parent := c.toInode(header.NodeId)
	if !parent.IsDir() {
		log.Printf("Lookup %q called on non-Directory node %d", name, header.NodeId)
		return fuse.ENOTDIR
	}
	outAttr := (*fuse.Attr)(&out.Attr)
	child, code := c.fsConn().internalLookup(outAttr, parent, name, header)
	if code == fuse.ENOENT && parent.mount.negativeEntry(out) {
		return fuse.OK
	}
	if !code.Ok() {
		return code
	}
	if child == nil {
		log.Println("Lookup returned fuse.OK with nil child", name)
	}

	child.mount.fillEntry(out)
	out.NodeId, out.Generation = c.fsConn().lookupUpdate(child)
	out.Ino = out.NodeId

	return fuse.OK
}

func (c *rawBridge) Forget(nodeID, nlookup uint64) {
	c.fsConn().forgetUpdate(nodeID, int(nlookup))
}

func (c *rawBridge) GetAttr(input *fuse.GetAttrIn, out *fuse.AttrOut) (code fuse.Status) {
	node := c.toInode(input.NodeId)

	var f File
	if input.Flags()&fuse.FUSE_GETATTR_FH != 0 {
		if opened := node.mount.getOpenedFile(input.Fh()); opened != nil {
			f = opened.WithFlags.File
		}
	}

	dest := (*fuse.Attr)(&out.Attr)
	code = node.fsInode.GetAttr(dest, f, &input.Context)
	if !code.Ok() {
		return code
	}

	node.mount.fillAttr(out, input.NodeId)
	return fuse.OK
}

func (c *rawBridge) OpenDir(input *fuse.OpenIn, out *fuse.OpenOut) (code fuse.Status) {
	node := c.toInode(input.NodeId)
	stream, err := node.fsInode.OpenDir(&input.Context)
	if err != fuse.OK {
		return err
	}
	stream = append(stream, node.getMountDirEntries()...)
	de := &connectorDir{
		node: node.Node(),
		stream: append(stream,
			fuse.DirEntry{Mode: fuse.S_IFDIR, Name: "."},
			fuse.DirEntry{Mode: fuse.S_IFDIR, Name: ".."}),
		rawFS: c,
	}
	h, opened := node.mount.registerFileHandle(node, de, nil, input.Flags)
	out.OpenFlags = opened.FuseFlags
	out.Fh = h
	return fuse.OK
}

func (c *rawBridge) ReadDir(input *fuse.ReadIn, out *fuse.DirEntryList) fuse.Status {
	node := c.toInode(input.NodeId)
	opened := node.mount.getOpenedFile(input.Fh)
	return opened.dir.ReadDir(input, out)
}

func (c *rawBridge) ReadDirPlus(input *fuse.ReadIn, out *fuse.DirEntryList) fuse.Status {
	node := c.toInode(input.NodeId)
	opened := node.mount.getOpenedFile(input.Fh)
	return opened.dir.ReadDirPlus(input, out)
}

func (c *rawBridge) Open(input *fuse.OpenIn, out *fuse.OpenOut) (status fuse.Status) {
	node := c.toInode(input.NodeId)
	f, code := node.fsInode.Open(input.Flags, &input.Context)
	if !code.Ok() || f == nil {
		return code
	}
	h, opened := node.mount.registerFileHandle(node, nil, f, input.Flags)
	out.OpenFlags = opened.FuseFlags
	out.Fh = h
	return fuse.OK
}

func (c *rawBridge) SetAttr(input *fuse.SetAttrIn, out *fuse.AttrOut) (code fuse.Status) {
	node := c.toInode(input.NodeId)

	var f File
	if input.Valid&fuse.FATTR_FH != 0 {
		opened := node.mount.getOpenedFile(input.Fh)
		f = opened.WithFlags.File
	}

	if code.Ok() && input.Valid&fuse.FATTR_MODE != 0 {
		permissions := uint32(07777) & input.Mode
		code = node.fsInode.Chmod(f, permissions, &input.Context)
	}
	if code.Ok() && (input.Valid&(fuse.FATTR_UID|fuse.FATTR_GID) != 0) {
		code = node.fsInode.Chown(f, uint32(input.Uid), uint32(input.Gid), &input.Context)
	}
	if code.Ok() && input.Valid&fuse.FATTR_SIZE != 0 {
		code = node.fsInode.Truncate(f, input.Size, &input.Context)
	}
	if code.Ok() && (input.Valid&(fuse.FATTR_ATIME|fuse.FATTR_MTIME|fuse.FATTR_ATIME_NOW|fuse.FATTR_MTIME_NOW) != 0) {
		now := time.Now()
		var atime *time.Time
		var mtime *time.Time

		if input.Valid&fuse.FATTR_ATIME != 0 {
			if input.Valid&fuse.FATTR_ATIME_NOW != 0 {
				atime = &now
			} else {
				t := time.Unix(int64(input.Atime), int64(input.Atimensec))
				atime = &t
			}
		}

		if input.Valid&fuse.FATTR_MTIME != 0 {
			if input.Valid&fuse.FATTR_MTIME_NOW != 0 {
				mtime = &now
			} else {
				t := time.Unix(int64(input.Mtime), int64(input.Mtimensec))
				mtime = &t
			}
		}

		code = node.fsInode.Utimens(f, atime, mtime, &input.Context)
	}

	if !code.Ok() {
		return code
	}

	// Must call GetAttr(); the filesystem may override some of
	// the changes we effect here.
	attr := (*fuse.Attr)(&out.Attr)
	code = node.fsInode.GetAttr(attr, nil, &input.Context)
	if code.Ok() {
		node.mount.fillAttr(out, input.NodeId)
	}
	return code
}

func (c *rawBridge) Fallocate(input *fuse.FallocateIn) (code fuse.Status) {
	n := c.toInode(input.NodeId)
	opened := n.mount.getOpenedFile(input.Fh)

	return n.fsInode.Fallocate(opened, input.Offset, input.Length, input.Mode, &input.Context)
}

func (c *rawBridge) Readlink(header *fuse.InHeader) (out []byte, code fuse.Status) {
	n := c.toInode(header.NodeId)
	return n.fsInode.Readlink(&header.Context)
}

func (c *rawBridge) Mknod(input *fuse.MknodIn, name string, out *fuse.EntryOut) (code fuse.Status) {
	parent := c.toInode(input.NodeId)

	child, code := parent.fsInode.Mknod(name, input.Mode, uint32(input.Rdev), &input.Context)
	if code.Ok() {
		c.childLookup(out, child, &input.Context)
		code = child.fsInode.GetAttr((*fuse.Attr)(&out.Attr), nil, &input.Context)
	}
	return code
}

func (c *rawBridge) Mkdir(input *fuse.MkdirIn, name string, out *fuse.EntryOut) (code fuse.Status) {
	parent := c.toInode(input.NodeId)

	child, code := parent.fsInode.Mkdir(name, input.Mode, &input.Context)
	if code.Ok() {
		c.childLookup(out, child, &input.Context)
		code = child.fsInode.GetAttr((*fuse.Attr)(&out.Attr), nil, &input.Context)
	}
	return code
}

func (c *rawBridge) Unlink(header *fuse.InHeader, name string) (code fuse.Status) {
	parent := c.toInode(header.NodeId)
	return parent.fsInode.Unlink(name, &header.Context)
}

func (c *rawBridge) Rmdir(header *fuse.InHeader, name string) (code fuse.Status) {
	parent := c.toInode(header.NodeId)
	return parent.fsInode.Rmdir(name, &header.Context)
}

func (c *rawBridge) Symlink(header *fuse.InHeader, pointedTo string, linkName string, out *fuse.EntryOut) (code fuse.Status) {
	parent := c.toInode(header.NodeId)

	child, code := parent.fsInode.Symlink(linkName, pointedTo, &header.Context)
	if code.Ok() {
		c.childLookup(out, child, &header.Context)
		code = child.fsInode.GetAttr((*fuse.Attr)(&out.Attr), nil, &header.Context)
	}
	return code
}

func (c *rawBridge) Rename(input *fuse.RenameIn, oldName string, newName string) (code fuse.Status) {
	oldParent := c.toInode(input.NodeId)

	child := oldParent.GetChild(oldName)
	if child == nil {
		return fuse.ENOENT
	}
	if child.mountPoint != nil {
		return fuse.EBUSY
	}

	newParent := c.toInode(input.Newdir)
	if oldParent.mount != newParent.mount {
		return fuse.EXDEV
	}

	return oldParent.fsInode.Rename(oldName, newParent.fsInode, newName, &input.Context)
}

func (c *rawBridge) Link(input *fuse.LinkIn, name string, out *fuse.EntryOut) (code fuse.Status) {
	existing := c.toInode(input.Oldnodeid)
	parent := c.toInode(input.NodeId)

	if existing.mount != parent.mount {
		return fuse.EXDEV
	}

	child, code := parent.fsInode.Link(name, existing.fsInode, &input.Context)
	if code.Ok() {
		c.childLookup(out, child, &input.Context)
		code = child.fsInode.GetAttr((*fuse.Attr)(&out.Attr), nil, &input.Context)
	}

	return code
}

func (c *rawBridge) Access(input *fuse.AccessIn) (code fuse.Status) {
	n := c.toInode(input.NodeId)
	return n.fsInode.Access(input.Mask, &input.Context)
}

func (c *rawBridge) Create(input *fuse.CreateIn, name string, out *fuse.CreateOut) (code fuse.Status) {
	parent := c.toInode(input.NodeId)
	f, child, code := parent.fsInode.Create(name, uint32(input.Flags), input.Mode, &input.Context)
	if !code.Ok() {
		return code
	}

	c.childLookup(&out.EntryOut, child, &input.Context)
	handle, opened := parent.mount.registerFileHandle(child, nil, f, input.Flags)

	out.OpenOut.OpenFlags = opened.FuseFlags
	out.OpenOut.Fh = handle
	return code
}

func (c *rawBridge) Release(input *fuse.ReleaseIn) {
	if input.Fh != 0 {
		node := c.toInode(input.NodeId)
		opened := node.mount.unregisterFileHandle(input.Fh, node)
		opened.WithFlags.File.Release()
	}
}

func (c *rawBridge) ReleaseDir(input *fuse.ReleaseIn) {
	if input.Fh != 0 {
		node := c.toInode(input.NodeId)
		node.mount.unregisterFileHandle(input.Fh, node)
	}
}

func (c *rawBridge) GetXAttrSize(header *fuse.InHeader, attribute string) (sz int, code fuse.Status) {
	node := c.toInode(header.NodeId)
	data, errno := node.fsInode.GetXAttr(attribute, &header.Context)
	return len(data), errno
}

func (c *rawBridge) GetXAttrData(header *fuse.InHeader, attribute string) (data []byte, code fuse.Status) {
	node := c.toInode(header.NodeId)
	return node.fsInode.GetXAttr(attribute, &header.Context)
}

func (c *rawBridge) RemoveXAttr(header *fuse.InHeader, attr string) fuse.Status {
	node := c.toInode(header.NodeId)
	return node.fsInode.RemoveXAttr(attr, &header.Context)
}

func (c *rawBridge) SetXAttr(input *fuse.SetXAttrIn, attr string, data []byte) fuse.Status {
	node := c.toInode(input.NodeId)
	return node.fsInode.SetXAttr(attr, data, int(input.Flags), &input.Context)
}

func (c *rawBridge) ListXAttr(header *fuse.InHeader) (data []byte, code fuse.Status) {
	node := c.toInode(header.NodeId)
	attrs, code := node.fsInode.ListXAttr(&header.Context)
	if code != fuse.OK {
		return nil, code
	}

	b := bytes.NewBuffer([]byte{})
	for _, v := range attrs {
		b.Write([]byte(v))
		b.WriteByte(0)
	}

	return b.Bytes(), code
}

////////////////
// files.

func (c *rawBridge) Write(input *fuse.WriteIn, data []byte) (written uint32, code fuse.Status) {
	node := c.toInode(input.NodeId)
	opened := node.mount.getOpenedFile(input.Fh)

	var f File
	if opened != nil {
		f = opened.WithFlags.File
	}

	return node.Node().Write(f, data, int64(input.Offset), &input.Context)
}

func (c *rawBridge) Read(input *fuse.ReadIn, buf []byte) (fuse.ReadResult, fuse.Status) {
	node := c.toInode(input.NodeId)
	opened := node.mount.getOpenedFile(input.Fh)

	var f File
	if opened != nil {
		f = opened.WithFlags.File
	}

	return node.Node().Read(f, buf, int64(input.Offset), &input.Context)
}

func (c *rawBridge) StatFs(header *fuse.InHeader, out *fuse.StatfsOut) fuse.Status {
	node := c.toInode(header.NodeId)
	s := node.Node().StatFs()
	if s == nil {
		return fuse.ENOSYS
	}
	*out = *s
	return fuse.OK
}

func (c *rawBridge) Flush(input *fuse.FlushIn) fuse.Status {
	node := c.toInode(input.NodeId)
	opened := node.mount.getOpenedFile(input.Fh)

	if opened != nil {
		return opened.WithFlags.File.Flush()
	}
	return fuse.OK
}


text:
<?php

$rawBody = file_get_contents('php://input');
echo "Raw body is: " . htmlentities($rawBody);


text:
package io.aos.endpoint.socket.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class BioTcpEchoServer3 {

    public static void main(String... args) throws IOException {
        ServerSocket serverSocket = null;

        try {
            serverSocket = new ServerSocket(10007);
        } catch (IOException e) {
            System.err.println("Could not listen on port: 10007.");
            System.exit(1);
        }

        Socket clientSocket = null;
        System.out.println("Waiting for connection.....");

        try {
            clientSocket = serverSocket.accept();
        } catch (IOException e) {
            System.err.println("Accept failed.");
            System.exit(1);
        }

        System.out.println("Connection successful");

        PrintWriter outputStream = new PrintWriter(clientSocket.getOutputStream(), true);

        BufferedReader inputStream= new BufferedReader(new InputStreamReader(
                clientSocket.getInputStream()));

        String cAddress = "";
        String inputLine;

        cAddress = clientSocket.getInetAddress().toString();

        while ((inputLine = inputStream.readLine()) != null) {
            System.out.println("Server: " + inputLine + "  " + cAddress + " ");
            outputStream.println(inputLine + " " + cAddress);

            if (inputLine.equals("bye"))
                break;
        }

        outputStream.close();
        inputStream.close();
        clientSocket.close();
        serverSocket.close();
    }

}


text:
Flask-Scrypt
============
[![Build Status](https://travis-ci.org/cryptojuice/flask-scrypt.svg?branch=master)](https://travis-ci.org/cryptojuice/flask-scrypt)

Flask-Scrypt is a Flask extension used to generate scrypt password hashes and random salts. For those looking for extra security compared to SHA-1 and MD5 encryption.
Flask-Scrypt depends on [py-scrypt](https://pypi.python.org/pypi/scrypt/) which should install automatically but can be installed manually using pip install scrypt.

## Installation

    $ pip install flask-scrypt

## Usage

    from flask.ext.scrypt import generate_password_hash, generate_random_salt, check_password_hash

Generate random salt for use with the generate_password_hash function. You will want to store this salt with the rest of your users database information. This salt along with the generated hash will be used to check the password later on.

    salt = generate_random_salt()
    password_hash = generate_password_hash('mypassword', salt)

Pull stored salt and password_hash from database:

    salt = 'Users salt you stored in database'
    password_hash = 'Hash you stored in database'

Check if password matches hash/salt combo:

    check_password_hash('mypassword', password_hash, salt)
check_password_hash() returns True is password checks out, otherwise returns False.


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;
using TravelClient.UX.Ajax.Models;
using TravelService.Model;
using TravelService.Model.Base.Travel;
using TravelService.Model.ServiceModel;
using TravelService.Service;
using TravelService.Service.ServiceRepository;

namespace TravelClient.UX.Ajax
{
    public partial class PostAjax : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request["queryType"] == "addPicture")
            {
                Response.Write(AddPicture());
            }

            if (Request["queryType"] == "getproducts")
            {
                Response.Write(GetProducts());
            }

             if (Request["queryType"] == "removePicture")
            {
                RemovePicture();
            }

             if (Request["queryType"] == "getcategory")
             {
                 Response.Write(GetCategoryList());
             }

             if (Request["queryType"] == "getpostsbycategoryid")
             {
                 Response.Write(GetArticlesByCategoryId());
             }

             if (Request["queryType"] == "getarticlebyid")
             {
                 Response.Write(GetArticleByID());
             }

             if (Request["queryType"] == "savearticle")
             {
                 Response.Write(SubmitArticle());
             }

        }

        private string GetArticlesByCategoryId() {

            JavaScriptSerializer jss = new JavaScriptSerializer();
            var paramDes = jss.Deserialize<TravelDiary>(Request["queryParam"]);

            return "";
        }

        private string GetProducts() {
            JavaScriptSerializer jss = new JavaScriptSerializer();

            GetAssociatedProductsInfoRequest registerReq = new GetAssociatedProductsInfoRequest();

            ServiceRequest request = new ServiceRequest(registerReq);
            ServiceResponse response = new ServiceResponse();

            IService service = ServiceFactory.getInstance().getService(service_type.GET_ASSOCIATED_PRODUCT);

            service.process(request, response);
            GetAssociatedProductsInfoResponse responseU = (GetAssociatedProductsInfoResponse)response.responseObj;
            return jss.Serialize(responseU.products);
        }
        private string SubmitArticle() {

            JavaScriptSerializer jss = new JavaScriptSerializer();
            var paramDes = jss.Deserialize<TravelDiary>(Request["queryParam"]);

            PublishTravelDiaryRequest registerReq = new PublishTravelDiaryRequest();
            registerReq.diary = paramDes;

            ServiceRequest request = new ServiceRequest(registerReq);
            ServiceResponse response = new ServiceResponse();

            IService service = ServiceFactory.getInstance().getService(service_type.PUBLISH_TRAVEL_DIARY);

            service.process(request, response);
            PublishTravelDiaryResponse responseU = (PublishTravelDiaryResponse)response.responseObj;
            return responseU.diaryId.ToString();

        }
        private string GetArticleByID() {
            JavaScriptSerializer jss = new JavaScriptSerializer();

            string articleId = Request["id"].ToString();

            GetTravelDiaryDetailInfoRequest registerReq = new GetTravelDiaryDetailInfoRequest();
            registerReq.diaryid = int.Parse(articleId);

            ServiceRequest request = new ServiceRequest(registerReq);
            ServiceResponse response = new ServiceResponse();

            IService service = ServiceFactory.getInstance().getService(service_type.GET_TRAVEL_DIARY_DETAIL);

            service.process(request, response);
            GetTravelDiaryDetailInfoResponse responseU = (GetTravelDiaryDetailInfoResponse)response.responseObj;
            return jss.Serialize(responseU.diaryInfo);
        }
        private void RemovePicture()
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            var paramDes = jss.Deserialize<ListQueryParameterPicture>(Request["queryParam"]);

            foreach (var item in paramDes)
            {
                FileInfo myfileinf = new FileInfo(Server.MapPath(item));
                myfileinf.Delete();
            }
        }

        private string GetCategoryList() {

            JavaScriptSerializer jss = new JavaScriptSerializer();

            GetCategoryRequest registerReq = new GetCategoryRequest();

            ServiceRequest request = new ServiceRequest(registerReq);
            ServiceResponse response = new ServiceResponse();

            IService service = ServiceFactory.getInstance().getService(service_type.GET_DISPLAY_CATEGORY);

            service.process(request, response);
            GetCategoryResponse responseU = (GetCategoryResponse)response.responseObj;
            return jss.Serialize(responseU.categories);
        }

        private string AddPicture()
        {
            string output = "";
            Guid subString = Guid.NewGuid();
            // Get the post data
            if (Request.Files == null)
            {
                output = "Querystring:uploaded file is null!";
            }
            //var paramDes = jss.Deserialize<QueryParameterPicture>(Request["data"]);

            string logicalPath = "";
            //if (paramDes.SaveLocation != string.Empty)
            //{
            //    // Save int temp location
            //    picturePath = Server.MapPath("../CustomerPicture/Temp/");
            //    logicalPath = "../CustomerPicture/Temp/";
            //}
            //else
            //{
            var picturePath = Server.MapPath("../CustomerPicture/");
            logicalPath = "../CustomerPicture/";
            //}
            string[] stringSplit = Request.Files[0].FileName.Split('\\');
            int temp = stringSplit.Length;

            string newFileName = picturePath + subString + stringSplit[temp - 1];
            Directory.CreateDirectory(Path.GetDirectoryName(newFileName));

            string newLogicFileName = logicalPath + subString + stringSplit[temp - 1];

            using (FileStream fileStream = File.Create(newFileName))
            {
                var buffer = new byte[Request.Files[0].ContentLength];
                int readCount = Request.Files[0].InputStream.Read(buffer, 0, buffer.Length);

                if (readCount > 0)
                {
                    fileStream.Write(buffer, 0, readCount);
                }
            }
            Console.Write("Hello");
            return newLogicFileName;
        }
    }
}


text:
package com.projectrixor.rixor.scrimmage.commands;

import com.projectrixor.rixor.scrimmage.Rixor;
import com.projectrixor.rixor.scrimmage.map.Map;
import com.projectrixor.rixor.scrimmage.map.MapTeam;
import com.projectrixor.rixor.scrimmage.player.Client;
import com.sk89q.minecraft.util.commands.CommandContext;
import com.sk89q.minecraft.util.commands.CommandException;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

public class JoinCommand{

	@com.sk89q.minecraft.util.commands.Command(aliases = { "join", "p", "play", "playgame", "joingame"}, desc = "Joins the game", usage = "[team]", min = 0, max = 1)
	public static void join(final CommandContext args, CommandSender sender) throws Exception {
		if(sender instanceof Player == false) {
			throw new CommandException("This command is for players only!");
		}
		Map map = Rixor.getRotation().getSlot().getMap();
		Client client = Client.getClient((Player) sender);

		if (Rixor.getRotation().getSlot().getMatch().isHasEnded()){
			throw new CommandException("The match has ended! Please wait for the server to cycle.");
		}

		MapTeam team = map.getObservers();
		if(args.argsLength() == 0) {
			team = map.getLowest();
		} else if(args.argsLength() == 1) {
			team = map.getTeam(args.getString(0));
			if(team == null) {
				throw new CommandException("No teams matched query.");
			}
		} else {
			sender.sendMessage(ChatColor.RED + "/join (team)");
		}
		if (client.getTeam().equals(team)) {
			sender.sendMessage(ChatColor.RED + "You are already on that team!");
		} else {
			Rixor.broadcast(team.getColor()+sender.getName()+ChatColor.GRAY+" has joined the "+team.getColor()+team.getDisplayName()+ChatColor.GRAY+".");
	    }
		client.setTeam(team);
		((Player) sender).setScoreboard(team.getMap().getBoard());

	}

}


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Class bad_function_call</title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../index.html" title="Chapter 1. Boost.TypeErasure">
<link rel="up" href="../../boost_typeerasure/reference.html#header.boost.type_erasure.exception_hpp" title="Header <boost/type_erasure/exception.hpp>">
<link rel="prev" href="dynamic_binding.html" title="Class template dynamic_binding">
<link rel="next" href="bad_any_cast.html" title="Class bad_any_cast">

Home
Libraries
People
FAQ
More

Class bad_function_call

boost::type_erasure::bad_function_call

Synopsis

// In header: <boost/type_erasure/exception.hpp>

class bad_function_call {
public:
  // construct/copy/destruct
  bad_function_call();
};

Description

Exception thrown when the arguments to a primitive concept are incorrect.

See Also:

 call,  require_match

bad_function_call
        public
       construct/copy/destruct

bad_function_call();

Copyright © 2011-2013 Steven Watanabe

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text: Symlink to ~/.config


text:
#ifndef VIS_VIS_MAIN_H_
#define VIS_VIS_MAIN_H_

extern int window;
extern int window_height;
extern int window_width;

void InitGL(void);
void InitGlut(int argc, char **argv);
void DrawGLScene(void);

#endif  // VIS_VIS_MAIN_H_


text:
import {getFlipperLib} from 'flipper-plugin';

const cmd = 'klist --json';
const endWith = '@THEFACEBOOK.COM';

export async function isFBEmployee(): Promise<boolean> {
  return getFlipperLib()
    .remoteServerContext.childProcess.exec(cmd)
    .then(
      (stdobj: {stderr: string; stdout: string}) => {
        const principal = String(JSON.parse(stdobj.stdout).principal);

        return principal.endsWith(endWith);
      },
      (_err: Error) => {
        return false;
      },
    );
}


text:
package com.hazelcast.concurrent.countdownlatch.operations;

import com.hazelcast.concurrent.countdownlatch.CountDownLatchService;
import com.hazelcast.spi.BlockingOperation;
import com.hazelcast.spi.WaitNotifyKey;

import static com.hazelcast.concurrent.countdownlatch.CountDownLatchDataSerializerHook.AWAIT_OPERATION;
import static java.lang.Boolean.TRUE;

public class AwaitOperation extends AbstractCountDownLatchOperation implements BlockingOperation {

    public AwaitOperation() {
    }

    public AwaitOperation(String name, long timeout) {
        super(name);
        setWaitTimeout(timeout);
    }

    @Override
    public void run() throws Exception {
    }

    @Override
    public Object getResponse() {
        return TRUE;
    }

    @Override
    public WaitNotifyKey getWaitKey() {
        return waitNotifyKey();
    }

    @Override
    public boolean shouldWait() {
        CountDownLatchService service = getService();
        return service.shouldWait(name);
    }

    @Override
    public void onWaitExpire() {
        sendResponse(false);
    }

    @Override
    public int getId() {
        return AWAIT_OPERATION;
    }
}


text:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace Avalara.AvaTax.RestClient
{
    /// <summary>
    /// Settle this transaction with your ledger by executing one or many actions against that transaction.
    ///
    /// You may use this endpoint to verify the transaction, change the transaction's code, and commit the transaction for reporting purposes.
    /// This endpoint may be used to execute any or all of these actions at once.
    /// </summary>
    public class SettleTransactionModel
    {
        /// <summary>
        ///
        /// </summary>
        public VerifyTransactionModel verify { get; set; }

        /// <summary>
        ///
        /// </summary>
        public ChangeTransactionCodeModel changeCode { get; set; }

        /// <summary>
        ///
        /// </summary>
        public CommitTransactionModel commit { get; set; }

        /// <summary>
        /// Convert this object to a JSON string of itself
        /// </summary>
        /// <returns>A JSON string of this object</returns>
        public override string ToString()
        {
            return JsonConvert.SerializeObject(this, new JsonSerializerSettings() { Formatting = Formatting.Indented });
        }
    }
}


text:
#include "MKLDNNTester.h"
#include "paddle/gserver/layers/MKLDNNBase.h"
#include "paddle/gserver/layers/MKLDNNLayer.h"
#include "paddle/trainer/Trainer.h"

namespace paddle {

// init data layer and test layer of both dnn and reference
void MKLDNNTester::reset(const TestConfig& dnn,
                         const TestConfig& ref,
                         size_t batchSize) {
  const bool trans = false;
  const bool useGpu = false;

  // clear
  configs_.clear();
  layerNames_.clear();
  dataLayers_.clear();
  datas_.clear();
  layerMaps_.clear();
  parameters_.clear();
  testLayers_.clear();

  // resize
  configs_.resize(NUM);
  layerNames_.resize(NUM);
  dataLayers_.resize(NUM);
  datas_.resize(NUM);
  layerMaps_.resize(NUM);
  parameters_.resize(NUM);
  testLayers_.resize(NUM);

  // reset configs and layer names
  configs_[DNN] = dnn;
  configs_[REF] = ref;
  layerNames_[DNN] = "mkldnn";     // the first is mkldnn layer
  layerNames_[REF] = "reference";  // second is reference layer

  // reset others
  for (size_t i = 0; i < NUM; ++i) {
    configs_[i].layerConfig.set_name(layerNames_[i]);
    initDataLayer(configs_[i],
                  &(dataLayers_[i]),
                  &(datas_[i]),
                  &(layerMaps_[i]),
                  layerNames_[i],
                  batchSize,
                  trans,
                  useGpu);
    initTestLayer(
        configs_[i], &(layerMaps_[i]), &(parameters_[i]), &(testLayers_[i]));
  }
  refLayer_ = testLayers_[REF];
  dnnLayer_ = testLayers_[DNN];
  EXPECT_EQ(dataLayers_[DNN].size(), dataLayers_[REF].size());
  EXPECT_EQ(parameters_[DNN].size(), parameters_[REF].size());
  setInputImgSize();

  // for comparison with Paddle reference results,
  // need manually add cpu device output for test
  MKLDNNLayerPtr dnnLayer = std::dynamic_pointer_cast<MKLDNNLayer>(dnnLayer_);
  if (dnnLayer) {
    dnnLayer->addOutputArgument(CPU_DEVICE);
  }
}

void MKLDNNTester::setInputImgSize() {
  for (size_t n = 0; n < dataLayers_.size(); ++n) {
    for (size_t i = 0; i < dataLayers_[n].size(); ++i) {
      // TODO(TJ): fix me when concat and elewise ready
      dataLayers_[n][i]->getOutput().setFrameHeight(ih_);
      dataLayers_[n][i]->getOutput().setFrameWidth(iw_);
    }
  }
}

// init randome parameters of ref, and copy to mkldnn
void MKLDNNTester::randomWgtDatas() {
  EXPECT_EQ(parameters_[DNN].size(), parameters_[REF].size());
  const bool isBN = refLayer_->getType() == "batch_norm";
  for (size_t i = 0; i < parameters_[REF].size(); ++i) {
    const VectorPtr& dnnValue = parameters_[DNN][i]->getBuf(PARAMETER_VALUE);
    const VectorPtr& refValue = parameters_[REF][i]->getBuf(PARAMETER_VALUE);
    parameters_[REF][i]->randomize();
    if (isBN && i == 2) {
      // this param is moving average in batch norm, which must larger than 0
      real offset = fabs(refValue->getMin()) + 1.0;
      refValue->add(offset);
    }
    dnnValue->copyFrom(*refValue);

    VLOG(MKLDNN_TESTS) << "Random weight " << parameters_[DNN][i]->getName();
    printVector(dnnValue);
  }
}

// random botdata of ref layer and copy same to mkldnn
void MKLDNNTester::randomBotDatas() {
  CHECK_EQ(dataLayers_.size(), NUM);
  for (size_t i = 0; i < dataLayers_[DNN].size(); ++i) {
    dataLayers_[REF][i]->getOutputValue()->randomizeUniform();
    dataLayers_[DNN][i]->getOutputValue()->copyFrom(
        *(dataLayers_[REF][i]->getOutputValue()));
    VLOG(MKLDNN_TESTS) << "Random Foward, InputValue " << i;
    printMatrix(dataLayers_[REF][i]->getOutputValue());
  }
}

void MKLDNNTester::randomTopDiffs() {
  refLayer_->getOutputGrad()->randomizeUniform();
  dnnLayer_->getOutput(CPU_DEVICE)
      .grad->copyFrom(*(refLayer_->getOutputGrad()));
  VLOG(MKLDNN_TESTS) << "Random Backward, OutputGrad";
  printMatrix(refLayer_->getOutputGrad());
}

void MKLDNNTester::checkForward() {
  VLOG(MKLDNN_TESTS) << "Check Forward";
  printTopDatas();
  double delta =
      compareMatrix(dnnLayer_->getOutputValue(), refLayer_->getOutputValue());
  EXPECT_LE(fabs(delta), eps_);
}

void MKLDNNTester::checkBackwardData() {
  VLOG(MKLDNN_TESTS) << "Check Backward Data";
  const bool isBN = refLayer_->getType() == "batch_norm";
  for (size_t i = 0; i < dataLayers_[DNN].size(); ++i) {
    const MatrixPtr& dnnDiff = dataLayers_[DNN][i]->getOutputGrad();
    const MatrixPtr& refDiff = dataLayers_[REF][i]->getOutputGrad();
    VLOG(MKLDNN_ALL) << "MKLDNN Backward Result: InputGrad " << i;
    printMatrix(dnnDiff);
    VLOG(MKLDNN_ALL) << "Reference Backward Result: InputGrad " << i;
    printMatrix(refDiff);

    double delta = compareMatrix(dnnDiff, refDiff);
    EXPECT_LE(fabs(delta), eps_);
    if (isBN) {
      // the other two inputs in batch norm are for moving mean and var
      // do not have grad to compare
      break;
    }
  }
}

void MKLDNNTester::checkBackwardWgts() {
  VLOG(MKLDNN_TESTS) << "Check Backward Weight";
  CHECK_EQ(parameters_[DNN].size(), parameters_[REF].size());
  vector<VectorPtr> dnnWgts;  // used to temply save mkldnn weights
  saveWgt(parameters_[DNN], dnnWgts);

  MKLDNNLayerPtr dnnLayer = std::dynamic_pointer_cast<MKLDNNLayer>(dnnLayer_);
  if (dnnLayer) {
    dnnLayer->convertWeightsToPaddle();
  }
  for (size_t i = 0; i < parameters_[DNN].size(); ++i) {
    const VectorPtr& dnn = parameters_[DNN][i]->getBuf(PARAMETER_VALUE);
    const VectorPtr& ref = parameters_[REF][i]->getBuf(PARAMETER_VALUE);
    VLOG(MKLDNN_ALL) << "MKLDNN Result: weight value"
                     << parameters_[DNN][i]->getName();
    printVector(dnn);
    VLOG(MKLDNN_ALL) << "Reference Result: weight value "
                     << parameters_[REF][i]->getName();
    printVector(ref);

    double delta = compareVector(dnn, ref);
    EXPECT_LE(fabs(delta), eps_);
  }

  VLOG(MKLDNN_ALL) << "Restore dnn weights before comapre";
  restoreWgt(dnnWgts, parameters_[DNN]);
}

void MKLDNNTester::saveWgt(const vector<ParameterPtr>& from,
                           vector<VectorPtr>& to) {
  const bool useGpu = false;
  to.resize(from.size());
  for (size_t i = 0; i < to.size(); ++i) {
    const VectorPtr& wgt = from[i]->getBuf(PARAMETER_VALUE);
    to[i] = Vector::create(wgt->getSize(), useGpu);
    to[i]->copyFrom(*wgt);
  }
}

void MKLDNNTester::restoreWgt(const vector<VectorPtr>& from,
                              vector<ParameterPtr>& to) {
  CHECK_EQ(from.size(), to.size());
  for (size_t i = 0; i < from.size(); ++i) {
    const VectorPtr& wgt = to[i]->getBuf(PARAMETER_VALUE);
    wgt->copyFrom(*from[i]);
  }
}

// clear parameters grad
void MKLDNNTester::clearWgtDiffs(size_t id) {
  CHECK_LE(id, parameters_.size());
  for (size_t n = 0; n < parameters_.size(); ++n) {
    if (id == n || id == parameters_.size()) {
      for (size_t i = 0; i < parameters_[n].size(); ++i) {
        const VectorPtr& grad = parameters_[n][i]->getBuf(PARAMETER_GRADIENT);
        if (grad) {
          grad->zeroMem();
        }
      }
    }
  }
}

void MKLDNNTester::clearBotDiffs(size_t id) {
  CHECK_LE(id, dataLayers_.size());
  for (size_t n = 0; n < dataLayers_.size(); ++n) {
    if (id == n || id == dataLayers_.size()) {
      // clear inputs layers of this specific layer
      for (size_t i = 0; i < dataLayers_[n].size(); ++i) {
        dataLayers_[n][i]->getOutputGrad()->zeroMem();
      }
    }
  }
}

void MKLDNNTester::clearTopDatas(size_t id) {
  CHECK_LE(id, testLayers_.size());
  for (size_t i = 0; i < testLayers_.size(); ++i) {
    if (id == i || id == testLayers_.size()) {
      testLayers_[i]->getOutputValue()->zeroMem();
    }
  }
}

void MKLDNNTester::printTopDatas() {
  if (!log_) {
    return;
  }

  for (int n = 0; n < NUM; ++n) {
    VLOG(MKLDNN_ALL) << testLayers_[n]->getType()
                     << " Forward Result: OutputValue";
    printMatrix(testLayers_[n]->getOutputValue());
  }
}

void MKLDNNTester::printMatrix(const MatrixPtr& m) {
  if (!log_) {
    return;
  }

  std::ostringstream ostr;
  m->print(ostr);
  VLOG(MKLDNN_ALL) << std::endl << ostr.str();
}

void MKLDNNTester::printVector(const VectorPtr& v) {
  if (!log_) {
    return;
  }

  std::ostringstream ostr;
  v->print(ostr, v->getSize());
  VLOG(MKLDNN_ALL) << std::endl << ostr.str();
}

double MKLDNNTester::getDelta(const real* d1,
                              const real* d2,
                              size_t len,
                              const float failRate,
                              const float thres) {
  double delta = 0, sum = 0;
  int failCnt = 0;
  const double eps = 1e-5;
  double maxOut = 0;
  for (size_t i = 0; i < len; ++i) {
    double ref = fabs(d2[i]);
    double diff = fabs(d1[i] - d2[i]);
    delta += diff;
    sum += ref;
    if (ref > eps && fabs(d1[i]) > eps && diff / ref > thres) {
      maxOut = std::max(maxOut, diff / ref);
      failCnt++;
    }
  }
  EXPECT_TRUE(std::isnormal(sum));
  EXPECT_FALSE(std::isinf(sum));
  EXPECT_FALSE(std::isnan(delta));
  VLOG(MKLDNN_ALL) << "reference avg data: " << sum / len
                   << ", delta: " << delta / sum << ", failCnt:" << failCnt;
  return (failCnt / (float)len) > failRate ? maxOut : delta / sum;
}

double MKLDNNTester::compareMatrix(const MatrixPtr& m1, const MatrixPtr& m2) {
  CHECK_EQ(m1->getElementCnt(), m2->getElementCnt());
  return getDelta(m1->getData(), m2->getData(), m1->getElementCnt());
}

double MKLDNNTester::compareVector(const VectorPtr& v1, const VectorPtr& v2) {
  CHECK_EQ(v1->getSize(), v2->getSize());
  return getDelta(v1->getData(), v2->getData(), v1->getSize());
}

void MKLDNNTester::runOnce() {
  // test forward
  randomBotDatas();
  dnnLayer_->forward(passType_);
  refLayer_->forward(passType_);
  checkForward();

  if (passType_ == PASS_TEST) {
    return;
  }

  // test backward
  // simple updater
  UpdateCallback updateCallback = [](Parameter* para) {
    auto& grad = para->getBuf(PARAMETER_GRADIENT);
    auto& value = para->getBuf(PARAMETER_VALUE);
    real lr = 1e-2;
    value->add(*grad, lr);
    grad->zeroMem();
  };
  randomTopDiffs();
  dnnLayer_->backward(updateCallback);
  refLayer_->backward(updateCallback);
  checkBackwardData();
  checkBackwardWgts();

  // clear buffers
  // ref code will addto the diff, dnn code will writeto it
  // and clearTopDatas(REF) should be coverd by ref layers
  clearBotDiffs(REF);
  clearWgtDiffs(REF);
  // it is necessary to clear bottom diffs when only activation is dnn type
  if (configs_[DNN].layerConfig.active_type().compare(0, 7, "mkldnn_") == 0) {
    clearBotDiffs(DNN);
  }
}

void MKLDNNTester::run(const TestConfig& dnn,
                       const TestConfig& ref,
                       size_t batchSize,
                       size_t inputImgH,
                       size_t inputImgW,
                       PassType passType,
                       bool printDetails,
                       size_t iter,
                       float epsilon) {
  CHECK(dnn.layerConfig.type().compare(0, 7, "mkldnn_") == 0 ||
        dnn.layerConfig.active_type().compare(0, 7, "mkldnn_") == 0)
      << "should be MKLDNN layer or MKLDNN activation";
  if (dnn.layerConfig.type() == ref.layerConfig.type()) {
    VLOG(MKLDNN_TESTS) << "Test MKLDNN functionality: "
                       << dnn.layerConfig.active_type() << " vs "
                       << ref.layerConfig.active_type();
  } else {
    VLOG(MKLDNN_TESTS) << "Test MKLDNN functionality: "
                       << dnn.layerConfig.type() << " vs "
                       << ref.layerConfig.type();
  }

  ih_ = inputImgH;
  iw_ = inputImgW;
  passType_ = passType;
  log_ = printDetails;
  iter_ = iter;
  eps_ = epsilon;

  // Firstly test mkldnn init from PARAM_FORMAT_ORIGINAL weight
  reset(dnn, ref, batchSize);
  randomWgtDatas();
  clearWgtDiffs();
  clearBotDiffs();
  for (size_t i = 0; i < iter_; ++i) {
    VLOG(MKLDNN_TESTS) << "Check Iteration " << i;
    runOnce();
  }

  if (parameters_[DNN].empty()) {
    // has no paramters
    return;
  }

  // After run some iterations, the mkldnn weight has been stored in dnnLayer
  // and we can also get the mkldnn weight parameter header format.
  // Weight parameter should always be index 0 (and bias index 1).
  // TODO(TJ): should also consider mean and var format when batchnorm ready
  int dnnWgtFmt = parameters_[DNN][0]->getHeaderFormat();
  int refWgtFmt = parameters_[REF][0]->getHeaderFormat();
  if (dnnWgtFmt == refWgtFmt) {
    // weight format are equal, so no need check more
    return;
  }

  // then save the weights and restart again
  vector<VectorPtr> dnnWgts, refWgts;
  CHECK_EQ(parameters_[DNN].size(), parameters_[REF].size());
  saveWgt(parameters_[DNN], dnnWgts);
  saveWgt(parameters_[REF], refWgts);

  // restart again with dnn weight format
  reset(dnn, ref, batchSize);
  // TODO(TJ): should also considerate mean and var format when batchnorm ready
  parameters_[DNN][0]->setHeaderFormat(dnnWgtFmt);

  // restore wgt
  restoreWgt(dnnWgts, parameters_[DNN]);
  restoreWgt(refWgts, parameters_[REF]);
  clearWgtDiffs();
  clearBotDiffs();

  for (size_t i = 0; i < iter_; ++i) {
    VLOG(MKLDNN_TESTS) << "Check Iteration " << i;
    runOnce();
  }
}

void MKLDNNTester::initArgument(DataIn& data,
                                const std::string& configPath,
                                const size_t iter) {
  TrainerConfigHelper config(configPath);
  size_t batchSize = config.getOptConfig().batch_size();
  data.inArgs.resize(iter);
  data.outGrads.resize(iter);
  data.paraValues.clear();
  for (const auto& layer_name : config.getModelConfig().input_layer_names()) {
    auto layer_config = std::find_if(config.getModelConfig().layers().begin(),
                                     config.getModelConfig().layers().end(),
                                     [=](const LayerConfig& layer_config) {
                                       return layer_config.name() == layer_name;
                                     });
    CHECK(layer_config != config.getModelConfig().layers().end());

    size_t layerSize = layer_config->size();
    for (size_t i = 0; i < iter; ++i) {
      Argument arg;
      arg.value = Matrix::create(batchSize, layerSize, false, false);
      arg.grad = Matrix::create(batchSize, layerSize, false, false);
      arg.value->randomizeUniform();
      arg.value->add(-0.5);
      arg.value->sigmoid(*arg.value);
      arg.grad->zeroMem();
      arg.ids = VectorT<int>::create(batchSize, false);
      arg.ids->rand(layerSize);
      generateSequenceStartPositions(batchSize, arg.sequenceStartPositions);
      data.inArgs[i].push_back(arg);
    }
  }

  for (const auto& layer_name : config.getModelConfig().output_layer_names()) {
    auto layer_config = std::find_if(config.getModelConfig().layers().begin(),
                                     config.getModelConfig().layers().end(),
                                     [=](const LayerConfig& layer_config) {
                                       return layer_config.name() == layer_name;
                                     });
    CHECK(layer_config != config.getModelConfig().layers().end());

    size_t layerSize = layer_config->size();
    for (size_t i = 0; i < iter; ++i) {
      MatrixPtr grad = Matrix::create(batchSize, layerSize, false, false);
      grad->randomizeUniform();
      data.outGrads[i].push_back(grad);
    }
  }

  for (const auto& para_config : config.getModelConfig().parameters()) {
    VectorPtr value = Vector::create(para_config.size(), false);
    value->randnorm(0, 2);
    data.paraValues.push_back(value);
  }
}

void MKLDNNTester::getOutResult(const std::string& configPath,
                                DataIn& in,
                                DataOut& out,
                                bool use_mkldnn,
                                size_t iter) {
  FLAGS_use_gpu = false;
  FLAGS_use_mkldnn = use_mkldnn;
  *ThreadLocalRand::getSeed() = 1;
  srand(1);

  Trainer trainer;
  auto config = std::make_shared<TrainerConfigHelper>(configPath);
  trainer.init(config, false);
  auto gradientMachine = trainer.getGradientMachine();
  std::vector<ParameterPtr> parameters = gradientMachine->getParameters();
  for (size_t i = 0; i < in.paraValues.size(); i++) {
    parameters[i]->getBuf(PARAMETER_VALUE)->copyFrom(*in.paraValues[i]);
  }
  UpdateCallback simpleUpdate = [](Parameter* para) {
    auto& grad = para->getBuf(PARAMETER_GRADIENT);
    auto& value = para->getBuf(PARAMETER_VALUE);
    real lr = 1e-2;
    value->add(*grad, lr);
    grad->zeroMem();
  };

  vector<Argument> outArgs;
  gradientMachine->start();
  out.outValues.clear();
  out.paraValues.clear();
  for (size_t i = 0; i < iter; ++i) {
    VLOG(MKLDNN_TESTS) << "runing iteration " << i;
    gradientMachine->forward(in.inArgs[i], &outArgs, PASS_TRAIN);
    // save forward result
    for (size_t k = 0; k < outArgs.size(); k++) {
      MatrixPtr value = Matrix::create(outArgs[k].value->getHeight(),
                                       outArgs[k].value->getWidth(),
                                       false,
                                       false);
      value->copyFrom(*outArgs[k].value);
      out.outValues.push_back(value);
    }

    // random backward input
    for (size_t k = 0; k < outArgs.size(); k++) {
      outArgs[k].grad->copyFrom(*in.outGrads[i][k]);
    }
    gradientMachine->backward(simpleUpdate);
  }
  gradientMachine->finish();

  // save param value
  for (size_t i = 0; i < in.paraValues.size(); i++) {
    VectorPtr val = Vector::create(
        parameters[i]->getBuf(PARAMETER_VALUE)->getSize(), false);
    val->copyFrom(*parameters[i]->getBuf(PARAMETER_VALUE));
    out.paraValues.push_back(val);
  }
}

void MKLDNNTester::compareResult(DataOut& ref, DataOut& dnn, float eps) {
  CHECK_EQ(ref.outValues.size(), dnn.outValues.size());
  CHECK_EQ(ref.paraValues.size(), dnn.paraValues.size());
  VLOG(MKLDNN_TESTS) << "compare value size: " << ref.outValues.size();
  for (size_t i = 0; i < ref.outValues.size(); i++) {
    EXPECT_LE(fabs(compareMatrix(ref.outValues[i], dnn.outValues[i])), eps);
  }
  VLOG(MKLDNN_TESTS) << "compare param size: " << ref.outValues.size();
  for (size_t i = 0; i < ref.paraValues.size(); i++) {
    EXPECT_LE(fabs(compareVector(ref.paraValues[i], dnn.paraValues[i])), eps);
  }
}

void MKLDNNTester::runBranchesTest(const std::string& configPath,
                                   size_t iter,
                                   float eps) {
  DataIn in;
  initArgument(in, configPath, iter);
  DataOut outCpu, outDnn;
  VLOG(MKLDNN_TESTS) << "runing cpu network";
  getOutResult(configPath, in, outCpu, false, iter);
  VLOG(MKLDNN_TESTS) << "runing mkldnn network";
  getOutResult(configPath, in, outDnn, true, iter);

  compareResult(outCpu, outDnn, eps);
}

}  //  namespace paddle


text:
using System.Windows;

namespace Odin.Views
{
    /*
     * ViewModelからの変更通知などの各種イベントを受け取る場合は、PropertyChangedWeakEventListenerや
     * CollectionChangedWeakEventListenerを使うと便利です。独自イベントの場合はLivetWeakEventListenerが使用できます。
     * クローズ時などに、LivetCompositeDisposableに格納した各種イベントリスナをDisposeする事でイベントハンドラの開放が容易に行えます。
     *
     * WeakEventListenerなので明示的に開放せずともメモリリークは起こしませんが、できる限り明示的に開放するようにしましょう。
     */

    /// <summary>
    ///     MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}


text:
layout: post
date: 2017-08-18
title: "Jovani Silver Feather Mermaid Prom Dress 32427 Sleeveless Floor-Length Mermaid/Trumpet"
category: Jovani
tags: [Jovani ,Jovani,Mermaid/Trumpet,Halter,Floor-Length,Sleeveless]
---
### Jovani Silver Feather Mermaid Prom Dress 32427
Just **$454.98**
###   Sleeveless Floor-Length Mermaid/Trumpet

BRANDS	Jovani

Silhouette	Mermaid/Trumpet

Neckline	Halter

Hemline/Train	Floor-Length

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/jovani-/39177-jovani-silver-feather-mermaid-prom-dress-32427.html](https://www.readybrides.com/en/jovani-/39177-jovani-silver-feather-mermaid-prom-dress-32427.html)


text:
package org.brjia.qs.web;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.brjia.qs.model.AreaRegDTO;
import org.brjia.qs.service.CollectService;
import org.brjia.qs.service.FightingService;
import org.brjia.qs.service.UserService;
import org.brjia.qs.util.Const;
import org.brjia.qs.util.FileUploadUtil;
import org.brjia.qs.util.QnyhCollectArg;
import org.brjia.qs.util.ResultMessage;
import org.brjia.qs.util.UserInfo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * 站点控制器
 *
 * @author hujiawei
 *
 */
@Controller
public class SiteController {

	@Resource
	private UserService userService;
	@Resource
	private CollectService service;

	@RequestMapping(value = "area", method = RequestMethod.POST)
	@ResponseBody
	public ResultMessage createArea(@RequestParam("areaName") String name) {
		ResultMessage ms = new ResultMessage();
		AreaRegDTO res = userService.createArea(name);
		if(res==null){
			ms.setMsg("已存在");
		}else{
			ms.setData(res);
		}
		return ms;
	}
	@RequestMapping(value = "username/exist", method = RequestMethod.GET)
	@ResponseBody
	public ResultMessage isExistUser(@RequestParam("email") String name) {
		ResultMessage ms = new ResultMessage();
		ms.setData(userService.isExistUser(name));
		return ms;
	}
	@RequestMapping(value = "login", method = RequestMethod.POST)
	@ResponseBody
	public ResultMessage doLogin(@RequestParam("email") String name, @RequestParam("pwd") String password,HttpSession ses) {
		UserInfo user = userService.findUser(name,password);
		if(user==null){
			return new ResultMessage("密码错误");
		}
		ses.setAttribute(Const.USER_KEY, user);
		ResultMessage ms = new ResultMessage();
		ms.setData(user);
		return ms;
	}

	@RequestMapping(value = "logout", method = RequestMethod.GET)
	@ResponseBody
	public ResultMessage doLogout(HttpSession session) {
		session.invalidate();
		ResultMessage rm = new ResultMessage();
		rm.setData(true);
		return rm;
	}

	@RequestMapping(value = "data/register", method = RequestMethod.POST)
	public String doRegister(@RequestParam Map<String, String> args,HttpSession ses) {
		userService.insertUser(args);
		return "redirect:../index";
	}
	@RequestMapping(value = "profile/{pid:\\d*}", method = RequestMethod.GET)
	public String prefile(@PathVariable Integer pid, ModelMap model,HttpSession ses) {
		UserInfo user = (UserInfo) ses.getAttribute(Const.USER_KEY);
		if(user==null || !user.getUserId().equals(pid)){
			return "error";
		}//TODO 关联角色
		model.addAttribute("user",user);
		model.addAttribute("memberList",userService.selectMemberList());
		//关联-退出家族
		//
		return "profile";
	}
	@RequestMapping(value = "role", method = RequestMethod.POST)
	@ResponseBody
	public ResultMessage relateRole(@RequestParam Integer roleId,HttpSession ses) {
		UserInfo user = (UserInfo) ses.getAttribute(Const.USER_KEY);
		ResultMessage rs = new ResultMessage();
		if(user==null){
			rs.setMsg("未登录");
			return rs;
		}
		if(userService.updateRole(roleId,user)){
			rs.setData(user.getName());
			return rs;
		}
		rs.setMsg("关联失败");
		return rs;
	}

	/**
	 * 校验规则 上传:空文件,错误文本类型,总体积,单个文件体积 完整性:文件名时间范围校验,时间格式,内容格式
	 * 重复文件:文件名时间+内容中的帮会名称+地区id+内容签名
	 *
	 * 上传文件
	 *
	 * @param fileItems
	 */
	@RequestMapping(value = "data/upload", method = RequestMethod.POST)
	public String upload(@RequestParam MultipartFile[] file,ModelMap model,HttpSession session) {
		String check = FileUploadUtil.check(file);
		if (check != null) {
			model.put("msg", check);
			return "uploadresult";
		}
		List<QnyhCollectArg> list = FileUploadUtil.readString(file);
		check = service.insertFightingSummary((UserInfo)session.getAttribute(Const.USER_KEY), list);
		if (check != null) {
			model.put("msg", check);
			return "uploadresult";
		}
		return "uploadresult";

	}

}


text:
package com.sillelien.dollar.api;

import com.sillelien.dollar.api.types.DollarFactory;
import org.jetbrains.annotations.NotNull;

/**
 * @author hello@neilellis.me
 */
public interface StringAware {

    /**
     * Remove whitespace before and after the first and last non-whitespace characters.
     *
     * @return
     */
    @NotNull
    default var $trim() {
        return DollarFactory.fromStringValue(toString().trim());
    }

}


text:
package com.opensource.opencamera;

/**
 * This class represents the condition that we cannot open the camera hardware
 * successfully. For example, another process is using the camera.
 */
public class CameraHardwareException extends Exception {

    public CameraHardwareException(Throwable t) {
        super(t);
    }
}


text:
MEDUSA_BEGIN;

//Note: window maybe smaller than container and container maybe smaller than window too
class IScrollMathModel
{
public:
	enum class ScrollState
	{
		None,
		Begin,
		StaticScroll,
		Scrolling,
		Spring,
		End
	};
public:
	IScrollMathModel(ScrollDirection direction = ScrollDirection::FreeFromCurrent);
	virtual ~IScrollMathModel(void);
	ActionEvent OnScrollEvent;
public:
	void Initialize(const Size2F& containerSize, const Rect2F& window);
	void Initialize(const Size2F& containerSize, const Size2F& windowSize);
	void Initialize(const Rect2F& container, const Rect2F& window);

	ScrollDirection Direction() const { return mDirection; }
	void SetDirection(ScrollDirection val);

	bool IsVertical()const;
	bool IsHorizontal()const;

	ScrollState State() const { return mState; }
	const Rect2F& CurrentWindow() const { return mCurrentWindow; }
	const Rect2F& Container() const { return mContainer; }

	Point2F Movement()const { return mCurrentWindow.Origin - mPrevWindow.Origin; }
	void ApplyMovement() { mPrevWindow = mCurrentWindow; }
	Point2F MovementToEnd()const;	//on direction
	Point2F MovementToStart()const;	//on direction

	bool IsRectVisible(const Rect2F& rect)const;
	Point2F ConvertToWindowSpace(Point2F pos);

	Point2F Offset()const;
	float OffsetX()const;
	float OffsetY()const;

	virtual void StaticScroll(Point2F movement);
	virtual void StartScrolling(Point2F initialVelocity);

	virtual void ScrollTo(Point2F offset);
	virtual void ScrollBy(Point2F movement);
	virtual void ScrollToStart();
	virtual void ScrollToEnd();

	Point2F PageCount()const;

	Point2F Page()const;
	float PageX()const;
	float PageY()const;
	void ScrollByPage(Point2F page);
	void ScrollByPageX(float page);
	void ScrollByPageY(float page);

	void ScrollToPage(Point2F page);
	void ScrollToPageX(float page);
	void ScrollToPageY(float page);

	void UpdateWindow(const Size2F& sizeChanged, bool isApplyToLast = true);
	void UpdateContainer(const Size2F& sizeChanged, bool isApplyToLast = true);

	float HorizontalScrollBarOffset()const;
	float VerticalScrollBarOffset()const;
	Point2F ScrollBarOffset()const;

	float HorizontalScrollBarWidth()const;
	float VerticalScrollBarHeight()const;

	bool NeedHorizontalScrollBar()const;
	bool NeedVerticalScrollBar()const;

	virtual void Focus();
	virtual void Release();

	virtual bool UpdateModel(float dt);
protected:
	virtual void OnUpdate();
	virtual void OnRestrictScroll();
	virtual void OnScrollingEnd();
	virtual void OnScroll();

protected:
	ScrollDirection mDirection;

	ScrollState mState;

	Rect2F mContainer;
	Rect2F mCurrentWindow;
	Rect2F mPrevWindow;			//used to calculate movement
	Point2F mInitialOffset;

	//limit bound
	RangeF mStaticLimitX;	//cache
	RangeF mStaticLimitY;	//cache

	Point2F mCurrentVelocity;	//cache
};

MEDUSA_END;


text:
<?php

namespace Oro\Bundle\WorkflowBundle\Tests\Unit\Model\Condition;

use Doctrine\Common\Collections\ArrayCollection;

use Oro\Bundle\WorkflowBundle\Model\Condition\AbstractCondition;

class AbstractConditionTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $condition;

    protected function setUp()
    {
        $this->condition = $this->getMockBuilder('Oro\Bundle\WorkflowBundle\Model\Condition\AbstractCondition')
            ->setMethods(array('isConditionAllowed'))
            ->getMockForAbstractClass();
    }

    public function testMessages()
    {
        $this->assertSame($this->condition, $this->condition->setMessage('Test'));
        $this->assertAttributeEquals('Test', 'message', $this->condition);
    }

    /**
     * @param bool $allowed
     * @param bool $message
     * @param bool $expectMessage
     * @dataProvider isAllowedDataProvider
     */
    public function testIsAllowed($allowed, $message, $expectMessage = false)
    {
        $errorMessage = 'Some error message';
        $context = array('key' => 'value');

        $this->condition->expects($this->any())
            ->method('isConditionAllowed')
            ->with($context)
            ->will($this->returnValue($allowed));

        if ($message) {
            $this->condition->setMessage($errorMessage);
        }

        // without message collection
        $this->assertEquals($allowed, $this->condition->isAllowed($context));

        // with message collection
        $errors = new ArrayCollection();
        $this->assertEquals($allowed, $this->condition->isAllowed($context, $errors));
        if ($expectMessage) {
            $this->assertEquals(1, $errors->count());
            $this->assertEquals(
                array('message' => $errorMessage, 'parameters' => array()),
                $errors->get(0)
            );
        } else {
            $this->assertEmpty($errors->getValues());
        }
    }

    /**
     * @return array
     */
    public function isAllowedDataProvider()
    {
        return array(
            'allowed, no error message' => array(
                'allowed' => true,
                'message' => false,
            ),
            'not allowed, no error message' => array(
                'allowed' => false,
                'message' => false,
            ),
            'allowed, with error message' => array(
                'allowed' => true,
                'message' => true,
            ),
            'not allowed, with error message' => array(
                'allowed' => false,
                'message' => true,
                'expectMessage' => true,
            ),
        );
    }

    public function testIsConditionAllowedDefault()
    {
        /** @var AbstractCondition $condition */
        $condition = $this->getMockBuilder('Oro\Bundle\WorkflowBundle\Model\Condition\AbstractCondition')
            ->getMockForAbstractClass();
        $this->assertFalse($condition->isAllowed('anything'));
    }

    public function testAddError()
    {
        $context = array('foo' => 'fooValue', 'bar' => 'barValue');
        $options = array('left' => 'foo', 'right' => 'bar');

        $left = $options['left'];
        $right = $options['right'];

        $this->condition->initialize($options);
        $message = 'Error message.';
        $this->condition->setMessage($message);

        $this->condition->expects($this->once())->method('isConditionAllowed')
            ->with($context)
            ->will($this->returnValue(false));

        $errors = new ArrayCollection();

        $this->assertFalse($this->condition->isAllowed($context, $errors));

        $this->assertEquals(1, $errors->count());
        $this->assertEquals(array('message' => $message, 'parameters' => array()), $errors->get(0));
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.devtools.j2objc.translate;

import com.google.devtools.j2objc.ast.AbstractTypeDeclaration;
import com.google.devtools.j2objc.ast.Block;
import com.google.devtools.j2objc.ast.EnumDeclaration;
import com.google.devtools.j2objc.ast.MethodDeclaration;
import com.google.devtools.j2objc.ast.TreeUtil;
import com.google.devtools.j2objc.ast.TreeVisitor;
import com.google.devtools.j2objc.ast.TypeDeclaration;

import org.eclipse.jdt.core.dom.IMethodBinding;

import java.util.HashSet;
import java.util.Set;

/**
 * Adds the implicie default constructors for classes that have no declared
 * constructors.
 */
public class DefaultConstructorAdder extends TreeVisitor {

  @Override
  public void endVisit(TypeDeclaration node) {
    visitType(node);
  }

  @Override
  public void endVisit(EnumDeclaration node) {
    visitType(node);
  }

  private void visitType(AbstractTypeDeclaration node) {
    Set<IMethodBinding> declaredInAst = new HashSet<>();
    for (MethodDeclaration methodDecl : TreeUtil.getMethodDeclarations(node)) {
      declaredInAst.add(methodDecl.getMethodBinding());
    }
    for (IMethodBinding methodBinding : node.getTypeBinding().getDeclaredMethods()) {
      if (!declaredInAst.contains(methodBinding) && isDefaultConstructor(methodBinding)) {
        addDefaultConstructor(node, methodBinding);
      }
    }
  }

  private boolean isDefaultConstructor(IMethodBinding method) {
    return method.isConstructor() && method.getParameterTypes().length == 0;
  }

  private void addDefaultConstructor(AbstractTypeDeclaration node, IMethodBinding methodBinding) {
    MethodDeclaration methodDecl = new MethodDeclaration(methodBinding);
    methodDecl.setBody(new Block());
    node.getBodyDeclarations().add(methodDecl);
  }
}


text:
package info.tongrenlu.domain;

import java.io.Serializable;
import java.util.Date;

public class DtoBean implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    private Integer id;

    private Date updDate;

    private String delFlg;

    public Integer getId() {
        return this.id;
    }

    public void setId(final Integer id) {
        this.id = id;
    }

    public Date getUpdDate() {
        return this.updDate;
    }

    public void setUpdDate(final Date updDate) {
        this.updDate = updDate;
    }

    public String getDelFlg() {
        return this.delFlg;
    }

    public void setDelFlg(final String delFlg) {
        this.delFlg = delFlg;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + (this.id == null ? 0 : this.id.hashCode());
        return result;
    }

    @Override
    public boolean equals(final Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (this.getClass() != obj.getClass()) {
            return false;
        }
        final DtoBean other = (DtoBean) obj;
        if (this.id == null) {
            if (other.id != null) {
                return false;
            }
        } else if (!this.id.equals(other.id)) {
            return false;
        }
        return true;
    }

}


text:
// This file is automatically generated.

package adila.db;

/*
 * FarEasTone Smart 505
 *
 * DEVICE: Smart505
 * MODEL: Smart 505
 */
final class smart505_smart20505 {
    public static final String DATA = "FarEasTone|Smart 505|";
}


text:
require 'tupelo/app'
require_relative 'update'

NUM_WORKERS = 4
NUM_VERTICES = 10
PRNG_SEED = 1234

Tupelo.application do

  NUM_WORKERS.times do |i|
    child passive: true do
      log.progname = "worker #{i}"

      loop do
        step = vertex = nil
        transaction do
          step = read(step: Numeric)["step"]
          vertex = take id: nil, step: step, rank: nil, active: true
          # wait for a vertex to be available on current step, but retry if
          # step changes
        end

        v_me = vertex["id"]
        vs_dst = read_all(src: v_me, dst: nil).map {|h| h["dst"]}
        vs_src = read_all(src: nil, dst: v_me).map {|h| h["src"]}

        incoming_messages = transaction do
          vs_src.inject([]) do |ms, v_src|
            while m=take_nowait(src: v_src, dst: v_me, step: step, rank: nil)
              ms << m
            end
            ms
          end
        end

        vertex, outgoing_messages = update(vertex, incoming_messages, vs_dst)
        write vertex, *outgoing_messages

        transaction do
          n = take(count: Integer, active: vertex["active"])["count"]
          write count: n + 1, active: vertex["active"]
        end
      end
    end
  end

  child do
    log.progname = "coordinator"

    step = 0
    v_ids = (0...NUM_VERTICES).to_a

    v_ids.each do |v_id|
      write id: v_id, step: step, rank: 1.0/NUM_VERTICES, active: true
    end

    srand PRNG_SEED
    v_ids.each do |v_src|
      v_ids.sample(4).each do |v_dst|
        write src: v_src, dst: v_dst
      end
    end

    write count: 0, active: true
    write count: 0, active: false
    loop do
      log "step: #{step}"
      transaction do
        write step: step
        take count: nil, active: true
        write count: 0, active: true
      end

      # wait for all vertices to finish step and maybe become inactive
      done = transaction do
        n_active = read(count: nil, active: true)["count"]
        read(count: NUM_VERTICES - n_active, active: false)
        n_active == 0
      end

      if done
        vs = read_all(id: nil, step: nil, rank: nil, active: nil)
        log vs.sort_by {|v| v["id"]}.map {|v| v["rank"]}
        exit
      end

      take step: step
      step += 1
    end
  end
end


text:
/**
 * Apache Licence Version 2.0
 * Please read the LICENCE file
 */
package org.hypothesis.data.model;

/**
 * @author Kamil Morong, Tilioteo Ltd
 *
 *         Hypothesis
 *
 */
public interface TableConstants {

	String BRANCH_TABLE = "tbl_branch";
	String BRANCH_TASK_TABLE = "tbl_branch_task";
	String BRANCH_TREK_TABLE = "tbl_branch_trek";
	String BRANCH_BRANCH_TREK_TABLE = "tbl_branch_branch_trek"; // not used?
	String BRANCH_OUTPUT_TABLE = "tbl_branch_output";
	String EVENT_TABLE = "tbl_event";
	String GROUP_TABLE = "tbl_group";
	String GROUP_USER_TABLE = "tbl_group_user";
	String GROUP_PERMISSION_TABLE = "tbl_group_permission";
	String PACK_TABLE = "tbl_pack";
	String PACK_BRANCH_TABLE = "tbl_pack_branch";
	String ROLE_TABLE = "tbl_role";
	String SLIDE_TABLE = "tbl_slide";
	String SLIDE_ORDER_TABLE = "tbl_slide_order";
	String SLIDE_TEMPLATE_TABLE = "tbl_slide_template";
	String TASK_TABLE = "tbl_task";
	String TASK_SLIDE_TABLE = "tbl_task_slide";
	String TEST_TABLE = "tbl_test";
	String TEST_EVENT_TABLE = "tbl_test_event";
	String TOKEN_TABLE = "tbl_token";
	String USER_TABLE = "tbl_user";
	String USER_ROLE_TABLE = "tbl_user_role";
	String USER_PERMISSION_TABLE = "tbl_user_permission";
	String MESSAGE_TABLE = "tbl_message";
	String SCORE_TABLE = "tbl_score";
	String TEST_SCORE_TABLE = "tbl_test_score";

	String BRANCH_GENERATOR = "branchGenerator";
	String BRANCH_SEQUENCE = "hbn_branch_seq";
	String BRANCH_OUTPUT_GENERATOR = "branchOutputGenerator";
	String BRANCH_OUTPUT_SEQUENCE = "hbn_branch_output_seq";
	String BRANCH_TREK_GENERATOR = "branchTrekGenerator";
	String BRANCH_TREK_SEQUENCE = "hbn_branch_trek_seq";
	String EVENT_GENERATOR = "eventGenerator";
	String EVENT_SEQUENCE = "hbn_event_seq";
	String GROUP_GENERATOR = "groupGenerator";
	String GROUP_SEQUENCE = "hbn_group_seq";
	String GROUP_PERMISSION_GENERATOR = "groupPermissionGenerator";
	String GROUP_PERMISSION_SEQUENCE = "hbn_group_permission_seq";
	String PACK_GENERATOR = "packGenerator";
	String PACK_SEQUENCE = "hbn_pack_seq";
	String ROLE_GENERATOR = "roleGenerator";
	String ROLE_SEQUENCE = "hbn_role_seq";
	String SLIDE_GENERATOR = "slideGenerator";
	String SLIDE_SEQUENCE = "hbn_slide_seq";
	String SLIDE_ORDER_GENERATOR = "slideOrderGenerator";
	String SLIDE_ORDER_SEQUENCE = "hbn_slide_order_seq";
	String TASK_GENERATOR = "taskGenerator";
	String TASK_SEQUENCE = "hbn_task_seq";
	String TEST_GENERATOR = "testGenerator";
	String TEST_SEQUENCE = "hbn_test_seq";
	String USER_GENERATOR = "userGenerator";
	String USER_SEQUENCE = "hbn_user_seq";
	String USER_PERMISSION_GENERATOR = "userPermissionGenerator";
	String USER_PERMISSION_SEQUENCE = "hbn_user_permission_seq";
	String SCORE_GENERATOR = "scoreGenerator";
	String SCORE_SEQUENCE = "hbn_score_seq";

}


text:
import {uiutil,dialogMgr} from "/apogeeui/apogeeUiLib.js";

/** This method shows a dialog to select from additional components. */
export function showSelectComponentDialog(componentInfoList,onSelectFunction) {

    var dialog = dialogMgr.createDialog({"movable":true});

    //add a scroll container
    var contentContainer = uiutil.createElement("div",null,
        {
			"display":"block",
            "position":"relative",
            "top":"0px",
            "height":"100%",
            "overflow": "auto"
        });
	dialog.setContent(contentContainer,uiutil.SIZE_WINDOW_TO_CONTENT);

    var line;

	var content = uiutil.createElement("div",null,
			{
				"display":"table",
				"overflow":"hidden"
			});
	contentContainer.appendChild(content);

    var line;

    //title
    line = uiutil.createElement("div",{"className":"dialogLine"});
    line.appendChild(uiutil.createElement("div",{"className":"dialogTitle","innerHTML":"Select Component Type"}));
    content.appendChild(line);

    //folder selection
    line = uiutil.createElement("div",{"className":"dialogLine"});
    line.appendChild(document.createTextNode("Component:"));
    var select = uiutil.createElement("select");
    line.appendChild(select);
    componentInfoList.forEach( componentInfo => {
		select.add(uiutil.createElement("option",{"text":componentInfo.displayName,"value":componentInfo.uniqueName}));
    });
    content.appendChild(line);

    //buttons
    line = uiutil.createElement("div",{"className":"dialogLine"});
    var onCancel = function() {
        dialogMgr.closeDialog(dialog);
    }

    var onCreate = function() {
		var componentClass = select.value;
        onSelectFunction(componentClass);
        dialogMgr.closeDialog(dialog);
    }
    line.appendChild(uiutil.createElement("button",{"className":"dialogButton","innerHTML":"Create","onclick":onCreate}));
    line.appendChild(uiutil.createElement("button",{"className":"dialogButton","innerHTML":"Cancel","onclick":onCancel}));
    content.appendChild(line);

    dialog.setContent(content,uiutil.SIZE_WINDOW_TO_CONTENT);

    //show dialog
    dialogMgr.showDialog(dialog);
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('chunks', '0002_auto__add_field_chunk_description'),
    ]

    operations = [
        migrations.AddField(
            model_name='chunk',
            name='file',
            field=models.FileField(blank=True, null=True, upload_to=b'uploads', verbose_name='File or image'),
        ),
    ]