text:
(function(_http, _path, _url, _fs, _qs, _multipart, _vfs)
{
  /**
   * Globals and default settings etc.
   */
  var HANDLER = null;
  var ROOTDIR = _path.join(_path.dirname(__filename), '/../../');
  var DISTDIR = (process && process.argv.length > 2) ? process.argv[2] : 'dist';
  var CONFIG  = {
    port:       8000,
    directory:  null, // Automatic
    appdirs:    null, // Automatic, but overrideable
    vfsdir:     _path.join(ROOTDIR, 'vfs/home/demo'), // FIXME
    tmpdir:     _path.join(ROOTDIR, 'vfs/tmp'),
    publicdir:  _path.join(ROOTDIR, 'vfs/public'),
    repodir:    _path.join(ROOTDIR, 'src/packages'),
    distdir:    _path.join(ROOTDIR, DISTDIR),
    mimes:      {}
  };

  /////////////////////////////////////////////////////////////////////////////
  // HELPERS
  /////////////////////////////////////////////////////////////////////////////

  /**
   * HTTP Output
   */
  var respond = function(data, mime, response, headers, code) {
    data    = data    || '';
    headers = headers || [];
    mime    = mime    || "text/html";
    code    = code    || 200;

    //console.log(">>>", 'respond()', mime, data.length);

    for ( var i = 0; i < headers.length; i++ ) {
      response.writeHead.apply(response, headers[i]);
    }

    response.writeHead(code, {"Content-Type": mime});
    response.write(data);
    response.end();
  };

  var respondJSON = function(data, response, headers) {
    data = JSON.stringify(data);
    console.log(">>>", 'application/json', data.length || 0);
    respond(data, 'application/json', response, headers);
  };

  /**
   * File Output
   */
  var respondFile = function(path, request, response, jpath) {
    var fullPath = jpath ? _path.join(CONFIG.directory, path) : _vfs.getRealPath(path, CONFIG).root;
    _fs.exists(fullPath, function(exists) {
      if ( exists ) {
        _fs.readFile(fullPath, function(error, data) {
          if ( error ) {
            console.log(">>>", '500', fullPath);
            console.warn(error);
            respond("500 Internal Server Error", null, response, null, 500);
          } else {
            var mime = _vfs.getMime(fullPath, CONFIG);
            console.log(">>>", '200', mime, fullPath, data.length);
            respond(data, mime, response);
          }
        });
      } else {
        console.log('!!!', '404', fullPath);
        respond("404 Not Found", null, response, null, 404);
      }
    });
  };

  var readConfig = function(filename) {
    var path = _path.join(ROOTDIR, filename);
    if ( _fs.existsSync(path) ) {
      try {
        console.info('-->', 'Found configuration', filename);
        return JSON.parse(_fs.readFileSync(path).toString());
      } catch ( e ) {
        console.warn('!!!', 'Failed to parse configuration', filename, e);
      }
    } else {
      console.warn('!!!', 'Did not find configuration', path);
    }
    return false;
  };

  /////////////////////////////////////////////////////////////////////////////
  // API
  /////////////////////////////////////////////////////////////////////////////

  /**
   * OS.js API
   */
  var api = {
    FileGET : function(path, request, response, arg) {
      if ( !arg ) {
        console.log('---', 'FileGET', path);
      }
      respondFile(unescape(path), request, response, arg);
    },

    FilePOST : function(fields, files, request, response) {
      var srcPath = files.upload.path;
      var tmpPath = (fields.path + '/' + files.upload.name).replace('////', '///'); // FIXME
      var dstPath = _vfs.getRealPath(tmpPath, CONFIG).root;

      _fs.exists(srcPath, function(exists) {
        if ( exists ) {
          _fs.exists(dstPath, function(exists) {
            if ( exists ) {
              respond('Target already exist!', "text/plain", response, null, 500);
            } else {
              _fs.rename(srcPath, dstPath, function(error, data) {
                if ( error ) {
                  respond('Error renaming/moving: ' + error, "text/plain", response, null, 500);
                } else {
                  respond("1", "text/plain", response);
                }
              });
            }
          });
        } else {
          respond('Source does not exist!', "text/plain", response, null, 500);
        }
      });
    },

    CoreAPI : function(url, path, POST, request, response) {
      if ( path.match(/^\/API/) ) {
        try {
          var data   = JSON.parse(POST);
          var method = data.method;
          var args   = data['arguments'] || {}

          console.log('---', 'CoreAPI', method, args);

          switch ( method ) {
            case 'application' :
              var apath = args.path || null;
              var aname = args.application || null;
              var ameth = args.method || null;
              var aargs = args['arguments'] || [];

              var aroot = _path.join(CONFIG.repodir, apath);
              var fpath = _path.join(aroot, "api.js");

              try {
                var api = require(fpath);
                api[aname].call(ameth, aargs, function(result, error) {
                  error = error || null;
                  if ( error !== null ) {
                    result = null;
                  }
                  respondJSON({result: result, error: error}, response);
                });
              } catch ( e ) {
                respondJSON({result: null, error: "Application API error or missing: " + e.toString()}, response);
              }
            break;

            case 'fs' :
              var m = args.method;
              var a = args['arguments'] || [];

              if ( _vfs[m] ) {
                _vfs[m](a, request, function(json) {
                  respondJSON(json, response);
                }, CONFIG);
              } else {
                throw "Invalid VFS method: " + m;
              }
            break;

            default :
              var found = false;
              if ( HANDLER ) {
                found = HANDLER.request(method, args, function(error, result) {
                  respondJSON({result: result, error: error}, response);
                }, request, response);
              }

              if ( !found ) {
                throw "Invalid method: " + method;
              }
            break;
          }
        } catch ( e ) {
          console.error("!!! Caught exception", e);
          console.warn(e.stack);

          respondJSON({result: null, error: "500 Internal Server Error: " + e}, response);
        }
        return true;
      }
      return false;
    }
  };

  /////////////////////////////////////////////////////////////////////////////
  // MAIN
  /////////////////////////////////////////////////////////////////////////////

  console.log('***');
  console.log('***', 'THIS IS A WORK IN PROGRESS!!!');
  console.log('***');

  /**
   * Initialize config
   */
  (function() {

    var settConfig = readConfig("src/server-node/settings.json");
    if ( settConfig !== false ) {
      for ( var i in settConfig ) {
        if ( settConfig.hasOwnProperty(i) && CONFIG.hasOwnProperty(i) ) {
          if ( i === 'vfsdir' ) {
            settConfig[i] += '/demo'; // FIXME
          }
          CONFIG[i] = settConfig[i];
        }
      }
    }

    var mimeConfig = readConfig("src/mime.json");
    if ( mimeConfig !== false ) {
      CONFIG.mimes = mimeConfig.mapping;
    }

    var repoConfig = readConfig("src/packages/repositories.json");
    if ( repoConfig !== false ) {
      CONFIG.appdirs = repoConfig;
    }

    if ( !CONFIG.directory ) {
      CONFIG.directory = _fs.realpathSync('.');
    }

    HANDLER = require(_path.join(ROOTDIR, 'src', 'server-node', 'handlers', settConfig.handler , 'handler.js'));
  })();

  console.log(JSON.stringify(CONFIG, null, 2));
  if ( !HANDLER ) {
    console.log("Invalid handler %s defined", CONFIG.handler);
    return;
  }

  /**
   * Server instance
   */
  _http.createServer(function(request, response) {

    var url     = _url.parse(request.url, true),
        path    = decodeURIComponent(url.pathname);

      if ( path === "/" ) path += "index.html";
      console.log('<<<', path);

      if ( request.method == 'POST' )
      {
        // File Uploads
        if ( path.match(/^\/FS$/) ) {
          var form = new _multipart.IncomingForm();
          form.parse(request, function(err, fields, files) {
            api.FilePOST(fields, files, request, response);
          });
        }

        // API Calls
        else {
          var body = '';
          request.on('data', function (data) {
            body += data;
          });

          request.on('end', function () {
            if ( !api.CoreAPI(url, path, body, request, response) ) {
              console.log(">>>", '404', path);
              respond("404 Not Found", null, response, [[404, {}]]);
            }
          });
        }
      }

      // File Gets
      else {
        if ( path.match(/^\/FS/) ) {
          api.FileGET(path.replace(/^\/FS/, ''), request, response, false);
        } else {
          api.FileGET(_path.join(DISTDIR, path), request, response, true);
        }
      }
  }).listen(CONFIG.port);

})(
  require("http"),
  require("path"),
  require("url"),
  require("node-fs-extra"),
  require("querystring"),
  require("formidable"),
  require("./vfs.js")
);


text:
title: Getting started with Crate on CoreOS
author: Mathias Fußenegger

As a Linux distribution targetted at cloud and cluster based environments, CoreOS is a perfect fit for a Crate cluster.

## Pre-requisites
We assume you have a CoreOS cluster running and can access the `fleetctl` tool installed on your local system or on a node in the CoreOS cluster.

## Create the Crate Service
Create a service file called *crate@.service* with the following contents:

```bash
[Unit]
Description=crate
After=docker.service
Requires=docker.service

[Service]
TimeoutSec=180
ExecStartPre=/usr/bin/mkdir -p /data/crate
ExecStartPre=/usr/bin/docker pull crate/crate

ExecStart=/usr/bin/docker run \
    --name %p-%i \
    --publish 4200:4200 \
    --publish 4300:4300 \
    --volume /data/crate:/data \
    crate/crate \
    /crate/bin/crate \
    -Cnode.name=%p%i \

ExecStop=/usr/bin/docker stop %p-%i
ExecStop=/usr/bin/docker rm %p-%i

[X-Fleet]
X-Conflicts=%p@*.service
```

The `TimeoutSec` setting is important because pulling a docker image for the first time takes some time and might cause a time out.

If you're familiar with systemd service files you'll notice that the crate service file looks similar to a regular systemd service file. The only difference is the `[X-Fleet]` section that ensures only one service named *crate@x.service* is assigned per node.

Submit it to the cluster using fleet (assuming a 3 node cluster):

```bash
fleetctl submit crate@{1,2,3}.service
```

Start the service across the cluster (assuming a 3 node cluster):

```bash
fleetctl start crate@{1,2,3}.service
```

Once a crate service starts a folder named */data/crate* will be created on each CoreOS node. The crate docker image is pulled and once finished the container launches.

Check Status:

```bash
fleetctl list-units
```

## Next Steps

- [Connect to Crate Cluster](/docs/connect)
- [Import Data](/docs/import)
- [Client Libraries](/docs/clients)
- [Scale a Cluster](/docs/scale)

redpajama_set_name: RedPajamaGithub


text:
<div ly-paper
  [elevation]="8"
  shadowColor="demoBg"
  bg="background:tertiary"
>
  <div [className]="classes.code">
    <button
      ly-button
      appearance="icon"
      [raised]="hasCode"
      [elevation]="hasCode ? 1 : null"
      (click)="toggleCode()"
      [lyTooltip]="'View source'"><ly-icon icon="code"></ly-icon></button>
    <button
      [style.margin]="'0 8px'"
      ly-button
      appearance="icon"
      [raised]="hasCode"
      [withClass]="classes.stackblitzButton"
      [elevation]="hasCode ? 1 : null"
      (click)="openPostStackblitz()"
      [lyTooltip]="'Edit in Stackblitz'"><ly-icon icon="Stackblitz"></ly-icon></button>
  </div>
  <div
    ly-paper
    bg="codeBg"
    *ngIf="hasCode">
    <ly-tabs
      [indicatorColor]="'primary'"
      [textColor]="'primary'"
      [elevation]="8"
      [shadowColor]="'demoBg'"
      scrollable
      [animationDuration]="0"
    >
      <ly-tab *ngFor="let file of files; let i = index">
        <button ly-tab-label>{{ file.label }}</button>
        <div [withClass]="classes.codeContainer" [innerHTML]="file.text | async">Loading...</div>
      </ly-tab>
    </ly-tabs>
  </div>
  <div [className]="classes.tabContainer">
    <ng-content></ng-content>
  </div>
</div>


text:
define(function (require) {
  var html = require('ui/timepicker/timepicker.html');
  var module = require('ui/modules').get('ui/timepicker');
  var _ = require('lodash');
  var dateMath = require('ui/utils/dateMath');
  var moment = require('moment');

  require('ui/directives/input_datetime');
  require('ui/directives/inequality');
  require('ui/timepicker/quick_ranges');
  require('ui/timepicker/refresh_intervals');
  require('ui/timepicker/time_units');
  require('ui/timepicker/toggle');

  module.directive('kbnTimepicker', function (quickRanges, timeUnits, refreshIntervals) {
    return {
      restrict: 'E',
      scope: {
        from: '=',
        to: '=',
        mode: '=',
        interval: '=',
        activeTab: '='
      },
      template: html,
      controller: function ($scope) {
        var init = function () {
          $scope.setMode($scope.mode);
        };

        $scope.format = 'MMMM Do YYYY, HH:mm:ss.SSS';
        $scope.modes = ['quick', 'relative', 'absolute'];
        $scope.activeTab = $scope.activeTab || 'filter';

        if (_.isUndefined($scope.mode)) $scope.mode = 'quick';

        $scope.quickLists = _(quickRanges).groupBy('section').values().value();
        $scope.refreshLists = _(refreshIntervals).groupBy('section').values().value();

        $scope.relative = {
          count: 1,
          unit: 'm',
          preview: undefined,
          round: false
        };

        $scope.absolute = {
          from: moment(),
          to: moment()
        };

        $scope.units = timeUnits;

        $scope.relativeOptions = [
          {text: 'Seconds ago', value: 's'},
          {text: 'Minutes ago', value: 'm'},
          {text: 'Hours ago', value: 'h'},
          {text: 'Days ago', value: 'd'},
          {text: 'Weeks ago', value: 'w'},
          {text: 'Months ago', value: 'M'},
          {text: 'Years ago', value: 'y'},
        ];

        $scope.$watch('absolute.from', function (date) {
          if (_.isDate(date)) $scope.absolute.from = moment(date);
        });

        $scope.$watch('absolute.to', function (date) {
          if (_.isDate(date)) $scope.absolute.to = moment(date);
        });

        $scope.setMode = function (thisMode) {
          switch (thisMode) {
            case 'quick':
              break;
            case 'relative':
              var fromParts = $scope.from.toString().split('-');
              var relativeParts = [];

              // Try to parse the relative time, if we can't use moment duration to guestimate
              if ($scope.to.toString() === 'now' && fromParts[0] === 'now' && fromParts[1]) {
                relativeParts = fromParts[1].match(/([0-9]+)([smhdwMy]).*/);
              }
              if (relativeParts[1] && relativeParts[2]) {
                $scope.relative.count = parseInt(relativeParts[1], 10);
                $scope.relative.unit = relativeParts[2];
              } else {
                var duration = moment.duration(moment().diff(dateMath.parse($scope.from)));
                var units = _.pluck(_.clone($scope.relativeOptions).reverse(), 'value');
                if ($scope.from.toString().split('/')[1]) $scope.relative.round = true;
                for (var i = 0; i < units.length; i++) {
                  var as = duration.as(units[i]);
                  if (as > 1) {
                    $scope.relative.count = Math.round(as);
                    $scope.relative.unit = units[i];
                    break;
                  }
                }
              }

              if ($scope.from.toString().split('/')[1]) $scope.relative.round = true;
              $scope.formatRelative();

              break;
            case 'absolute':
              $scope.absolute.from = dateMath.parse($scope.from || moment().subtract('minutes', 15));
              $scope.absolute.to = dateMath.parse($scope.to || moment(), true);
              break;
          }

          $scope.mode = thisMode;
        };

        $scope.setQuick = function (from, to, description) {
          $scope.from = from;
          $scope.to = to;
        };

        $scope.setToNow = function () {
          $scope.absolute.to = moment();
        };

        $scope.formatRelative = function () {
          var parsed = dateMath.parse(getRelativeString());
          $scope.relative.preview =  parsed ? parsed.format($scope.format) : undefined;
          return parsed;
        };

        $scope.applyRelative = function () {
          $scope.from = getRelativeString();
          $scope.to = 'now';
        };

        function getRelativeString() {
          return 'now-' + $scope.relative.count + $scope.relative.unit + ($scope.relative.round ? '/' + $scope.relative.unit : '');
        }

        $scope.applyAbsolute = function () {
          $scope.from = moment($scope.absolute.from);
          $scope.to = moment($scope.absolute.to);
        };

        $scope.setRefreshInterval = function (interval) {
          interval = _.clone(interval);
          console.log('before: ' + interval.pause);
          interval.pause = (interval.pause == null || interval.pause === false) ? false : true;

          console.log('after: ' + interval.pause);
          $scope.interval = interval;
        };

        init();
      }
    };
  });

});


text:
Style Guide
==================

Style and branding guidelines for the NCSU Libraries website.  Using Foundation 4.

- For Foundation documentation about the Grid, UI elements, etc just go to Foundations docs page (http://foundation.zurb.com/docs/)
- For all NCSU Library Website Guidelines go to (http://webdev.lib.ncsu.edu/website-guidelines/)
- Use app.scss for custom styles. Do no add to ncsu-libraries.scss. If necessary commenting out core Foundation styles is reccommended
- If you need to add SASS variables add them to _settings.scss

Updates 11.21.13
=================
- Updated Header nav. Dropdowns are different color
- Updated Minimum Bar guidelines and styles
- Updated various style settings in _settings.php
- Added media query to target mobile devices

Updates 2.5.14
=================
- Renamed this repo "Style Guide" to better reflect what this thing actually is.


text:
export declare class ObjectComparator {
    static compare(value1: any, operation: string, value2: any): boolean;
    static areEqual(value1: any, value2: any): boolean;
    static areNotEqual(value1: any, value2: any): boolean;
    static less(value1: any, value2: any): boolean;
    static more(value1: any, value2: any): boolean;
    static match(value1: any, value2: any): boolean;
}


text:
FROM maven:3.6.1-jdk-8

RUN apt-get -qq update && apt-get -qq install -y \
  unzip

WORKDIR /tmp

RUN curl -sSL https://github.com/protocolbuffers/protobuf/releases/download/v3.14.0/\
protoc-3.14.0-linux-x86_64.zip -o protoc.zip && \
  unzip -qq protoc.zip && \
  cp ./bin/protoc /usr/local/bin/protoc

RUN curl -sSL https://github.com/grpc/grpc-web/releases/download/1.4.2/\
protoc-gen-grpc-web-1.4.2-linux-x86_64 -o /usr/local/bin/protoc-gen-grpc-web && \
  chmod +x /usr/local/bin/protoc-gen-grpc-web

WORKDIR /var/www/html/dist

WORKDIR /github/grpc-web

RUN git clone https://github.com/grpc/grpc-web . && \
  cd src/connector && \
  mvn install --no-transfer-progress && \
  cd ../../net/grpc/gateway/examples/grpc-web-java/interop-test-service && \
  mvn package --no-transfer-progress

ENTRYPOINT ["java", "-cp", "net/grpc/gateway/examples/grpc-web-java/interop-test-service/target/interop-test-0.1-jar-with-dependencies.jar", "grpcweb.examples.StartServiceAndGrpcwebProxy"]


text:
namespace GTM HIDDEN {

typedef struct gtm_jmpbuf
{
  unsigned long s[7];	/* r8-r14 */
  void *cfa;
  unsigned long pc;
  unsigned long gbr;
#ifdef __SH_FPU_ANY__
  unsigned long fpscr;
  unsigned long f[4];	/* fr12-fr15 */
#endif
} gtm_jmpbuf;

/* SH generally uses a fixed page size of 4K.  */
#define PAGE_SIZE	4096
#define FIXED_PAGE_SIZE	1

/* ??? The size of one line in hardware caches (in bytes). */
#define HW_CACHELINE_SIZE 32

static inline void
cpu_relax (void)
{
  __asm volatile ("" : : : "memory");
}

} // namespace GTM


text:
package models;

import com.google.gson.annotations.Expose;

/**
 * FriendRequest entity
 */
public class FriendRequest {

    @Expose
    private String caller,receiver;

    /**
     * Empty constructor (used for Jersey's json parser
     */
    public FriendRequest(){
        this(null,null);
    }

    /**
     * Creates a FriendRequest
     * @param caller a {@link User#pseudo}
     * @param receiver a {@link User#pseudo}
     */
    public FriendRequest(String caller, String receiver){
        this.caller = caller;
        this.receiver = receiver;
    }

    /**
     * Gets the caller
     * @return a {@code String} that represents the {@link User#pseudo} of the caller
     */
    public String getCaller() {
        return caller;
    }

    /**
     * Gets the receiver
     * @return a {@code String} that represents the {@link User#pseudo} of the receiver
     */
    public String getReceiver() {
        return receiver;
    }

    /**
     * Sets the caller
     * @param caller a  a {@code String} that represents the {@link User#pseudo} of the caller
     */
    public void setCaller(String caller) {
        this.caller = caller;
    }

    /**
     * Sets the receiver
     * @param receiver  a {@code String} that represents the {@link User#pseudo} of the receiver
     */
    public void setReceiver(String receiver) {
        this.receiver = receiver;
    }

    /**
     * Returns a {@code String} that represents the friend request
     * @return a {@code String} where caller and receiver are printed
     */
    public String toString(){
        return "caller:"+caller+"/receiver:"+receiver;
    }

    /**
     * Overrides {@link Object#equals(Object)}
     * @param o any Object
     * @return true if the object equals the friendrequest, false otherwise
     * @see Object#equals(Object)
     */
    @Override
    public boolean equals(Object o) {
        return o instanceof FriendRequest
                && ((((FriendRequest) o).getReceiver().equals(receiver)
                    && ((FriendRequest) o).getCaller().equals(caller))
                || (((FriendRequest) o).getReceiver().equals(caller)
                    && ((FriendRequest) o).getCaller().equals(receiver)));
    }
}


text:
// This file was generated by Mendix Business Modeler.
//
// WARNING: Only the following code will be retained when actions are regenerated:
// - the import list
// - the code between BEGIN USER CODE and END USER CODE
// - the code between BEGIN EXTRA CODE and END EXTRA CODE
// Other code you write will be lost the next time you deploy the project.
// Special characters, e.g., é, ö, à, etc. are supported in comments.

package amazons3connector.actions;

import java.io.InputStream;
import amazons3connector.AmazonHelper;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import com.mendix.core.Core;
import com.mendix.systemwideinterfaces.core.IContext;
import com.mendix.webui.CustomJavaAction;
import com.mendix.systemwideinterfaces.core.IMendixObject;

/**
 *
 */
public class JAV_GetObject_FileContent extends CustomJavaAction<Boolean>
{
	private IMendixObject __AwsConfigParameter1;
	private amazons3connector.proxies.AwsConfig AwsConfigParameter1;
	private IMendixObject __S3BucketParameter1;
	private amazons3connector.proxies.S3Bucket S3BucketParameter1;
	private IMendixObject __S3Object;
	private amazons3connector.proxies.S3SummaryObject S3Object;
	private IMendixObject __OutputS3FileDocument;
	private amazons3connector.proxies.S3FileDocument OutputS3FileDocument;

	public JAV_GetObject_FileContent(IContext context, IMendixObject AwsConfigParameter1, IMendixObject S3BucketParameter1, IMendixObject S3Object, IMendixObject OutputS3FileDocument)
	{
		super(context);
		this.__AwsConfigParameter1 = AwsConfigParameter1;
		this.__S3BucketParameter1 = S3BucketParameter1;
		this.__S3Object = S3Object;
		this.__OutputS3FileDocument = OutputS3FileDocument;
	}

	@Override
	public Boolean executeAction() throws Exception
	{
		this.AwsConfigParameter1 = __AwsConfigParameter1 == null ? null : amazons3connector.proxies.AwsConfig.initialize(getContext(), __AwsConfigParameter1);

		this.S3BucketParameter1 = __S3BucketParameter1 == null ? null : amazons3connector.proxies.S3Bucket.initialize(getContext(), __S3BucketParameter1);

		this.S3Object = __S3Object == null ? null : amazons3connector.proxies.S3SummaryObject.initialize(getContext(), __S3Object);

		this.OutputS3FileDocument = __OutputS3FileDocument == null ? null : amazons3connector.proxies.S3FileDocument.initialize(getContext(), __OutputS3FileDocument);

		// BEGIN USER CODE
		AmazonS3 s3client = AmazonHelper.GetS3Client(AwsConfigParameter1);

		S3Object object = null;
		try
		{
			object = s3client.getObject(
					new GetObjectRequest(S3BucketParameter1.getName(), S3Object.getKey()));
			InputStream objectData = object.getObjectContent();

			Core.storeFileDocumentContent(getContext(), OutputS3FileDocument.getMendixObject(), objectData);
		}
		finally
		{
			if (object != null)
				object.close();
		}

		return true;
		// END USER CODE
	}

	/**
	 * Returns a string representation of this action
	 */
	@Override
	public String toString()
	{
		return "JAV_GetObject_FileContent";
	}

	// BEGIN EXTRA CODE
	// END EXTRA CODE
}


text:
#import "RCTImageSource.h"

@interface RCTImageSource ()

@property (nonatomic, assign) BOOL packagerAsset;

@end

@implementation RCTImageSource

- (instancetype)initWithURL:(NSURL *)url size:(CGSize)size scale:(CGFloat)scale
{
  if ((self = [super init])) {
    _imageURL  = url;
    _size = size;
    _scale = scale;
  }
  return self;
}

- (instancetype)imageSourceWithSize:(CGSize)size scale:(CGFloat)scale
{
  RCTImageSource *imageSource = [[RCTImageSource alloc] initWithURL:_imageURL
                                                               size:size
                                                              scale:scale];
  imageSource.packagerAsset = _packagerAsset;
  return imageSource;
}

- (BOOL)isEqual:(RCTImageSource *)object
{
  if (![object isKindOfClass:[RCTImageSource class]]) {
    return NO;
  }
  return [_imageURL isEqual:object.imageURL] && _scale == object.scale &&
  (CGSizeEqualToSize(_size, object.size) || CGSizeEqualToSize(object.size, CGSizeZero));
}

@end

@implementation RCTConvert (ImageSource)

+ (RCTImageSource *)RCTImageSource:(id)json
{
  if (!json) {
    return nil;
  }

  NSURL *imageURL;
  CGSize size = CGSizeZero;
  CGFloat scale = 1.0;
  BOOL packagerAsset = NO;
  if ([json isKindOfClass:[NSDictionary class]]) {
    if (!(imageURL = [self NSURL:json[@"uri"]])) {
      return nil;
    }
    size = [self CGSize:json];
    scale = [self CGFloat:json[@"scale"]] ?: [self BOOL:json[@"deprecated"]] ? 0.0 : 1.0;
    packagerAsset = [self BOOL:json[@"__packager_asset"]];
  } else if ([json isKindOfClass:[NSString class]]) {
    imageURL = [self NSURL:json];
  } else {
    RCTLogConvertError(json, @"an image. Did you forget to call resolveAssetSource() on the JS side?");
    return nil;
  }

  RCTImageSource *imageSource = [[RCTImageSource alloc] initWithURL:imageURL
                                                               size:size
                                                              scale:scale];
  imageSource.packagerAsset = packagerAsset;
  return imageSource;
}

@end


text:
<?php

namespace Telegramapp\Telegram\Laravel\Controllers;

use Illuminate\Http\Request;
use Sentinel;
use App\Data\Models\User;
use DB;

class LoginController extends Controller
{
    protected $Users;

    public function login()
    {
      return view('vendor.login');
    }

    public function postLogin(Request $request, User $user)
    {

        if(Sentinel::authenticate($request->all()));
            $user = Sentinel::getUser();
            try {

                  if ($user === null){

                    return redirect()->back()->with(['error' => "Adres email lub hasło są niepoprawne."])
                        ->withInput($request->input());
                }
                if($user->isAdmin() && $user->chat_id === null){
                    return view('vendor/telegramRegister', function($vm)use($user){

										/**
										* @var $vm UserEditViewModel
										*/

										$vm->User = $user;
									});

									}elseif( $user->isAdmin())
									{
                                        return redirect('/dashboard');
                                    }

                                if($user->isTeacher() && $user->chat_id === null){
                                    return view('vendor/telegramRegister');
									} elseif( $user->isTeacher())
									{
                                        return redirect('/teacher');
                                    }

                if($user->isStudent() && $user->chat_id === null){
										return $this->renderView('vendor/telegramRegister', function($vm)use($user){

										/**
										* @var $vm UserEditViewModel
										*/

										$vm->User = $user;
									});
									} elseif( $user->isStudent()) {return redirect("/profile/{$user->id}");
                }

            } catch (Exception $ex) {
                }

    }

    public function logout()
    {
        Sentinel::logout();

        return redirect('/login');
    }

    public function skipTelegramLogin(User $user)
    {
        $users = Sentinel::getUser();

        $chat_id = $users->chat_id;

        $email = $users->email;

        if($chat_id === null){
            $table = DB::table('users')->update(['chat_id' => 0]);
        }

        // dd($chat_id);
        return back();
    }
}


text:
//============================================================================
// Name        : SystemSoftware.cpp
// Author      : Samet Sait Talayhan
// Version     : 0.001
// Copyright   : The MIT License (MIT)
//
// Description : CSE241_HW3 in C++, Ansi-style
//============================================================================

#include "101044044HW06P02.h"

namespace Talayhan {

SystemSoftware::SystemSoftware() {
	// TODO Auto-generated constructor stub
	++aliveObjectNumbersSystem;
}

SystemSoftware::~SystemSoftware() {
	// TODO Auto-generated destructor stub
	--aliveObjectNumbersSystem;
}

 int SystemSoftware::getAliveObjectNumbers() {
	return aliveObjectNumbersSystem;
}

const string& SystemSoftware::getName() const {
	return name;
}

void SystemSoftware::setName(const string& name) {
	this->name = name;
}

} /* namespace Talayhan */


text:
@implementation NSData (Hexit)

- (NSString *)hexString {
  NSMutableString *str = [NSMutableString stringWithCapacity:[self length]];
  const unsigned char *byte = [self bytes];
  const unsigned char *endByte = byte + [self length];
  for (; byte != endByte; ++byte) [str appendFormat:@"%02x", *byte];
  return str;
}

@end

@implementation NSString (HMAC)

- (NSString *)hexString {
  const char *cStr = [self UTF8String];
  return [[NSData dataWithBytes:cStr length:strlen(cStr)] hexString];
}

- (NSString *)hmacWithKey:(NSString *)key {
  const char *cKey  = [key cStringUsingEncoding:NSASCIIStringEncoding];
  const char *cData = [self cStringUsingEncoding:NSASCIIStringEncoding];
  unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH];
  CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
  return [[NSData dataWithBytes:cHMAC length:sizeof(cHMAC)] hexString];
}

@end


text:
Date: 2018-04-02

The latest feature has been added to the master branch. `fitsio` now
supports reading image data into [`ndarray`] arrays.

Replicating some of the functionality of the Python [numpy] library,
where an array object can be treated like a simple scalar variable.

For example:

```rust
{{#include ../../fitsioexample/src/bin/ndarray_support.rs:9:14}}
```

Currently, only reading images is supported. I do see writing `Array`
objects coming in the future, but it is not currently supported.

I hope to be adding `ndarray` support to a formal versioned release
soon.

## Contributions

- [astrojghu] for seeding the idea in [this thread]

[`ndarray`]: https://crates.io/crates/ndarray
[astrojghu]: https://users.rust-lang.org/u/astrojhgu/summary
[this thread]: https://users.rust-lang.org/t/calling-all-rusty-astronomers/14099
[numpy]: https://pypi.python.org/pypi/numpy


text:
describe("InvoiceManager", function () {

  describe("calculateOrderFulfillmentAmount", function () {

    describe('customer bought BTC with YEN', function() {

      it('directly converts between YEN and BTC', function() {

        // We want to know how many satoshis you get for this amount of
        var yen = 1000;
        // Based on the current exchange rate for BTC to YEN (fictional here)
        var exchangeRates = { btcJpy: 10 };
        // Taking into account fixed numbers like Company fee and satoshis factor
        var companyFee = 1.0775;
        var btcToSatoshis = 100000000;

        var result = InvoiceManager.calculateOrderFulfillmentAmount('YEN', yen, exchangeRates);

        expect(result).to.equal(
          Math.floor(yen / companyFee / exchangeRates.btcJpy * btcToSatoshis)
        );

      });

    });

    describe('customer bought BTC with USD', function() {

      it('Converts from YEN to USD to BTC', function() {

        // We want to know how many satoshis you get for this amount of
        var yen = 1000;
        // Based on the current exchange rate for BTC to YEN (fictional here)
        var exchangeRates = {
          jpyUsd: 10,
          btcUsd: 10
        };
        // Taking into account fixed numbers like <COMPANY> fee and satoshis factor
        var companyFee = 1.0775;
        var btcToSatoshis = 100000000;

        var result = InvoiceManager.calculateOrderFulfillmentAmount('USD', yen, exchangeRates);

        expect(result).to.equal(
          Math.floor(yen / companyFee / exchangeRates.jpyUsd / exchangeRates.btcUsd * btcToSatoshis)
        );

      });

    });

  });

});


text:
require 'spec_helper'
require 'chemistrykit/config/reporting'

describe ChemistryKit::Config::Reporting do

  VALID_REPORTS_PATH = 'evidence'

  before(:each) do
    @reporting =  ChemistryKit::Config::Reporting.new
  end

  it 'should be initialized with no arguments' do
    @reporting.should be_an_instance_of ChemistryKit::Config::Reporting
  end

  it 'should return "evidence" for the log path' do
    @reporting.path.should eq VALID_REPORTS_PATH
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>org.jenkins-ci.plugins</groupId>
    <artifactId>plugin</artifactId>
    <version>1.580.3</version>
  </parent>
  <groupId>org.fedoraproject.jenkins.plugins</groupId>
  <artifactId>fedmsg-trigger</artifactId>
  <version>0.1-SNAPSHOT</version>
  <packaging>hpi</packaging>

  <name>Fedmsg Trigger Plugin</name>
  <description>Jenkins plugin for triggering builds via Fedmsg messages</description>
  <url>http://wiki.jenkins-ci.org/display/JENKINS/Fedmsg+Trigger+Plugin</url>

  <properties>
    <jeromq.version>0.3.4</jeromq.version>
    <jackson.version>2.5.2</jackson.version>
  </properties>

  <licenses>
    <license>
      <name>MIT License</name>
      <url>http://opensource.org/licenses/MIT</url>
    </license>
  </licenses>

  <scm>
    <connection>scm:git:ssh://github.com/jenkinsci/fedmsg-trigger-plugin.git</connection>
    <developerConnection>scm:git:ssh://git@github.com/jenkinsci/fedmsg-trigger-plugin.git</developerConnection>
    <url>https://github.com/jenkinsci/fedmsg-trigger-plugin</url>
  </scm>

  <developers>
    <developer>
      <id>msrb</id>
      <name>Michal Srb</name>
      <email>msrb@redhat.com</email>
    </developer>
  </developers>

  <dependencies>
    <dependency>
      <groupId>org.zeromq</groupId>
      <artifactId>jeromq</artifactId>
      <version>${jeromq.version}</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>${jackson.version}</version>
    </dependency>
  </dependencies>

  <repositories>
    <repository>
      <id>repo.jenkins-ci.org</id>
      <url>http://repo.jenkins-ci.org/public/</url>
    </repository>
  </repositories>
  <pluginRepositories>
    <pluginRepository>
      <id>repo.jenkins-ci.org</id>
      <url>http://repo.jenkins-ci.org/public/</url>
    </pluginRepository>
  </pluginRepositories>
</project>


text:
package fr.javatronic.blog.massive.annotation_041;

import fr.javatronic.blog.processor.Annotation_041;

@Annotation_041
public class Class_041_001 {
}


text:
// See LICENSE for license details.
// Based on Rocket Chip's stage implementation

package chipyard.stage

import freechips.rocketchip.stage.ConfigsAnnotation
import firrtl.options.{HasShellOptions, ShellOption}

/** This hijacks the existing ConfigAnnotation to accept the legacy _-delimited format  */
private[stage] object UnderscoreDelimitedConfigsAnnotation extends HasShellOptions {
  override val options = Seq(
    new ShellOption[String](
      longOption = "legacy-configs",
      toAnnotationSeq = a => {
        val split = a.split(':')
        assert(split.length == 2)
        val packageName = split.head
        val configs     = split.last.split("_")
        Seq(new ConfigsAnnotation(configs map { config => if (config contains ".") s"${config}" else s"${packageName}.${config}" } ))
      },
      helpText = "A string of underscore-delimited configs (configs have decreasing precendence from left to right).",
      shortOption = Some("LC")
    )
  )
}


text:
class Person < ActiveRecord::Base
  set_table_name 'people'
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <groupId>org.arquillian.universe</groupId>
        <artifactId>arquillian-universe-parent</artifactId>
        <version>1.0.0.Final-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <modelVersion>4.0.0</modelVersion>

    <artifactId>arquillian-spring</artifactId>
    <name>Arquillian Spring</name>
    <packaging>pom</packaging>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.arquillian.universe</groupId>
                <artifactId>arquillian-core</artifactId>
                <version>${project.version}</version>
                <scope>import</scope>
                <type>pom</type>
            </dependency>
            <dependency>
                <groupId>org.jboss.arquillian.extension</groupId>
                <artifactId>arquillian-service-integration-spring-inject</artifactId>
                <version>${version.arquillian_spring}</version>
            </dependency>
            <dependency>
                <groupId>org.jboss.arquillian.extension</groupId>
                <artifactId>arquillian-service-integration-spring-javaconfig</artifactId>
                <version>${version.arquillian_spring}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.arquillian.universe</groupId>
            <artifactId>arquillian-core</artifactId>
            <version>${project.version}</version>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>org.jboss.arquillian.extension</groupId>
            <artifactId>arquillian-service-integration-spring-inject</artifactId>
        </dependency>
        <dependency>
            <groupId>org.jboss.arquillian.extension</groupId>
            <artifactId>arquillian-service-integration-spring-javaconfig</artifactId>
        </dependency>
    </dependencies>
</project>


text:
import argparse
import importlib

def run(parser):
    config = parser.__dict__
    modstr = "scalpels.cli.actions.%s" % config.pop("action")
    mod = importlib.import_module(modstr)
    func = getattr(mod, "run")
    return func(config)

def main():
    rootparser = argparse.ArgumentParser(description="main entry point for scalpels")
    subparsers = rootparser.add_subparsers(title="actions", dest="action")

    # setup load actions
    load = subparsers.add_parser("load")
    load.add_argument("--storm", action="store_true", dest="storm", help="run concurrency nova boot")

    # setup start actions
    start = subparsers.add_parser("start")
    start.add_argument("-f", "--file", action="store", dest="file", help="config file for this task", required=False)
    start.add_argument("-a", "--agent", action="append", dest="agent", help="agent(s) to run", required=False)

    # setup report actions
    report = subparsers.add_parser("report")
    report.add_argument("--last", action="store_true", dest="last", help="report the last task")
    report.add_argument("uuid", type=str, default="", nargs="?", help="report the last task")

    # setup re-setup actions
    setup = subparsers.add_parser("setup")
    setup.add_argument("--force", action="store_true", dest="force", help="re-create db")

    parser = rootparser.parse_args()
    try:
        run(parser)
    except Exception as e:
        raise
        return 1
    else:
        return 0

if __name__ == "__main__":
    main()


text:
from marionette_harness import MarionetteTestCase
import json
import testsuite

class Test(MarionetteTestCase):

    def setUp(self):
        MarionetteTestCase.setUp(self)

        ts = testsuite.TestSuite()
        self.ts = ts

        self.URL = 'https://pinning-test.badssl.com/'

    def test_pinning(self):
        m = self.marionette

        with m.using_context('content'):

            res = False
            try:
                m.navigate(self.URL)
            except Exception:
                res = True

            self.assertTrue(res, msg="Page could be loaded")

            if res:
                errorCode = m.find_element('id', 'errorShortDescText2')
                self.assertEqual(json.loads(errorCode.get_attribute('data-l10n-args'))["error"],
                        'MOZILLA_PKIX_ERROR_KEY_PINNING_FAILURE',
                        msg='Wrong error code')


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>The nova.db.sqlalchemy.migrate_repo.versions.128_add_indexes_to_instances Module — nova 2012.2.1 documentation</title>

    <link rel="stylesheet" href="../_static/nature.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../_static/tweaks.css" type="text/css" />

    <link rel="top" title="nova 2012.2.1 documentation" href="../index.html" />
    <link rel="up" title="<no title>" href="autoindex.html" />
    <link rel="next" title="The nova.db.sqlalchemy.migrate_repo.versions.129_add_indexes_to_iscsi_targets Module" href="nova.db.sqlalchemy.migrate_repo.versions.129_add_indexes_to_iscsi_targets.html" />
    <link rel="prev" title="The nova.db.sqlalchemy.migrate_repo.versions.127_add_indexes_to_instance_type_extra_specs Module" href="nova.db.sqlalchemy.migrate_repo.versions.127_add_indexes_to_instance_type_extra_specs.html" />

OpenStack

Home

Projects

User Stories

Community

Blog

Wiki

Documentation

The <tt class="xref py py-mod docutils literal">nova.db.sqlalchemy.migrate_repo.versions.128_add_indexes_to_instances</tt> Module¶

<tt class="descname">downgrade</tt><big>(</big>migrate_engine<big>)</big>¶

<tt class="descname">upgrade</tt><big>(</big>migrate_engine<big>)</big>¶

Previous topic

The <tt class="docutils literal docutils literal docutils literal">nova.db.sqlalchemy.migrate_repo.versions.127_add_indexes_to_instance_type_extra_specs</tt> Module

Next topic

The <tt class="docutils literal">nova.db.sqlalchemy.migrate_repo.versions.129_add_indexes_to_iscsi_targets</tt> Module

This Page

Show Source

Quick search

              <form class="search" action="../search.html" method="get">
                <input type="text" name="q" size="18" />
                <input type="submit" value="Go" />
                <input type="hidden" name="check_keywords" value="yes" />
                <input type="hidden" name="area" value="default" />
              </form>

              Enter search terms or a module, class or function name.

Navigation

          index

          modules |

          next |

          previous |

nova 2012.2.1 documentation »

Developer Guide »

<no title> »

        © Copyright 2010-present, OpenStack, LLC.
      Last updated on Thu Nov 1 16:11:51 2012, commit 4ed8d3e.
      Created using Sphinx 1.1.3.


text:
package org.apache.camel.component.aws.xray;

import java.util.concurrent.TimeUnit;

import org.apache.camel.Exchange;
import org.apache.camel.builder.NotifyBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.aws.xray.bean.ProcessingCamelBean;
import org.apache.camel.component.aws.xray.component.CommonEndpoints;
import org.apache.camel.spi.InterceptStrategy;
import org.junit.Test;

import static org.apache.camel.component.aws.xray.TestDataBuilder.createSegment;
import static org.apache.camel.component.aws.xray.TestDataBuilder.createSubsegment;
import static org.apache.camel.component.aws.xray.TestDataBuilder.createTrace;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.greaterThan;

/**
 * This test uses a custom component that will trigger a long-running backing task for certain
 * specific states. The task is forwarded via an asynchronous send to a Camel route which then
 * performs the task, such as an upload or a computation.
 *

 * AWS XRay does monitor the subsegment count per segment and only emits the segment to the local
 * XRay daemon once the segment is closed and its internal count reaches 0. If the segment is closed
 * before the counter reached 0 the segment is not emitted till the last subsegments belonging to
 * that segment got closed.
 *

 * Due to the asynchronous nature of the backing {@link ProcessingCamelBean processing camel bean},
 * the first request is still in progress when the second request is triggered. As those tasks
 * aren't executed in parallel, AWS XRay does not take notice of the seconds processing Camel bean
 * invocation yet which leads to a premature emit of that segment and thus missing subsegments
 * for the route and bean invocation. This is possible as the count of the segment reached 0 when
 * the segment got closed as Camel has not had a chance yet to create the subsegments for the
 * asynchronously executed route and its bean invocation.
 */
public class CustomComponentTest extends CamelAwsXRayTestSupport {

    private static final String START = "seda:start";
    private static final String DELIVERY = "seda:delivery";
    private static final String IN_QUEUE = "seda:inqueue";
    private static final String PERSISTENCE_QUEUE = "seda:persistence-queue";
    private static final String PERSISTING = "seda:persisting";

    public CustomComponentTest() {
        super(
                createTrace().inRandomOrder()
                        .withSegment(createSegment("start")
                                .withSubsegment(createSubsegment(DELIVERY))
                        )
                        .withSegment(createSegment("delivery")
                                .withSubsegment(createSubsegment(CommonEndpoints.RECEIVED)
                                        .withSubsegment(createSubsegment("seda:backingTask"))
                                        .withSubsegment(createSubsegment("seda:backingTask"))
                                        .withMetadata("state", "received")
                                )
                                .withSubsegment(createSubsegment(IN_QUEUE))
                        )
                        .withSegment(createSegment("processing")
                                .withSubsegment(createSubsegment(CommonEndpoints.PROCESSING))
                                .withSubsegment(createSubsegment(PERSISTENCE_QUEUE))
                        )
                        .withSegment(createSegment("wait-for-persisting")
                                .withSubsegment(createSubsegment(CommonEndpoints.PERSISTENCE_QUEUE))
                                .withSubsegment(createSubsegment(PERSISTING))
                        )
                        .withSegment(createSegment("persisting")
                                .withSubsegment(createSubsegment(CommonEndpoints.READY)
                                        // not available due to the asynchronous, long-running nature of the processing
                                        // bean. If the sleep is commented out in the bean, this subsegments should be
                                        // available
//                                        .withSubsegment(createSubsegment("backingTask")
//                                                .withSubsegment(createSubsegment("bean:ProcessingCamelBean"))
//                                        )
//                                        .withMetadata("state", "ready")
                                )
                        )
        );
    }

    @Override
    protected InterceptStrategy getTracingStrategy() {
        return new TraceAnnotatedTracingStrategy();
    }

    @Test
    public void testRoute() {
        NotifyBuilder notify = new NotifyBuilder(context).whenDone(7).create();

        template.requestBody(START, "Hello");

        assertThat("Not all exchanges were fully processed",
                notify.matches(10, TimeUnit.SECONDS), is(equalTo(true)));

        verify();

        assertThat(ProcessingCamelBean.gotInvoked(), is(greaterThan(0)));
    }

    @Override
    protected RouteBuilder createRouteBuilder() {

        return new RouteBuilder() {
            @Override
            public void configure() {
                from(START).routeId("start")
                        .log("Starting test")
                        .inOnly(DELIVERY);

                from(DELIVERY).routeId("delivery")
                        .log("Doing some stuff")
                        .to(CommonEndpoints.RECEIVED)
                        .delay(100)
                        .inOnly(IN_QUEUE);

                from(IN_QUEUE).routeId("processing")
                        .log("Do some more stuff")
                        .to(CommonEndpoints.PROCESSING)
                        .delay(100)
                        .inOnly(PERSISTENCE_QUEUE);

                from(PERSISTENCE_QUEUE).routeId("wait-for-persisting")
                        .log("Waiting on available persisting instance")
                        .to(CommonEndpoints.PERSISTENCE_QUEUE)
                        .delay(100)
                        .inOnly(PERSISTING);

                from(PERSISTING).routeId("persisting")
                        .log("Payload ready for usage")
                        .to(CommonEndpoints.READY)
                        .delay(100)
                        .log("done");

                from("seda:backingTask").routeId("backingTask")
                        .onException(Exception.class)
                        .redeliveryDelay(100L)
                        .onRedelivery((Exchange exchange) -> System.err.println(">> Retrying due to "
                                + exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class).getLocalizedMessage()))
                        .logExhausted(true)
                        .handled(true)
                        .logStackTrace(true)
                        .end()

                        .log("routing at ${routeId}")
                        .bean(ProcessingCamelBean.class)
                        .log("processing camel bean invoked");
            }
        };
    }
}


text:
from flask import Blueprint

tracking_view = Blueprint('tracking', __name__, template_folder='templates')

from analyticpi.views import tracking

auth_view = Blueprint('auth', __name__, template_folder='templates')

from analyticpi.views import auth

home_view = Blueprint('home', __name__, template_folder='templates')

from analyticpi.views import home

site_view = Blueprint('site', __name__, template_folder='templates')

from analyticpi.views import site


text:
"""
Pass helpers.
"""

from __future__ import print_function, division, absolute_import
from pykit.ir import defs, combine
from pykit.ir.builder import OpBuilder, Builder
from pykit.utils import prefix as prefix_, mergedicts

class FunctionPass(object):
    """
    Can be used from visitors or transformers, holds a builder and opbuilder.
    """

    opbuilder = OpBuilder()

    def __init__(self, func):
        self.func = func
        self.builder = Builder(func)

#===------------------------------------------------------------------===
# Pass to group operations such as add/mul
#===------------------------------------------------------------------===

def opgrouper(visitor, prefix='op_'):
    """
    op_add, op_mul, ... -> op_binary
    """
    handlers = mergedicts(unop_handlers(visitor.op_unary, prefix),
                          binop_handlers(visitor.op_binary, prefix),
                          compare_handlers(visitor.op_compare, prefix))
    return combine(visitor, handlers)

def unop_handlers(handler, prefix='op_'):
    return dict.fromkeys(prefix_(defs.unary, prefix), handler)

def binop_handlers(handler, prefix='op_'):
    return dict.fromkeys(prefix_(defs.binary, prefix), handler)

def compare_handlers(handler, prefix='op_'):
    return dict.fromkeys(prefix_(defs.compare, prefix), handler)


text:
package net.bytebuddy.instrumentation.method.bytecode.stack.collection;

import net.bytebuddy.instrumentation.Instrumentation;
import net.bytebuddy.instrumentation.method.bytecode.stack.StackManipulation;
import net.bytebuddy.instrumentation.method.bytecode.stack.StackSize;
import net.bytebuddy.instrumentation.type.TypeDescription;
import net.bytebuddy.test.utility.MockitoRule;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.TestRule;
import org.mockito.Mock;
import org.mockito.asm.Type;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

import java.util.Collections;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.mockito.Mockito.*;

public abstract class AbstractArrayFactoryTest {

    @Rule
    public TestRule mockitoRule = new MockitoRule(this);

    @Mock
    private TypeDescription componentTypeDescription;

    @Mock
    private MethodVisitor methodVisitor;

    @Mock
    private StackManipulation stackManipulation;

    @Mock
    private Instrumentation.Context instrumentationContext;

    @Before
    public void setUp() throws Exception {
        when(stackManipulation.isValid()).thenReturn(true);
    }

    @After
    public void tearDown() throws Exception {
        verifyZeroInteractions(instrumentationContext);
    }

    protected void testCreationUsing(Class<?> componentType, int storageOpcode) throws Exception {
        defineComponentType(componentType);
        CollectionFactory arrayFactory = ArrayFactory.targeting(componentTypeDescription);
        StackManipulation arrayStackManipulation = arrayFactory.withValues(Collections.singletonList(stackManipulation));
        assertThat(arrayStackManipulation.isValid(), is(true));
        verify(stackManipulation, atLeast(1)).isValid();
        StackManipulation.Size size = arrayStackManipulation.apply(methodVisitor, instrumentationContext);
        assertThat(size.getSizeImpact(), is(1));
        assertThat(size.getMaximalSize(), is(3 + StackSize.of(componentType).toIncreasingSize().getSizeImpact()));
        verify(methodVisitor).visitInsn(Opcodes.ICONST_1);
        verifyArrayCreation(methodVisitor);
        verify(methodVisitor).visitInsn(Opcodes.DUP);
        verify(methodVisitor).visitInsn(Opcodes.ICONST_0);
        verify(stackManipulation).apply(methodVisitor, instrumentationContext);
        verify(methodVisitor).visitInsn(storageOpcode);
        verifyNoMoreInteractions(methodVisitor);
        verifyNoMoreInteractions(stackManipulation);
    }

    protected abstract void verifyArrayCreation(MethodVisitor methodVisitor);

    private void defineComponentType(Class<?> componentType) {
        when(componentTypeDescription.isPrimitive()).thenReturn(componentType.isPrimitive());
        when(componentTypeDescription.represents(componentType)).thenReturn(true);
        when(componentTypeDescription.getInternalName()).thenReturn(Type.getInternalName(componentType));
        when(componentTypeDescription.getStackSize()).thenReturn(StackSize.of(componentType));
        when(stackManipulation.apply(any(MethodVisitor.class), any(Instrumentation.Context.class)))
                .thenReturn(StackSize.of(componentType).toIncreasingSize());
    }
}


text:
package leo.modules

import leo.datastructures.TPTP.AnnotatedFormula
import leo.datastructures.{Role_Definition, Role_Type, Signature}
import leo.{Configuration, Out}
import leo.modules.output._
import leo.modules.input.{Input, ProblemStatistics}

object Modes {
  final def apply(beginTime: Long, parsedProblem: Seq[AnnotatedFormula], stats: ProblemStatistics): Unit = {
    val timeout = Configuration.TIMEOUT
    if (Configuration.isSet("seq")) {
      seqLoop(beginTime, timeout, parsedProblem, stats)
    } else if (Configuration.isSet("scheduled")) {
      scheduledSeq(beginTime, timeout, parsedProblem)
    } else if (Configuration.isSet("processOnly")) {
      normalizationOnly(parsedProblem)
    } else if (Configuration.isSet("syntaxcheck")) {
      syntaxCheck(parsedProblem)
    } else if (Configuration.isSet("typecheck")) {
      typeCheck(parsedProblem)
    } else if (Configuration.isSet("toTHF")) {
      toTHF(parsedProblem)
    } else {
      seqLoop(beginTime, timeout, parsedProblem, stats)
    }
  }

  final def toTHF(parsedProblem: scala.Seq[AnnotatedFormula]): Unit = {
    implicit val sig: Signature = Signature.freshWithHOL()
    val sb: StringBuilder = new StringBuilder
    val erg = Input.processProblem(parsedProblem)
    sb.append(ToTPTP(sig))
    sb.append(ToTPTP.printDefinitions(sig))
    erg.foreach {case (id, t, role) =>
      if (role != Role_Definition && role != Role_Type) {
        sb.append(ToTPTP.toTPTP(id, termToClause(t), role)(sig))
        sb.append("\n")
      }
    }
    Out.output(SZSResult(SZS_Success, Configuration.PROBLEMFILE, s"Translation finished."))
    Out.output(SZSOutput(SZS_ListOfTHF, Configuration.PROBLEMFILE, sb.toString()))
  }

  final def syntaxCheck(parsedProblem: scala.Seq[AnnotatedFormula]): Unit = {
    // if it fails the catch in Main will print the error
    Out.output(SZSResult(SZS_Success, Configuration.PROBLEMFILE, s"Syntax check succeeded"))
  }

  final def typeCheck(parsedProblem: scala.Seq[AnnotatedFormula]): Unit = {
    import leo.datastructures.{Term, Role}
    implicit val sig: Signature = Signature.freshWithHOL()
    val erg = Input.processProblem(parsedProblem)
    var notWellTyped: Seq[(Input.FormulaId, Term, Role)] = Seq.empty
    erg.foreach {case (id, t, role) =>
      val wellTyped = Term.wellTyped(t)
      if (!wellTyped) notWellTyped = notWellTyped :+ (id, t, role)
    }
    if (notWellTyped.isEmpty)
      Out.output(SZSResult(SZS_Success, Configuration.PROBLEMFILE, "Type check succeeded"))
    else {
      Out.output(SZSResult(SZS_TypeError, Configuration.PROBLEMFILE, "Problem is not well-typed"))
      Out.output(SZSOutput(SZS_LogicalData, Configuration.PROBLEMFILE, s"Formulae ${notWellTyped.map(_._1).mkString(", ")} are not well-typed."))
    }
  }

  final def normalizationOnly(parsedProblem: Seq[AnnotatedFormula]): Unit = {
    Out.info("Running in processOnly mode.")
    modes.Normalization(parsedProblem)
  }

  final def seqLoop(startTime: Long, timeout: Int, parsedProblem: Seq[AnnotatedFormula], stats: ProblemStatistics): Unit = {
    Out.info("Running in sequential loop mode.")
    prover.SeqLoop(startTime, timeout, parsedProblem, stats)
  }

  final def scheduledSeq(startTime: Long, timeout: Int, parsedProblem: Seq[AnnotatedFormula]): Unit = {
    Out.info("Running in scheduled sequential loop mode.")
    modes.ScheduledRun(startTime, timeout, parsedProblem)
  }

}


text:
// Copyright 2018 The Cobalt Authors. All Rights Reserved.
//
// 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.

#include "starboard/shared/starboard/player/filter/media_time_provider_impl.h"

#include "starboard/common/log.h"

namespace starboard {
namespace shared {
namespace starboard {
namespace player {
namespace filter {

MediaTimeProviderImpl::MediaTimeProviderImpl(
    scoped_ptr<MonotonicSystemTimeProvider> system_time_provider)
    : system_time_provider_(system_time_provider.Pass()) {
  SB_DCHECK(system_time_provider_);
}

void MediaTimeProviderImpl::Play() {
  SB_DCHECK(BelongsToCurrentThread());

  if (is_playing_) {
    return;
  }

  ScopedLock scoped_lock(mutex_);
  seek_to_time_ = GetCurrentMediaTime_Locked(&seek_to_time_set_at_);
  is_playing_ = true;
}

void MediaTimeProviderImpl::Pause() {
  SB_DCHECK(BelongsToCurrentThread());

  if (!is_playing_) {
    return;
  }

  ScopedLock scoped_lock(mutex_);
  seek_to_time_ = GetCurrentMediaTime_Locked(&seek_to_time_set_at_);
  is_playing_ = false;
}

void MediaTimeProviderImpl::SetPlaybackRate(double playback_rate) {
  SB_DCHECK(BelongsToCurrentThread());

  if (playback_rate_ == playback_rate) {
    return;
  }

  ScopedLock scoped_lock(mutex_);
  seek_to_time_ = GetCurrentMediaTime_Locked(&seek_to_time_set_at_);
  playback_rate_ = playback_rate;
}

void MediaTimeProviderImpl::Seek(SbTime seek_to_time) {
  SB_DCHECK(BelongsToCurrentThread());

  ScopedLock scoped_lock(mutex_);

  seek_to_time_ = seek_to_time;
  seek_to_time_set_at_ = system_time_provider_->GetMonotonicNow();

  // This is unnecessary, but left it here just in case scheduled job is added
  // in future.
  CancelPendingJobs();
}

SbTime MediaTimeProviderImpl::GetCurrentMediaTime(bool* is_playing,
                                                  bool* is_eos_played,
                                                  bool* is_underflow,
                                                  double* playback_rate) {
  ScopedLock scoped_lock(mutex_);

  SbTime current = GetCurrentMediaTime_Locked();

  *is_playing = is_playing_;
  *is_eos_played = false;
  *is_underflow = false;
  *playback_rate = playback_rate_;

  return current;
}

SbTime MediaTimeProviderImpl::GetCurrentMediaTime_Locked(
    SbTimeMonotonic* current_time /*= NULL*/) {
  mutex_.DCheckAcquired();

  SbTimeMonotonic now = system_time_provider_->GetMonotonicNow();

  if (!is_playing_ || playback_rate_ == 0.0) {
    if (current_time) {
      *current_time = now;
    }
    return seek_to_time_;
  }

  SbTimeMonotonic elapsed = (now - seek_to_time_set_at_) * playback_rate_;
  if (current_time) {
    *current_time = now;
  }
  return seek_to_time_ + elapsed;
}

}  // namespace filter
}  // namespace player
}  // namespace starboard
}  // namespace shared
}  // namespace starboard


text:
package cc.schieder.jira.pvp.test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.util.List;

import org.junit.Test;

import cc.schieder.jira.pvp.PVPHelper;

public class PVPHelperTest {

	@Test
	public void testParsePVPRoles(){
		String roleString = null;
		List<String> roles = null;
		//PVP Standard
		roleString = "project1-users();project1-developers";
		roles = new PVPHelper().parsePVPRoles(roleString);
		assertEquals(2, roles.size());
		assertTrue(roles.contains("project1-users"));
		assertTrue(roles.contains("project1-developers"));

		//STAT.AT-Standard
		roleString = "GROUPS(NAME=jira-users,NAME=edv-users,NAME=edv-developers,NAME=edv-administrators)";
		roles = new PVPHelper().parsePVPRoles(roleString);
		assertEquals(4, roles.size());
		assertTrue(roles.contains("jira-users"));
		assertTrue(roles.contains("edv-users"));
		assertTrue(roles.contains("edv-developers"));
		assertTrue(roles.contains("edv-administrators"));

	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="tool_bar" type="id"/>
    <item name="empty_view" type="id"/>

    <item name="alipay_bar" type="id"/>
    <item name="alipay_snap" type="id"/>
</resources>


text:
package io.motown.operatorapi.viewmodel.persistence.repositories;

import io.motown.operatorapi.viewmodel.persistence.entities.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import java.util.List;

public class TransactionRepository {

    private static final Logger LOG = LoggerFactory.getLogger(TransactionRepository.class);

    private EntityManagerFactory entityManagerFactory;

    public Transaction createOrUpdate(Transaction transaction) {
        EntityManager entityManager = getEntityManager();

        EntityTransaction tx = null;
        try {
            tx = entityManager.getTransaction();
            tx.begin();

            Transaction persistedTransaction = entityManager.merge(transaction);

            tx.commit();

            return persistedTransaction;
        } catch (Exception e) {
            LOG.error("Exception while trying to persist transaction.", e);
            if(tx != null && tx.isActive()) {
                tx.rollback();
            }
            throw e;
        } finally {
            entityManager.close();
        }
    }

    /**
     * Find transactions by transaction id (not the auto-increment transaction.id)
     */
    public Transaction findByTransactionId(String transactionId) {
        EntityManager entityManager = getEntityManager();
        try {
            return entityManager.createQuery("SELECT t FROM io.motown.operatorapi.viewmodel.persistence.entities.Transaction AS t WHERE t.transactionId = :transactionId", Transaction.class)
                    .setParameter("transactionId", transactionId)
                    .getSingleResult();
        } finally {
            entityManager.close();
        }
    }

    public List<Transaction> findAll(int offset, int limit) {
        EntityManager entityManager = getEntityManager();
        try {
            return entityManager.createQuery("SELECT t FROM io.motown.operatorapi.viewmodel.persistence.entities.Transaction AS t", Transaction.class)
                    .setFirstResult(offset)
                    .setMaxResults(limit)
                    .getResultList();
        } finally {
            entityManager.close();
        }
    }

    public Long getTotalNumberOfTransactions() {
        EntityManager entityManager = getEntityManager();
        try {
            return entityManager.createQuery("SELECT COUNT(t) FROM io.motown.operatorapi.viewmodel.persistence.entities.Transaction t", Long.class).getSingleResult();
        } finally {
            entityManager.close();
        }
    }

    public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
        this.entityManagerFactory = entityManagerFactory;
    }

    private EntityManager getEntityManager() {
        return entityManagerFactory.createEntityManager();
    }
}


text:
#ifndef _FS_EASE_EXPR_H_
#define _FS_EASE_EXPR_H_

#include "FsObject.h"
#include "FsMacros.h"

NS_FS_BEGIN

enum
{
	FS_EASE_IN=0,
	FS_EASE_OUT=1,
	FS_EASE_INOUT=2,
	FS_EASE_OUTIN=3,
};

class EaseExpr:public FsObject
{
	public:
		float getValue(float t);
		float getValue(float t,int mode);
		void setMode(int mode);
		int getMode();

	public:
		virtual float getEaseIn(float t)=0;
		virtual float getEaseOut(float t);
		virtual float getEaseInOut(float t);
		virtual float getEaseOutIn(float t);

		/* inherit FsObject */
		const char* className();

	protected:
		EaseExpr(int mode);
		EaseExpr();
		virtual ~EaseExpr();

	private:
		int m_easeMode;

};

NS_FS_END
#endif /*_FS_EASE_EXPR_H_*/


text:
<!DOCTYPE html>
<script src="../resources/testharness.js"></script>
<script src="../resources/testharnessreport.js"></script>
<script src="resources/test-helpers.js"></script>
<script>
service_worker_test('resources/register-foreign-fetch-errors-worker.js',
                    'foreign fetch registration');
</script>


text:
import React from 'react';
import _ from 'lodash';
import ReplOutput from '../common/ReplOutput';
import ReplCommon from '../common/ReplCommon';
import ReplOutputObject from './ReplOutputObject';
import ReplActions from '../actions/ReplActions';

export default class ReplOutputFunction extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      collapse: true,
      funCollapse: true
    }

    this.onToggleCollapse = this.onToggleCollapse.bind(this);
    this.onToggleFunCollapse = this.onToggleFunCollapse.bind(this);
    this.getType = this.getType.bind(this);
    this.getAllProps = this.getAllProps.bind(this);
    this.bindObjectToContext = this.bindObjectToContext.bind(this);
  }

  shouldComponentUpdate(nextProps, nextState) {
    return !(_.isEqual(nextState, this.state) && _.isEqual(nextProps, this.props));
  }

  onToggleCollapse() {
    this.setState({
      collapse: !this.state.collapse
    });
  }

  onToggleFunCollapse() {
    this.setState({
      funCollapse: !this.state.funCollapse
    });
  }

  getType() {
    let type = ReplCommon.funType(this.props.fun);
    return ` ${type} {}`;
  }

  getAllProps() {
    let names = Object.getOwnPropertyNames(this.props.fun);
    let symbols = Object.getOwnPropertySymbols(this.props.fun);
    return _.sortBy(names.concat(symbols), (value) => {
      return value.toString();
    });
  }

  bindObjectToContext() {
    ReplActions.bindObjectToContext(this.props.fun, ReplOutput.transformObject(this.props.fun));
  }

  render() {
    let label = ReplCommon.highlight(this.getType());
    return (

        {
          this.state.collapse
          ?

          :

              {
                _.map(this.getAllProps(), (key) => {
                  let value = ReplOutput.readProperty(this.props.fun, key);
                  let keyClass = Object.prototype.propertyIsEnumerable.call(this.props.fun, key) ? 'object-key' : 'object-key dull';
                  return (

                      {

                          {key.toString()}
                          :

                      }
                      {
                        value && value._isReactElement
                          ? value
                          : ReplOutput.transformObject(value)
                      }

                  )
                })
              }
              {
                this.props.fun.__proto__
                ?

                      __proto__
                      :
                      <ReplOutputObject object={Object.getPrototypeOf(this.props.fun)} primitive={false}/>

                : null
              }
              {
                this.props.expandable
                  ? this.state.funCollapse
                      ?

                      :

                  :

              }

        }

    );
  }
}


text:
class Customer::RepliesController < Customer::Base
  before_action :prepare_message

  def new
    @reply = CustomerMessage.new
  end

  # POST
  def confirm
    @reply = CustomerMessage.new(customer_message_params)
    if @reply.valid?
      render action: 'confirm'
    else
      flash.now.alert = t('.flash_alert')
      render action: 'new'
    end
  end

  def create
    @reply = CustomerMessage.new(customer_message_params)
    if params[:commit]
      @reply.parent = @message
      if @reply.save
        flash.notice = t('.flash_notice')
        redirect_to :customer_messages
      else
        flash.now.alert = t('.flash_alert')
        render action: 'new'
      end
    else
      render action: 'new'
    end
  end

  private
  def prepare_message
    @message = StaffMessage.find(params[:message_id])
  end

  def customer_message_params
    params.require(:customer_message).permit(:subject, :body)
  end

end


text:
package com.tremolosecurity.scalejs.token.sdk;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpSession;

import com.tremolosecurity.proxy.auth.AuthInfo;
import com.tremolosecurity.proxy.filter.HttpFilterConfig;
import com.tremolosecurity.saml.Attribute;

public class AttributeToken implements TokenLoader {

	ArrayList<String> attributes;

	@Override
	public void init(HttpFilterConfig config) throws Exception {
		this.attributes = new ArrayList<String>();
		this.attributes.addAll(config.getAttribute("attributes").getValues());

	}

	@Override
	public Object loadToken(AuthInfo user, HttpSession session) throws Exception {
		HashMap<String,String> attrs = new HashMap<String,String>();

		for (String attrName : this.attributes) {
			Attribute attr = user.getAttribs().get(attrName);
			if (attr != null) {
				attrs.put(attr.getName(),attr.getValues().get(0));
			}
		}

		return attrs;
	}

}


text:
module Gridhook
  class Engine < ::Rails::Engine
  end
end


text:
namespace crashpad {
namespace test {
namespace {

void GetSystemInfoStream(const std::string& file_contents,
                         size_t csd_version_length,
                         const MINIDUMP_SYSTEM_INFO** system_info,
                         const MINIDUMP_STRING** csd_version) {
  // The expected number of bytes for the CSD version's MINIDUMP_STRING::Buffer.
  const size_t kCSDVersionBytes =
      csd_version_length * sizeof(MINIDUMP_STRING::Buffer[0]);
  const size_t kCSDVersionBytesWithNUL =
      kCSDVersionBytes + sizeof(MINIDUMP_STRING::Buffer[0]);

  const size_t kDirectoryOffset = sizeof(MINIDUMP_HEADER);
  const size_t kSystemInfoStreamOffset =
      kDirectoryOffset + sizeof(MINIDUMP_DIRECTORY);
  const size_t kCSDVersionOffset =
      kSystemInfoStreamOffset + sizeof(MINIDUMP_SYSTEM_INFO);
  const size_t kFileSize =
      kCSDVersionOffset + sizeof(MINIDUMP_STRING) + kCSDVersionBytesWithNUL;

  ASSERT_EQ(kFileSize, file_contents.size());

  const MINIDUMP_HEADER* header =
      reinterpret_cast<const MINIDUMP_HEADER*>(&file_contents[0]);

  VerifyMinidumpHeader(header, 1, 0);
  if (testing::Test::HasFatalFailure()) {
    return;
  }

  const MINIDUMP_DIRECTORY* directory =
      reinterpret_cast<const MINIDUMP_DIRECTORY*>(
          &file_contents[kDirectoryOffset]);

  ASSERT_EQ(kMinidumpStreamTypeSystemInfo, directory->StreamType);
  ASSERT_EQ(sizeof(MINIDUMP_SYSTEM_INFO), directory->Location.DataSize);
  ASSERT_EQ(kSystemInfoStreamOffset, directory->Location.Rva);

  *system_info = reinterpret_cast<const MINIDUMP_SYSTEM_INFO*>(
      &file_contents[kSystemInfoStreamOffset]);

  ASSERT_EQ(kCSDVersionOffset, (*system_info)->CSDVersionRva);

  *csd_version = reinterpret_cast<const MINIDUMP_STRING*>(
      &file_contents[kCSDVersionOffset]);

  ASSERT_EQ(kCSDVersionBytes, (*csd_version)->Length);
}

TEST(MinidumpSystemInfoWriter, Empty) {
  MinidumpFileWriter minidump_file_writer;
  MinidumpSystemInfoWriter system_info_writer;

  system_info_writer.SetCSDVersion(std::string());

  minidump_file_writer.AddStream(&system_info_writer);

  StringFileWriter file_writer;
  ASSERT_TRUE(minidump_file_writer.WriteEverything(&file_writer));

  const MINIDUMP_SYSTEM_INFO* system_info;
  const MINIDUMP_STRING* csd_version;

  GetSystemInfoStream(file_writer.string(), 0, &system_info, &csd_version);
  if (Test::HasFatalFailure()) {
    return;
  }

  EXPECT_EQ(kMinidumpCPUArchitectureUnknown,
            system_info->ProcessorArchitecture);
  EXPECT_EQ(0u, system_info->ProcessorLevel);
  EXPECT_EQ(0u, system_info->ProcessorRevision);
  EXPECT_EQ(0u, system_info->NumberOfProcessors);
  EXPECT_EQ(0u, system_info->ProductType);
  EXPECT_EQ(0u, system_info->MajorVersion);
  EXPECT_EQ(0u, system_info->MinorVersion);
  EXPECT_EQ(0u, system_info->BuildNumber);
  EXPECT_EQ(0u, system_info->PlatformId);
  EXPECT_EQ(0u, system_info->SuiteMask);
  EXPECT_EQ(0u, system_info->Cpu.X86CpuInfo.VendorId[0]);
  EXPECT_EQ(0u, system_info->Cpu.X86CpuInfo.VendorId[1]);
  EXPECT_EQ(0u, system_info->Cpu.X86CpuInfo.VendorId[2]);
  EXPECT_EQ(0u, system_info->Cpu.X86CpuInfo.VersionInformation);
  EXPECT_EQ(0u, system_info->Cpu.X86CpuInfo.FeatureInformation);
  EXPECT_EQ(0u, system_info->Cpu.X86CpuInfo.AMDExtendedCpuFeatures);
  EXPECT_EQ(0u, system_info->Cpu.OtherCpuInfo.ProcessorFeatures[0]);
  EXPECT_EQ(0u, system_info->Cpu.OtherCpuInfo.ProcessorFeatures[1]);

  EXPECT_EQ('\0', csd_version->Buffer[0]);
}

TEST(MinidumpSystemInfoWriter, X86_Win) {
  MinidumpFileWriter minidump_file_writer;
  MinidumpSystemInfoWriter system_info_writer;

  const MinidumpCPUArchitecture kCPUArchitecture = kMinidumpCPUArchitectureX86;
  const uint16_t kCPULevel = 0x0010;
  const uint16_t kCPURevision = 0x0602;
  const uint8_t kCPUCount = 1;
  const MinidumpOS kOS = kMinidumpOSWin32NT;
  const MinidumpOSType kOSType = kMinidumpOSTypeWorkstation;
  const uint32_t kOSVersionMajor = 6;
  const uint32_t kOSVersionMinor = 1;
  const uint32_t kOSVersionBuild = 7601;
  const char kCSDVersion[] = "Service Pack 1";
  const uint16_t kSuiteMask = VER_SUITE_SINGLEUSERTS;
  const char kCPUVendor[] = "AuthenticAMD";
  const uint32_t kCPUVersion = 0x00100f62;
  const uint32_t kCPUFeatures = 0x078bfbff;
  const uint32_t kAMDFeatures = 0xefd3fbff;

  uint32_t cpu_vendor_registers[3];
  ASSERT_EQ(sizeof(cpu_vendor_registers), strlen(kCPUVendor));
  memcpy(cpu_vendor_registers, kCPUVendor, sizeof(cpu_vendor_registers));

  system_info_writer.SetCPUArchitecture(kCPUArchitecture);
  system_info_writer.SetCPULevelAndRevision(kCPULevel, kCPURevision);
  system_info_writer.SetCPUCount(kCPUCount);
  system_info_writer.SetOS(kOS);
  system_info_writer.SetOSType(kMinidumpOSTypeWorkstation);
  system_info_writer.SetOSVersion(
      kOSVersionMajor, kOSVersionMinor, kOSVersionBuild);
  system_info_writer.SetCSDVersion(kCSDVersion);
  system_info_writer.SetSuiteMask(kSuiteMask);
  system_info_writer.SetCPUX86VendorString(kCPUVendor);
  system_info_writer.SetCPUX86VersionAndFeatures(kCPUVersion, kCPUFeatures);
  system_info_writer.SetCPUX86AMDExtendedFeatures(kAMDFeatures);

  minidump_file_writer.AddStream(&system_info_writer);

  StringFileWriter file_writer;
  ASSERT_TRUE(minidump_file_writer.WriteEverything(&file_writer));

  const MINIDUMP_SYSTEM_INFO* system_info;
  const MINIDUMP_STRING* csd_version;

  GetSystemInfoStream(
      file_writer.string(), strlen(kCSDVersion), &system_info, &csd_version);
  if (Test::HasFatalFailure()) {
    return;
  }

  EXPECT_EQ(kCPUArchitecture, system_info->ProcessorArchitecture);
  EXPECT_EQ(kCPULevel, system_info->ProcessorLevel);
  EXPECT_EQ(kCPURevision, system_info->ProcessorRevision);
  EXPECT_EQ(kCPUCount, system_info->NumberOfProcessors);
  EXPECT_EQ(kOSType, system_info->ProductType);
  EXPECT_EQ(kOSVersionMajor, system_info->MajorVersion);
  EXPECT_EQ(kOSVersionMinor, system_info->MinorVersion);
  EXPECT_EQ(kOSVersionBuild, system_info->BuildNumber);
  EXPECT_EQ(kOS, system_info->PlatformId);
  EXPECT_EQ(kSuiteMask, system_info->SuiteMask);
  EXPECT_EQ(cpu_vendor_registers[0], system_info->Cpu.X86CpuInfo.VendorId[0]);
  EXPECT_EQ(cpu_vendor_registers[1], system_info->Cpu.X86CpuInfo.VendorId[1]);
  EXPECT_EQ(cpu_vendor_registers[2], system_info->Cpu.X86CpuInfo.VendorId[2]);
  EXPECT_EQ(kCPUVersion, system_info->Cpu.X86CpuInfo.VersionInformation);
  EXPECT_EQ(kCPUFeatures, system_info->Cpu.X86CpuInfo.FeatureInformation);
  EXPECT_EQ(kAMDFeatures, system_info->Cpu.X86CpuInfo.AMDExtendedCpuFeatures);

  for (size_t index = 0; index < strlen(kCSDVersion); ++index) {
    EXPECT_EQ(kCSDVersion[index], csd_version->Buffer[index]) << index;
  }
}

TEST(MinidumpSystemInfoWriter, X86_64_Mac) {
  MinidumpFileWriter minidump_file_writer;
  MinidumpSystemInfoWriter system_info_writer;

  const MinidumpCPUArchitecture kCPUArchitecture =
      kMinidumpCPUArchitectureAMD64;
  const uint16_t kCPULevel = 0x0006;
  const uint16_t kCPURevision = 0x3a09;
  const uint8_t kCPUCount = 8;
  const MinidumpOS kOS = kMinidumpOSMacOSX;
  const MinidumpOSType kOSType = kMinidumpOSTypeWorkstation;
  const uint32_t kOSVersionMajor = 10;
  const uint32_t kOSVersionMinor = 9;
  const uint32_t kOSVersionBuild = 4;
  const char kCSDVersion[] = "13E28";
  const uint64_t kCPUFeatures[2] = {0x10427f4c, 0x00000000};

  system_info_writer.SetCPUArchitecture(kCPUArchitecture);
  system_info_writer.SetCPULevelAndRevision(kCPULevel, kCPURevision);
  system_info_writer.SetCPUCount(kCPUCount);
  system_info_writer.SetOS(kOS);
  system_info_writer.SetOSType(kMinidumpOSTypeWorkstation);
  system_info_writer.SetOSVersion(
      kOSVersionMajor, kOSVersionMinor, kOSVersionBuild);
  system_info_writer.SetCSDVersion(kCSDVersion);
  system_info_writer.SetCPUOtherFeatures(kCPUFeatures[0], kCPUFeatures[1]);

  minidump_file_writer.AddStream(&system_info_writer);

  StringFileWriter file_writer;
  ASSERT_TRUE(minidump_file_writer.WriteEverything(&file_writer));

  const MINIDUMP_SYSTEM_INFO* system_info;
  const MINIDUMP_STRING* csd_version;

  GetSystemInfoStream(
      file_writer.string(), strlen(kCSDVersion), &system_info, &csd_version);
  if (Test::HasFatalFailure()) {
    return;
  }

  EXPECT_EQ(kCPUArchitecture, system_info->ProcessorArchitecture);
  EXPECT_EQ(kCPULevel, system_info->ProcessorLevel);
  EXPECT_EQ(kCPURevision, system_info->ProcessorRevision);
  EXPECT_EQ(kCPUCount, system_info->NumberOfProcessors);
  EXPECT_EQ(kOSType, system_info->ProductType);
  EXPECT_EQ(kOSVersionMajor, system_info->MajorVersion);
  EXPECT_EQ(kOSVersionMinor, system_info->MinorVersion);
  EXPECT_EQ(kOSVersionBuild, system_info->BuildNumber);
  EXPECT_EQ(kOS, system_info->PlatformId);
  EXPECT_EQ(0u, system_info->SuiteMask);
  EXPECT_EQ(kCPUFeatures[0],
            system_info->Cpu.OtherCpuInfo.ProcessorFeatures[0]);
  EXPECT_EQ(kCPUFeatures[1],
            system_info->Cpu.OtherCpuInfo.ProcessorFeatures[1]);
}

TEST(MinidumpSystemInfoWriter, X86_CPUVendorFromRegisters) {
  // MinidumpSystemInfoWriter.X86_Win already tested SetCPUX86VendorString().
  // This test exercises SetCPUX86Vendor() to set the vendor from register
  // values.
  MinidumpFileWriter minidump_file_writer;
  MinidumpSystemInfoWriter system_info_writer;

  const MinidumpCPUArchitecture kCPUArchitecture = kMinidumpCPUArchitectureX86;
  const uint32_t kCPUVendor[] = {'uneG', 'Ieni', 'letn'};

  system_info_writer.SetCPUArchitecture(kCPUArchitecture);
  system_info_writer.SetCPUX86Vendor(
      kCPUVendor[0], kCPUVendor[1], kCPUVendor[2]);
  system_info_writer.SetCSDVersion(std::string());

  minidump_file_writer.AddStream(&system_info_writer);

  StringFileWriter file_writer;
  ASSERT_TRUE(minidump_file_writer.WriteEverything(&file_writer));

  const MINIDUMP_SYSTEM_INFO* system_info;
  const MINIDUMP_STRING* csd_version;

  GetSystemInfoStream(file_writer.string(), 0, &system_info, &csd_version);
  if (Test::HasFatalFailure()) {
    return;
  }

  EXPECT_EQ(kCPUArchitecture, system_info->ProcessorArchitecture);
  EXPECT_EQ(0u, system_info->ProcessorLevel);
  EXPECT_EQ(kCPUVendor[0], system_info->Cpu.X86CpuInfo.VendorId[0]);
  EXPECT_EQ(kCPUVendor[1], system_info->Cpu.X86CpuInfo.VendorId[1]);
  EXPECT_EQ(kCPUVendor[2], system_info->Cpu.X86CpuInfo.VendorId[2]);
  EXPECT_EQ(0u, system_info->Cpu.X86CpuInfo.VersionInformation);
}

TEST(MinidumpSystemInfoWriterDeathTest, NoCSDVersion) {
  MinidumpFileWriter minidump_file_writer;
  MinidumpSystemInfoWriter system_info_writer;
  minidump_file_writer.AddStream(&system_info_writer);

  StringFileWriter file_writer;
  ASSERT_DEATH(minidump_file_writer.WriteEverything(&file_writer),
               "csd_version_");
}

}  // namespace
}  // namespace test
}  // namespace crashpad


text:
const test = require('tape')
const virtualSidebar = require('./')

test('should assert input types', function (t) {
  t.plan(1)
  t.throws(virtualSidebar)
})


text:
        <title>Doctrine Console</title>
        <link rel="stylesheet" href="http://necolas.github.io/normalize.css/2.1.3/normalize.css" />

doctrine>>
<input class="command" id="command" />


text:
package com.sun.xml.internal.ws.assembler.dev;

import com.sun.istack.internal.NotNull;
import com.sun.istack.internal.Nullable;
import com.sun.xml.internal.ws.api.model.SEIModel;
import com.sun.xml.internal.ws.api.model.wsdl.WSDLPort;
import com.sun.xml.internal.ws.api.pipe.Codec;
import com.sun.xml.internal.ws.api.pipe.ServerTubeAssemblerContext;
import com.sun.xml.internal.ws.api.pipe.Tube;
import com.sun.xml.internal.ws.api.server.WSEndpoint;
import com.sun.xml.internal.ws.policy.PolicyMap;

/**
 *
 * @author Marek Potociar (marek.potociar at sun.com)
 */
public interface ServerTubelineAssemblyContext extends TubelineAssemblyContext {

    /**
     * Gets the {@link Codec} that is set by {@link #setCodec} or the default codec
     * based on the binding. The codec is a full codec that is responsible for
     * encoding/decoding entire protocol message(for e.g: it is responsible to
     * encode/decode entire MIME messages in SOAP binding)
     *
     * @return codec to be used for web service requests
     * @see com.sun.xml.internal.ws.api.pipe.Codecs
     */
    @NotNull
    Codec getCodec();

    /**
     *
     * The created pipeline is used to serve this {@link com.sun.xml.internal.ws.api.server.WSEndpoint}.
     * Specifically, its {@link com.sun.xml.internal.ws.api.WSBinding} should be of interest to  many
     * {@link com.sun.xml.internal.ws.api.pipe.Pipe}s.
     * @return Always non-null.
     */
    @NotNull
    WSEndpoint getEndpoint();

    PolicyMap getPolicyMap();

    /**
     * The created pipeline will use seiModel to get java concepts for the endpoint
     *
     * @return Null if the service doesn't have SEI model e.g. Provider endpoints,
     * and otherwise non-null.
     */
    @Nullable
    SEIModel getSEIModel();

    /**
     * The last {@link com.sun.xml.internal.ws.api.pipe.Pipe} in the pipeline. The assembler is expected to put
     * additional {@link com.sun.xml.internal.ws.api.pipe.Pipe}s in front of it.
     *
     *

     * (Just to give you the idea how this is used, normally the terminal pipe
     * is the one that invokes the user application or {@link javax.xml.ws.Provider}.)
     *
     * @return always non-null terminal pipe
     */
    @NotNull
    Tube getTerminalTube();

    ServerTubeAssemblerContext getWrappedContext();

    /**
     * The created pipeline will be used to serve this port.
     *
     * @return Null if the service isn't associated with any port definition in WSDL,
     * and otherwise non-null.
     */
    @Nullable
    WSDLPort getWsdlPort();

    boolean isPolicyAvailable();

    /**
     * If this server pipeline is known to be used for serving synchronous transport,
     * then this method returns true. This can be potentially use as an optimization
     * hint, since often synchronous versions are cheaper to execute than asycnhronous
     * versions.
     */
    boolean isSynchronous();

    /**
     * Interception point to change {@link Codec} during {@link Tube}line assembly. The
     * new codec will be used by jax-ws server runtime for encoding/decoding web service
     * request/response messages. {@link WSEndpoint#createCodec()} will return a copy
     * of this new codec and will be used in the server runtime.
     *
     *

     * The codec is a full codec that is responsible for
     * encoding/decoding entire protocol message(for e.g: it is responsible to
     * encode/decode entire MIME messages in SOAP binding)
     *
     *

     * the codec should correctly implement {@link Codec#copy} since it is used while
     * serving requests concurrently.
     *
     * @param codec codec to be used for web service requests
     * @see com.sun.xml.internal.ws.api.pipe.Codecs
     */
    void setCodec(@NotNull
    Codec codec);

}


text:
layout: nav/section
section: Push back on PDFs
---


text:
/**
 * There are JeeSite code generation
 */
package com.thinkgem.jeesite.modules.edu.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.thinkgem.jeesite.modules.edu.entity.Emergency;
import com.thinkgem.jeesite.modules.edu.service.EmergencyService;

/**
 * 重要提示Controller
 * @author lala
 * @version 2015-03-30
 */
@Controller
@RequestMapping(value = "${adminPath}/edu/emergency")
public class EmergencyController extends BaseController {

	@Autowired
	private EmergencyService emergencyService;

	@ModelAttribute
	public Emergency get(@RequestParam(required=false) String id) {
		if (StringUtils.isNotBlank(id)){
			return emergencyService.get(id);
		}else{
			return new Emergency();
		}
	}

	@RequiresPermissions("edu:emergency:view")
	@RequestMapping(value = {"list", ""})
	public String list(Emergency emergency, HttpServletRequest request, HttpServletResponse response, Model model) {
		User user = UserUtils.getUser();
		if (!user.isAdmin()){
			emergency.setCreateBy(user);
		}
        Page<Emergency> page = emergencyService.find(new Page<Emergency>(request, response), emergency);
        model.addAttribute("page", page);
		return "modules/" + "edu/emergencyList";
	}

	@RequiresPermissions("edu:emergency:view")
	@RequestMapping(value = "form")
	public String form(Emergency emergency, Model model) {
		model.addAttribute("emergency", emergency);
		return "modules/" + "edu/emergencyForm";
	}

	@RequiresPermissions("edu:emergency:edit")
	@RequestMapping(value = "save")
	public String save(Emergency emergency, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, emergency)){
			return form(emergency, model);
		}
		emergency.setContent(StringEscapeUtils.unescapeHtml4(emergency.getContent()));
		if(emergency.getTop().byteValue()== 1 ){
			emergencyService.clearTop(emergency);
		}
		emergencyService.save(emergency);
		addMessage(redirectAttributes, "保存重要提示'" + emergency.getTitle() + "'成功");
		return "redirect:"+Global.getAdminPath()+"/edu/emergency/?repage";
	}

	@RequiresPermissions("edu:emergency:edit")
	@RequestMapping(value = "delete")
	public String delete(String id, RedirectAttributes redirectAttributes) {
		emergencyService.delete(id);
		addMessage(redirectAttributes, "删除重要提示成功");
		return "redirect:"+Global.getAdminPath()+"/edu/emergency/?repage";
	}

	@RequiresPermissions("edu:emergency:edit")
	@RequestMapping(value = "publish")
	public String publish(String id,Byte status, RedirectAttributes redirectAttributes) {
		Emergency emergency = emergencyService.get(id);
		emergency.setStatus(status);
		emergencyService.save(emergency);
		if(status==1)
		addMessage(redirectAttributes, "发布重要提示成功");
		else
		addMessage(redirectAttributes, "取消发布重要提示成功");

		return "redirect:"+Global.getAdminPath()+"/edu/emergency/?repage";
	}

}


text:
package search

import (
	"github.com/stretchr/testify/assert"
	"math"
	"testing"
)

func TestGroupByHistogram_GetName(t *testing.T) {
	group := GroupByHistogram{}
	group.SetName("group1")
	assert.Equal(t, "group1", group.GroupByName)
}

func TestGroupByHistogram_GetType(t *testing.T) {
	group := GroupByHistogram{}
	assert.Equal(t, GroupByHistogramType, group.GetType())
}

func TestGroupByHistogram_FieldName(t *testing.T) {
	group := GroupByHistogram{}
	group.SetFieldName("col1")
	assert.Equal(t, "col1", group.Field)
}

func TestGroupByHistogram_GetField(t *testing.T) {
	group := GroupByHistogram{}
	group.SetFieldName("col1")
	assert.Equal(t, "col1", group.GetField())
}

func TestGroupByHistogram_SetMinDocCount(t *testing.T) {
	group := GroupByHistogram{}
	group.SetMinDocCount(1)
	assert.Equal(t, int64(1), *group.MinDocCount)
}

func TestGroupByHistogram_SubAggregation(t *testing.T) {
	subAggList := []Aggregation{
		&MaxAggregation{AggName: "sub_agg1", Field: "field1"},
		&SumAggregation{AggName: "sub_agg2", Field: "field2"},
	}

	{
		group := GroupByHistogram{}
		group.SubAggregations(subAggList[0]).SubAggregation(subAggList[1])
		assert.Equal(t, subAggList, group.SubAggList)
	}
	{
		group := GroupByHistogram{}
		group.SubAggregations(subAggList[0], subAggList[1])
		assert.Equal(t, subAggList, group.SubAggList)
	}
}

func TestGroupByHistogram_SubGroupBy(t *testing.T) {
	subGroupByList := []GroupBy{
		&GroupByFilter{AggName: "sub_group_by1", Queries: []Query{&MatchAllQuery{}}},
		&GroupByRange{AggName: "sub_group_by2", Field: "field3", RangeList: []Range{{from: 1, to: 2}, {from: 2, to: math.Inf(1)}}},
	}

	{
		group := GroupByHistogram{}
		group.SubGroupBy(subGroupByList[0]).SubGroupBy(subGroupByList[1])
		assert.Equal(t, subGroupByList, group.SubGroupByList)
	}
	{
		group := GroupByHistogram{}
		group.SubGroupBys(subGroupByList[0], subGroupByList[1])
		assert.Equal(t, subGroupByList, group.SubGroupByList)
	}
}


text: module.exports = require('./ifttt');