text:
var gulp = require('gulp')
  , gutil = require('gulp-util')
  , clean = require('gulp-clean')
  , concat = require('gulp-concat')
  , rename = require('gulp-rename')
  , minifycss = require('gulp-minify-css')
  , minifyhtml = require('gulp-minify-html')
  , processhtml = require('gulp-processhtml')
  , jshint = require('gulp-jshint')
  , uglify = require('gulp-uglify')
  , connect = require('gulp-connect')
  , paths;

paths = {
  assets: 'src/assets/**/*',
  css:    'src/css/*.css',
  js:  [
    'src/js/keyboard.js',
    'src/js/bullet.js',
    'src/js/player.js',
    'src/js/enemies.js',
    'src/js/enemy.js',
    'src/js/game.js',
    'src/js/render.js',
    'src/js/start.js'
  ],
  dist:   './dist/'
};

gulp.task('clean', function () {
  return gulp.src(paths.dist, {read: false})
    .pipe(clean({force: true}))
    .on('error', gutil.log);
});

gulp.task('copy', ['clean'], function () {
  return gulp.src(paths.assets)
    .pipe(gulp.dest(paths.dist + 'assets'))
    .on('error', gutil.log);
});

gulp.task('uglify', ['lint'], function () {
  return gulp.src(paths.js)
      .pipe(concat('main.min.js'))
      .pipe(uglify({outSourceMap: true}))
      .pipe(gulp.dest(paths.dist));
});

gulp.task('minifycss', function () {
  return gulp.src(paths.css)
    .pipe(minifycss({
      keepSpecialComments: false,
      removeEmpty: true
    }))
    .pipe(rename({suffix: '.min'}))
    .pipe(gulp.dest(paths.dist))
    .on('error', gutil.log);
});

gulp.task('processhtml', function() {
  return gulp.src('src/index.html')
    .pipe(processhtml('index.html'))
    .pipe(gulp.dest(paths.dist))
    .on('error', gutil.log);
});

gulp.task('minifyhtml', function() {
  return gulp.src('dist/index.html')
    .pipe(minifyhtml())
    .pipe(gulp.dest(paths.dist))
    .on('error', gutil.log);
});

gulp.task('lint', function() {
  return gulp.src(paths.js)
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter('default'))
    .on('error', gutil.log);
});

gulp.task('html', function(){
  return gulp.src('src/*.html')
    .pipe(connect.reload())
    .on('error', gutil.log);
});

gulp.task('connect', function () {
  connect.server({
    root: [__dirname + '/src'],
    port: 9000,
    livereload: true
  });
});

gulp.task('prod', function () {
  connect.server({
    root: [__dirname + '/dist'],
    port: 9000,
    livereload: true
  });
});

gulp.task('watch', function () {
  gulp.watch(paths.js, ['lint']);
  gulp.watch(['./src/index.html', paths.css, paths.js], ['html']);
});

gulp.task('default', ['connect', 'watch']);
gulp.task('build', ['clean', 'copy', 'uglify', 'minifycss', 'processhtml', 'minifyhtml']);


text:
var get$ = Ember.get;
Em.onLoad('Ember.Application', function (application) {
  application.initializer({
    name: 'ember-auth',
    initialize: function (container, app) {
      app.register('auth:main', get$(app, 'Auth') || get$(Em, 'Auth'), { singleton: true });
      app.inject('route', 'auth', 'auth:main');
      app.inject('controller', 'auth', 'auth:main');
      return app.inject('view', 'auth', 'auth:main');
    }
  });
  return application.initializer({
    name: 'ember-auth-load',
    after: 'ember-auth',
    initialize: function (container, app) {
      return container.lookup('auth:main');
    }
  });
});// Generated by EmberScript 0.0.7
void function () {
  var $;
  var get$ = Ember.get;
  var set$ = Ember.set;
  $ = jQuery;
  set$(Em, 'Auth', Ember.Object.extend({
    _defaults: {},
    _config: function (namespace, defaults) {
      if (null != defaults) {
        return function (accum$) {
          var k, v;
          for (k in defaults) {
            v = defaults[k];
            get$(this, '_defaults')[namespace] || (get$(this, '_defaults')[namespace] = {});
            accum$.push(get$(this, '_defaults')[namespace][k] = v);
          }
          return accum$;
        }.call(this, []);
      } else {
        return $.extend(true, {}, get$(this, '_defaults')[namespace], this.get(namespace));
      }
    },
    _handlers: {
      signInSuccess: [],
      signInError: [],
      signOutSuccess: [],
      signOutError: [],
      sendSuccess: [],
      sendError: []
    },
    module: Ember.computed(function () {
      var moduleName, modules;
      modules = {};
      for (var i$ = 0, length$ = get$(this, 'modules').length; i$ < length$; ++i$) {
        moduleName = get$(this, 'modules')[i$];
        modules[moduleName] = get$(this, 'container').lookup('authModule:' + moduleName);
      }
      return modules;
    }).property('modules.@each'),
    _request: Ember.computed(function () {
      return get$(this, 'container').lookup('authRequest:' + get$(this, 'request'));
    }).property('request'),
    _response: Ember.computed(function () {
      return get$(this, 'container').lookup('authResponse:' + get$(this, 'response'));
    }).property('response'),
    _strategy: Ember.computed(function () {
      return get$(this, 'container').lookup('authStrategy:' + get$(this, 'strategy'));
    }).property('strategy'),
    _session: Ember.computed(function () {
      return get$(this, 'container').lookup('authSession:' + get$(this, 'session'));
    }).property('session'),
    signIn: function (url, opts) {
      var this$;
      if (typeof opts === 'undefined') {
        opts = url;
        url = get$(this, '_request').resolveUrl(get$(this, 'signInEndPoint'));
      } else {
        url = get$(this, '_request').resolveUrl(url);
      }
      opts || (opts = {});
      return new (get$(get$(Em, 'RSVP'), 'Promise'))((this$ = this, function (resolve, reject) {
        var this$1, this$2;
        return get$(this$, '_request').signIn(url, get$(this$, '_strategy').serialize(opts)).then((this$1 = this$, function (response) {
          var data, handler, promises;
          data = get$(this$1, '_response').canonicalize(response);
          promises = [];
          promises.push(get$(this$1, '_strategy').deserialize(data));
          promises.push(get$(this$1, '_session').start(data));
          for (var i$ = 0, length$ = get$(get$(this$1, '_handlers'), 'signInSuccess').length; i$ < length$; ++i$) {
            handler = get$(get$(this$1, '_handlers'), 'signInSuccess')[i$];
            promises.push(handler(data));
          }
          return get$(Em, 'RSVP').all(promises).then(function () {
            return resolve(data);
          }).fail(function () {
            return reject(data);
          });
        })).fail((this$2 = this$, function (response) {
          var data, handler, promises;
          data = get$(this$2, '_response').canonicalize(response);
          promises = [];
          promises.push(get$(this$2, '_strategy').deserialize(data));
          promises.push(get$(this$2, '_session').end(data));
          for (var i$ = 0, length$ = get$(get$(this$2, '_handlers'), 'signInError').length; i$ < length$; ++i$) {
            handler = get$(get$(this$2, '_handlers'), 'signInError')[i$];
            promises.push(handler(data));
          }
          return get$(Em, 'RSVP').all(promises).then(function () {
            return reject(data);
          }).fail(function () {
            return reject(data);
          });
        }));
      }));
    },
    signOut: function (url, opts) {
      var this$;
      if (typeof opts === 'undefined') {
        opts = url;
        url = get$(this, '_request').resolveUrl(get$(this, 'signOutEndPoint'));
      } else {
        url = get$(this, '_request').resolveUrl(url);
      }
      opts || (opts = {});
      return new (get$(get$(Em, 'RSVP'), 'Promise'))((this$ = this, function (resolve, reject) {
        var this$1, this$2;
        return get$(this$, '_request').signOut(url, get$(this$, '_strategy').serialize(opts)).then((this$1 = this$, function (response) {
          var data, handler, promises;
          data = get$(this$1, '_response').canonicalize(response);
          promises = [];
          promises.push(get$(this$1, '_strategy').deserialize(data));
          promises.push(get$(this$1, '_session').end(data));
          for (var i$ = 0, length$ = get$(get$(this$1, '_handlers'), 'signOutSuccess').length; i$ < length$; ++i$) {
            handler = get$(get$(this$1, '_handlers'), 'signOutSuccess')[i$];
            promises.push(handler(data));
          }
          return get$(Em, 'RSVP').all(promises).then(function () {
            return resolve(data);
          }).fail(function () {
            return reject(data);
          });
        })).fail((this$2 = this$, function (response) {
          var data, handler, promises;
          data = get$(this$2, '_response').canonicalize(response);
          promises = [];
          for (var i$ = 0, length$ = get$(get$(this$2, '_handlers'), 'signOutError').length; i$ < length$; ++i$) {
            handler = get$(get$(this$2, '_handlers'), 'signOutError')[i$];
            promises.push(handler(data));
          }
          return get$(Em, 'RSVP').all(promises).then(function () {
            return reject(data);
          }).fail(function () {
            return reject(data);
          });
        }));
      }));
    },
    send: function (url, opts) {
      var this$;
      if (typeof opts === 'undefined') {
        opts = url;
        url = get$(this, '_request').resolveUrl('');
      } else {
        url = get$(this, '_request').resolveUrl(url);
      }
      opts || (opts = {});
      return new (get$(get$(Em, 'RSVP'), 'Promise'))((this$ = this, function (resolve, reject) {
        var this$1, this$2;
        return get$(this$, '_request').send(url, get$(this$, '_strategy').serialize(opts)).then((this$1 = this$, function (response) {
          var handler, promises;
          promises = [];
          for (var i$ = 0, length$ = get$(get$(this$1, '_handlers'), 'sendSuccess').length; i$ < length$; ++i$) {
            handler = get$(get$(this$1, '_handlers'), 'sendSuccess')[i$];
            promises.push(handler(response));
          }
          return get$(Em, 'RSVP').all(promises).then(function () {
            return resolve(response);
          }).fail(function () {
            return reject(response);
          });
        })).fail((this$2 = this$, function (response) {
          var handler, promises;
          promises = [];
          for (var i$ = 0, length$ = get$(get$(this$2, '_handlers'), 'sendError').length; i$ < length$; ++i$) {
            handler = get$(get$(this$2, '_handlers'), 'sendError')[i$];
            promises.push(handler(response));
          }
          return get$(Em, 'RSVP').all(promises).then(function () {
            return reject(response);
          }).fail(function () {
            return reject(response);
          });
        }));
      }));
    },
    createSession: function (data) {
      var this$;
      return new (get$(get$(Em, 'RSVP'), 'Promise'))((this$ = this, function (resolve, reject) {
        var handler, promises;
        if (typeof data === 'string')
          data = get$(this$, '_response').canonicalize(data);
        promises = [];
        promises.push(get$(this$, '_strategy').deserialize(data));
        promises.push(get$(this$, '_session').start(data));
        for (var i$ = 0, length$ = get$(get$(this$, '_handlers'), 'signInSuccess').length; i$ < length$; ++i$) {
          handler = get$(get$(this$, '_handlers'), 'signInSuccess')[i$];
          promises.push(handler(data));
        }
        return get$(Em, 'RSVP').all(promises).then(function () {
          return resolve(data);
        }).fail(function () {
          return reject(data);
        });
      }));
    },
    destroySession: function (data) {
      var this$;
      if (null == data)
        data = {};
      return new (get$(get$(Em, 'RSVP'), 'Promise'))((this$ = this, function (resolve, reject) {
        var handler, promises;
        if (typeof data === 'string')
          data = get$(this$, '_response').canonicalize(data);
        promises = [];
        promises.push(get$(this$, '_strategy').deserialize(data));
        promises.push(get$(this$, '_session').end(data));
        for (var i$ = 0, length$ = get$(get$(this$, '_handlers'), 'signOutSuccess').length; i$ < length$; ++i$) {
          handler = get$(get$(this$, '_handlers'), 'signOutSuccess')[i$];
          promises.push(handler(data));
        }
        return get$(Em, 'RSVP').all(promises).then(function () {
          return resolve(data);
        }).fail(function () {
          return reject(data);
        });
      }));
    },
    addHandler: function (type, handler) {
      var msg;
      msg = 'Handler type unrecognized; you passed in `' + type + '`';
      Em.assert(msg, null != get$(this, '_handlers')[type]);
      msg = 'Handler must be a function';
      Em.assert(msg, typeof handler === 'function');
      return get$(this, '_handlers')[type].pushObject(handler);
    },
    removeHandler: function (type, handler) {
      var msg;
      msg = 'Handler type unrecognized; you passed in `' + type + '`';
      Em.assert(msg, null != get$(this, '_handlers')[type]);
      msg = 'Handler must be a function or omitted for removing all handlers';
      Em.assert(msg, typeof handler === 'function' || typeof handler === 'undefined');
      if (null != handler) {
        return get$(this, '_handlers')[type].removeObject(handler);
      } else {
        return get$(this, '_handlers')[type] = [];
      }
    },
    _ensurePromise: function (ret) {
      if (typeof get$(ret, 'then') === 'function') {
        return ret;
      } else {
        return new (get$(get$(Em, 'RSVP'), 'resolve'))(ret);
      }
    }
  }));
}.call(this);// Generated by EmberScript 0.0.7
void function () {
  var mustImplement;
  var get$ = Ember.get;
  var set$ = Ember.set;
  mustImplement = function (method) {
    return function () {
      throw new (get$(Em, 'Error'))('Your request adapter ' + this.toString() + ' must implement the required method `' + method + '`');
    };
  };
  set$(get$(Em, 'Auth'), 'AuthRequest', Ember.Object.extend({
    signIn: mustImplement('signIn'),
    signOut: mustImplement('signOut'),
    send: mustImplement('send'),
    resolveUrl: function (path) {
      var base;
      base = get$(get$(this, 'auth'), 'baseUrl');
      if (base && base[get$(base, 'length') - 1] === '/')
        base = base.substr(0, get$(base, 'length') - 1);
      if ((null != path ? path[0] : void 0) === '/')
        path = path.substr(1, get$(path, 'length'));
      return [
        base,
        path
      ].join('/');
    }
  }));
}.call(this);// Generated by EmberScript 0.0.7
void function () {
  var mustImplement;
  var get$ = Ember.get;
  var set$ = Ember.set;
  mustImplement = function (method) {
    return function () {
      throw new (get$(Em, 'Error'))('Your response adapter ' + this.toString() + ' must implement the required method `' + method + '`');
    };
  };
  set$(get$(Em, 'Auth'), 'AuthResponse', Ember.Object.extend({ canonicalize: mustImplement('canonicalize') }));
}.call(this);// Generated by EmberScript 0.0.7
void function () {
  var mustImplement;
  var get$ = Ember.get;
  var set$ = Ember.set;
  mustImplement = function (method) {
    return function () {
      throw new (get$(Em, 'Error'))('Your strategy adapter ' + this.toString() + ' must implement the required method `' + method + '`');
    };
  };
  set$(get$(Em, 'Auth'), 'AuthStrategy', Ember.Object.extend({
    serialize: mustImplement('serialize'),
    deserialize: mustImplement('deserialize')
  }));
}.call(this);// Generated by EmberScript 0.0.7
void function () {
  var mustImplement;
  var get$ = Ember.get;
  var set$ = Ember.set;
  mustImplement = function (method) {
    return function () {
      throw new (get$(Em, 'Error'))('Your session adapter ' + this.toString() + ' must implement the required method `' + method + '`');
    };
  };
  set$(get$(Em, 'Auth'), 'AuthSession', Ember.Object.extend({
    init: function () {
      get$(this, 'auth').reopen({
        signedIn: get$(Em, 'computed').alias('_session.signedIn'),
        userId: get$(Em, 'computed').alias('_session.userId'),
        startTime: get$(Em, 'computed').alias('_session.startTime'),
        endTime: get$(Em, 'computed').alias('_session.endTime')
      });
      get$(this, 'auth').addHandler('signInSuccess', get$(this, 'start'));
      return get$(this, 'auth').addHandler('signOutSuccess', get$(this, 'end'));
    },
    signedIn: false,
    userId: null,
    startTime: null,
    endTime: null,
    start: function () {
      set$(this, 'signedIn', true);
      set$(this, 'startTime', new Date);
      return set$(this, 'endTime', null);
    },
    end: function () {
      set$(this, 'signedIn', false);
      set$(this, 'userId', null);
      set$(this, 'startTime', null);
      return set$(this, 'endTime', new Date);
    },
    retrieve: mustImplement('retrieve'),
    store: mustImplement('store'),
    remove: mustImplement('remove')
  }));
}.call(this);// Generated by EmberScript 0.0.7
var get$ = Ember.get;
get$(Em, 'Auth').reopen({
  request: 'jquery',
  response: 'json',
  strategy: 'token',
  session: 'cookie',
  modules: [],
  signInEndPoint: null,
  signOutEndPoint: null,
  baseUrl: null
});

redpajama_set_name: RedPajamaGithub


text:
fan.httpd
=========

### `serv_info_table = httpd.bind(arg:table)`
create a simple http server, `serv_info_table` contains `host` and `port`.

---------
keys in `serv_info_table`

* `serv` the server instance.
    * `rebind()` rebind the same host/port.(e.g. resume back in mobile device, rebind port.)
* `host` bind host.
* `port` bind port.

---------
keys in the `arg`:

* `host: string?`

http service listening host, default "0.0.0.0"

* `port: integer?`

http service listening port, leave empty for random port that available.

* `onService`

on request callback, arg1 => [http_request](#http_request), arg2 => [http_response](#http_response)

* `cert`

ssl support, if using core `config.httpd_using_core`, this property only available with libevent2.1.5+

* `key`

ssl support, if using core `config.httpd_using_core`, this property only available with libevent2.1.5+

HTTP_REQUEST
============

properties:
### `path:string`

### `query:string`

### `method:string`

### `params:table`

### `body:string`
income body.

### `headers:table`
format as `{singlekey = "value", multikey = {"value1", "value2"}}`

### `remoteip:string`

### `remoteport:integer`

apis:
### `available():integer`
return available input stream length to read.

### `read()`
read data buf from input stream, return nil if no data.

HTTP_RESPONSE
=============

apis:
### `addheader(k:string, v:string)`
add one response header.

### `reply(status_code:integer, msg:string, bodydata:string?)`
response to client.

### `reply_start(status_code:integer, msg:string)`

### `reply_chunk(data:string)`

### `reply_end()`


text:
package org.hisp.dhis.webapi.controller;

import org.hisp.dhis.web.HttpStatus;
import org.hisp.dhis.webapi.DhisControllerConvenienceTest;
import org.junit.jupiter.api.Test;

/**
 * Tests the {@link PdfFormController} using (mocked) REST requests.
 *
 * @author Jan Bernitt
 */
class PdfFormControllerTest extends DhisControllerConvenienceTest
{

    @Test
    void testSendFormPdfDataSet_Empty()
    {
        assertWebMessage( "Conflict", 409, "ERROR", "An error occurred, please check import summary.",
            POST( "/pdfForm/dataSet", "{}" ).content( HttpStatus.CONFLICT ) );
    }
}


text:
package io.quarkus.resteasy.reactive.server.test.simple;

import java.io.IOException;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.ext.Provider;

@Provider
public class TestRequestFilter implements ContainerRequestFilter {

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        String previousFilterHeaderValue = requestContext.getHeaders().getFirst("filter-request");
        requestContext.getHeaders().putSingle("filter-request", previousFilterHeaderValue + "-default");
    }

}


text:
define(
"dijit/form/nls/hu/validate", ({
	invalidMessage: "A megadott érték érvénytelen.",
	missingMessage: "Meg kell adni egy értéket.",
	rangeMessage: "Az érték kívül van a megengedett tartományon."
})
);


text:
package io.pivotal.springsamples.fakes;

import io.pivotal.springsamples.EventRepository;
import io.pivotal.springsamples.EventRepositoryTest;

public class InMemoryEventRepositoryTest extends EventRepositoryTest {

    private EventRepository eventRepository = new InMemoryEventRepository();

    @Override
    protected EventRepository repository() {
        return eventRepository;
    }
}


text:
JSON objects

Data Marshaller is a module that produces for a set of pairs (property full path, property value) the data (that eventually contains a JSON object).
**SRS_DATA_MARSHALLER_99_002: [**  DataMarshaller shall have the following interface **]**

```c
#define DATA_MARSHALLER_RESULT_VALUES           \
DATA_MARSHALLER_OK,                             \
DATA_MARSHALLER_INVALID_ARG,                    \
DATA_MARSHALLER_NO_DEVICE_IDENTITY,             \
DATA_MARSHALLER_SCHEMA_FAILED,                  \
DATA_MARSHALLER_INVALID_MODEL_PROPERTY,         \
DATA_MARSHALLER_JSON_ENCODER_ERROR,             \
DATA_MARSHALLER_ERROR,                          \
DATA_MARSHALLER_AGENT_DATA_TYPES_ERROR,         \
DATA_MARSHALLER_MULTITREE_ERROR,                \

DEFINE_ENUM(DATA_MARSHALLER_RESULT, DATA_MARSHALLER_RESULT_VALUES);

typedef struct DATA_MARSHALLER_VALUE_TAG
{
    const char* PropertyPath;
    const AGENT_DATA_TYPE* Value;
} DATA_MARSHALLER_VALUE;

typedef void* DATA_MARSHALLER_HANDLE;

DATA_MARSHALLER_HANDLE DataMarshaller_Create(SCHEMA_MODEL_TYPE_HANDLE modelHandle, bool includePropertyPath);
extern void DataMarshaller_Destroy(DATA_MARSHALLER_HANDLE dataMarshallerHandle);
DATA_MARSHALLER_RESULT DataMarshaller_SendData(DATA_MARSHALLER_HANDLE dataMarshallerHandle, size_t valueCount, const DATA_MARSHALLER_VALUE* values, unsigned char** destination, size_t* destinationSize);
```

### DataMarshaller_Create
```c
DATA_MARSHALLER_HANDLE DataMarshaller_Create(SCHEMA_MODEL_TYPE_HANDLE modelHandle, bool includePropertyPath)
```

**SRS_DATA_MARSHALLER_99_018: [**  DataMarshaller_Create shall create a new DataMarshaller instance and on success it shall return a non NULL handle. **]**

**SRS_DATA_MARSHALLER_99_019: [**  DataMarshaller_Create shall return NULL if any argument is NULL. **]**

**SRS_DATA_MARSHALLER_99_048: [** On any other errors not explicitly specified, DataMarshaller_Create shall return NULL. **]**

### DataMarshaller_Destroy
```c
extern void DataMarshaller_Destroy(DATA_MARSHALLER_HANDLE dataMarshallerHandle);
```

**SRS_DATA_MARSHALLER_99_022: [**  DataMarshaller_Destroy shall free all resources associated with the dataMarshallerHandle argument. **]**

**SRS_DATA_MARSHALLER_99_024: [**  When called with a NULL handle, DataMarshaller_Destroy shall do nothing. **]**

### DataMarshaller_SendData
```c
DATA_MARSHALLER_RESULT DataMarshaller_SendData(DATA_MARSHALLER_HANDLE dataMarshallerHandle, size_t valueCount, const DATA_MARSHALLER_VALUE* values, unsigned char** destination, size_t* destinationSize)
```

DataMarshaller_SendData shall use JSON encoder and MultiTree to produce a JSON object from all the pairs of (model property full path, property value) and it shall provide the object in (*destination, destinationSize) pair of output parameters.

**SRS_DATA_MARSHALLER_99_003: [**  DATA_MARSHALLER_OK shall be returned when the function execution finishes successfully. **]**

**SRS_DATA_MARSHALLER_99_004: [**  DATA_MARSHALLER_INVALID_ARG shall be returned when the function has detected an invalid parameter (NULL) being passed to the function. **]**

**SRS_DATA_MARSHALLER_99_033: [**  DATA_MARSHALLER_INVALID_ARG shall be returned if the valueCount is zero. **]**

**SRS_DATA_MARSHALLER_99_042: [** The entity set name shall be obtained by calling Schema_GetModelRootName. **]**

**SRS_DATA_MARSHALLER_99_043: [** The namespace shall be obtained by using Schema_GetSchemaNamespace. **]**

**SRS_DATA_MARSHALLER_99_044: [** If any Schema APIs fail, DATA_MARSHALLER_SCHEMA_FAILED shall be returned. **]**

**SRS_DATA_MARSHALLER_99_007: [**  DATA_MARSHALLER_INVALID_MODEL_PROPERTY shall be returned when any of the items in values contain invalid data **]**

**SRS_DATA_MARSHALLER_99_034: [** All argument checks shall be performed before calling any other modules. **]**

**SRS_DATA_MARSHALLER_99_027: [**  DATA_MARSHALLER_JSON_ENCODER_ERROR shall be returned when JSONEncoder returns an error code. **]**

**SRS_DATA_MARSHALLER_99_037: [** DataMarshaller shall store as MultiTree the data to be encoded by the JSONEncoder module. **]**

**SRS_DATA_MARSHALLER_99_035: [** DATA_MARSHALLER_MULTITREE_ERROR shall be returned in case any MultiTree API call fails. **]**

**SRS_DATA_MARSHALLER_99_036: [** DATA_MARSHALLER_AGENT_DATA_TYPES_ERROR shall be returned in case any AgentTypeSystem APIs fails. **]**

**SRS_DATAMARSHALLER_02_007: [** DataMarshaller_SendData shall copy in the output parameters *destination, *destinationSize the content and the content length of the encoded JSON tree. **]**

**SRS_DATA_MARSHALLER_99_015: [**  DATA_MARSHALLER_ERROR shall be returned in all the other error cases not explicitly defined here. **]**

Remarks:
	**SRS_DATA_MARSHALLER_99_038: [** For each pair in the values argument, a string:value pair shall exist in the JSON object in the form of propertyName:value. **]**

**SRS_DATA_MARSHALLER_99_039: [**  If the includePropertyPath argument passed to DataMarshaller_Create was true each property shall be placed in the appropriate position in the JSON according to its path in the model. **]**

**SRS_DATAMARSHALLER_01_001: [** If the includePropertyPath argument passed to DataMarshaller_Create was false and only one struct is being sent, the relative path of the value passed to DataMarshaller_SendData – including property name - shall be ignored and the value shall be placed at JSON root. **]**

**SRS_DATAMARSHALLER_01_004: [** In this case the members of the struct shall be added as leafs into the MultiTree, each leaf having the name of the struct member. **]**

**SRS_DATAMARSHALLER_01_002: [** If the includePropertyPath argument passed to DataMarshaller_Create was false and the number of values passed to SendData is greater than 1 and at least one of them is a struct, DataMarshaller_SendData shall fallback to  including the complete property path in the output JSON. **]**


text:
module.exports = function (grunt) {
    grunt.loadNpmTasks('grunt-karma');
    grunt.loadNpmTasks('grunt-contrib-jshint');

    // Default task.
    grunt.registerTask('default', ['karma', 'jshint']);

    var karmaConfig = function(configFile, customOptions) {
        var options = { configFile: configFile, keepalive: true };
        var travisOptions = process.env.TRAVIS && { browsers: ['Firefox'], reporters: 'dots' };
        return grunt.util._.extend(options, customOptions, travisOptions);
    };

    // Project configuration.
    grunt.initConfig({
        karma: {
            unit: {
            options: karmaConfig('test/test.conf.js')
            }
        },
        jshint:{
            files:['src/**/*.js', 'test/**/*.js', 'demo/js/controllers/todoCtrl.js'],
            options: {
                curly:true,
                eqeqeq:true,
                immed:true,
                latedef:true,
                newcap:true,
                noarg:true,
                sub:true,
                boss:true,
                eqnull:true,
                devel:true,
                globals:{}
            }
        }
    });
}


text:
Yet Another GetOpt Library For Go
=================================

By Tim Henderson (tim.tadh@gmail.com)

BSD Licenced

Motivation
----------

The existing libraries[1,2,3,4] don't exactly work how I would like them to
work. Specifically, I want it to work exactly like how the Python `getopt`
module works. The reason being, that particular implementation has proven
through years of use to be incredibly scalable and flexible. While, there are
definitely easier to use approaches (see for instance `argparse`) none have the
flexibility of the simple `getopt`.

The current solutions also try to do too much while not implementing the basic
functionality in a sensible way. This library will simply pull out a list of the
flags found, and their options (as strings). Parsing the arguments into Go
datatypes will be up to the user of the library.

### Todo

1. Lots more tests (currently it only tests basic functionality, complex
   situations are probably missed.)

### Contributing

1. "Fork"
2. Make a feature branch.
3. Do your commits
4. Send "pull request". This can be
    1. A github pull request
    2. A issue with a pointer to your publicly readable git repo
    3. An email to me with a pointer to your publicly readable git repo

Docs
----

    PACKAGE

    package getopt
        import "github.com/timtadh/getopt"

    FUNCTIONS

    func GetOpt(
        args []string,
        shortopts string,
        longopts []string,
    ) (
        leftovers []string,
        optargs []OptArg,
        err error,
    )
        GetOpt works like `getopt` in python's `getopt` module in the stdlib
        (modulus implementation bugs).

        params

      args - the argv []string slice
      shortopts - a string of options (similar to what GNU's getopt excepts).
                  Options which desire an argument should have a colon, ":",
                  subsequent to them. There are no optional arguments at this
                  time.
                  ex. "hvx:r" would accept -h -v -x asdf -r
      longopts - a list of strings which describe the long options (eg those with
                 "--" in front). Placing an = on the end indicates a required
                 argument.
                 ex. []string{"help", "example="}
                   would accept --help --example=tom

    TYPES

    type OptArg interface {
        Opt() string
        Arg() string
    }
        The GetOpt function will return a list of OptArgs. If there is no arg
        then Arg() will return "". Opt will contain a leading "-" for short and
        "--" for long args.

#### Footnotes

- [1] flag
- [2] https://github.com/droundy/goopt
- [3] https://github.com/jteeuwen/go-pkg-optarg
- [4] https://github.com/kesselborn/go-getopt


text:
cask "zappy" do
  version "3.1.3"
  sha256 "e1ed595cef62d0550a2eac1591e35f9a7fff3d1d0e51d965bf986a1dffd94a25"

  url "https://zappy.zapier.com/releases/zappy-#{version}.dmg"
  name "Zappy"
  desc "Screen capture tool for remote teams"
  homepage "https://zapier.com/zappy"

  livecheck do
    url "https://zappy.zapier.com/releases/appcast.xml"
    strategy :sparkle
  end

  auto_updates true
  depends_on macos: ">= :catalina"

  app "Zappy.app"

  uninstall quit: "com.blackbeltlabs.Zappy"

  zap trash: [
    "~/Library/Application Support/com.blackbeltlabs.Zappy",
    "~/Library/Caches/com.blackbeltlabs.Zappy",
    "~/Library/Preferences/com.blackbeltlabs.Zappy.plist",
    "~/Library/zappy",
  ]
end


text:
import find from '../jsutils/find'
import invariant from '../jsutils/invariant'
import keyValMap from '../jsutils/keyValMap'
import { valueFromAST } from 'graphql/utilities/valueFromAST'
import { TokenKind } from 'graphql/language/lexer'
import { parse } from 'graphql/language/parser'
import { Source } from 'graphql/language/source'
import { getArgumentValues } from '../execution/values'

import {
  GraphQLTypeResolver,
  GraphQLFieldResolver,
  GraphQLError,
} from 'graphql'

import {
  LIST_TYPE,
  NON_NULL_TYPE,
  DOCUMENT,
  SCHEMA_DEFINITION,
  SCALAR_TYPE_DEFINITION,
  OBJECT_TYPE_DEFINITION,
  INTERFACE_TYPE_DEFINITION,
  ENUM_TYPE_DEFINITION,
  UNION_TYPE_DEFINITION,
  INPUT_OBJECT_TYPE_DEFINITION,
  DIRECTIVE_DEFINITION,
} from 'graphql/language/kinds'

import {
  Location,
  DocumentNode,
  DirectiveNode,
  TypeNode,
  NamedTypeNode,
  SchemaDefinitionNode,
  TypeDefinitionNode,
  ScalarTypeDefinitionNode,
  ObjectTypeDefinitionNode,
  InputValueDefinitionNode,
  InterfaceTypeDefinitionNode,
  UnionTypeDefinitionNode,
  EnumTypeDefinitionNode,
  InputObjectTypeDefinitionNode,
  DirectiveDefinitionNode,
  FieldDefinitionNode,
} from 'graphql/language/ast'

import { GraphQLSchema } from 'graphql/type/schema'

import {
  GraphQLString,
  GraphQLInt,
  GraphQLFloat,
  GraphQLBoolean,
  GraphQLID,
} from 'graphql/type/scalars'

import {
  GraphQLScalarType,
  GraphQLObjectType,
  GraphQLInterfaceType,
  GraphQLUnionType,
  GraphQLEnumType,
  GraphQLInputObjectType,
  GraphQLList,
  GraphQLNonNull,
  isInputType,
  isOutputType,
} from 'graphql/type/definition'

import { GraphQLObjectTypeExt } from '../type/object'

import {
  GraphQLType,
  GraphQLNamedType,
  GraphQLInputType,
  GraphQLOutputType,
  GraphQLInputFieldConfigMap,
  GraphQLFieldConfigArgumentMap,
} from 'graphql/type/definition'

import {
  GraphQLDirective,
  GraphQLSkipDirective,
  GraphQLIncludeDirective,
  GraphQLDeprecatedDirective,
} from 'graphql/type/directives'

import {
  GraphQLRelationDirective,
  GraphQLDirectiveValue,
} from '../type/directives'

import {
  GraphQLFieldConfigMapExt,
  GraphQLFieldConfigExt,
} from '../type/object'

import {
  __Schema,
  __Directive,
  __DirectiveLocation,
  __Type,
  __Field,
  __InputValue,
  __EnumValue,
  __TypeKind,
} from 'graphql/type/introspection'

import {
  TypeResolverMap,
} from './ResolverMap'

import {
  locationForDirectiveDefinition,
} from './locationForDirectiveDefinition'

function buildWrappedType(
  innerType: GraphQLType,
  inputTypeNode: TypeNode,
): GraphQLType {
  if (inputTypeNode.kind === LIST_TYPE) {
    return new GraphQLList(buildWrappedType(innerType, inputTypeNode.type))
  }
  if (inputTypeNode.kind === NON_NULL_TYPE) {
    const wrappedType = buildWrappedType(innerType, inputTypeNode.type)
    invariant(!(wrappedType instanceof GraphQLNonNull), 'No nesting nonnull.')
    return new GraphQLNonNull(wrappedType)
  }
  return innerType
}

function getNamedTypeNode(typeNode: TypeNode): NamedTypeNode {
  let namedType = typeNode
  while (namedType.kind === LIST_TYPE || namedType.kind === NON_NULL_TYPE) {
    namedType = namedType.type
  }
  return namedType
}

// <TSource, TContext> = (
//   schema: GraphQLSchema,
//   type: GraphQLObjectType,
//   field: GraphQLField<TSource, TContext>,
// ) => GraphQLFieldResolver<TSource, TContext> | null

/**
 * This takes the ast of a schema document produced by the parse function in
 * src/language/parser.js.
 *
 * If no schema definition is provided, then it will look for types named Query
 * and Mutation.
 *
 * Given that AST it constructs a GraphQLSchema. The resulting schema
 * has no resolve methods, so execution will use default resolvers.
 */
export function buildASTSchema(
  ast: DocumentNode,
  resolverMap: TypeResolverMap<mixed, mixed> = {},
): GraphQLSchema {
  if (!ast || ast.kind !== DOCUMENT) {
    throw new Error('Must provide a document ast.')
  }

  let schemaDef: SchemaDefinitionNode | null = null

  const typeDefs: Array<TypeDefinitionNode> = []
  const nodeMap: {[name: string]: TypeDefinitionNode} = Object.create(null)
  const directiveDefs: Array<DirectiveDefinitionNode> = []
  for (let d of ast.definitions) {
    switch (d.kind) {
      case SCHEMA_DEFINITION:
        if (schemaDef) {
          throw new Error('Must provide only one schema definition.')
        }
        schemaDef = d
        break
      case SCALAR_TYPE_DEFINITION:
      case OBJECT_TYPE_DEFINITION:
      case INTERFACE_TYPE_DEFINITION:
      case ENUM_TYPE_DEFINITION:
      case UNION_TYPE_DEFINITION:
      case INPUT_OBJECT_TYPE_DEFINITION:
        typeDefs.push(d)
        nodeMap[d.name.value] = d
        break
      case DIRECTIVE_DEFINITION:
        directiveDefs.push(d)
        break
      default:
        break
    }
  }

  let queryTypeName: string | null = null
  let mutationTypeName: string | null = null
  let subscriptionTypeName: string | null = null
  if (schemaDef) {
    schemaDef.operationTypes.forEach(operationType => {
      const typeName = operationType.type.name.value
      if (operationType.operation === 'query') {
        if (queryTypeName) {
          throw new Error('Must provide only one query type in schema.')
        }
        if (!nodeMap[typeName]) {
          throw new Error(
            `Specified query type "${typeName}" not found in document.`,
          )
        }
        queryTypeName = typeName
      } else if (operationType.operation === 'mutation') {
        if (mutationTypeName) {
          throw new Error('Must provide only one mutation type in schema.')
        }
        if (!nodeMap[typeName]) {
          throw new Error(
            `Specified mutation type "${typeName}" not found in document.`,
          )
        }
        mutationTypeName = typeName
      } else if (operationType.operation === 'subscription') {
        if (subscriptionTypeName) {
          throw new Error('Must provide only one subscription type in schema.')
        }
        if (!nodeMap[typeName]) {
          throw new Error(
            `Specified subscription type "${typeName}" not found in document.`,
          )
        }
        subscriptionTypeName = typeName
      }
    })
  } else {
    if (nodeMap.Query) {
      queryTypeName = 'Query'
    }
    if (nodeMap.Mutation) {
      mutationTypeName = 'Mutation'
    }
    if (nodeMap.Subscription) {
      subscriptionTypeName = 'Subscription'
    }
  }

  if (!queryTypeName) {
    throw new Error(
      'Must provide schema definition with query type or a type named Query.',
    )
  }

  const innerTypeMap = {
    String: GraphQLString,
    Int: GraphQLInt,
    Float: GraphQLFloat,
    Boolean: GraphQLBoolean,
    ID: GraphQLID,
    __Schema,
    __Directive,
    __DirectiveLocation,
    __Type,
    __Field,
    __InputValue,
    __EnumValue,
    __TypeKind,
  }

  const types = typeDefs.map(def => typeDefNamed(def.name.value))

  const directives = directiveDefs.map(getDirective)

  // If specified directives were not explicitly declared, add them.
  if (!directives.some(directive => directive.name === 'skip')) {
    directives.push(GraphQLSkipDirective)
  }

  if (!directives.some(directive => directive.name === 'include')) {
    directives.push(GraphQLIncludeDirective)
  }

  if (!directives.some(directive => directive.name === 'deprecated')) {
    directives.push(GraphQLDeprecatedDirective)
  }

  if (!directives.some(directive => directive.name === 'relation')) {
    directives.push(GraphQLRelationDirective)
  }

  return new GraphQLSchema({
    query: getObjectType(nodeMap[queryTypeName]),
    mutation: mutationTypeName ?
      getObjectType(nodeMap[mutationTypeName]) :
      undefined,
    subscription: subscriptionTypeName ?
      getObjectType(nodeMap[subscriptionTypeName]) :
      undefined,
    types,
    directives,
  })

  function getDirective(
    directiveNode: DirectiveDefinitionNode,
  ): GraphQLDirective {
    return new GraphQLDirective({
      name: directiveNode.name.value,
      description: getDescription(directiveNode),
      locations: directiveNode.locations.map(
        node => node.value,
      ),
      args: directiveNode.arguments && makeInputValues(directiveNode.arguments) as GraphQLFieldConfigArgumentMap,
    })
  }

  function getObjectType(typeNode: TypeDefinitionNode): GraphQLObjectType {
    const type = typeDefNamed(typeNode.name.value)
    invariant(
      type instanceof GraphQLObjectType,
      'AST must provide object type.',
    )
    return type as GraphQLObjectType
  }

  function produceType(typeNode: TypeNode): GraphQLType {
    const typeName = getNamedTypeNode(typeNode).name.value
    const typeDef = typeDefNamed(typeName)
    return buildWrappedType(typeDef, typeNode)
  }

  function produceInputType(typeNode: TypeNode): GraphQLInputType {
    const type = produceType(typeNode)
    invariant(isInputType(type), 'Expected Input type.')
    return type as GraphQLInputType
  }

  function produceOutputType(typeNode: TypeNode): GraphQLOutputType {
    const type = produceType(typeNode)
    invariant(isOutputType(type), 'Expected Output type.')
    return type as GraphQLOutputType
  }

  function produceObjectType(typeNode: TypeNode): GraphQLObjectType {
    const type = produceType(typeNode)
    invariant(type instanceof GraphQLObjectType, 'Expected Object type.')
    return type as GraphQLObjectType
  }

  function produceInterfaceType(typeNode: TypeNode): GraphQLInterfaceType {
    const type = produceType(typeNode)
    invariant(type instanceof GraphQLInterfaceType, 'Expected Interface type.')
    return type as GraphQLInterfaceType
  }

  function produceDirectiveValue(
    def: ObjectTypeDefinitionNode | FieldDefinitionNode,
    directiveNode: DirectiveNode,
  ): GraphQLDirectiveValue {
    const directiveType = directives.find(o => o.name === directiveNode.name.value)
    const directive = directives.find(dir => dir.name === directiveNode.name.value)
    if (!directiveType || !directive) {
      throw new GraphQLError(
        `Unrecognized directive ${directiveNode.name.value} found on schema`,
        [directiveNode],
        undefined,
      )
    }
    return new GraphQLDirectiveValue({
      name: directiveNode.name.value,
      description: getDescription(directiveNode),
      args: getArgumentValues(directiveType, directiveNode),
      location: locationForDirectiveDefinition(directive, def),
    })
  }

  function typeDefNamed(typeName: string): GraphQLNamedType {
    if (innerTypeMap[typeName]) {
      return innerTypeMap[typeName]
    }

    if (!nodeMap[typeName]) {
      throw new Error(`Type "${typeName}" not found in document.`)
    }

    const innerTypeDef = makeSchemaDef(nodeMap[typeName])
    if (!innerTypeDef) {
      throw new Error(`Nothing constructed for "${typeName}".`)
    }
    innerTypeMap[typeName] = innerTypeDef
    return innerTypeDef
  }

  function makeSchemaDef(def: TypeDefinitionNode): GraphQLObjectType | GraphQLInterfaceType | GraphQLEnumType | GraphQLUnionType | GraphQLInputObjectType | GraphQLScalarType {
    if (!def) {
      throw new Error('def must be defined')
    }
    switch (def.kind) {
      case OBJECT_TYPE_DEFINITION:
        return makeTypeDef(def)
      case INTERFACE_TYPE_DEFINITION:
        return makeInterfaceDef(def)
      case ENUM_TYPE_DEFINITION:
        return makeEnumDef(def)
      case UNION_TYPE_DEFINITION:
        return makeUnionDef(def)
      case SCALAR_TYPE_DEFINITION:
        return makeScalarDef(def)
      case INPUT_OBJECT_TYPE_DEFINITION:
        return makeInputObjectDef(def)
      default:
        throw new Error(`Type kind "${def}" not supported.`)
    }
  }

  function makeTypeDef(def: ObjectTypeDefinitionNode): GraphQLObjectType {
    const typeName = def.name.value
    return new GraphQLObjectTypeExt({
      name: typeName,
      description: getDescription(def),
      fields: () => makeObjectFieldDefMap(def),
      interfaces: () => makeImplementedInterfaces(def),
      directives: () => makeDirectiveValues(def),
    })
  }

  function getResolver(
    type: ObjectTypeDefinitionNode,
    field: FieldDefinitionNode,
  ): GraphQLFieldResolver<mixed, mixed> {
    if (resolverMap && resolverMap[type.name.value] && resolverMap[type.name.value][field.name.value]) {
      return resolverMap[type.name.value][field.name.value]
    }
    // If no resolver is defined, return the identity function.
    return (s: mixed) => s ? s[field.name.value] : s
  }

  function makeObjectFieldDefMap(
    def: ObjectTypeDefinitionNode,
  ): GraphQLFieldConfigMapExt<mixed, mixed> {
    return keyValMap<FieldDefinitionNode, GraphQLFieldConfigExt<mixed, mixed>> (
      def.fields,
      field => field.name.value,
      field => ({
        type: produceOutputType(field.type),
        description: getDescription(field),
        args: makeInputValues(field.arguments) as GraphQLFieldConfigArgumentMap,
        deprecationReason: getDeprecationReason(field.directives),
        directives: makeDirectiveValues(field),
        resolve: getResolver(def, field),
      }),
    )
  }

  function makeInterfaceFieldDefMap(
    def: InterfaceTypeDefinitionNode,
  ): GraphQLFieldConfigMapExt<mixed, mixed> {
    return keyValMap<FieldDefinitionNode, GraphQLFieldConfigExt<mixed, mixed>> (
      def.fields,
      field => field.name.value,
      field => ({
        type: produceOutputType(field.type),
        description: getDescription(field),
        args: makeInputValues(field.arguments) as GraphQLFieldConfigArgumentMap,
        deprecationReason: getDeprecationReason(field.directives),
        directives: makeDirectiveValues(field),
      }),
    )
  }

  function makeImplementedInterfaces(def: ObjectTypeDefinitionNode): Array<GraphQLInterfaceType> {
    return def.interfaces ?
      def.interfaces.map(iface => produceInterfaceType(iface)) :
      []
  }

  function makeDirectiveValues(def: ObjectTypeDefinitionNode | FieldDefinitionNode): Array<GraphQLDirectiveValue> {
    return def.directives ?
      def.directives.map(dir => produceDirectiveValue(def, dir)) :
      []
  }

  function makeInputValues(values: Array<InputValueDefinitionNode>): { [name: string]: mixed } {
    return keyValMap(
      values,
      value => value.name.value,
      value => {
        const type = produceInputType(value.type)
        return {
          type,
          description: getDescription(value),
          defaultValue: valueFromAST(value.defaultValue!, type),
        }
      },
    )
  }

  function makeInterfaceDef(def: InterfaceTypeDefinitionNode): GraphQLInterfaceType {
    const typeName = def.name.value
    return new GraphQLInterfaceType({
      name: typeName,
      description: getDescription(def),
      fields: () => makeInterfaceFieldDefMap(def),
      resolveType: cannotExecuteSchema,
    })
  }

  function makeEnumDef(def: EnumTypeDefinitionNode): GraphQLEnumType {
    const enumType = new GraphQLEnumType({
      name: def.name.value,
      description: getDescription(def),
      values: keyValMap(
        def.values,
        enumValue => enumValue.name.value,
        enumValue => ({
          description: getDescription(enumValue),
          deprecationReason: getDeprecationReason(enumValue.directives),
        }),
      ),
    })

    return enumType
  }

  function makeUnionDef(def: UnionTypeDefinitionNode): GraphQLUnionType {
    return new GraphQLUnionType({
      name: def.name.value,
      description: getDescription(def),
      types: def.types.map(t => produceObjectType(t)),
      resolveType: cannotExecuteSchema,
    })
  }

  function makeScalarDef(def: ScalarTypeDefinitionNode): GraphQLScalarType {
    return new GraphQLScalarType({
      name: def.name.value,
      description: getDescription(def),
      serialize: () => null,
      // Note: validation calls the parse functions to determine if a
      // literal value is correct. Returning null would cause use of custom
      // scalars to always fail validation. Returning false causes them to
      // always pass validation.
      parseValue: () => false,
      parseLiteral: () => false,
    })
  }

  function makeInputObjectDef(def: InputObjectTypeDefinitionNode): GraphQLInputObjectType {
    return new GraphQLInputObjectType({
      name: def.name.value,
      description: getDescription(def),
      fields: () => makeInputValues(def.fields) as GraphQLInputFieldConfigMap,
    })
  }
}

/**
 * Given a collection of directives, returns the string value for the
 * deprecation reason.
 */
export function getDeprecationReason(
  directives?: Array<DirectiveNode>,
): string | undefined {
  const deprecatedAST = directives && find(
    directives,
    directive => directive.name.value === GraphQLDeprecatedDirective.name,
  )
  if (!deprecatedAST) {
    return
  }
  const { reason } = getArgumentValues(
    GraphQLDeprecatedDirective,
    deprecatedAST,
  )
  return reason as string
}

/**
 * Given an ast node, returns its string description based on a contiguous
 * block full-line of comments preceding it.
 */
export function getDescription(node: { loc?: Location }): string | undefined {
  const loc = node.loc
  if (!loc) {
    return
  }
  const comments = []
  let minSpaces: number | undefined = undefined
  let token = loc.startToken.prev
  while (
    token &&
    token.kind === TokenKind.COMMENT &&
    token.next && token.prev &&
    token.line + 1 === token.next.line &&
    token.line !== token.prev.line
  ) {
    const value = String(token.value)
    const spaces = leadingSpaces(value)
    if (minSpaces === undefined || spaces < minSpaces) {
      minSpaces = spaces
    }
    comments.push(value)
    token = token.prev
  }
  return comments
    .reverse()
    .map(comment => comment.slice(minSpaces))
    .join('\n')
}

/**
 * A helper function to build a GraphQLSchema directly from a source
 * document.
 */
export function buildSchema(source: string | Source): GraphQLSchema {
  return buildASTSchema(parse(source))
}

// Count the number of spaces on the starting side of a string.
function leadingSpaces(str: string): number {
  let i = 0
  for (; i < str.length; i++) {
    if (str[i] !== ' ') {
      break
    }
  }
  return i
}

const cannotExecuteSchema: GraphQLTypeResolver<mixed, mixed> = () => {
  throw new Error(
    'Generated Schema cannot use Interface or Union types for execution.',
  )
}


text:
Spree::Promotion.class_eval do

  has_one :image, :as => :viewable, :dependent => :destroy, :class_name => "Spree::PromotionImage"
  accepts_nested_attributes_for :image, :reject_if => lambda { |i| i[:attachment].blank? && i[:_destroy] != "1" }, :allow_destroy => true
  attr_accessible :image_attributes, :image

end


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<!--

 Copyright 2003 - 2012 The eFaps Team

 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.

 Author:          The eFaps Team
 Revision:        $Rev: 5752 $
 Last Changed:    $Date: 2010-10-27 13:08:36 -0500 (mié, 27 oct 2010) $
 Last Changed By: $Author: jan.moxter $

-->

<datamodel-type xmlns="http://www.efaps.org/xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.efaps.org/xsd http://www.efaps.org/xsd/eFaps_1.0.xsd">

    <uuid>de6ba9c3-eba1-4e0f-afac-c2a470666a77</uuid>
    <file-application>eFapsApp-Sales</file-application>
    <file-revision>$Rev: 5752 $</file-revision>
    <definition>
        <version-expression>(version==latest)</version-expression>
        <name>Sales_EventScheduleAbstract</name>
        <parent>ERP_EventScheduleAbstract</parent>
        <purpose abstract="true"/>
    </definition>
</datamodel-type>


text:
using namespace json_spirit;
using namespace std;

Value getconnectioncount(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getconnectioncount\n"
            "\nReturns the number of connections to other nodes.\n"
            "\nbResult:\n"
            "n          (numeric) The connection count\n"
            "\nExamples:\n" +
            HelpExampleCli("getconnectioncount", "") + HelpExampleRpc("getconnectioncount", ""));

    LOCK2(cs_main, cs_vNodes);

    return (int)vNodes.size();
}

Value ping(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "ping\n"
            "\nRequests that a ping be sent to all other nodes, to measure ping time.\n"
            "Results provided in getpeerinfo, pingtime and pingwait fields are decimal seconds.\n"
            "Ping command is handled in queue with all other commands, so it measures processing backlog, not just network ping.\n"
            "\nExamples:\n" +
            HelpExampleCli("ping", "") + HelpExampleRpc("ping", ""));

    // Request that each node send a ping during next message processing pass
    LOCK2(cs_main, cs_vNodes);

    BOOST_FOREACH (CNode* pNode, vNodes) {
        pNode->fPingQueued = true;
    }

    return Value::null;
}

static void CopyNodeStats(std::vector<CNodeStats>& vstats)
{
    vstats.clear();

    LOCK(cs_vNodes);
    vstats.reserve(vNodes.size());
    BOOST_FOREACH (CNode* pnode, vNodes) {
        CNodeStats stats;
        pnode->copyStats(stats);
        vstats.push_back(stats);
    }
}

Value getpeerinfo(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getpeerinfo\n"
            "\nReturns data about each connected network node as a json array of objects.\n"
            "\nbResult:\n"
            "[\n"
            "  {\n"
            "    \"id\": n,                   (numeric) Peer index\n"
            "    \"addr\":\"host:port\",      (string) The ip address and port of the peer\n"
            "    \"addrlocal\":\"ip:port\",   (string) local address\n"
            "    \"services\":\"xxxxxxxxxxxxxxxx\",   (string) The services offered\n"
            "    \"lastsend\": ttt,           (numeric) The time in seconds since epoch (Jan 1 1970 GMT) of the last send\n"
            "    \"lastrecv\": ttt,           (numeric) The time in seconds since epoch (Jan 1 1970 GMT) of the last receive\n"
            "    \"bytessent\": n,            (numeric) The total bytes sent\n"
            "    \"bytesrecv\": n,            (numeric) The total bytes received\n"
            "    \"conntime\": ttt,           (numeric) The connection time in seconds since epoch (Jan 1 1970 GMT)\n"
            "    \"timeoffset\": ttt,         (numeric) The time offset in seconds\n"
            "    \"pingtime\": n,             (numeric) ping time\n"
            "    \"pingwait\": n,             (numeric) ping wait\n"
            "    \"version\": v,              (numeric) The peer version, such as 7001\n"
            "    \"subver\": \"/Satoshi:0.8.5/\",  (string) The string version\n"
            "    \"inbound\": true|false,     (boolean) Inbound (true) or Outbound (false)\n"
            "    \"startingheight\": n,       (numeric) The starting height (block) of the peer\n"
            "    \"banscore\": n,             (numeric) The ban score\n"
            "    \"synced_headers\": n,       (numeric) The last header we have in common with this peer\n"
            "    \"synced_blocks\": n,        (numeric) The last block we have in common with this peer\n"
            "    \"inflight\": [\n"
            "       n,                        (numeric) The heights of blocks we're currently asking from this peer\n"
            "       ...\n"
            "    ]\n"
            "  }\n"
            "  ,...\n"
            "]\n"
            "\nExamples:\n" +
            HelpExampleCli("getpeerinfo", "") + HelpExampleRpc("getpeerinfo", ""));

    LOCK(cs_main);

    vector<CNodeStats> vstats;
    CopyNodeStats(vstats);

    Array ret;

    BOOST_FOREACH (const CNodeStats& stats, vstats) {
        Object obj;
        CNodeStateStats statestats;
        bool fStateStats = GetNodeStateStats(stats.nodeid, statestats);
        obj.push_back(Pair("id", stats.nodeid));
        obj.push_back(Pair("addr", stats.addrName));
        if (!(stats.addrLocal.empty()))
            obj.push_back(Pair("addrlocal", stats.addrLocal));
        obj.push_back(Pair("services", strprintf("%016x", stats.nServices)));
        obj.push_back(Pair("lastsend", stats.nLastSend));
        obj.push_back(Pair("lastrecv", stats.nLastRecv));
        obj.push_back(Pair("bytessent", stats.nSendBytes));
        obj.push_back(Pair("bytesrecv", stats.nRecvBytes));
        obj.push_back(Pair("conntime", stats.nTimeConnected));
        obj.push_back(Pair("timeoffset", stats.nTimeOffset));
        obj.push_back(Pair("pingtime", stats.dPingTime));
        if (stats.dPingWait > 0.0)
            obj.push_back(Pair("pingwait", stats.dPingWait));
        obj.push_back(Pair("version", stats.nVersion));
        // Use the sanitized form of subver here, to avoid tricksy remote peers from
        // corrupting or modifiying the JSON output by putting special characters in
        // their ver message.
        obj.push_back(Pair("subver", stats.cleanSubVer));
        obj.push_back(Pair("inbound", stats.fInbound));
        obj.push_back(Pair("startingheight", stats.nStartingHeight));
        if (fStateStats) {
            obj.push_back(Pair("banscore", statestats.nMisbehavior));
            obj.push_back(Pair("synced_headers", statestats.nSyncHeight));
            obj.push_back(Pair("synced_blocks", statestats.nCommonHeight));
            Array heights;
            BOOST_FOREACH (int height, statestats.vHeightInFlight) {
                heights.push_back(height);
            }
            obj.push_back(Pair("inflight", heights));
        }
        obj.push_back(Pair("whitelisted", stats.fWhitelisted));

        ret.push_back(obj);
    }

    return ret;
}

Value gettrafficshaping(const Array& params, bool fHelp)
{
    string strCommand;
    if (params.size() == 1) {
        strCommand = params[0].get_str();
    }

    if (fHelp || (params.size() != 0))
        throw runtime_error(
            "gettrafficshaping"
            "\nReturns the current settings for the network send and receive bandwidth and burst in kilobytes per second.\n"
            "\nArguments: None\n"
            "\nResult:\n"
            "  {\n"
            "    \"sendBurst\" : 40,   (string) The maximum send bandwidth in Kbytes/sec\n"
            "    \"sendAve\" : 30,   (string) The average send bandwidth in Kbytes/sec\n"
            "    \"recvBurst\" : 20,   (string) The maximum receive bandwidth in Kbytes/sec\n"
            "    \"recvAve\" : 10,   (string) The average receive bandwidth in Kbytes/sec\n"
            "  }\n"
            "\n NOTE: if the send and/or recv parameters do not exist, shaping in that direction is disabled.\n"
            "\nExamples:\n" +
            HelpExampleCli("gettrafficshaping", "") + HelpExampleRpc("gettrafficshaping", ""));
    Object ret;
    int64_t max, ave;
    sendShaper.get(&max, &ave);
    if (ave != LONG_MAX) {
        ret.push_back(Pair("sendBurst", max / 1024));
        ret.push_back(Pair("sendAve", ave / 1024));
    }
    receiveShaper.get(&max, &ave);
    if (ave != LONG_MAX) {
        ret.push_back(Pair("recvBurst", max / 1024));
        ret.push_back(Pair("recvAve", ave / 1024));
    }
    return ret;
}

Value settrafficshaping(const Array& params, bool fHelp)
{
    bool disable = false;
    bool badArg = false;
    string strCommand;
    CLeakyBucket* bucket = NULL;
    if (params.size() >= 2) {
        strCommand = params[0].get_str();
        if (strCommand == "send")
            bucket = &sendShaper;
        if (strCommand == "receive")
            bucket = &receiveShaper;
        if (strCommand == "recv")
            bucket = &receiveShaper;
    }
    if (params.size() == 2) {
        if (params[1].get_str() == "disable")
            disable = true;
        else
            badArg = true;
    } else if (params.size() != 3)
        badArg = true;

    if (fHelp || badArg || bucket == NULL)
        throw runtime_error(
            "settrafficshaping \"send|receive\" \"burstKB\" \"averageKB\""
            "\nSets the network send or receive bandwidth and burst in kilobytes per second.\n"
            "\nArguments:\n"
            "1. \"send|receive\"     (string, required) Are you setting the transmit or receive bandwidth\n"
            "2. \"burst\"  (integer, required) Specify the maximum burst size in Kbytes/sec (actual max will be 1 packet larger than this number)\n"
            "2. \"average\"  (integer, required) Specify the average throughput in Kbytes/sec\n"
            "\nExamples:\n" +
            HelpExampleCli("settrafficshaping", "\"receive\" 10000 1024") + HelpExampleCli("settrafficshaping", "\"receive\" disable") + HelpExampleRpc("settrafficshaping", "\"receive\" 10000 1024"));

    if (disable) {
        if (bucket)
            bucket->disable();
    } else {
        uint64_t burst;
        uint64_t ave;
        if (params[1].is_uint64())
            burst = params[1].get_uint64();
        else {
            string temp = params[1].get_str();
            burst = boost::lexical_cast<uint64_t>(temp);
        }
        if (params[2].is_uint64())
            ave = params[2].get_uint64();
        else {
            string temp = params[2].get_str();
            ave = boost::lexical_cast<uint64_t>(temp);
        }
        if (burst < ave) {
            throw runtime_error("Burst rate must be greater than the average rate"
                                "\nsettrafficshaping \"send|receive\" \"burst\" \"average\"");
        }

        bucket->set(burst * 1024, ave * 1024);
    }

    return Value::null;
}

Value addnode(const Array& params, bool fHelp)
{
    string strCommand;
    if (params.size() == 2)
        strCommand = params[1].get_str();
    if (fHelp || params.size() != 2 ||
        (strCommand != "onetry" && strCommand != "add" && strCommand != "remove"))
        throw runtime_error(
            "addnode \"node\" \"add|remove|onetry\"\n"
            "\nAttempts add or remove a node from the addnode list.\n"
            "Or try a connection to a node once.\n"
            "\nArguments:\n"
            "1. \"node\"     (string, required) The node (see getpeerinfo for nodes)\n"
            "2. \"command\"  (string, required) 'add' to add a node to the list, 'remove' to remove a node from the list, 'onetry' to try a connection to the node once\n"
            "\nExamples:\n" +
            HelpExampleCli("addnode", "\"192.168.0.6:8333\" \"onetry\"") + HelpExampleRpc("addnode", "\"192.168.0.6:8333\", \"onetry\""));

    string strNode = params[0].get_str();

    if (strCommand == "onetry") {
        CAddress addr;
        OpenNetworkConnection(addr, NULL, strNode.c_str());
        return Value::null;
    }

    LOCK(cs_vAddedNodes);
    vector<string>::iterator it = vAddedNodes.begin();
    for (; it != vAddedNodes.end(); it++)
        if (strNode == *it)
            break;

    if (strCommand == "add") {
        if (it != vAddedNodes.end())
            throw JSONRPCError(RPC_CLIENT_NODE_ALREADY_ADDED, "Error: Node already added");
        vAddedNodes.push_back(strNode);
    } else if (strCommand == "remove") {
        if (it == vAddedNodes.end())
            throw JSONRPCError(RPC_CLIENT_NODE_NOT_ADDED, "Error: Node has not been added.");
        vAddedNodes.erase(it);
    }

    return Value::null;
}

Value getaddednodeinfo(const Array& params, bool fHelp)
{
    if (fHelp || params.size() < 1 || params.size() > 2)
        throw runtime_error(
            "getaddednodeinfo dns ( \"node\" )\n"
            "\nReturns information about the given added node, or all added nodes\n"
            "(note that onetry addnodes are not listed here)\n"
            "If dns is false, only a list of added nodes will be provided,\n"
            "otherwise connected information will also be available.\n"
            "\nArguments:\n"
            "1. dns        (boolean, required) If false, only a list of added nodes will be provided, otherwise connected information will also be available.\n"
            "2. \"node\"   (string, optional) If provided, return information about this specific node, otherwise all nodes are returned.\n"
            "\nResult:\n"
            "[\n"
            "  {\n"
            "    \"addednode\" : \"192.168.0.201\",   (string) The node ip address\n"
            "    \"connected\" : true|false,          (boolean) If connected\n"
            "    \"addresses\" : [\n"
            "       {\n"
            "         \"address\" : \"192.168.0.201:8333\",  (string) The bitcoin server host and port\n"
            "         \"connected\" : \"outbound\"           (string) connection, inbound or outbound\n"
            "       }\n"
            "       ,...\n"
            "     ]\n"
            "  }\n"
            "  ,...\n"
            "]\n"
            "\nExamples:\n" +
            HelpExampleCli("getaddednodeinfo", "true") + HelpExampleCli("getaddednodeinfo", "true \"192.168.0.201\"") + HelpExampleRpc("getaddednodeinfo", "true, \"192.168.0.201\""));

    bool fDns = params[0].get_bool();

    list<string> laddedNodes(0);
    if (params.size() == 1) {
        LOCK(cs_vAddedNodes);
        BOOST_FOREACH (string& strAddNode, vAddedNodes)
            laddedNodes.push_back(strAddNode);
    } else {
        string strNode = params[1].get_str();
        LOCK(cs_vAddedNodes);
        BOOST_FOREACH (string& strAddNode, vAddedNodes)
            if (strAddNode == strNode) {
                laddedNodes.push_back(strAddNode);
                break;
            }
        if (laddedNodes.size() == 0)
            throw JSONRPCError(RPC_CLIENT_NODE_NOT_ADDED, "Error: Node has not been added.");
    }

    Array ret;
    if (!fDns) {
        BOOST_FOREACH (string& strAddNode, laddedNodes) {
            Object obj;
            obj.push_back(Pair("addednode", strAddNode));
            ret.push_back(obj);
        }
        return ret;
    }

    list<pair<string, vector<CService> > > laddedAddreses(0);
    BOOST_FOREACH (string& strAddNode, laddedNodes) {
        vector<CService> vservNode(0);
        if (Lookup(strAddNode.c_str(), vservNode, Params().GetDefaultPort(), fNameLookup, 0))
            laddedAddreses.push_back(make_pair(strAddNode, vservNode));
        else {
            Object obj;
            obj.push_back(Pair("addednode", strAddNode));
            obj.push_back(Pair("connected", false));
            Array addresses;
            obj.push_back(Pair("addresses", addresses));
        }
    }

    LOCK(cs_vNodes);
    for (list<pair<string, vector<CService> > >::iterator it = laddedAddreses.begin(); it != laddedAddreses.end(); it++) {
        Object obj;
        obj.push_back(Pair("addednode", it->first));

        Array addresses;
        bool fConnected = false;
        BOOST_FOREACH (CService& addrNode, it->second) {
            bool fFound = false;
            Object node;
            node.push_back(Pair("address", addrNode.ToString()));
            BOOST_FOREACH (CNode* pnode, vNodes)
                if (pnode->addr == addrNode) {
                    fFound = true;
                    fConnected = true;
                    node.push_back(Pair("connected", pnode->fInbound ? "inbound" : "outbound"));
                    break;
                }
            if (!fFound)
                node.push_back(Pair("connected", "false"));
            addresses.push_back(node);
        }
        obj.push_back(Pair("connected", fConnected));
        obj.push_back(Pair("addresses", addresses));
        ret.push_back(obj);
    }

    return ret;
}

Value getnettotals(const Array& params, bool fHelp)
{
    if (fHelp || params.size() > 0)
        throw runtime_error(
            "getnettotals\n"
            "\nReturns information about network traffic, including bytes in, bytes out,\n"
            "and current time.\n"
            "\nResult:\n"
            "{\n"
            "  \"totalbytesrecv\": n,   (numeric) Total bytes received\n"
            "  \"totalbytessent\": n,   (numeric) Total bytes sent\n"
            "  \"timemillis\": t        (numeric) Total cpu time\n"
            "}\n"
            "\nExamples:\n" +
            HelpExampleCli("getnettotals", "") + HelpExampleRpc("getnettotals", ""));

    Object obj;
    obj.push_back(Pair("totalbytesrecv", CNode::GetTotalBytesRecv()));
    obj.push_back(Pair("totalbytessent", CNode::GetTotalBytesSent()));
    obj.push_back(Pair("timemillis", GetTimeMillis()));
    return obj;
}

static Array GetNetworksInfo()
{
    Array networks;
    for (int n = 0; n < NET_MAX; ++n) {
        enum Network network = static_cast<enum Network>(n);
        if (network == NET_UNROUTABLE)
            continue;
        proxyType proxy;
        Object obj;
        GetProxy(network, proxy);
        obj.push_back(Pair("name", GetNetworkName(network)));
        obj.push_back(Pair("limited", IsLimited(network)));
        obj.push_back(Pair("reachable", IsReachable(network)));
        obj.push_back(Pair("proxy", proxy.IsValid() ? proxy.proxy.ToStringIPPort() : string()));
        obj.push_back(Pair("proxy_randomize_credentials", proxy.randomize_credentials));
        networks.push_back(obj);
    }
    return networks;
}

Value getnetworkinfo(const Array& params, bool fHelp)
{
    if (fHelp || params.size() != 0)
        throw runtime_error(
            "getnetworkinfo\n"
            "Returns an object containing various state info regarding P2P networking.\n"
            "\nResult:\n"
            "{\n"
            "  \"version\": xxxxx,                      (numeric) the server version\n"
            "  \"subversion\": \"/Satoshi:x.x.x/\",     (string) the server subversion string\n"
            "  \"protocolversion\": xxxxx,              (numeric) the protocol version\n"
            "  \"localservices\": \"xxxxxxxxxxxxxxxx\", (string) the services we offer to the network\n"
            "  \"timeoffset\": xxxxx,                   (numeric) the time offset\n"
            "  \"connections\": xxxxx,                  (numeric) the number of connections\n"
            "  \"networks\": [                          (array) information per network\n"
            "  {\n"
            "    \"name\": \"xxx\",                     (string) network (ipv4, ipv6 or onion)\n"
            "    \"limited\": true|false,               (boolean) is the network limited using -onlynet?\n"
            "    \"reachable\": true|false,             (boolean) is the network reachable?\n"
            "    \"proxy\": \"host:port\"               (string) the proxy that is used for this network, or empty if none\n"
            "  }\n"
            "  ,...\n"
            "  ],\n"
            "  \"relayfee\": x.xxxxxxxx,                (numeric) minimum relay fee for non-free transactions in btc/kb\n"
            "  \"localaddresses\": [                    (array) list of local addresses\n"
            "  {\n"
            "    \"address\": \"xxxx\",                 (string) network address\n"
            "    \"port\": xxx,                         (numeric) network port\n"
            "    \"score\": xxx                         (numeric) relative score\n"
            "  }\n"
            "  ,...\n"
            "  ]\n"
            "}\n"
            "\nExamples:\n" +
            HelpExampleCli("getnetworkinfo", "") + HelpExampleRpc("getnetworkinfo", ""));

    LOCK(cs_main);

    Object obj;
    obj.push_back(Pair("version", CLIENT_VERSION));
    obj.push_back(Pair("subversion",
                       FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>())));
    obj.push_back(Pair("protocolversion", PROTOCOL_VERSION));
    obj.push_back(Pair("localservices", strprintf("%016x", nLocalServices)));
    obj.push_back(Pair("timeoffset", GetTimeOffset()));
    obj.push_back(Pair("connections", (int)vNodes.size()));
    obj.push_back(Pair("networks", GetNetworksInfo()));
    obj.push_back(Pair("relayfee", ValueFromAmount(::minRelayTxFee.GetFeePerK())));
    Array localAddresses;
    {
        LOCK(cs_mapLocalHost);
        BOOST_FOREACH (const PAIRTYPE(CNetAddr, LocalServiceInfo) & item, mapLocalHost) {
            Object rec;
            rec.push_back(Pair("address", item.first.ToString()));
            rec.push_back(Pair("port", item.second.nPort));
            rec.push_back(Pair("score", item.second.nScore));
            localAddresses.push_back(rec);
        }
    }
    obj.push_back(Pair("localaddresses", localAddresses));
    return obj;
}


text:
from __future__ import unicode_literals

from operator import itemgetter

from flask import session
from marshmallow import ValidationError, fields, post_dump, validate, validates_schema
from marshmallow.fields import Boolean, DateTime, Function, Method, Nested, Number, Pluck, String
from marshmallow_enum import EnumField

from indico.core.db.sqlalchemy.links import LinkType
from indico.core.db.sqlalchemy.protection import ProtectionMode
from indico.core.marshmallow import mm
from indico.modules.events.sessions.models.blocks import SessionBlock
from indico.modules.rb.models.blocked_rooms import BlockedRoom, BlockedRoomState
from indico.modules.rb.models.blockings import Blocking
from indico.modules.rb.models.equipment import EquipmentType
from indico.modules.rb.models.locations import Location
from indico.modules.rb.models.map_areas import MapArea
from indico.modules.rb.models.principals import RoomPrincipal
from indico.modules.rb.models.reservation_edit_logs import ReservationEditLog
from indico.modules.rb.models.reservation_occurrences import ReservationOccurrence
from indico.modules.rb.models.reservations import RepeatFrequency, Reservation, ReservationLink, ReservationState
from indico.modules.rb.models.room_attributes import RoomAttribute, RoomAttributeAssociation
from indico.modules.rb.models.room_bookable_hours import BookableHours
from indico.modules.rb.models.room_features import RoomFeature
from indico.modules.rb.models.room_nonbookable_periods import NonBookablePeriod
from indico.modules.rb.models.rooms import Room
from indico.modules.rb.util import rb_is_admin
from indico.modules.users.schemas import UserSchema
from indico.util.i18n import _
from indico.util.marshmallow import NaiveDateTime, Principal, PrincipalList, PrincipalPermissionList
from indico.util.string import natural_sort_key

class RoomAttributeValuesSchema(mm.ModelSchema):
    title = String(attribute='attribute.title')
    name = String(attribute='attribute.name')

    class Meta:
        model = RoomAttributeAssociation
        fields = ('value', 'title', 'name')

class AttributesSchema(mm.ModelSchema):
    class Meta:
        model = RoomAttribute
        fields = ('name', 'title', 'is_required', 'is_hidden')

class RoomSchema(mm.ModelSchema):
    owner_name = String(attribute='owner.full_name')

    class Meta:
        model = Room
        fields = ('id', 'name', 'capacity', 'building', 'floor', 'number', 'is_public', 'location_name', 'full_name',
                  'comments', 'division', 'is_reservable', 'reservations_need_confirmation', 'sprite_position',
                  'surface_area', 'latitude', 'longitude', 'telephone', 'key_location', 'max_advance_days',
                  'owner_name', 'available_equipment', 'has_photo', 'verbose_name')

class AdminRoomSchema(mm.ModelSchema):
    class Meta:
        modal = Room
        fields = ('id', 'location_id', 'name', 'full_name', 'sprite_position', 'owner_name', 'comments')

class RoomUpdateSchema(RoomSchema):
    owner = Principal()
    acl_entries = PrincipalPermissionList(RoomPrincipal)
    protection_mode = EnumField(ProtectionMode)

    class Meta(RoomSchema.Meta):
        fields = RoomSchema.Meta.fields + ('notification_before_days', 'notification_before_days_weekly', 'owner',
                                           'notification_before_days_monthly', 'notifications_enabled',
                                           'end_notification_daily', 'end_notification_weekly',
                                           'end_notification_monthly', 'end_notifications_enabled',
                                           'verbose_name', 'site', 'notification_emails', 'booking_limit_days',
                                           'acl_entries', 'protection_mode')

class RoomUpdateArgsSchema(mm.Schema):
    verbose_name = fields.String(allow_none=True)
    site = fields.String(allow_none=True)
    building = fields.String(validate=lambda x: x is not None)
    floor = fields.String(validate=lambda x: x is not None)
    number = fields.String(validate=lambda x: x is not None)
    longitude = fields.Float(allow_none=True)
    latitude = fields.Float(allow_none=True)
    is_reservable = fields.Boolean(allow_none=True)
    reservations_need_confirmation = fields.Boolean(allow_none=True)
    notification_emails = fields.List(fields.Email())
    notification_before_days = fields.Int(validate=lambda x: 1 <= x <= 30, allow_none=True)
    notification_before_days_weekly = fields.Int(validate=lambda x: 1 <= x <= 30, allow_none=True)
    notification_before_days_monthly = fields.Int(validate=lambda x: 1 <= x <= 30, allow_none=True)
    notifications_enabled = fields.Boolean()
    end_notification_daily = fields.Int(validate=lambda x: 1 <= x <= 30, allow_none=True)
    end_notification_weekly = fields.Int(validate=lambda x: 1 <= x <= 30, allow_none=True)
    end_notification_monthly = fields.Int(validate=lambda x: 1 <= x <= 30, allow_none=True)
    end_notifications_enabled = fields.Boolean()
    booking_limit_days = fields.Int(validate=lambda x: x >= 1, allow_none=True)
    owner = Principal(validate=lambda x: x is not None, allow_none=True)
    key_location = fields.String()
    telephone = fields.String()
    capacity = fields.Int(validate=lambda x: x >= 1)
    division = fields.String(allow_none=True)
    surface_area = fields.Int(validate=lambda x: x >= 0, allow_none=True)
    max_advance_days = fields.Int(validate=lambda x: x >= 1, allow_none=True)
    comments = fields.String()
    acl_entries = PrincipalPermissionList(RoomPrincipal)
    protection_mode = EnumField(ProtectionMode)

class RoomEquipmentSchema(mm.ModelSchema):
    class Meta:
        model = Room
        fields = ('available_equipment',)

class MapAreaSchema(mm.ModelSchema):
    class Meta:
        model = MapArea
        fields = ('name', 'top_left_latitude', 'top_left_longitude', 'bottom_right_latitude', 'bottom_right_longitude',
                  'is_default', 'id')

class ReservationSchema(mm.ModelSchema):
    start_dt = NaiveDateTime()
    end_dt = NaiveDateTime()

    class Meta:
        model = Reservation
        fields = ('id', 'booking_reason', 'booked_for_name', 'room_id', 'is_accepted', 'start_dt', 'end_dt')

class ReservationLinkedObjectDataSchema(mm.Schema):
    id = Number()
    title = Method('_get_title')
    event_title = Function(lambda obj: obj.event.title)
    event_url = Function(lambda obj: obj.event.url)
    own_room_id = Number()
    own_room_name = Function(lambda obj: (obj.own_room.name if obj.own_room else obj.own_room_name) or None)

    def _get_title(self, obj):
        if isinstance(obj, SessionBlock):
            return obj.full_title
        return obj.title

class ReservationUserEventSchema(mm.Schema):
    id = Number()
    title = String()
    url = String()
    start_dt = DateTime()
    end_dt = DateTime()

class ReservationOccurrenceSchema(mm.ModelSchema):
    reservation = Nested(ReservationSchema)
    state = EnumField(ReservationState)
    start_dt = NaiveDateTime()
    end_dt = NaiveDateTime()

    class Meta:
        model = ReservationOccurrence
        fields = ('start_dt', 'end_dt', 'is_valid', 'reservation', 'rejection_reason', 'state')

class ReservationOccurrenceSchemaWithPermissions(ReservationOccurrenceSchema):
    permissions = Method('_get_permissions')

    class Meta:
        fields = ReservationOccurrenceSchema.Meta.fields + ('permissions',)

    def _get_permissions(self, occurrence):
        methods = ('can_cancel', 'can_reject')
        admin_permissions = None
        user_permissions = {x: getattr(occurrence, x)(session.user, allow_admin=False) for x in methods}
        if rb_is_admin(session.user):
            admin_permissions = {x: getattr(occurrence, x)(session.user) for x in methods}
        return {'user': user_permissions, 'admin': admin_permissions}

class ReservationConcurrentOccurrenceSchema(ReservationOccurrenceSchema):
    reservations = Nested(ReservationSchema, many=True)

    class Meta:
        fields = ReservationOccurrenceSchema.Meta.fields + ('reservations',)
        exclude = ('reservation',)

class ReservationEditLogSchema(UserSchema):
    class Meta:
        model = ReservationEditLog
        fields = ('id', 'timestamp', 'info', 'user_name')

    @post_dump(pass_many=True)
    def sort_logs(self, data, many, **kwargs):
        if many:
            data = sorted(data, key=itemgetter('timestamp'), reverse=True)
        return data

class ReservationLinkSchema(mm.ModelSchema):
    type = EnumField(LinkType, attribute='link_type')
    id = Function(lambda link: link.object.id)

    class Meta:
        model = ReservationLink
        fields = ('type', 'id')

class ReservationDetailsSchema(mm.ModelSchema):
    booked_for_user = Nested(UserSchema, only=('id', 'identifier', 'full_name', 'phone', 'email'))
    created_by_user = Nested(UserSchema, only=('id', 'identifier', 'full_name', 'email'))
    edit_logs = Nested(ReservationEditLogSchema, many=True)
    can_accept = Function(lambda booking: booking.can_accept(session.user))
    can_cancel = Function(lambda booking: booking.can_cancel(session.user))
    can_delete = Function(lambda booking: booking.can_delete(session.user))
    can_edit = Function(lambda booking: booking.can_edit(session.user))
    can_reject = Function(lambda booking: booking.can_reject(session.user))
    permissions = Method('_get_permissions')
    state = EnumField(ReservationState)
    is_linked_to_object = Function(lambda booking: booking.link is not None)
    link = Nested(ReservationLinkSchema)
    start_dt = NaiveDateTime()
    end_dt = NaiveDateTime()

    class Meta:
        model = Reservation
        fields = ('id', 'start_dt', 'end_dt', 'repetition', 'booking_reason', 'created_dt', 'booked_for_user',
                  'room_id', 'created_by_user', 'edit_logs', 'permissions',
                  'is_cancelled', 'is_rejected', 'is_accepted', 'is_pending', 'rejection_reason',
                  'is_linked_to_object', 'link', 'state')

    def _get_permissions(self, booking):
        methods = ('can_accept', 'can_cancel', 'can_delete', 'can_edit', 'can_reject')
        admin_permissions = None
        user_permissions = {x: getattr(booking, x)(session.user, allow_admin=False) for x in methods}
        if rb_is_admin(session.user):
            admin_permissions = {x: getattr(booking, x)(session.user) for x in methods}
        return {'user': user_permissions, 'admin': admin_permissions}

class BlockedRoomSchema(mm.ModelSchema):
    room = Nested(RoomSchema, only=('id', 'name', 'sprite_position', 'full_name'))
    state = EnumField(BlockedRoomState)

    class Meta:
        model = BlockedRoom
        fields = ('room', 'state', 'rejection_reason', 'rejected_by')

    @post_dump(pass_many=True)
    def sort_rooms(self, data, many, **kwargs):
        if many:
            data = sorted(data, key=lambda x: natural_sort_key(x['room']['full_name']))
        return data

class BlockingSchema(mm.ModelSchema):
    blocked_rooms = Nested(BlockedRoomSchema, many=True)
    allowed = PrincipalList()
    permissions = Method('_get_permissions')
    created_by = Pluck(UserSchema, 'full_name', attribute='created_by_user')

    class Meta:
        model = Blocking
        fields = ('id', 'start_date', 'end_date', 'reason', 'blocked_rooms', 'allowed', 'created_by', 'permissions')

    def _get_permissions(self, blocking):
        methods = ('can_delete', 'can_edit')
        admin_permissions = None
        user_permissions = {x: getattr(blocking, x)(session.user, allow_admin=False) for x in methods}
        if rb_is_admin(session.user):
            admin_permissions = {x: getattr(blocking, x)(session.user) for x in methods}
        return {'user': user_permissions, 'admin': admin_permissions}

class NonBookablePeriodSchema(mm.ModelSchema):
    start_dt = NaiveDateTime()
    end_dt = NaiveDateTime()

    class Meta:
        model = NonBookablePeriod
        fields = ('start_dt', 'end_dt')

class BookableHoursSchema(mm.ModelSchema):
    class Meta:
        model = BookableHours
        fields = ('start_time', 'end_time')

class LocationsSchema(mm.ModelSchema):
    rooms = Nested(RoomSchema, many=True, only=('id', 'name', 'full_name', 'sprite_position'))

    class Meta:
        model = Location
        fields = ('id', 'name', 'rooms')

class AdminLocationsSchema(mm.ModelSchema):
    can_delete = Function(lambda loc: not loc.rooms)

    class Meta:
        model = Location
        fields = ('id', 'name', 'can_delete', 'map_url_template', 'room_name_format')

class RBUserSchema(UserSchema):
    has_owned_rooms = mm.Method('has_managed_rooms')
    is_rb_admin = mm.Function(lambda user: rb_is_admin(user))

    class Meta:
        fields = UserSchema.Meta.fields + ('has_owned_rooms', 'is_admin', 'is_rb_admin', 'identifier', 'full_name')

    def has_managed_rooms(self, user):
        from indico.modules.rb.operations.rooms import has_managed_rooms
        return has_managed_rooms(user)

class CreateBookingSchema(mm.Schema):
    start_dt = fields.DateTime(required=True)
    end_dt = fields.DateTime(required=True)
    repeat_frequency = EnumField(RepeatFrequency, required=True)
    repeat_interval = fields.Int(missing=0, validate=lambda x: x >= 0)
    room_id = fields.Int(required=True)
    booked_for_user = Principal(data_key='user', allow_external_users=True)
    booking_reason = fields.String(data_key='reason', validate=validate.Length(min=3), required=True)
    is_prebooking = fields.Bool(missing=False)
    link_type = EnumField(LinkType)
    link_id = fields.Int()
    link_back = fields.Bool(missing=False)
    admin_override_enabled = fields.Bool(missing=False)

    @validates_schema(skip_on_field_errors=True)
    def validate_dts(self, data):
        if data['start_dt'] >= data['end_dt']:
            raise ValidationError(_('Booking cannot end before it starts'))

class RoomFeatureSchema(mm.ModelSchema):
    class Meta:
        model = RoomFeature
        fields = ('id', 'name', 'title', 'icon')

class EquipmentTypeSchema(mm.ModelSchema):
    features = Nested(RoomFeatureSchema, many=True)
    used = Function(lambda eq, ctx: eq.id in ctx['used_ids'])

    class Meta:
        model = EquipmentType
        fields = ('id', 'name', 'features', 'used')

class AdminEquipmentTypeSchema(mm.ModelSchema):
    class Meta:
        model = EquipmentType
        fields = ('id', 'name', 'features')

class RoomAttributeSchema(mm.ModelSchema):
    hidden = Boolean(attribute='is_hidden')

    class Meta:
        model = RoomAttribute
        fields = ('id', 'name', 'title', 'hidden')

attributes_schema = AttributesSchema(many=True)
rb_user_schema = RBUserSchema()
rooms_schema = RoomSchema(many=True)
room_attribute_values_schema = RoomAttributeValuesSchema(many=True)
room_update_schema = RoomUpdateSchema()
room_update_args_schema = RoomUpdateArgsSchema()
room_equipment_schema = RoomEquipmentSchema()
map_areas_schema = MapAreaSchema(many=True)
reservation_occurrences_schema = ReservationOccurrenceSchema(many=True)
reservation_occurrences_schema_with_permissions = ReservationOccurrenceSchemaWithPermissions(many=True)
concurrent_pre_bookings_schema = ReservationConcurrentOccurrenceSchema(many=True)
reservation_schema = ReservationSchema()
reservation_details_schema = ReservationDetailsSchema()
reservation_linked_object_data_schema = ReservationLinkedObjectDataSchema()
reservation_user_event_schema = ReservationUserEventSchema(many=True)
blockings_schema = BlockingSchema(many=True)
simple_blockings_schema = BlockingSchema(many=True, only=('id', 'reason'))
nonbookable_periods_schema = NonBookablePeriodSchema(many=True)
bookable_hours_schema = BookableHoursSchema()
locations_schema = LocationsSchema(many=True)
admin_locations_schema = AdminLocationsSchema(many=True)
create_booking_args = CreateBookingSchema()
admin_equipment_type_schema = AdminEquipmentTypeSchema()
room_feature_schema = RoomFeatureSchema()
room_attribute_schema = RoomAttributeSchema()


text:
using System;
using System.Linq;
using System.Threading.Tasks;

namespace Contacts.Plugin.Abstractions
{
  /// <summary>
  /// Interface for Contacts
  /// </summary>
  public interface IContacts
  {
    Task<bool> RequestPermission();
    IQueryable<Task<Contact>> Contacts { get; }
    Contact LoadContact(string id);

    bool LoadSupported { get; }
    bool PreferContactAggregation { get; set; }
    bool AggregateContactsSupported { get; }
    bool SingleContactsSupported { get; }
    bool IsReadOnly { get; }
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Pyrenophora hungarica Moesz

### Remarks
null


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>CreateDateRate | DateRate</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">

            Menu

            Your date rating

                    Your rating identifier

                <input name="" id="evalutaionId" placeholder="" value="Still not working, press start rating " type="text" readonly />

                Share


text:
const { resolve } = require('path')
const { ipcMain, app } = require('electron')
const BugsnagIpcMain = require('./bugsnag-ipc-main')
const serializeConfigForRenderer = require('./lib/config-serializer')
const { CHANNEL_CONFIG, CHANNEL_RENDERER_TO_MAIN, CHANNEL_RENDERER_TO_MAIN_SYNC } = require('./lib/constants')

module.exports = {
  load: (client) => {
    /* configuration requests from renderers */

    // pre serialise config outside of the sync IPC call so we avoid unnecessary computation while the process is blocked
    let configStr
    const updateConfigStr = () => {
      configStr = serializeConfigForRenderer(client._config, client._metadata, client._features, client.getUser(), client.getContext())
    }
    updateConfigStr()

    // this callback returns the main client's configuration to renderer so it can start its own client
    ipcMain.on(CHANNEL_CONFIG, (event, data) => {
      // the renderer blocks until this function returns a value
      event.returnValue = configStr
    })

    /* synchronisation from renderers */

    const bugsnagIpcMain = new BugsnagIpcMain(client)

    // delegate all method calls to the BugsnagIpcMain class's handle method
    ipcMain.handle(CHANNEL_RENDERER_TO_MAIN, bugsnagIpcMain.handle)
    ipcMain.on(CHANNEL_RENDERER_TO_MAIN_SYNC, bugsnagIpcMain.handleSync)

    setPreload()
  }
}

const setPreload = () => {
  const bugsnagPreload = resolve(__dirname, 'dist', 'preload.bundle.js')

  // for every session created, insert Bugsnag's preload script
  app.on('session-created', session => {
    // setPreloads replaces any existing value, so check the existing value first
    const existingPreloads = session.getPreloads()
    session.setPreloads([bugsnagPreload, ...existingPreloads])

    // ensure our preload is never replaced with subsequent setPreloads calls
    const setPreloads = session.setPreloads
    session.setPreloads = (...args) => {
      // if an invalid (non-array) parameter is passed, send it through to the
      // original method to let that raise an error in the default way
      if (!Array.isArray(args[0])) setPreloads.call(session, ...args)
      setPreloads.call(session, [bugsnagPreload, ...args[0]])
    }
  })
}


text:
using EngineLayer;
using MassSpectrometry;
using MzLibUtil;
using NUnit.Framework;
using System.Collections.Generic;
using System.Linq;
using TaskLayer;

namespace Test
{
    [TestFixture]
    internal class TestScanManagement
    {
        //[Test]
        public static void TestGetCombinedMs2Scans()
        {
            var myMsDataFile = new TestDataFile(5);

            Tolerance DeconvolutionMassTolerance = new PpmTolerance(5);

            var listOfSortedms2Scans = MetaMorpheusTask.GetMs2Scans(myMsDataFile, null, new CommonParameters()).OrderBy(b => b.PrecursorMass).ToArray();

            //Write prime code to combine MS2MS3
            Dictionary<int, double> listOfScanPrecusor = new Dictionary<int, double>();

            List<MsDataScan> ListOfSortedMsScans = new List<MsDataScan>();
            List<Ms2ScanWithSpecificMass> test = new List<Ms2ScanWithSpecificMass>();

            foreach (var ms2scan in myMsDataFile.GetAllScansList().Where(x => x.MsnOrder != 1))
            {
                if (ms2scan.MsnOrder == 2 && !listOfScanPrecusor.Contains(new KeyValuePair<int, double>(ms2scan.OneBasedPrecursorScanNumber.Value, ms2scan.SelectedIonMZ.Value)))
                {
                    if (ms2scan.OneBasedPrecursorScanNumber.HasValue)
                    {
                        listOfScanPrecusor.Add(ms2scan.OneBasedPrecursorScanNumber.Value, ms2scan.SelectedIonMZ.Value);
                        List<int> currentScanMS2OneBasedScanNumber = new List<int>
                        {
                            ms2scan.OneBasedScanNumber
                        };
                        var mz2 = ms2scan.MassSpectrum.XArray.ToList();
                        var intensities2 = ms2scan.MassSpectrum.YArray.ToList();
                        for (int i = 1; i < 7; i++)
                        {
                            if (ms2scan.OneBasedScanNumber + i <= myMsDataFile.NumSpectra)
                            {
                                var x = myMsDataFile.GetOneBasedScan(ms2scan.OneBasedScanNumber + i);
                                //var x = myMsDataFile.OfType<IMsDataScanWithPrecursor<IMzSpectrum<IMzPeak>>>().ElementAt(i);

                                if (x.MsnOrder == 2 && x.SelectedIonMZ == ms2scan.SelectedIonMZ)
                                {
                                    currentScanMS2OneBasedScanNumber.Add(x.OneBasedScanNumber);
                                    mz2.AddRange(x.MassSpectrum.XArray.ToList());
                                    intensities2.AddRange(x.MassSpectrum.YArray.ToList());
                                }
                                if (x.MsnOrder == 3 && currentScanMS2OneBasedScanNumber.Contains(x.OneBasedPrecursorScanNumber.Value))
                                {
                                    mz2.AddRange(x.MassSpectrum.XArray.ToList());
                                    intensities2.AddRange(x.MassSpectrum.YArray.ToList());
                                }
                            }
                        }
                        var MassSpectrum2 = new MzSpectrum(mz2.ToArray(), intensities2.ToArray(), false);
                        ListOfSortedMsScans.Add(new MsDataScan(MassSpectrum2, ms2scan.OneBasedScanNumber, ms2scan.MsnOrder, ms2scan.IsCentroid, Polarity.Positive, ms2scan.RetentionTime,
                            ms2scan.ScanWindowRange, ms2scan.ScanFilter, ms2scan.MzAnalyzer, ms2scan.TotalIonCurrent, ms2scan.InjectionTime, null, "", ms2scan.SelectedIonMZ, ms2scan.SelectedIonChargeStateGuess, ms2scan.SelectedIonIntensity, ms2scan.IsolationMz, null, ms2scan.DissociationType, ms2scan.OneBasedPrecursorScanNumber, ms2scan.SelectedIonMonoisotopicGuessMz));
                    }
                }
            }
            foreach (var ms2scan in ListOfSortedMsScans.Where(x => x.MsnOrder != 1))
            {
                test.Add(new Ms2ScanWithSpecificMass(ms2scan, ms2scan.SelectedIonMonoisotopicGuessMz.Value, ms2scan.SelectedIonChargeStateGuess.Value, "", new CommonParameters()));
            }
            var testToArray = test.OrderBy(b => b.PrecursorMass).ToArray();

        }
    }
}


text:
class MoveStateFromRadioAssignmentToRadio < ActiveRecord::Migration[4.2]
  def change
    remove_column :radio_assignments, :state
    add_column :radios, :state, :string, default: :in
  end
end


text:
<?php

class Google_Service_CloudSearch_SourceCrowdingConfig extends Google_Model
{
  public $field;
  public $numResults;
  public $numSuggestions;
  public $source;

  public function setField($field)
  {
    $this->field = $field;
  }
  public function getField()
  {
    return $this->field;
  }
  public function setNumResults($numResults)
  {
    $this->numResults = $numResults;
  }
  public function getNumResults()
  {
    return $this->numResults;
  }
  public function setNumSuggestions($numSuggestions)
  {
    $this->numSuggestions = $numSuggestions;
  }
  public function getNumSuggestions()
  {
    return $this->numSuggestions;
  }
  public function setSource($source)
  {
    $this->source = $source;
  }
  public function getSource()
  {
    return $this->source;
  }
}


text:
Use conventions to name your Sketch layers and Framer Navigation will add navigation to your [Framer.js](http://framerjs.com) prototype automagically.

## How to use
* Open your Framer Studio project folder (e.g. "myapp.framer")
* Add [framer-navigation.js](https://github.com/penrosestudio/framer-navigation/blob/master/framer-navigation.js) to the `framer` subfolder.
* Open `index.html` and add `<script src="framer/framer-navigation.js"></script>` after the line `<script src="framer/init.js"></script>`.
* In Framer Studio, after importing your layers, call initialize:
```
    layers = Framer.Importer.load "..."
    Framer.Navigation.initialize layers
```

## Behaviours

Note: Framer Navigation assumes screen layers (or artboards) are given a name ending in 'Screen'.

### 1. Goto
Clicking on a layer with a name ending 'Goto [X]' will slide in layer [X]. For example, clicking 'Button Goto Cart Screen' will slide in 'Cart Screen'.

### 2. Back
Clicking on a layer with the name 'Back Button' will slide back in the previous screen. (A history stack is kept so you can go back repeatedly).

### 3. Hamburger
Clicking on a layer with the name 'Hamburger' will slide in a layer named 'Hamburger Drawer'. Clicking outside of the hamburger drawer will close it.

### 4. everyLayer and onClickSlideTo
The above behaviours are built from the functions `everyLayer` and `onClickSlideTo`, and you can use them directly to build your own custom behaviour. See the `Framer.Navigation.setup[...]` functions for examples.

## Reporting Issues

- Add an issue, or email chris@penrosestudio.com