text:
var assert = require('assert');
var fs = require('fs');
var crypto = require('crypto');
var util = require('util');

var testutil = require('../../framework/util');
var TestSuite = require('../../framework/test-suite');
var azure = testutil.libRequire('azure-storage');

var suite = new TestSuite('blobservice-uploaddownload-scale-tests');
var runOrSkip = suite.isMocked ? it.skip : it;

var blobService = null;
var containerName = 'blobservicescaletest';

describe('BlobServiceUploadDownloadScale', function () {
  before(function (done) {
    if (suite.isMocked) {
      testutil.POLL_REQUEST_INTERVAL = 0;
    }
    suite.setupSuite(function () {
      blobService = azure.createBlobService().withFilter(new azure.ExponentialRetryPolicyFilter());
      done();
    });
  });

  after(function (done) {
    suite.teardownSuite(done);
  });

  beforeEach(function (done) {
    suite.setupTest(done);
  });

  afterEach(function (done) {
    suite.teardownTest(done);
  });

  describe('prepare blob scale test', function () {
    runOrSkip('should create the test container', function (done) {
      blobService.createContainer(containerName, function (error) {
        done();
      });
    });
  });

  describe('file scale test', function () {
    var apis = ['createBlockBlobFromLocalFile', 'createPageBlobFromLocalFile', 'createAppendBlobFromLocalFile'];
    var sizes = [0, 1024, 1024 * 1024, 4 * 1024 * 1024, 32 * 1024 * 1024, 64 * 1024 * 1024, 148 * 1024 * 1024 - 512, 148 * 1024 * 1024, 148 * 1024 * 1024 + 512];
    for (var i = 0; i < apis.length; i++) {
      for (var j = 0; j < sizes.length; j++) {
        runOrSkip(util.format('%s should work %s bytes file', apis[i], sizes[j]), getTestFunction(apis[i], sizes[j]));
      }
    }

    function getTestFunction(api, size) {
      return function(done) {
        var name = api + 'scale' + size + '.tmp';
        var uploadFunc = blobService[api];
        generateTempFile(name, size, function(error, fileInfo) {
          assert.equal(error, null);
          var blobName = api + size;
          var uploadOptions = { storeBlobContentMD5: true, parallelOperationThreadCount: 5 };
          if (api === 'createAppendBlobFromLocalFile') {
            uploadOptions.useTransactionalMD5 = true;
            if (size === 0) {
              try { fs.unlinkSync(name); } catch (e) { }
              done();
              return;
            }
          }
          uploadFunc.call(blobService, containerName, blobName, fileInfo.name, uploadOptions, function(error) {
            if(api === 'createPageBlobFromLocalFile' && size !== 0 && size % 512 !== 0) {
              assert.equal(error.message, util.format('The page blob size must be aligned to a 512-byte boundary. The current stream length is %s', size));
              done();
            } else {
              assert.equal(error, null);
              blobService.getBlobProperties(containerName, blobName, function (error, blob) {
                assert.equal(blob.contentSettings.contentMD5, fileInfo.contentMD5);
                assert.equal(blob.contentLength, fileInfo.size);
                var downloadFileName = blobName + '_download.tmp';
                var downloadOptions = {useTransactionalMD5: true, parallelOperationThreadCount: 5};

                // Test downloading to a local file.
                blobService.getBlobToLocalFile(containerName, blobName, downloadFileName, downloadOptions, function (error, blob) {
                  assert.equal(error, null);
                  assert.equal(blob.contentSettings.contentMD5, fileInfo.contentMD5);
                  fs.stat(downloadFileName, function(error, stat) {
                    assert.equal(error, null);
                    assert.equal(stat.size, fileInfo.size);

                    // Test downloading to a readable stream and pipe.
                    var writable = fs.createWriteStream(downloadFileName);
                    blobService.createReadStream(containerName, blobName, downloadOptions, function (error, blob) {
                      assert.equal(error, null);
                      assert.equal(blob.contentSettings.contentMD5, fileInfo.contentMD5);
                    }).pipe(writable);

                    writable.on('finish', function () {
                      fs.stat(downloadFileName, function (error, stat) {
                        assert.equal(error, null);
                        assert.equal(stat.size, fileInfo.size);
                        try { fs.unlinkSync(name); } catch (e) { }
                        try { fs.unlinkSync(downloadFileName); } catch (e) { }
                        done();
                      });
                    });
                  });
                });
              });
            }
          });
        });
      }
    }
  });

  describe('cleanup blob scale test', function () {
    runOrSkip('should delete the test container', function (done) {
      blobService.deleteContainer(containerName, function(error) {
        done();
      });
    });
  });

  var internalBuffer = null;
  function generateTempFile(fileName, size, callback) {
    var blockSize = 4 * 1024 * 1024;
    if(!internalBuffer) {
      internalBuffer = new Buffer(blockSize);
    }
    var md5hash = crypto.createHash('md5');
    var fileInfo = {name: fileName, contentMD5: '', size: size};
    var offset = 0;
    var fd = fs.openSync(fileName, 'w');
    var count = 1;
    do {
      var content = null;
      if (size >= blockSize) {
        content = internalBuffer;
        size -= blockSize;
      } else {
        content = new Buffer(size);
        size = 0;
      }
      if (content.length) {
        if(count % 2 === 0) {
          content[0] = 0;
        } else {
          content[0] = count; //Buffer should not be all zero
        }
        count++;
      }
      fs.writeSync(fd, content, 0, content.length, offset);
      offset += content.length;
      md5hash.update(content);
    } while(size);

    fileInfo.contentMD5 = md5hash.digest('base64');
    callback(null, fileInfo);
  }
});


text:
package com.cognitect.transit.impl;

import com.cognitect.transit.Link;
import com.cognitect.transit.URI;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class LinkImpl implements Link {

    private static final String LINK = "link";
    private static final String IMAGE = "image";

    private static final String HREF = "href";
    private static final String REL = "rel";
    private static final String PROMPT = "prompt";
    private static final String NAME = "name";
    private static final String RENDER = "render";

    private Map<String, Object> m;

    public LinkImpl(URI href, String rel, String name, String render, String prompt) {
        Map<String, Object> m = new HashMap<String, Object>(5);
        if (href == null) throw new IllegalArgumentException("Value of href cannot be null");
        m.put(HREF, href);
        if (rel == null) throw new IllegalArgumentException("Value of rel cannot be null");
        m.put(REL, rel);
        if (name != null) m.put(NAME, name);
        if (prompt != null) m.put(PROMPT, prompt);
        if (render != null) {
            if ((render == LINK) || (render == IMAGE)) {
                m.put(RENDER, render);
            } else {
                throw new IllegalArgumentException("Value of render must be \"link\" or \"image\"");
            }
        }
        this.m = Collections.unmodifiableMap(m);
    }

    @SuppressWarnings("unchecked")
    public LinkImpl(Map m) {
        this.m = (Map<String, Object>) Collections.unmodifiableMap(m);
    }

    public Map<String, Object> toMap() { return m; }

    @Override
    public URI getHref() { return (URI) m.get(HREF); }

    @Override
    public String getRel() {
        return (String) m.get(REL);
    }

    @Override
    public String getName() {
        return (String) m.get(NAME);
    }

    @Override
    public String getPrompt() {
        return (String) m.get(PROMPT);
    }

    @Override
    public String getRender() {
        return (String) m.get(RENDER);
    }
}

redpajama_set_name: RedPajamaGithub


text:
from apps.categories.models import MCategory
from apps.reader.models import UserSubscriptionFolders
from utils import json_functions as json
from utils.user_functions import ajax_login_required

@json.json_view
def all_categories(request):
    categories = MCategory.serialize()

    return categories

@ajax_login_required
@json.json_view
def subscribe(request):
    user = request.user
    categories = MCategory.serialize()
    category_titles = [c['title'] for c in categories['categories']]
    subscribe_category_titles = request.POST.getlist('category') or request.POST.getlist('category[]')

    invalid_category_title = False
    for category_title in subscribe_category_titles:
        if category_title not in category_titles:
            invalid_category_title = True

    if not subscribe_category_titles or invalid_category_title:
        message = "Choose one or more of these categories: %s" % ', '.join(category_titles)
        return dict(code=-1, message=message)

    for category_title in subscribe_category_titles:
        MCategory.subscribe(user.pk, category_title)

    usf = UserSubscriptionFolders.objects.get(user=user.pk)

    return dict(code=1, message="Subscribed to %s %s" % (
        len(subscribe_category_titles),
        'category' if len(subscribe_category_titles) == 1 else 'categories',
    ), folders=json.decode(usf.folders))


text:
classdef rgcLayer < cellLayer
% Create an rgcLayer object
%
% Syntax:
%   myRgcLayer = rgcLayer();
%
% Description:
%    This is a subclass of the general class 'cellLayer'. It inherits all
%    of the properties of that class, including slots for an input, fig,
%    center, size, etc...
%
%    The rgcLayer class stores general properties of the RGC layer patch
%    and stores the rgcMosaic objects in its mosaic property field. (This
%    object replaces the innerretina object.)
%
%      obj = rgcLayer(inputObj, params);
%
%    Usually called internally from rgcLayerCreate ... not sure why. Maybe
%    that will change?  It seems like the input parameters to rgcLayer()
%    should be those of the
%
%    An ir object takes as input a bipolar object or an outerSegment
%    object. The ir (inner retina) object stores basic properties about the
%    inner retina such as the position of the simulated retinal patch.
%
%    See Pillow, Jonathan W., et al. "Spatio-temporal correlations and
%    visual signalling in a complete neuronal population." Nature 454.7207
%    (2008) and Chichilnisky, E. J., and Rachel S. Kalmar. "Functional
%    asymmetries in ON and OFF ganglion cells of primate retina." The
%    Journal of Neuroscience 22.7 (2002).
%
%    Properties:
%      Established by constructor parameters
%        name:      animal, ir; example: 'macaque ir'
%        numberTrials: number of trials for spike generation
%
%      Inherited from bipolar input
%        row:       N Stimulus row samples
%        col:       N Stimulus col samples
%        size:      Stimulus input spacing (m)
%        timing:    Stimulus input time step (sec)
%
%      Established by the mosaicCreate method
%        mosaic: cell array of rgc mosaics
%
%    Methods:
%        set, get, compute, plot
%
%    This function contains examples of usage inline. To access these, type
%    'edit rgcLayer.m' into the Command Window.
%
% References:
%    * ISETBIO wiki: RGCS.
%

% History:
%    09/XX/15  JRG  (c) isetbio team
%    07/XX/16  JRG  updated
%    06/11/19  JNM  Documentation pass

% Examples:
%{
    % ETTBSkip - skipping broken examples
    %
    % This needs code to define the objects invoked before it could
    % possibly work.
    bpL = bipolarLayer(coneMosaic);
    rgcL = rgcLayer(bpLayer, 'name', 'myRGC');

    params.name = 'Macaque inner retina 1';
    params.eyeSide = 'left';
    params.eyeRadius = 2;
    rgcL = rgcLayer(bpLayer, params);
%}

%%
% Public read/write properties
properties
end

% Public, read-only properties.
properties (SetAccess = public, GetAccess = public)
    % MOSAIC Cell array containing ganglion cell mosaics
    % Cells are added by mosaicCreate method
    mosaic = {};  % The spatial sampling differs for each mosaic
end

% Protected properties; Methods of the parent class and all of its
% subclasses can set these.
properties (SetAccess = protected)
end

% Private properties. Only methods of the parent class can set these
properties(Access = private)
end

% Public methods
methods
    function obj = rgcLayer(bpLayer, varargin)
        % Constructor
        %
        % Syntax:
        %   rgcL = rgcLayer(bipolarLayer, [varargin])
        %
        % Description:
        %    The coupled-GLM model is described in the Pillow, Shlens,
        %    Paninski, Sher, Litke, Chichilnisky & Simoncelli, Nature
        %    (2008) paper.
        %
        % Inputs:
        %    bpLayer - Object. A bipolar layer object.
        %
        % Outputs:
        %    obj     - Object. A rgc layer object.
        %
        % Optional key/value pairs:
        %    name    - String. The instance name.
        %    nTrials - Numeric. The number of trials.
        %
        % References:
        %    * The coupled-GLM model is described in Pillow, Shlens,
        %      Paninski, Sher, Litke, Chichilnisky & Simoncelli,
        %      Nature (2008).
        %    * The LNP and GLM models here are based on the code by Pillow
        %      http://pillowlab.princeton.edu/code_GLM.html
        %      under the GNU General Public License.
        %

        % History:
        %    09/XX/15  JRG  Copyright ISETBIO Team
        %    07/XX/16  JRG  updated
        %    06/11/19  JNM  Documentation pass

        % parse input
        p = inputParser;

        % Should this by a bipolarLayer??
        p.addRequired('bpLayer', @(x)(isa(x, 'bipolarLayer')));
        p.addParameter('name', 'rgcLayer', @ischar);
        p.addParameter('nTrials', 1, @isscalar);
        p.KeepUnmatched = true;

        p.parse(bpLayer, varargin{:});
        obj.name = p.Results.name;
        obj.nTrials = p.Results.nTrials;

        % Should match the cone mosaic patch size and time step
        obj.size = bpLayer.size;          % Bipolar patch size
        obj.timeStep = bpLayer.timeStep;  % Temporal sampling

        % Spatial position on the retina (meters, fovea is 0, 0).
        obj.center = bpLayer.center;
        obj.input = bpLayer;  % Bipolar layer link kept here
    end

    % Show the RGC layer window
    function hdl = window(obj, varargin)
        hdl = rgcLayerWindow(obj);
    end

    function val = eccentricity(obj, varargin)
        % Default is units of meters.
        p = inputParser;

        % Should check for valid units
        p.addParameter('units', 'm', @ischar);
        p.parse(varargin{:});

        units = p.Results.units;
        val = sqrt(sum(obj.center .^ 2));
        val = val * ieUnitScaleFactor(units);
    end

end

% Methods that must only be implemented in the subclasses.
methods (Abstract, Access=public)
end

% Methods may be called by the subclasses, but are otherwise private
methods (Access = protected)
    spConvolve(obj);
    timeConvolve(obj);
end

% Methods that are totally private (subclasses cannot call these)
methods (Access = private)
end

end


text:
This warning occures when there is an aspect class that does nothing - does not contain any effect.
```c#
[Aspect(Scope.Global)]
public class MyAspect
{

}
```

Consider adding an [Advice](../advice.md) or a [Mixin](../mixin.md) to your aspect.


text:
@interface VLRadiusBoundary : VLBoundary

@property double longitude;
@property double latitude;
@property double radius;

- (id) init;
- (id) initWithRadius: (double) radius latitude:(double)latitude longitude:(double) longitude;
- (id) initWithDictionary:(NSDictionary *)dictionary;
- (NSDictionary *) toDictionary;

@end


text:
// Type definitions for tlf-log 1.3
// Project: https://github.com/thislooksfun/tlf-log
// Definitions by: thislooksfun <https://github.com/thislooksfun>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

export interface NewLevel {
    afterLog?: () => void;
}
export interface NewLevelBefore extends NewLevel {
    before: string;
}
export interface NewLevelAfter extends NewLevel {
    after: string;
}

/**
 * Logs the given messages, then calls `process.exit(1)`.
 *
 * @param messages The items to log.
 */
export function fatal(...messages: any[]): never;

/**
 * Logs the given messages with no trailing newline, then calls `process.exit(1)`.
 *
 * @param messages The items to log.
 */
export function fatal_(...messages: any[]): never;

/**
 * Logs the given messages at the "error" level.
 *
 * @param messages The items to log.
 */
export function error(...messages: any[]): void;

/**
 * Logs the given messages at the "error" level with no trailing newline.
 *
 * @param messages The items to log.
 */
export function error_(...messages: any[]): void;

/**
 * Logs the given messages at the "warn" level.
 *
 * @param messages The items to log.
 */
export function warn(...messages: any[]): void;

/**
 * Logs the given messages at the "warn" level with no trailing newline.
 *
 * @param messages The items to log.
 */
export function warn_(...messages: any[]): void;

/**
 * Logs the given messages at the "info" level.
 *
 * @param messages The items to log.
 */
export function info(...messages: any[]): void;

/**
 * Logs the given messages at the "info" level with no trailing newline.
 *
 * @param messages The items to log.
 */
export function info_(...messages: any[]): void;

/**
 * Logs the given messages at the "trace" level.
 *
 * @param messages The items to log.
 */
export function trace(...messages: any[]): void;

/**
 * Logs the given messages at the "trace" level with no trailing newline.
 *
 * @param messages The items to log.
 */
export function trace_(...messages: any[]): void;

/**
 * Logs the given messages at the "debug" level.
 *
 * @param messages The items to log.
 */
export function debug(...messages: any[]): void;

/**
 * Logs the given messages at the "debug" level with no trailing newline.
 *
 * @param messages The items to log.
 */
export function debug_(...messages: any[]): void;

/**
 * Sets the minimum level a message has to be to be logged.
 *
 * If `level` is set to 'silent' it will silence all log levels aside from
 * `fatal`
 *
 * @param level The name of the level to be the new minimum.
 */
export function _setLevel(level: string): void;

/**
 * Adds a new log level.
 *
 * Note: You can't add a new level before 'debug' or after 'fatal'.
 *
 * @param name The name of the new level.
 * @param opts The options to use to create the new level.
 */
export function _addLevel(name: string, opts: NewLevelBefore | NewLevelAfter): void;

/**
 * Indents the following messages by 2 spaces.
 *
 * If you want to indent by a different amount see {@link _prefix}.
 */
export function _indent(): void;

/**
 * Deindents the following messages by 2 spaces.
 *
 * If the indent level is already 0 then this is a no-op.
 */
export function _deindent(): void;

/**
 * Adds a prefix to the next messages.
 *
 * @param str The string to prefix the following messages with.
 */
export function _prefix(str: string): void;

/**
 * Removes the most recent prefix.
 */
export function _deprefix(): void;


text:
<?php
namespace Neos\Flow\Persistence\Generic\Qom;

/**
 * Base class for constraints in the QOM.
 *
 * @api
 * @deprecated since Flow 6.0
 */
class Constraint
{
}


text:
package jsprit.core.algorithm.state;

import java.util.Arrays;
import java.util.List;

/**
 * Created by schroeder on 28.07.14.
 */
class StateFactory {

    final static List<String> reservedIds = Arrays.asList("max_load", "load", "costs", "load_at_beginning", "load_at_end", "duration", "latest_operation_start_time", "earliest_operation_start_time"
            , "future_max_load", "past_max_load", "skills");

    static StateId createId(String name){
        if(reservedIds.contains(name)){ throwReservedIdException(name); }
        return new StateIdImpl(name, -1);
    }

    static StateId createId(String name, int index){
        if(reservedIds.contains(name)) throwReservedIdException(name);
        if(index < 10) throwReservedIdException(name);
        return new StateIdImpl(name, index);
    }

    static boolean isReservedId(String stateId){
        return reservedIds.contains(stateId);
    }

    static boolean isReservedId(StateId stateId){
        return reservedIds.contains(stateId.toString());
    }

    static void throwReservedIdException(String name) {
        throw new IllegalStateException("state-id with name '" + name + "' cannot be created. it is already reserved internally.");
    }

    static class StateIdImpl implements StateId {

        private int index;

        public int getIndex(){ return index; }

        /* (non-Javadoc)
         * @see java.lang.Object#hashCode()
         */
        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((name == null) ? 0 : name.hashCode());
            return result;
        }

        /* (non-Javadoc)
         * @see java.lang.Object#equals(java.lang.Object)
         */
        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            StateIdImpl other = (StateIdImpl) obj;
            if (name == null) {
                if (other.name != null)
                    return false;
            } else if (!name.equals(other.name))
                return false;
            return true;
        }

        private String name;

        public StateIdImpl(String name, int index) {
            super();
            this.name = name;
            this.index = index;
        }

        public String toString(){
            return name;
        }
    }
}


text:
package org.assertj.core.api;

import java.util.Comparator;

import org.assertj.core.data.Offset;
import org.assertj.core.data.Percentage;
import org.assertj.core.internal.ComparatorBasedComparisonStrategy;
import org.assertj.core.internal.Doubles;
import org.assertj.core.util.VisibleForTesting;

/**
 * Base class for all implementations of assertions for {@link Double}s.
 *
 * @param <S> the "self" type of this assertion class. Please read "Emulating 'self types' using Java Generics to simplify fluent API implementation"
 *          for more details.
 *
 * @author Yvonne Wang
 * @author David DIDIER
 * @author Alex Ruiz
 * @author Ansgar Konermann
 * @author Joel Costigliola
 * @author Mikhail Mazursky
 * @author Nicolas François
 */
public abstract class AbstractDoubleAssert<S extends AbstractDoubleAssert<S>> extends
    AbstractComparableAssert<S, Double> implements FloatingPointNumberAssert<S, Double> {

  @VisibleForTesting
  Doubles doubles = Doubles.instance();

  protected AbstractDoubleAssert(Double actual, Class<?> selfType) {
    super(actual, selfType);
  }

  /** {@inheritDoc} */
  @Override
  public S isNaN() {
    doubles.assertIsNaN(info, actual);
    return myself;
  }

  /** {@inheritDoc} */
  @Override
  public S isNotNaN() {
    doubles.assertIsNotNaN(info, actual);
    return myself;
  }

  /** {@inheritDoc} */
  @Override
  public S isZero() {
    doubles.assertIsZero(info, actual);
    return myself;
  }

  /** {@inheritDoc} */
  @Override
  public S isNotZero() {
    doubles.assertIsNotZero(info, actual);
    return myself;
  }

  /** {@inheritDoc} */
  @Override
  public S isPositive() {
    doubles.assertIsPositive(info, actual);
    return myself;
  }

  /** {@inheritDoc} */
  @Override
  public S isNegative() {
    doubles.assertIsNegative(info, actual);
    return myself;
  }

  /** {@inheritDoc} */
  @Override
  public S isNotNegative() {
    doubles.assertIsNotNegative(info, actual);
    return myself;
  }

  /** {@inheritDoc} */
  @Override
  public S isNotPositive() {
    doubles.assertIsNotPositive(info, actual);
    return myself;
  }

  /**
   * Verifies that the actual number is close to the given one within the given offset.

   * If difference is equal to offset value, assertion is considered valid.
   *

   * Example:
   *
   *

   * // assertion will pass
   * assertThat(8.1).isCloseTo(8.0, within(0.2));
   *
   * // you can use offset if you prefer
   * assertThat(8.1).isCloseTo(8.0, offset(0.2));
   *
   * // if difference is exactly equals to 0.1, it's ok
   * assertThat(8.1).isCloseTo(8.0, within(0.1));
   *
   * // assertion will fail
   * assertThat(8.1).isCloseTo(8.0, within(0.01));
   *

   *
   * @param other the given number to compare the actual value to.
   * @param offset the given positive offset.
   * @return {@code this} assertion object.
   * @throws NullPointerException if the given offset is {@code null}.
   * @throws NullPointerException if the expected number is {@code null}.
   * @throws AssertionError if the actual value is not equal to the given one.
   */
  // duplicate javadoc of isCloseTo(double other, Offset<Double> offset but can't define it in super class
  public S isCloseTo(final double other, final Offset<Double> offset) {
    doubles.assertIsCloseTo(info, actual, other, offset);
    return myself;
  }

  /**
   * Verifies that the actual number is close to the given one within the given offset.

   * If difference is equal to offset value, assertion is considered valid.
   *

   * Example:
   *
   *

   * // assertion will pass
   * assertThat(8.1).isCloseTo(Double.valueOf(8.0), within(0.2));
   *
   * // you can use offset if you prefer
   * assertThat(8.1).isCloseTo(Double.valueOf(8.0), offset(0.2));
   *
   * // if difference is exactly equals to 0.1, it's ok
   * assertThat(8.1).isCloseTo(Double.valueOf(8.0), within(0.1));
   *
   * // assertion will fail
   * assertThat(8.1).isCloseTo(Double.valueOf(8.0), within(0.01));
   *

   *
   * @param other the given number to compare the actual value to.
   * @param offset the given positive offset.
   * @return {@code this} assertion object.
   * @throws NullPointerException if the given offset is {@code null}.
   * @throws NullPointerException if the expected number is {@code null}.
   * @throws AssertionError if the actual value is not equal to the given one.
   */
  @Override
  public S isCloseTo(Double other, Offset<Double> offset) {
    doubles.assertIsCloseTo(info, actual, other, offset);
    return myself;
  }

  /**
   * Verifies that the actual number is close to the given one within the given percentage.

   * If difference is equal to the percentage value, assertion is considered valid.
   *

   * Example with double:
   *
   *

   * // assertions will pass:
   * assertThat(11.0).isCloseTo(Double.valueOf(10.0), withinPercentage(20d));
   *
   * // if difference is exactly equals to the computed offset (1.0), it's ok
   * assertThat(11.0).isCloseTo(Double.valueOf(10.0), withinPercentage(10d));
   *
   * // assertion will fail
   * assertThat(11.0).isCloseTo(Double.valueOf(10.0), withinPercentage(5d));
   *

   *
   * @param expected the given number to compare the actual value to.
   * @param percentage the given positive percentage between 0 and 100.
   * @return {@code this} assertion object.
   * @throws NullPointerException if the given offset is {@code null}.
   * @throws NullPointerException if the expected number is {@code null}.
   * @throws AssertionError if the actual value is not equal to the given one.
   */
  @Override
  public S isCloseTo(Double expected, Percentage percentage) {
    doubles.assertIsCloseToPercentage(info, actual, expected, percentage);
    return myself;
  }

  /**
   * Verifies that the actual number is close to the given one within the given percentage.

   * If difference is equal to the percentage value, assertion is considered valid.
   *

   * Example with double:
   *
   *

   * // assertions will pass:
   * assertThat(11.0).isCloseTo(10.0, withinPercentage(20d));
   *
   * // if difference is exactly equals to the computed offset (1.0), it's ok
   * assertThat(11.0).isCloseTo(10.0, withinPercentage(10d));
   *
   * // assertion will fail
   * assertThat(11.0).isCloseTo(10.0, withinPercentage(5d));
   *

   *
   * @param expected the given number to compare the actual value to.
   * @param percentage the given positive percentage between 0 and 100.
   * @return {@code this} assertion object.
   * @throws NullPointerException if the given offset is {@code null}.
   * @throws NullPointerException if the expected number is {@code null}.
   * @throws AssertionError if the actual value is not equal to the given one.
   */
  public S isCloseTo(double expected, Percentage percentage) {
    doubles.assertIsCloseToPercentage(info, actual, expected, percentage);
    return myself;
  }

  /**
   * Verifies that the actual value is equal to the given one.
   *

   * Example:
   *
   *

	 * // assertions will pass:
	 * assertThat(1.0).isEqualTo(1.0);
	 * assertThat(1D).isEqualTo(1.0);
	 *
	 * // assertions will fail:
	 * assertThat(0.0).isEqualTo(1.0);
	 * assertThat(-1.0).isEqualTo(1.0);
	 *

   *

   *
   * @param expected the given value to compare the actual value to.
   * @return {@code this} assertion object.
   * @throws AssertionError if the actual value is {@code null}.
   * @throws AssertionError if the actual value is not equal to the given one.
   */
  public S isEqualTo(double expected) {
    doubles.assertEqual(info, actual, expected);
    return myself;
  }

  /** {@inheritDoc} */
  @Override
  public S isEqualTo(Double expected, Offset<Double> offset) {
    doubles.assertEqual(info, actual, expected, offset);
    return myself;
  }

  /**
   * Verifies that the actual value is close to the given one by less than the given offset.

   * If difference is equal to offset value, assertion is considered valid.
   *

   * Example with double:
   *
   *

   * // assertion will pass:
   * assertThat(8.1).isEqualTo(8.0, offset(0.2));
   *
   * // if difference is exactly equals to the offset (0.1), it's ok
   * assertThat(8.1).isEqualTo(8.0, offset(0.1));
   *
   * // within is an alias of offset
   * assertThat(8.1).isEqualTo(8.0, within(0.1));
   *
   * // assertion will fail
   * assertThat(8.1).isEqualTo(8.0, offset(0.01));
   *

   *
   * @param expected the given value to compare the actual value to.
   * @param offset the given positive offset.
   * @return {@code this} assertion object.
   * @throws NullPointerException if the given offset is {@code null}.
   * @throws NullPointerException if the expected number is {@code null}.
   * @throws AssertionError if the actual value is not equal to the given one.
   */
  public S isEqualTo(double expected, Offset<Double> offset) {
    doubles.assertEqual(info, actual, expected, offset);
    return myself;
  }

  /**
   * Verifies that the actual value is not equal to the given one.
   *

   * Example:
   *
   *

	 * // assertions will pass:
	 * assertThat(0.0).isNotEqualTo(1.0);
	 * assertThat(-1.0).isNotEqualTo(1.0);
	 *
	 * // assertions will fail:
	 * assertThat(1.0).isNotEqualTo(1.0);
	 * assertThat(1D).isNotEqualTo(1.0);
	 *

   *

   *
   * @param other the given value to compare the actual value to.
   * @return {@code this} assertion object.
   * @throws AssertionError if the actual value is {@code null}.
   * @throws AssertionError if the actual value is equal to the given one.
   */
  public S isNotEqualTo(double other) {
    doubles.assertNotEqual(info, actual, other);
    return myself;
  }

  /**
   * Verifies that the actual value is less than the given one.
   *

   * Example:
   *
   *

	 * // assertion will pass:
	 * assertThat(1.0).isLessThan(2.0);
	 *
	 * // assertions will fail:
	 * assertThat(2.0).isLessThan(1.0);
	 * assertThat(1.0).isLessThan(1.0);
	 *

   *

   *
   * @param other the given value to compare the actual value to.
   * @return {@code this} assertion object.
   * @throws AssertionError if the actual value is {@code null}.
   * @throws AssertionError if the actual value is equal to or greater than the given one.
   */
  public S isLessThan(double other) {
    doubles.assertLessThan(info, actual, other);
    return myself;
  }

  /**
   * Verifies that the actual value is less than or equal to the given one.
   *

   * Example:
   *
   *

	 * // assertions will pass:
	 * assertThat(-1.0).isLessThanOrEqualTo(1.0);
	 * assertThat(1.0).isLessThanOrEqualTo(1.0);
	 *
	 * // assertion will fail:
	 * assertThat(2.0).isLessThanOrEqualTo(1.0);
	 *

   *

   *
   * @param other the given value to compare the actual value to.
   * @return {@code this} assertion object.
   * @throws AssertionError if the actual value is {@code null}.
   * @throws AssertionError if the actual value is greater than the given one.
   */
  public S isLessThanOrEqualTo(double other) {
    doubles.assertLessThanOrEqualTo(info, actual, other);
    return myself;
  }

  /**
   * Verifies that the actual value is greater than the given one.
   *

   * Example:
   *
   *

	 * // assertion will pass:
	 * assertThat(2.0).isGreaterThan(1.0);
	 *
	 * // assertions will fail:
	 * assertThat(1.0).isGreaterThan(1.0);
	 * assertThat(1.0).isGreaterThan(2.0);
	 *

   *

   *
   * @param other the given value to compare the actual value to.
   * @return {@code this} assertion object.
   * @throws AssertionError if the actual value is {@code null}.
   * @throws AssertionError if the actual value is equal to or less than the given one.
   */
  public S isGreaterThan(double other) {
    doubles.assertGreaterThan(info, actual, other);
    return myself;
  }

  /**
   * Verifies that the actual value is greater than or equal to the given one.
   *

   * Example:
   *
   *

	 * // assertions will pass:
	 * assertThat(2.0).isGreaterThanOrEqualTo(1.0);
	 * assertThat(1.0).isGreaterThanOrEqualTo(1.0);
	 *
	 * // assertion will fail:
	 * assertThat(1.0).isGreaterThanOrEqualTo(2.0);
	 *

   *

   *
   * @param other the given value to compare the actual value to.
   * @return {@code this} assertion object.
   * @throws AssertionError if the actual value is {@code null}.
   * @throws AssertionError if the actual value is less than the given one.
   */
  public S isGreaterThanOrEqualTo(double other) {
    doubles.assertGreaterThanOrEqualTo(info, actual, other);
    return myself;
  }

  /** {@inheritDoc} */
  @Override
  public S isBetween(Double start, Double end) {
    doubles.assertIsBetween(info, actual, start, end);
    return myself;
  }

  /** {@inheritDoc} */
  @Override
  public S isStrictlyBetween(Double start, Double end) {
    doubles.assertIsStrictlyBetween(info, actual, start, end);
    return myself;
  }

  @Override
  public S usingComparator(Comparator<? super Double> customComparator) {
    super.usingComparator(customComparator);
    doubles = new Doubles(new ComparatorBasedComparisonStrategy(customComparator));
    return myself;
  }

  @Override
  public S usingDefaultComparator() {
    super.usingDefaultComparator();
    doubles = Doubles.instance();
    return myself;
  }
}


text:
define([
        "jquery",
        "backbone",
        "ws",
        "mustache",
        "text!templates/transactions/timeline/debitsCreditsTemplate.mustache",
        "storage"
    ],
    function(
        $,
        Backbone,
        WebServices,
        Mustache,
        debitsCreditsTemplate,
        storage) {

        var debitscredits = Backbone.Model.extend({
            urlRoot: WebServices.v1.debitscredits,
            defaults: {
                isCredit: function() {
                    return this.debitsCredits.amount >= 0;
                },
                isDebit: function() {
                    return this.debitsCredits.amount < 0;
                },
                isFavoriteCurrency: function() {
                    return !this.debitsCredits.isForeignCurrency;
                },
                defaultCurrency: function() {
                    return storage.currencies.get(this.debitsCredits.currency).toString(this.debitsCredits.amount);
                },
                favoriteCurrency: function() {
                    return storage.currencies.get(storage.user.currency()).toString(this.debitsCredits.reference_amount);
                }
            },
            html: {
                list: function() {
                    return Mustache.render(debitsCreditsTemplate, {
                        debitsCredits: this.toJSON()
                    });
                }
            },
            validation: {
                name: {
                    required: true
                },
                amount: function(value, attr, computedState) {
                    if(value === 0) {
                      return 'Amount is required';
                    }
                },
                date: {
                  required: true
                },
                currency: {
                  required: true
                }
            }
        });

        return debitscredits;
    });


text:
#ifndef _RANDOM_H_
#define _RANDOM_H_

/* Structures needed */

#include "../../Headers/structures/geometry.h"
#include "../../Headers/structures/game.h"

t_axe   generate_rand_pos   (t_map *m, int type);
int     rand_pos            (int max);
int     initial_rand_pos    (int max);

#endif //_RANDOM_H_


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-parent</artifactId>
		<version>1.4.0.BUILD-SNAPSHOT</version>
		<relativePath>../spring-boot-parent</relativePath>
	</parent>
	<artifactId>spring-boot-actuator</artifactId>
	<name>Spring Boot Actuator</name>
	<description>Spring Boot Actuator</description>
	<url>http://projects.spring.io/spring-boot/</url>
	<organization>
		<name>Pivotal Software, Inc.</name>
		<url>http://www.spring.io</url>
	</organization>
	<properties>
		<main.basedir>${basedir}/..</main.basedir>
	</properties>
	<dependencies>
		<!-- Compile -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-autoconfigure</artifactId>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
		</dependency>
		<!-- Optional -->
		<dependency>
			<groupId>com.fasterxml.jackson.dataformat</groupId>
			<artifactId>jackson-dataformat-xml</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.hateoas</groupId>
			<artifactId>spring-hateoas</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.plugin</groupId>
			<artifactId>spring-plugin-core</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.webjars</groupId>
			<artifactId>hal-browser</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>com.github.ben-manes.caffeine</groupId>
			<artifactId>caffeine</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>com.google.guava</groupId>
			<artifactId>guava</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>com.hazelcast</groupId>
			<artifactId>hazelcast</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>com.hazelcast</groupId>
			<artifactId>hazelcast-spring</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>com.sun.mail</groupId>
			<artifactId>javax.mail</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>com.timgroup</groupId>
			<artifactId>java-statsd-client</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>io.dropwizard.metrics</groupId>
			<artifactId>metrics-core</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>javax.cache</groupId>
			<artifactId>cache-api</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>net.sf.ehcache</groupId>
			<artifactId>ehcache</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.apache.activemq</groupId>
			<artifactId>activemq-broker</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.flywaydb</groupId>
			<artifactId>flyway-core</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.infinispan</groupId>
			<artifactId>infinispan-spring4-embedded</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.liquibase</groupId>
			<artifactId>liquibase-core</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-messaging</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-cassandra</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-couchbase</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-mongodb</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-neo4j</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-redis</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-solr</artifactId>
			<optional>true</optional>
			<exclusions>
				<!-- the version of solr here is incompatible with jackson-xml because of an old woodstox -->
				<exclusion>
					<artifactId>wstx-asl</artifactId>
					<groupId>org.codehaus.woodstox</groupId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.integration</groupId>
			<artifactId>spring-integration-jmx</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.integration</groupId>
			<artifactId>spring-integration-core</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.elasticsearch</groupId>
			<artifactId>elasticsearch</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-web</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.apache.tomcat.embed</groupId>
			<artifactId>tomcat-embed-core</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.apache.tomcat.embed</groupId>
			<artifactId>tomcat-embed-el</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.crashub</groupId>
			<artifactId>crash.shell</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.crashub</groupId>
			<artifactId>crash.cli</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.crashub</groupId>
			<artifactId>crash.embed.spring</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.jolokia</groupId>
			<artifactId>jolokia-core</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.amqp</groupId>
			<artifactId>spring-rabbit</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.apache.tomcat</groupId>
			<artifactId>tomcat-jdbc</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>com.zaxxer</groupId>
			<artifactId>HikariCP-java6</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<optional>true</optional>
		</dependency>
		<!-- Annotation processing -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
			<optional>true</optional>
		</dependency>
		<!-- Test -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot</artifactId>
			<type>test-jar</type>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-test</artifactId>
			<type>test-jar</type>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>ch.qos.logback</groupId>
			<artifactId>logback-classic</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.jayway.jsonpath</groupId>
			<artifactId>json-path</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.tomcat.embed</groupId>
			<artifactId>tomcat-embed-logging-juli</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.crashub</groupId>
			<artifactId>crash.connectors.telnet</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.hsqldb</groupId>
			<artifactId>hsqldb</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-elasticsearch</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-rest-webmvc</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.yaml</groupId>
			<artifactId>snakeyaml</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>


text:
class UserPolicy < ApplicationPolicy

  def show?
    return true
  end

  def create?
    return true
  end

  def update?
    return true if user.admin?
    return true if record.id == user.id
  end

  def destroy?
    return true if user.admin?
    return true if record.id == user.id
  end

  class Scope < ApplicationPolicy::Scope
    def resolve
      scope.all
    end
  end

end


text:
//-----------------------------------------------------------------------
// <copyright file="AppNexusMeasureValues.cs" company="Rare Crowds Inc">
// Copyright 2012-2013 Rare Crowds, Inc.
//
//   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.
// </copyright>
//-----------------------------------------------------------------------

namespace AppNexusActivities.Measures
{
    /// AppNexus measure value names
    public static class AppNexusMeasureValues
    {
        /// AppNexus targeting id
        public const string AppNexusId = "APNXId";

        /// AppNexus Sandbox Id
        public const string AppNexusIdSandbox = "APNXId_Sandbox";

        /// AppNexus segment code
        public const string AppNexusCode = "APNXCode";
    }
}


text:
go-mapnik
=========

Description
-----------

Small wrapper for the Mapnik API to render beautiful maps from Go.

Features:

* Render to `[]byte`, `image.Image`, or file.
* Set scale denominator or scale factor.
* Enable/disable single layers.

Installation
------------

This package can be installed with the go get command:

    go get github.com/omniscale/go-mapnik
    go generate github.com/omniscale/go-mapnik

This package requires [Mapnik](http://mapnik.org/) (`libmapnik-dev` on Ubuntu/Debian, `mapnik --with-postgresql` in Homebrew).
Make sure `mapnik-config` is in your `PATH`.

Documentation
-------------

API documentation can be found here: <http://godoc.org/github.com/omniscale/go-mapnik>

License
-------

MIT, see LICENSE file.

Author
------

Oliver Tonnhofer, [Omniscale](http://maps.omniscale.com)

Thanks
------

This package is inspired/based on [`mapnik-c-api`](https://github.com/springmeyer/mapnik-c-api) by Dane Springmeyer and [`go-mapnik`](https://github.com/fawick/go-mapnik) by Fabian Wickborn.


text:
package com.p44.db

import reactivemongo.api.collections.default.BSONCollection
import reactivemongo.api.{DefaultDB, QueryOpts}
import reactivemongo.bson.{BSONDocument, BSONDocumentWriter}
import reactivemongo.core.commands.{GetLastError, LastError}

import scala.concurrent.{ExecutionContext, Future}

/**
 * For models that need only perform an insert.
 * Created by markwilson on 8/4/14.
 */
trait Insertable[T] {

  val collectionName: String // name of the mongodb collection
  val lastErrorDefault: GetLastError = GetLastError() //
  val queryOptsDefault: QueryOpts = QueryOpts() //

  val persistanceWriter: BSONDocumentWriter[T]
  def toBson(obj: T): BSONDocument

  implicit val ec = ExecutionContext.Implicits.global
  implicit val writer = persistanceWriter

  def getCollection(db: DefaultDB): BSONCollection = db.collection(collectionName)

  /**
   * Inserts one creating a new mongoId in the process
   * @param db
   * @param obj
   * @return a future of the LastError which holds the result data
   */
  def insertOneAsFuture(db: DefaultDB, obj: T): Future[LastError] = {
    getCollection(db).insert(obj)
  }

}


text:
using System.Collections.Generic;
namespace Serenity.Data
{
    public class InnerJoin : Join
    {
        public InnerJoin(string toTable, string alias, BaseCriteria onCriteria)
            : base(null, toTable, alias, onCriteria)
        {
        }

        public InnerJoin(IDictionary<string, Join> joins, string toTable, string alias, BaseCriteria onCriteria)
            : base(joins, toTable, alias, onCriteria)
        {
        }

        public override string GetKeyword()
        {
            return "INNER JOIN";
        }
     }
}


text:
package com.gitblit.manager;

import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gitblit.ConfigUserService;
import com.gitblit.Constants;
import com.gitblit.IStoredSettings;
import com.gitblit.IUserService;
import com.gitblit.Keys;
import com.gitblit.extensions.UserTeamLifeCycleListener;
import com.gitblit.models.TeamModel;
import com.gitblit.models.UserModel;
import com.gitblit.utils.StringUtils;
import com.google.inject.Inject;
import com.google.inject.Singleton;

/**
 * The user manager manages persistence and retrieval of users and teams.
 *
 * @author James Moger
 *
 */
@Singleton
public class UserManager implements IUserManager {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	private final IStoredSettings settings;

	private final IRuntimeManager runtimeManager;

	private final IPluginManager pluginManager;

	private final Map<String, String> legacyBackingServices;

	private IUserService userService;

	@Inject
	public UserManager(IRuntimeManager runtimeManager, IPluginManager pluginManager) {
		this.settings = runtimeManager.getSettings();
		this.runtimeManager = runtimeManager;
		this.pluginManager = pluginManager;

		// map of legacy realm backing user services
		legacyBackingServices = new HashMap<String, String>();
		legacyBackingServices.put("com.gitblit.HtpasswdUserService", "realm.htpasswd.backingUserService");
		legacyBackingServices.put("com.gitblit.LdapUserService", "realm.ldap.backingUserService");
		legacyBackingServices.put("com.gitblit.PAMUserService", "realm.pam.backingUserService");
		legacyBackingServices.put("com.gitblit.RedmineUserService", "realm.redmine.backingUserService");
		legacyBackingServices.put("com.gitblit.SalesforceUserService", "realm.salesforce.backingUserService");
		legacyBackingServices.put("com.gitblit.WindowsUserService", "realm.windows.backingUserService");
	}

	/**
	 * Set the user service. The user service authenticates *local* users and is
	 * responsible for persisting and retrieving all users and all teams.
	 *
	 * @param userService
	 */
	public void setUserService(IUserService userService) {
		this.userService = userService;
		this.userService.setup(runtimeManager);
		logger.info(userService.toString());
	}

	@Override
	public void setup(IRuntimeManager runtimeManager) {
		// NOOP
	}

	@Override
	public UserManager start() {
		if (this.userService == null) {
			String realm = settings.getString(Keys.realm.userService, "${baseFolder}/users.conf");
			IUserService service = null;
			if (legacyBackingServices.containsKey(realm)) {
				// create the user service from the legacy config
				String realmKey = legacyBackingServices.get(realm);
				logger.warn("");
				logger.warn(Constants.BORDER2);
				logger.warn(" Key '{}' is obsolete!", realmKey);
				logger.warn(" Please set '{}={}'", Keys.realm.userService, settings.getString(realmKey, "${baseFolder}/users.conf"));
				logger.warn(Constants.BORDER2);
				logger.warn("");
				File realmFile = runtimeManager.getFileOrFolder(realmKey, "${baseFolder}/users.conf");
				service = createUserService(realmFile);
			} else {
				// either a file path OR a custom user service
				try {
					// check to see if this "file" is a custom user service class
					Class<?> realmClass = Class.forName(realm);
					service = (IUserService) realmClass.newInstance();
				} catch (ClassNotFoundException t) {
					// typical file path configuration
					File realmFile = runtimeManager.getFileOrFolder(Keys.realm.userService, "${baseFolder}/users.conf");
					service = createUserService(realmFile);
				} catch (InstantiationException | IllegalAccessException  e) {
					logger.error("failed to instantiate user service {}: {}", realm, e.getMessage());
				}
			}
			setUserService(service);
		}
		return this;
	}

	protected IUserService createUserService(File realmFile) {
		IUserService service = null;
		if (realmFile.getName().toLowerCase().endsWith(".conf")) {
			// config-based realm file
			service = new ConfigUserService(realmFile);
		}

		assert service != null;

		if (!realmFile.exists()) {
			// Create the Administrator account for a new realm file
			try {
				realmFile.createNewFile();
			} catch (IOException x) {
				logger.error(MessageFormat.format("COULD NOT CREATE REALM FILE {0}!", realmFile), x);
			}
			UserModel admin = new UserModel("admin");
			admin.password = "admin";
			admin.canAdmin = true;
			admin.excludeFromFederation = true;
			service.updateUserModel(admin);
		}

		return service;
	}

	@Override
	public UserManager stop() {
		return this;
	}

	/**
	 * Returns true if the username represents an internal account
	 *
	 * @param username
	 * @return true if the specified username represents an internal account
	 */
	@Override
	public boolean isInternalAccount(String username) {
		return !StringUtils.isEmpty(username)
				&& (username.equalsIgnoreCase(Constants.FEDERATION_USER)
						|| username.equalsIgnoreCase(UserModel.ANONYMOUS.username));
	}

	/**
	 * Returns the cookie value for the specified user.
	 *
	 * @param model
	 * @return cookie value
	 */
	@Override
	public String getCookie(UserModel model) {
		return userService.getCookie(model);
	}

	/**
	 * Retrieve the user object for the specified cookie.
	 *
	 * @param cookie
	 * @return a user object or null
	 */
	@Override
	public UserModel getUserModel(char[] cookie) {
		UserModel user = userService.getUserModel(cookie);
		return user;
	}

	/**
	 * Retrieve the user object for the specified username.
	 *
	 * @param username
	 * @return a user object or null
	 */
	@Override
	public UserModel getUserModel(String username) {
		if (StringUtils.isEmpty(username)) {
			return null;
		}
		String usernameDecoded = StringUtils.decodeUsername(username);
		UserModel user = userService.getUserModel(usernameDecoded);
		return user;
	}

	/**
	 * Updates/writes a complete user object.
	 *
	 * @param model
	 * @return true if update is successful
	 */
	@Override
	public boolean updateUserModel(UserModel model) {
		final boolean isCreate = null == userService.getUserModel(model.username);
		if (userService.updateUserModel(model)) {
			if (isCreate) {
				callCreateUserListeners(model);
			}
			return true;
		}
		return false;
	}

	/**
	 * Updates/writes all specified user objects.
	 *
	 * @param models a list of user models
	 * @return true if update is successful
	 * @since 1.2.0
	 */
	@Override
	public boolean updateUserModels(Collection<UserModel> models) {
		return userService.updateUserModels(models);
	}

	/**
	 * Adds/updates a user object keyed by username. This method allows for
	 * renaming a user.
	 *
	 * @param username
	 *            the old username
	 * @param model
	 *            the user object to use for username
	 * @return true if update is successful
	 */
	@Override
	public boolean updateUserModel(String username, UserModel model) {
		final boolean isCreate = null == userService.getUserModel(username);
		if (userService.updateUserModel(username, model)) {
			if (isCreate) {
				callCreateUserListeners(model);
			}
			return true;
		}
		return false;
	}

	/**
	 * Deletes the user object from the user service.
	 *
	 * @param model
	 * @return true if successful
	 */
	@Override
	public boolean deleteUserModel(UserModel model) {
		if (userService.deleteUserModel(model)) {
			callDeleteUserListeners(model);
			return true;
		}
		return false;
	}

	/**
	 * Delete the user object with the specified username
	 *
	 * @param username
	 * @return true if successful
	 */
	@Override
	public boolean deleteUser(String username) {
		if (StringUtils.isEmpty(username)) {
			return false;
		}
		String usernameDecoded = StringUtils.decodeUsername(username);
		UserModel user = getUserModel(usernameDecoded);
		if (userService.deleteUser(usernameDecoded)) {
			callDeleteUserListeners(user);
			return true;
		}
		return false;
	}

	/**
	 * Returns the list of all users available to the login service.
	 *
	 * @return list of all usernames
	 */
	@Override
	public List<String> getAllUsernames() {
		List<String> names = new ArrayList<String>(userService.getAllUsernames());
		return names;
	}

	/**
	 * Returns the list of all users available to the login service.
	 *
	 * @return list of all users
	 * @since 0.8.0
	 */
	@Override
	public List<UserModel> getAllUsers() {
		List<UserModel> users = userService.getAllUsers();
		return users;
	}

	/**
	 * Returns the list of all teams available to the login service.
	 *
	 * @return list of all teams
	 * @since 0.8.0
	 */
	@Override
	public List<String> getAllTeamNames() {
		List<String> teams = userService.getAllTeamNames();
		return teams;
	}

	/**
	 * Returns the list of all teams available to the login service.
	 *
	 * @return list of all teams
	 * @since 0.8.0
	 */
	@Override
	public List<TeamModel> getAllTeams() {
		List<TeamModel> teams = userService.getAllTeams();
		return teams;
	}

	/**
	 * Returns the list of all teams who are allowed to bypass the access
	 * restriction placed on the specified repository.
	 *
	 * @param role
	 *            the repository name
	 * @return list of all teams that can bypass the access restriction
	 * @since 0.8.0
	 */
	@Override
	public List<String> getTeamNamesForRepositoryRole(String role) {
		List<String> teams = userService.getTeamNamesForRepositoryRole(role);
		return teams;
	}

	/**
	 * Retrieve the team object for the specified team name.
	 *
	 * @param teamname
	 * @return a team object or null
	 * @since 0.8.0
	 */
	@Override
	public TeamModel getTeamModel(String teamname) {
		TeamModel team = userService.getTeamModel(teamname);
		return team;
	}

	/**
	 * Updates/writes a complete team object.
	 *
	 * @param model
	 * @return true if update is successful
	 * @since 0.8.0
	 */
	@Override
	public boolean updateTeamModel(TeamModel model) {
		final boolean isCreate = null == userService.getTeamModel(model.name);
		if (userService.updateTeamModel(model)) {
			if (isCreate) {
				callCreateTeamListeners(model);
			}
			return true;
		}
		return false;
	}

	/**
	 * Updates/writes all specified team objects.
	 *
	 * @param models a list of team models
	 * @return true if update is successful
	 * @since 1.2.0
	 */
	@Override
	public boolean updateTeamModels(Collection<TeamModel> models) {
		return userService.updateTeamModels(models);
	}

	/**
	 * Updates/writes and replaces a complete team object keyed by teamname.
	 * This method allows for renaming a team.
	 *
	 * @param teamname
	 *            the old teamname
	 * @param model
	 *            the team object to use for teamname
	 * @return true if update is successful
	 * @since 0.8.0
	 */
	@Override
	public boolean updateTeamModel(String teamname, TeamModel model) {
		final boolean isCreate = null == userService.getTeamModel(teamname);
		if (userService.updateTeamModel(teamname, model)) {
			if (isCreate) {
				callCreateTeamListeners(model);
			}
			return true;
		}
		return false;
	}

	/**
	 * Deletes the team object from the user service.
	 *
	 * @param model
	 * @return true if successful
	 * @since 0.8.0
	 */
	@Override
	public boolean deleteTeamModel(TeamModel model) {
		if (userService.deleteTeamModel(model)) {
			callDeleteTeamListeners(model);
			return true;
		}
		return false;
	}

	/**
	 * Delete the team object with the specified teamname
	 *
	 * @param teamname
	 * @return true if successful
	 * @since 0.8.0
	 */
	@Override
	public boolean deleteTeam(String teamname) {
		TeamModel team = userService.getTeamModel(teamname);
		if (userService.deleteTeam(teamname)) {
			callDeleteTeamListeners(team);
			return true;
		}
		return false;
	}

	/**
	 * Returns the list of all users who are allowed to bypass the access
	 * restriction placed on the specified repository.
	 *
	 * @param role
	 *            the repository name
	 * @return list of all usernames that can bypass the access restriction
	 * @since 0.8.0
	 */
	@Override
	public List<String> getUsernamesForRepositoryRole(String role) {
		return userService.getUsernamesForRepositoryRole(role);
	}

	/**
	 * Renames a repository role.
	 *
	 * @param oldRole
	 * @param newRole
	 * @return true if successful
	 */
	@Override
	public boolean renameRepositoryRole(String oldRole, String newRole) {
		return userService.renameRepositoryRole(oldRole, newRole);
	}

	/**
	 * Removes a repository role from all users.
	 *
	 * @param role
	 * @return true if successful
	 */
	@Override
	public boolean deleteRepositoryRole(String role) {
		return userService.deleteRepositoryRole(role);
	}

	protected void callCreateUserListeners(UserModel user) {
		if (pluginManager == null || user == null) {
			return;
		}

		for (UserTeamLifeCycleListener listener : pluginManager.getExtensions(UserTeamLifeCycleListener.class)) {
			try {
				listener.onCreation(user);
			} catch (Throwable t) {
				logger.error(String.format("failed to call plugin.onCreation%s", user.username), t);
			}
		}
	}

	protected void callCreateTeamListeners(TeamModel team) {
		if (pluginManager == null || team == null) {
			return;
		}

		for (UserTeamLifeCycleListener listener : pluginManager.getExtensions(UserTeamLifeCycleListener.class)) {
			try {
				listener.onCreation(team);
			} catch (Throwable t) {
				logger.error(String.format("failed to call plugin.onCreation %s", team.name), t);
			}
		}
	}

	protected void callDeleteUserListeners(UserModel user) {
		if (pluginManager == null || user == null) {
			return;
		}

		for (UserTeamLifeCycleListener listener : pluginManager.getExtensions(UserTeamLifeCycleListener.class)) {
			try {
				listener.onDeletion(user);
			} catch (Throwable t) {
				logger.error(String.format("failed to call plugin.onDeletion %s", user.username), t);
			}
		}
	}

	protected void callDeleteTeamListeners(TeamModel team) {
		if (pluginManager == null || team == null) {
			return;
		}

		for (UserTeamLifeCycleListener listener : pluginManager.getExtensions(UserTeamLifeCycleListener.class)) {
			try {
				listener.onDeletion(team);
			} catch (Throwable t) {
				logger.error(String.format("failed to call plugin.onDeletion %s", team.name), t);
			}
		}
	}
}


text:
<resources>
    <string name="app_name">.Hike</string>

    <string name="action_settings">Settings</string>
    <string name="maps_activity_name">Maps</string>
    <string name="title_activity_home">HomeActivity</string>
    <string name="buttonTextStartHike">Start Hike</string>
    <string name="buttonTextEndHike">End Hike</string>
    <string name="buttonTextEnvCond">Env Cond</string>
    <string name="title_activity_results">ResultsActivity</string>
    <string name="hello_world">Hello world!</string>
    <string name="buttonTextResultsDone">Done</string>
    <string name="title_activity_env_cond">EnvCondActivity</string>
    <string name="buttonTextBackToMainHike">Back to Main Hike</string>
    <string name="textAppName">.Hike</string>
    <string name="textCurrentHumidity">Current Humidity</string>
    <string name="textCurrentTemperature">Current Temperature</string>
    <string name="textCurrentPressure">Current Pressure</string>
    <string name="textDisplayHumidity">Humidity Display</string>
    <string name="textDisplayTemperature">Temperature Display</string>
    <string name="textDisplayPressure">Pressure Display</string>
    <string name="title_activity_navigation">NavigationActivity</string>
    <string name="textBottonNavigationActivity">NavigationActivity</string>
    <string name="STConnectDialogFragmentTitle">Do you wish to connect to a TI SensorTag?</string>
    <string name="textSettings">Settings</string>
    <string name="textSensors">Sensors</string>
    <string name="textPastHikes">Past Hikes</string>
    <string name="textStartHike">Start Hike</string>
    <string name="textTemperatureSetting">Temperature</string>
    <string name="title_activity_past_hikes">PastHikesActivity</string>
    <string name="title_activity_past_statistics">PastStatisticsActivity</string>
    <string name="title_activity_exception">ExceptionActivity</string>
    <string name="exception_caught_title">Whoops! Something happened that we did not plan for</string>
    <string name="buttonTextPauseHike">Pause Hike</string>
    <string name="viewAndDeleteHint">View Hikes by Clicking. Delete by doing a long click</string>
    <string name="textAltitude">Altitude:</string>
    <string name="textPace">Pace:</string>
    <string name="textResultsTitle">Hike Results</string>
    <string name="textReadings">Readings:</string>
    <string name="textDistanceTraveled">Distance Traveled</string>
    <string name="title_activity_sensors">SensorsActivity</string>
    <string name="textStepCount">Step Count</string>
</resources>


text:
<?php

/**
 * Class containing upload options
 */

class TransferOptions extends Enum
{
    const EMAIL_ME_COPIES                           = 'email_me_copies';
    const EMAIL_ME_ON_EXPIRE                        = 'email_me_on_expire';
    const EMAIL_UPLOAD_COMPLETE                     = 'email_upload_complete';
    const EMAIL_DOWNLOAD_COMPLETE                   = 'email_download_complete';
    const EMAIL_DAILY_STATISTICS                    = 'email_daily_statistics';
    const EMAIL_REPORT_ON_CLOSING                   = 'email_report_on_closing';
    const ENABLE_RECIPIENT_EMAIL_DOWNLOAD_COMPLETE  = 'enable_recipient_email_download_complete';
    const ADD_ME_TO_RECIPIENTS                      = 'add_me_to_recipients';
    const EMAIL_RECIPIENT_WHEN_TRANSFER_EXPIRES     = 'email_recipient_when_transfer_expires';

    const GET_A_LINK                                = 'get_a_link';

    const REDIRECT_URL_ON_COMPLETE                  = 'redirect_url_on_complete';

    const ENCRYPTION                                = 'encryption';
    const COLLECTION                                = 'collection';
    const MUST_BE_LOGGED_IN_TO_DOWNLOAD             = 'must_be_logged_in_to_download';

    // Optional options specific to S3 storage
    const STORAGE_CLOUD_S3_BUCKET                   = 'storage_cloud_s3_bucket';

    const WEB_NOTIFICATION_WHEN_UPLOAD_IS_COMPLETE  = 'web_notification_when_upload_is_complete';

}


text: package winresources


text:
class DlgEditTrap : public CDialog
{
// Construction
public:
	DlgEditTrap(CWnd* pParent = NULL);   // standard constructor
	object_data *obj;
	int trigger;
// Dialog Data
	//{{AFX_DATA(DlgEditTrap)
	enum { IDD = IDD_EDIT_TRAP };
	CListCtrl	m_TrigList;
	int		charges;
	int		damage_type;
	int		level;
	int		percent;
	//}}AFX_DATA

// Overrides
	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(DlgEditTrap)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:

	// Generated message map functions
	//{{AFX_MSG(DlgEditTrap)
	virtual void OnOK();
	virtual BOOL OnInitDialog();
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_DLGEDITTRAP_H__21F38FDE_9B6A_422B_9219_80C1D728E406__INCLUDED_)


text:
import json, copy, base64, time
from twisted.trial import unittest
from twisted.web import http, client
from twisted.web.test.test_web import DummyRequest # not exactly stable
from twisted.internet import defer
from .common import TwoNodeMixin
from .. import rrid, eventsource
from ..database import Notice
from ..eventual import flushEventualQueue
from ..mailbox import delivery, retrieval
from .test_eventsource import parse_events

class Inbound(TwoNodeMixin, unittest.TestCase):
    def test_unknown_TTID(self):
        nA, nB, entA, entB = self.make_connected_nodes(transport="local")
        msgC = "msgC"
        trec = json.loads(entA["their_channel_record_json"])["transports"][0]
        bad_trec = copy.deepcopy(trec)
        TT_privkey, TT_pubkey = rrid.create_keypair()
        TTID, TT0 = rrid.create_token(TT_pubkey)
        bad_STT = rrid.randomize(TT0)
        bad_trec["STT"] = bad_STT.encode("hex")
        msgA = delivery.createMsgA(bad_trec, msgC)

        unknowns = []
        server = nB.agent.mailbox_server
        server.signal_unrecognized_TTID = unknowns.append
        server.handle_msgA(msgA)
        d = flushEventualQueue()
        def _then(res):
            self.failUnlessEqual(len(unknowns), 1)
            c = nB.db.execute("SELECT * FROM mailbox_server_messages")
            messages = c.fetchall()
            self.failUnlessEqual(len(messages), 0)
        d.addCallback(_then)
        return d

    def test_local_TTID(self):
        nA, nB, entA, entB = self.make_connected_nodes(transport="local")
        msgC = "msgC"
        trec = json.loads(entA["their_channel_record_json"])["transports"][0]
        msgA = delivery.createMsgA(trec, msgC)
        server = nB.agent.mailbox_server
        local_messages = []
        server.local_transport_handler = local_messages.append
        server.handle_msgA(msgA)
        d = flushEventualQueue()
        def _then(res):
            c = nB.db.execute("SELECT * FROM mailbox_server_messages")
            messages = c.fetchall()
            self.failUnlessEqual(len(messages), 0)
            self.failUnlessEqual(len(local_messages), 1)
            self.failUnlessEqual(local_messages[0], msgC)
        d.addCallback(_then)
        return d

    def test_nonlocal_TTID(self):
        n = self.make_nodes(transport="local")[1]
        msgC = "msgC"
        server = n.agent.mailbox_server

        tid, trec = self.add_recipient(n)
        msgA = delivery.createMsgA(trec, msgC)

        local_messages = []
        server.local_transport_handler = local_messages.append
        server.handle_msgA(msgA)

        d = flushEventualQueue()
        def _then(res):
            self.failUnlessEqual(len(local_messages), 0)
            c = n.db.execute("SELECT * FROM mailbox_server_messages")
            messages = c.fetchall()
            self.failUnlessEqual(len(messages), 1)
            self.failUnlessEqual(messages[0]["tid"], tid)
            self.failUnlessEqual(messages[0]["length"], len(msgC))
            self.failUnlessEqual(messages[0]["msgC"].decode("hex"), msgC)
        d.addCallback(_then)
        return d

    def test_two_nonlocal_TTID(self):
        n = self.make_nodes(transport="local")[1]
        tid1, trec1 = self.add_recipient(n)
        tid2, trec2 = self.add_recipient(n)

        msg1 = delivery.createMsgA(trec1, "msgC1")
        n.mailbox_server.handle_msgA(msg1)

        msg2 = delivery.createMsgA(trec2, "msgC2")
        n.mailbox_server.handle_msgA(msg2)

        d = flushEventualQueue()

        def _then(_):
            c = n.db.execute("SELECT * FROM mailbox_server_messages"
                             " WHERE tid=?", (tid1,))
            messages = c.fetchall()
            self.failUnlessEqual(len(messages), 1)
            self.failUnlessEqual(messages[0]["msgC"].decode("hex"), "msgC1")

            c = n.db.execute("SELECT * FROM mailbox_server_messages"
                             " WHERE tid=?", (tid2,))
            messages = c.fetchall()
            self.failUnlessEqual(len(messages), 1)
            self.failUnlessEqual(messages[0]["msgC"].decode("hex"), "msgC2")
        d.addCallback(_then)
        return d

def do_request(resource, t=None, method="GET"):
    req = DummyRequest([])
    req.method = method
    req.args = {}
    if t:
        req.args["t"] = [t]
    req.render(resource)
    return "".join(req.written), req

class Retrieval(TwoNodeMixin, unittest.TestCase):
    def test_resource(self):
        n = self.make_nodes(transport="local")[1]
        ms = n.mailbox_server
        tid1, trec1 = self.add_recipient(n)
        tid2, trec2 = self.add_recipient(n)
        TTID_1, TT0_1, RT_1, symkey_1 = ms.get_tid_data(tid1)
        TTID_2, TT0_2, RT_2, symkey_2 = ms.get_tid_data(tid2)

        ms.queue_msgC(tid1, "msgC1_first")
        ms.queue_msgC(tid1, "msgC1_second")
        ms.queue_msgC(tid2, "msgC2")

        c = n.db.execute("SELECT * FROM mailbox_server_messages"
                         " WHERE tid=?", (tid1,))
        messages = c.fetchall()
        self.failUnlessEqual(len(messages), 2)
        bodies = set([m["msgC"].decode("hex") for m in messages])
        self.failUnlessEqual(bodies, set(["msgC1_first", "msgC1_second"]))

        listres = ms.listres

        retrieval_pubkey = trec1["retrieval_pubkey"].decode("hex")
        reqkey, tmppub = retrieval.encrypt_list_request(retrieval_pubkey, RT_1)

        # test 'list'
        out,req = do_request(listres, base64.urlsafe_b64encode(reqkey))
        # that created the tokens, so now we check the DB
        messages = n.db.execute("SELECT * FROM mailbox_server_messages"
                                " WHERE tid=? ORDER BY id",
                                (tid1,)).fetchall()
        self.failUnlessEqual(len(messages), 2)

        self.failUnless(out.startswith("data: "), out)
        self.failUnless(out.endswith("\n\n"), out)
        fields = parse_events(out)
        self.failUnlessEqual(len(fields), 1)
        self.failUnlessEqual(fields[0][0], "data")
        responses = fields[0][1].split()

        r1 = base64.b64decode(responses[0])
        (fetch_token1, delete_token1, length1) = \
                       retrieval.decrypt_list_entry(r1, symkey_1, tmppub)
        self.failUnlessEqual(length1, len("msgC1_first"))
        self.failUnlessEqual(str(messages[0]["fetch_token"]),
                             fetch_token1.encode("hex"))
        self.failUnlessEqual(str(messages[0]["delete_token"]),
                             delete_token1.encode("hex"))
        self.failUnlessEqual(messages[0]["length"], length1)

        r2 = base64.b64decode(responses[1])
        (fetch_token2, delete_token2,
         length2) = retrieval.decrypt_list_entry(r2, symkey_1, tmppub)
        self.failUnlessEqual(length2, len("msgC1_second"))
        self.failUnlessEqual(str(messages[1]["fetch_token"]),
                             fetch_token2.encode("hex"))
        self.failUnlessEqual(str(messages[1]["delete_token"]),
                             delete_token2.encode("hex"))
        self.failUnlessEqual(messages[1]["length"], length2)

        r = n.web.get_root().getStaticEntity("retrieval")
        fetchres = r.getStaticEntity("fetch")
        deleteres = r.getStaticEntity("delete")

        # test 'fetch' on the first message
        out, req = do_request(fetchres,
                              base64.urlsafe_b64encode(fetch_token1))
        encrypted_m1 = out
        m1 = retrieval.decrypt_fetch_response(symkey_1, fetch_token1,
                                              encrypted_m1)
        self.failUnlessEqual(m1, "msgC1_first")

        # fetch_token is single-use
        out, req = do_request(fetchres,
                              base64.urlsafe_b64encode(fetch_token1))
        self.failUnlessEqual(req.responseCode, http.NOT_FOUND)
        self.failUnlessEqual(req.responseMessage, "unknown fetch_token")
        self.failUnlessEqual(out, "")
        messages = n.db.execute("SELECT * FROM mailbox_server_messages"
                                " WHERE tid=? ORDER BY id",
                                (tid1,)).fetchall()
        self.failUnlessEqual(len(messages), 2)
        self.failUnlessEqual(messages[0]["fetch_token"], None)

        # test delete_token
        out, req = do_request(deleteres,
                              base64.urlsafe_b64encode(delete_token1),
                              method="POST")
        self.failUnlessEqual(req.responseCode, http.OK)
        self.failUnlessEqual(out, "")
        messages = n.db.execute("SELECT * FROM mailbox_server_messages"
                                " WHERE tid=? ORDER BY id",
                                (tid1,)).fetchall()
        self.failUnlessEqual(len(messages), 1)

        # replay should be rejected
        out,req = do_request(listres, base64.urlsafe_b64encode(reqkey))
        self.failUnlessEqual(req.responseCode, http.BAD_REQUEST)

        # test unknown tokens
        out,req = do_request(fetchres, base64.urlsafe_b64encode("wrong"))
        self.failUnlessEqual(req.responseCode, 404)
        self.failUnlessEqual(req.responseMessage, "unknown fetch_token")
        self.failUnlessEqual(out, "")

        # timestamp in past (old replay)
        now = time.time()
        past = now - 24*3600
        future = now + 24*3600
        reqkey, tmppub = retrieval.encrypt_list_request(retrieval_pubkey,
                                                        RT_1, now=past)
        out,req = do_request(listres, base64.urlsafe_b64encode(reqkey))
        self.failUnlessEqual(req.responseCode, http.BAD_REQUEST)
        self.failUnlessEqual(req.responseMessage, "too much clock skew")
        self.failUnlessEqual(out, "Too much clock skew")

        # timestamp in future
        reqkey, tmppub = retrieval.encrypt_list_request(retrieval_pubkey,
                                                        RT_1, now=future)
        out,req = do_request(listres, base64.urlsafe_b64encode(reqkey))
        self.failUnlessEqual(req.responseCode, http.BAD_REQUEST)
        self.failUnlessEqual(req.responseMessage, "too much clock skew")
        self.failUnlessEqual(out, "Too much clock skew")

        self.failUnlessEqual(len(listres.old_requests), 1)
        listres.prune_old_requests(now=future)
        self.failUnlessEqual(len(listres.old_requests), 0)

        # unrecognized RT, causing KeyError (or nicer)
        unknown_RT = "unknown0" # 8 bytes
        reqkey, tmppub = retrieval.encrypt_list_request(retrieval_pubkey,
                                                        unknown_RT)
        out,req = do_request(listres, base64.urlsafe_b64encode(reqkey))
        self.failUnlessEqual(req.responseCode, http.NOT_FOUND)
        self.failUnlessEqual(req.responseMessage, "no such RT")
        self.failUnlessEqual(out, "no such RT")

        # since none of those "list" requests were accepted, the fetch_token2
        # should still be valid. We don't spend it now, to test how a second
        # "list" should cancel it.
        messages = n.db.execute("SELECT * FROM mailbox_server_messages"
                                " WHERE tid=? ORDER BY id",
                                (tid1,)).fetchall()
        self.failUnlessEqual(len(messages), 1)
        self.failUnlessEqual(messages[0]["fetch_token"],
                             fetch_token2.encode("hex"))
        # a second 'list' should revoke tokens from the first
        reqkey, tmppub = retrieval.encrypt_list_request(retrieval_pubkey, RT_1)
        out,req = do_request(listres, base64.urlsafe_b64encode(reqkey))
        messages = n.db.execute("SELECT * FROM mailbox_server_messages"
                                " WHERE tid=? ORDER BY id",
                                (tid1,)).fetchall()
        self.failUnlessEqual(len(messages), 1)
        self.failIfEqual(messages[0]["fetch_token"],
                         fetch_token2.encode("hex"))

    def GET(self, url):
        return client.getPage(url, method="GET",
                              headers={"accept": "application/json"})
    def POST(self, url, data):
        return client.getPage(url, method="POST", postdata=data,
                              headers={"accept": "application/json",
                                       "content-type": "application/json"})

    def test_web_list(self):
        n = self.make_nodes(transport="local")[1]
        ms = n.mailbox_server
        tid1, trec1 = self.add_recipient(n)
        tid2, trec2 = self.add_recipient(n)
        TTID_1, TT0_1, RT_1, symkey_1 = ms.get_tid_data(tid1)
        #TTID_2, TT0_2, RT_2, symkey_2 = ms.get_tid_data(tid2)

        ms.queue_msgC(tid1, "msgC1_first")
        ms.queue_msgC(tid1, "msgC1_second")
        ms.queue_msgC(tid2, "msgC2")

        baseurl = n.baseurl + "retrieval/"

        retrieval_pubkey = trec1["retrieval_pubkey"].decode("hex")
        reqkey, tmppub = retrieval.encrypt_list_request(retrieval_pubkey, RT_1)
        d = self.GET(baseurl+"list?t="+base64.urlsafe_b64encode(reqkey))
        def _then1(res):
            fields = parse_events(res)
            self.failUnlessEqual(len(fields), 1)
            self.failUnlessEqual(fields[0][0], "data")
            responses = fields[0][1].split()
            r1 = base64.b64decode(responses[0])
            (fetch_token1, delete_token1, length1) = \
                           retrieval.decrypt_list_entry(r1, symkey_1, tmppub)
            self.failUnlessEqual(length1, len("msgC1_first"))
        d.addCallback(_then1)
        return d

    def test_web_events(self):
        n = self.make_nodes(transport="local")[1]
        ms = n.mailbox_server
        tid1, trec1 = self.add_recipient(n)
        tid2, trec2 = self.add_recipient(n)
        TTID_1, TT0_1, RT_1, symkey_1 = ms.get_tid_data(tid1)
        TTID_2, TT0_2, RT_2, symkey_2 = ms.get_tid_data(tid2)

        ms.queue_msgC(tid1, "msgC1_first")
        ms.queue_msgC(tid1, "msgC1_second")
        ms.queue_msgC(tid2, "msgC2")

        baseurl = n.baseurl + "retrieval/"

        retrieval_pubkey = trec1["retrieval_pubkey"].decode("hex")
        reqkey, tmppub = retrieval.encrypt_list_request(retrieval_pubkey, RT_1)
        # test streaming/EventSource: new messages should trigger events
        url = baseurl+"list?t="+base64.urlsafe_b64encode(reqkey)

        fields = []
        def handler(name, data):
            fields.append( (name,data) )
        def check_f(min_fields):
            if len(fields) < min_fields:
                return False
            return True

        es = eventsource.EventSource(url, handler)
        finished_d = es.start()
        d = self.poll(lambda: check_f(2))
        def _then1(_):
            self.failUnlessEqual(len(fields), 2)
            self.failUnlessEqual(fields[0][0], "") # comment
            self.failUnlessEqual(fields[1][0], "data")
            responses = fields[1][1].split()
            self.failUnlessEqual(len(responses), 2)
            r1 = base64.b64decode(responses[0])
            (fetch_token1, delete_token1, length1) = \
                           retrieval.decrypt_list_entry(r1, symkey_1, tmppub)
            self.failUnlessEqual(length1, len("msgC1_first"))

            # resource should ignore UPDATE and DELETE
            ms.listres.new_message(Notice("mailbox_server_messages",
                                          "delete", 15, None, {}))
            # now trigger a third message
            ms.queue_msgC(tid1, "msgC1_third")
            return self.poll(lambda: check_f(3))
        d.addCallback(_then1)
        def _then2(_):
            self.failUnlessEqual(len(fields), 3)
            self.failUnlessEqual(fields[2][0], "data")
            responses = fields[2][1].split()
            self.failUnlessEqual(len(responses), 1)
            r3 = base64.b64decode(responses[0])
            (fetch_token3, delete_token3, length3) = \
                           retrieval.decrypt_list_entry(r3, symkey_1, tmppub)
            self.failUnlessEqual(length3, len("msgC1_third"))
        d.addCallback(_then2)
        def _shutdown(res):
            es.cancel()
            d2 = defer.Deferred()
            finished_d.addBoth(lambda _: d2.callback(res))
            return d2
        d.addBoth(_shutdown)
        return d

    def test_web_events_replacement(self):
        n = self.make_nodes(transport="local")[1]
        ms = n.mailbox_server
        tid1, trec1 = self.add_recipient(n)
        tid2, trec2 = self.add_recipient(n)
        TTID_1, TT0_1, RT_1, symkey_1 = ms.get_tid_data(tid1)
        TTID_2, TT0_2, RT_2, symkey_2 = ms.get_tid_data(tid2)

        ms.queue_msgC(tid1, "msgC1_first")
        ms.queue_msgC(tid1, "msgC1_second")
        ms.queue_msgC(tid2, "msgC2")

        baseurl = n.baseurl + "retrieval/"

        retrieval_pubkey = trec1["retrieval_pubkey"].decode("hex")
        reqkey1,tmppub1 = retrieval.encrypt_list_request(retrieval_pubkey, RT_1)
        url1 = baseurl+"list?t="+base64.urlsafe_b64encode(reqkey1)

        reqkey2,tmppub2 = retrieval.encrypt_list_request(retrieval_pubkey, RT_1)
        url2 = baseurl+"list?t="+base64.urlsafe_b64encode(reqkey2)

        fields1 = []
        def handler1(name, data):
            fields1.append( (name,data) )
        fields2 = []
        def handler2(name, data):
            fields2.append( (name,data) )

        def check_f(fields, min_fields):
            if len(fields) < min_fields:
                return False
            return True

        es1 = eventsource.EventSource(url1, handler1)
        es2 = eventsource.EventSource(url2, handler2)

        cleanup1_d = defer.Deferred()
        cleanup2_d = defer.Deferred()
        def fire_cleanup(res, cleanup_d):
            cleanup_d.callback(None)
            return res
        finished1_d = es1.start()
        finished1_d.addBoth(fire_cleanup, cleanup1_d)

        d = self.poll(lambda: check_f(fields1, 2))
        def _then1(_):
            self.failUnlessEqual(len(fields1), 2)
            self.failUnlessEqual(fields1[0][0], "") # comment
            self.failUnlessEqual(fields1[1][0], "data")
            responses = fields1[1][1].split()
            self.failUnlessEqual(len(responses), 2)
            r1 = base64.b64decode(responses[0])
            (fetch_token1, delete_token1, length1) = \
                           retrieval.decrypt_list_entry(r1, symkey_1, tmppub1)
            self.failUnlessEqual(length1, len("msgC1_first"))

            # starting a new request should cancel the existing one
            self.finished2_d = es2.start()
            self.finished2_d.addBoth(fire_cleanup, cleanup2_d)
            return finished1_d
        d.addCallback(_then1)
        d.addCallback(lambda _: self.poll(lambda: check_f(fields2, 2)))
        def _then2(_):
            self.failUnlessEqual(len(fields2), 2)
            self.failUnlessEqual(fields2[0][0], "") # comment
            self.failUnlessEqual(fields2[1][0], "data")
            responses = fields2[1][1].split()
            self.failUnlessEqual(len(responses), 2)
            r1 = base64.b64decode(responses[0])
            (fetch_token1, delete_token1, length1) = \
                           retrieval.decrypt_list_entry(r1, symkey_1, tmppub2)
            self.failUnlessEqual(length1, len("msgC1_first"))
        d.addCallback(_then2)

        def _shutdown(res):
            es1.cancel()
            es2.cancel()
            return res
        d.addBoth(_shutdown)
        d.addCallback(lambda _: cleanup1_d)
        d.addCallback(lambda _: cleanup2_d)
        return d