text:
<?xml version="1.0" encoding="utf-8"?>
<labels>
	Diário de Horas Trabalhadas
	Diário das Suas Horas Trabalhadas
	Diário de Horas Trabalhadas
	Total de Horas Trabalhadas
	Ver Detalhes
	Fechar Detalhes
	No Trabalhadas disponíveis para este período
	Total de Horas de Hoje
</labels>

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <servlet>
    <servlet-name>RedirectServlet</servlet-name>
    <servlet-class>com.vc.servlets.RedirectServlet</servlet-class>
  </servlet>

  <servlet>
    <servlet-name>VCDebugServlet</servlet-name>
    <servlet-class>com.vc.servlets.VCDebugServlet</servlet-class>
  </servlet>

  <servlet>
    <servlet-name>AuthGenerator</servlet-name>
    <servlet-class>com.vc.servlets.AuthSignatureServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>RedirectServlet</servlet-name>
    <url-pattern>/RedirectServlet</url-pattern>
  </servlet-mapping>

  <servlet-mapping>
    <servlet-name>VCDebugServlet</servlet-name>
    <url-pattern>/debug/*</url-pattern>
  </servlet-mapping>

  <servlet-mapping>
    <servlet-name>RedirectServlet</servlet-name>
    <url-pattern>/cmp1/*</url-pattern>
  </servlet-mapping>

  <servlet-mapping>
    <servlet-name>AuthGenerator</servlet-name>
    <url-pattern>/auth/*</url-pattern>
  </servlet-mapping>

</web-app>


text:
package com.taxisurfr.client.steps.ui.widget;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Widget;

public class TimeBox extends Composite
{

    private static TimeBoxUiBinder uiBinder = GWT.create(TimeBoxUiBinder.class);

    interface TimeBoxUiBinder extends UiBinder<Widget, TimeBox>
    {
    }

    @UiField
    ListBox box;

    public TimeBox()
    {
        initWidget(uiBinder.createAndBindUi(this));
        for (int hour = 7; hour <= 22; hour++)
        {
            String time = hour + ":";
            box.addItem(time + "00");
            box.addItem(time + "15");
            box.addItem(time + "30");
            box.addItem(time + "45");
        }
    }

}


text:
layout: page
title: Smith - Roberson Wedding
date: 2016-05-24
author: Jeremy Pittman
tags: weekly links, java
status: published
summary: Nunc id eleifend urna. Phasellus quis odio.
banner: images/banner/leisure-01.jpg
booking:
  startDate: 10/16/2019
  endDate: 10/19/2019
  ctyhocn: LAXBKHX
  groupCode: SRW
published: true
---
In hac habitasse platea dictumst. Duis ac gravida enim, id efficitur tellus. Donec egestas commodo mi sed feugiat. Fusce fringilla elit sit amet felis convallis ultricies. Curabitur vitae scelerisque justo, vitae placerat ipsum. Donec ac consequat nisl. Duis fermentum diam eu dolor varius vehicula. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. In arcu ligula, blandit non faucibus at, efficitur at urna.
Suspendisse et dui sit amet libero porta fringilla in quis quam. Sed pretium metus aliquet tellus finibus, sed faucibus nulla sollicitudin. Phasellus eleifend lectus et nisl congue ultricies. Vestibulum dignissim convallis est vel commodo. Phasellus luctus dignissim ante eu facilisis. Pellentesque pharetra libero id commodo venenatis. Etiam lacinia urna quis eros accumsan, id feugiat elit egestas. Donec nec tristique turpis. Vivamus pharetra orci ex, et fringilla ipsum tincidunt non. Aenean euismod id ipsum sollicitudin convallis. Maecenas odio sapien, viverra sed commodo sit amet, sagittis a nulla.

* Donec interdum nunc ut feugiat porta
* Nullam sed neque eget risus lacinia efficitur nec efficitur leo
* Nunc in elit vulputate, pellentesque augue in, scelerisque lectus
* Proin ornare quam vitae pretium ornare
* Aenean lobortis augue nec neque bibendum blandit.

Proin luctus interdum magna, sit amet malesuada nisi tristique id. Sed ullamcorper auctor sapien, vel gravida lorem sagittis quis. Phasellus eget pharetra risus. Aliquam non tristique eros. Nam volutpat sapien ut lacus consectetur tincidunt. Aenean vehicula rhoncus leo, eget posuere ante bibendum ac. Ut gravida in nibh auctor eleifend. Nulla facilisi.


text:
'use strict';

var services = angular.module('lunchServices');

services.service('lunchService', [ '$http', '$q',
  function($http, $q) {

      this.get = function(date) {
        return $q(function(resolve, reject) {
          $http.get('api/v2/lunches/' + date)
            .success( function(data, status, headers, config) {
              data.dishes = buildDishes(data.menu);
              resolve(data);
            })
            .error( function(data, status, headers, config) {
              if (status === 404) {
                var message = '404 No lunch found for ' + date;
                reject(message);
              } else {
                console.log(status);
                console.log(data);
                reject('Error loading lunch');
              }
            });
        });
      };

      function buildDishes(menu) {
        menu = cleanMenu(menu);
        var rawDishes = menu.split(";");
        var dishes = [];
        for (var i = 0; i < rawDishes.length; i++) {
          dishes.push(rawDishes[i].trim());
        }
        dishes.push("Salad Bar");
        return dishes;
      }

      // HACK: The app needs to be refactored and this should be done serverside only with libraries instead of this trash
      function cleanMenu(menu) {
        var noHtmlMenu = menu.replace(/<(?:.|\n)*?>/gm, '');
        var decodedMenu = noHtmlMenu;
        var decodedMenu = decodedMenu.replace(/&/g, '&');
        var decodedMenu = decodedMenu.replace(/</g, '<');
        var decodedMenu = decodedMenu.replace(/>/g, '>');
        var decodedMenu = decodedMenu.replace(/"/g, '"');
        var decodedMenu = decodedMenu.replace(/'/g, "'");
        return decodedMenu;
      }

      this.getAll = function() {
        return $q(function(resolve, reject) {
          $http.get('api/v2/lunches')
            .success( function(data, status, headers, config) {
              resolve(data);
            })
            .error( function(data, status, headers, config) {
                console.log(status);
                console.log(data);
                reject('Error loading lunches');
            });
        });
      };

      this.getGenerated = function() {
        return $q(function(resolve, errorHandler) {
          $http.get('api/v2/lunches/generate')
            .success( function(data, status, headers, config) {
              resolve(data);
            })
            .error( function(data, status, headers, config) {
              console.log(status);
              console.log(data);
              errorHandler("Error generating lunch");
            });
        });
      };

      this.translateMenu = function(menu) {
        return $q(function(resolve, errorHandler) {
          $http.post('api/v2/translate', {lunch: menu}).
            success(function(data, status, headers, config) {
              resolve(data.result);
            }).
            error(function(data, status, headers, config) {
              console.log(status);
              console.log(data);
              errorHandler('Error translating menu');
            });
        });
      };

      this.rate = function(date, dish, ratingNumber, source) {
        return $q(function(resolve, errorHandler) {
          var url = 'api/v2/lunches/' + date + '/ratings';
          var rating = {
            dish: dish,
            rating: ratingNumber,
            source: source
          }
          $http.post(url, rating)
            .success(function(data, status, headers, config) {
              resolve();
            })
            .error(function(data, status, headers, config) {
              console.log(status);
              console.log(data);
              if (data.message) {
                errorHandler(data.message);
              } else {
                errorHandler('Error saving rating');
              }
            });
        });
      };

      this.comment = function(date, name, message) {
        return $q(function(resolve, errorHandler) {
          var url = 'api/v2/lunches/' + date + '/comments';
          var comment = {
            name: name,
            message: message
          }
          $http.post(url, comment)
            .success(function(data, status, headers, config) {
              resolve();
            })
            .error(function(data, status, headers, config) {
              console.log(status);
              console.log(data);
              if (data.message) {
                errorHandler(data.message);
              } else {
                errorHandler('Error saving comment');
              }
            });
        });
      };

  }
]);


text:
class SanjiWindowService {
  constructor() {
    this.collection = [];
  }

  static factory() {
    return new SanjiWindowService();
  }

  _addInstance(instance) {
    this.collection.push(instance);
  }

  destroy(id) {
    let idx = this.collection.findIndex(item => item.id === id);
    this.collection.splice(idx, 1);
  }

  _isIdExist(id) {
    return -1 !== this.collection.findIndex(item => item.id === id) ? true : false;
  }

  get(id) {
    return this.collection.find(item => item.id === id);
  }

  create(id, options) {
    let instance = null;
    options = options || {};

    if (undefined === id) {
      throw new Error('Please give a window id.');
    }

    if (this._isIdExist(id)) {
      throw new Error('The window id ' + id + ' is already exist.');
    }

    class sanjiWindowInstance {
      constructor(options) {
        this.states = [];
        this.links = [];
        this.id = id;
        this.name = options.name || '';
        this.navigateContent = options.navigateContent || '';
        this.promise = null;
      }

      getId() {
        return this.id;
      }

      navigateTo(state) {
        this.navigateContent = state;
      }

      addState(state) {
        if (state.linkName) {
          this.links.push(state);
        }
        this.states.push(state);
      }

      clearStates() {
        this.links.length = 0;
        this.states.length = 0;
      }
    }
    instance = new sanjiWindowInstance(options);
    this._addInstance(instance);
    return instance;
  }

}
export default SanjiWindowService;


text:
module ManageIQ::Providers::Vmware::CloudManager::Vm::Operations::Power
  def validate_pause
    validate_unsupported("Pause operation")
  end

  def raw_start
    with_provider_object(&:power_on)
    update_attributes!(:raw_power_state => "on")
  end

  def raw_stop
    with_provider_object(&:power_off)
    update_attributes!(:raw_power_state => "off")
  end

  def raw_suspend
    with_provider_object(&:suspend)
    update_attributes!(:raw_power_state => "suspended")
  end

  def raw_restart
    with_provider_object(&:reset)
    update_attributes!(:raw_power_state => "on")
  end
end


text:
{% extends "/shared/site_template.html" %}
{% block title %}Index{% endblock %}

{% block page_css %}
    <meta name="google-signin-client_id" content="{{ google_client_id }}">
{% endblock %}

{% block page_js %}

{% endblock %}

{% block content %}

Welcome!

This is the template index! Log in or register!

        <form role="login" class="form-signin" data-bind="submit: loginOrRegister">

                Username
                <input type="text" id="username" class="form-control" placeholder="Username" data-bind="textInput: username">

                Password
                <input type="password" id="password" class="form-control" placeholder="Password" data-bind="textInput: password">

                Confirm Password
                <input type="password" id="confirmPassword" class="form-control" placeholder="Confirm Password" data-bind="textInput: confirmPassword">

                Email
                <input type="email" id="email" class="form-control" placeholder="Email" data-bind="textInput: email">

                <button type="submit" class="btn btn-lg btn-primary btn-block" data-bind="enable: readyToRegister">Register</button>

                <button type="submit" class="btn btn-lg btn-primary btn-block" data-bind="enable: readyToLogin">Login</button>

            OR

        </form>

{% endblock %}


text:
angular.module('app').config(function($routeProvider) {
    $routeProvider
        .when("/", {
            templateUrl : "views/home.html"
        });
});


text:
"""Tests for the language CLI arguments helper."""

from __future__ import unicode_literals

import argparse
import unittest

from plaso.cli import tools
from plaso.cli.helpers import language
from plaso.lib import errors

from tests.cli import test_lib as cli_test_lib

class LanguagergumentsHelperTest(cli_test_lib.CLIToolTestCase):
  """Tests for the language CLI arguments helper."""

  # pylint: disable=no-member,protected-access

  _EXPECTED_OUTPUT = """\
usage: cli_helper.py [--language LANGUAGE]

Test argument parser.

optional arguments:
  --language LANGUAGE  The preferred language identifier for Windows Event Log
                       message strings. Use "--language list" to see a list of
                       available language identifiers. Note that formatting
                       will fall back on en-US (LCID 0x0409) if the preferred
                       language is not available in the database of message
                       string templates.
"""

  def testAddArguments(self):
    """Tests the AddArguments function."""
    argument_parser = argparse.ArgumentParser(
        prog='cli_helper.py', description='Test argument parser.',
        add_help=False,
        formatter_class=cli_test_lib.SortedArgumentsHelpFormatter)

    language.LanguageArgumentsHelper.AddArguments(argument_parser)

    output = self._RunArgparseFormatHelp(argument_parser)
    self.assertEqual(output, self._EXPECTED_OUTPUT)

  def testParseOptions(self):
    """Tests the ParseOptions function."""
    options = cli_test_lib.TestOptions()
    options.preferred_language = 'is'

    test_tool = tools.CLITool()
    language.LanguageArgumentsHelper.ParseOptions(options, test_tool)

    self.assertEqual(test_tool._preferred_language, options.preferred_language)

    with self.assertRaises(errors.BadConfigObject):
      language.LanguageArgumentsHelper.ParseOptions(options, None)

if __name__ == '__main__':
  unittest.main()


text:
{% extends "base.html" %}
{% block body %}
Page 1 :)
{% endblock body %}


text:
//
//  ATOrder.h
//  Tracker
//

#import <Foundation/Foundation.h>
#import "ATBusinessObject.h"

@class ATTracker;
@class ATOrderDiscount;
@class ATOrderAmount;
@class ATOrderDelivery;
@class ATOrderCustomVars;

@interface ATOrder : ATBusinessObject

/**
 Order identifier
 */
@property (nonatomic, strong) NSString *orderId;

/**
 Turnover
 */
@property (nonatomic) double turnover;

/**
 Status
 */
@property (nonatomic) int status;

/**
 Discount
 */
@property (nonatomic, strong) ATOrderDiscount *discount;

/**
 Amount
 */
@property (nonatomic, strong) ATOrderAmount *amount;

/**
 Delivery
 */
@property (nonatomic, strong) ATOrderDelivery *delivery;

/**
 Custom variables
 */
@property (nonatomic, strong) ATOrderCustomVars *customVariables;

/**
 New customer
 */
@property (nonatomic) BOOL isNewCustomer;

/**
 Payment method
 */
@property (nonatomic) int paymentMethod;

/**
 Confirmation required
 */
@property (nonatomic) BOOL isConfirmationRequired;

/**
 Prepare parameters for the hit query string
 */
- (void)setEvent;

/**
 ATOrder initializer
 @param tracker the tracker instance
 @return ATOrder instance
 */
- (instancetype)initWithTracker:(ATTracker *)tracker;

@end

@interface ATOrders : NSObject

/**
 Tracker instance
 */
@property (nonatomic, strong) ATTracker *tracker;

/**
 Add tagging data for a new order
 @param orderId order identifier
 @param turnover order turnover
 @return the ATOrder instance
 */
- (ATOrder *)addWithId:(NSString *)orderId turnover:(double)turnover;

/**
 Add tagging data for a new order
 @param orderId order identifier
 @param turnover order turnover
 @param status order status
 @return the ATOrder instance
 */
- (ATOrder *)addWithId:(NSString *)orderId turnover:(double)turnover status:(int)status;

/**
 ATOrders initializer
 @param tracker the tracker instance
 @return ATOrders instance
 */
- (instancetype)initWithTracker:(ATTracker *)tracker;

@end

@interface ATOrderDiscount : NSObject

/**
 Discount with tax
 */
@property (nonatomic) double discountTaxIncluded;

/**
 Discount without tax
 */
@property (nonatomic) double discountTaxFree;

/**
 Promotional code
 */
@property (nonatomic, strong) NSString *promotionalCode;

/**
 Set tagging data for a discount
 @param discountTaxFree discount value tax free
 @param discountTaxIncluded discount value tax included
 @param promotionalCode promotional code
 @return the ATOrder instance
 */
- (ATOrder *)setWithDiscountTaxFree:(double)discountTaxFree discountTaxIncluded:(double)discountTaxIncluded promotionalCode:(NSString *)promotionalCode;

/**
 ATOrderDiscount initializer
 @param order the ATOrder instance
 @return ATOrderDiscount instance
 */
- (instancetype)initWithOrder:(ATOrder *)order;

@end

@interface ATOrderAmount : NSObject

/**
 Amount with tax
 */
@property (nonatomic) double amountTaxIncluded;

/**
 Amount without tax
 */
@property (nonatomic) double amountTaxFree;

/**
 Tax amount
 */
@property (nonatomic) double taxAmount;

/**
 Set tagging data for an amount
 @param amountTaxFree amount value tax free
 @param amountTaxIncluded amount value tax included
 @param taxAmount tax amount
 @return the ATOrder instance
 */
- (ATOrder *)setWithAmountTaxFree:(double)amountTaxFree amountTaxIncluded:(double)amountTaxIncluded taxAmount:(double)taxAmount;

/**
 ATOrderAmount initializer
 @param order the ATOrder instance
 @return ATOrderAmount instance
 */
- (instancetype)initWithOrder:(ATOrder *)order;

@end

@interface ATOrderDelivery : NSObject

/**
 Shipping fees with tax
 */
@property (nonatomic) double shippingFeesTaxIncluded;

/**
 Shipping fees without tax
 */
@property (nonatomic) double shippingFeesTaxFree;

/**
 Delivery method
 */
@property (nonatomic) NSString *deliveryMethod;

/**
 Set tagging data for a delivery
 @param shippingFeesTaxFree shipping fees tax free
 @param shippingFeesTaxIncluded shipping fees tax included
 @param deliveryMethod delivery method
 @return the ATOrder instance
 */
- (ATOrder *)setWithShippingFeesTaxFree:(double)shippingFeesTaxFree shippingFeesTaxIncluded:(double)shippingFeesTaxIncluded deliveryMethod:(NSString *)deliveryMethod;

/**
 ATOrderDelivery initializer
 @param order the ATOrder instance
 @return ATOrderDelivery instance
 */
- (instancetype)initWithOrder:(ATOrder *)order;

@end

@interface ATOrderCustomVar : NSObject

/**
 Custom var value
 */
@property (nonatomic, strong) NSString *value;

/**
 Custom var identifier
 */
@property (nonatomic) int varId;

/**
 ATOrderCustomVar initializer
 @param varId the custom var identifier
 @param value the custom var value
 @return ATOrderCustomVar instance
 */
- (instancetype)initWithVarId:(int)varId value:(NSString *)value;

@end

@interface ATOrderCustomVars : NSObject

/**
 Order instance
 */
@property (nonatomic, strong) ATOrder *order;

/**
 Custom var list
 */
@property (nonatomic, strong) NSMutableArray *list;

/**
 Add tagging data for custom var
 @param varId custom var identifier
 @param value custom var value
 @return the ATOrderCustomVar instance
 */
- (ATOrderCustomVar *)addWithId:(int)varId value:(NSString *)value;

/**
 ATOrderCustomVars initializer
 @param order the ATOrder instance
 @return ATOrderCustomVars instance
 */
- (instancetype)initWithOrder:(ATOrder *)order;

@end


text:
exports.Hookable = Hookable;

function Hookable() {
// hookable class
};

Hookable.afterInitialize = null;
Hookable.beforeValidation = null;
Hookable.afterValidation = null;
Hookable.beforeSave = null;
Hookable.afterSave = null;
Hookable.beforeCreate = null;
Hookable.afterCreate = null;
Hookable.beforeUpdate = null;
Hookable.afterUpdate = null;
Hookable.beforeDestroy = null;
Hookable.afterDestroy = null;

Hookable.prototype.trigger = function trigger(actionName, work, data) {
    var capitalizedName = capitalize(actionName);
    var afterHook = this.constructor['after' + capitalizedName];
    var beforeHook = this.constructor['before' + capitalizedName];
    var inst = this;

    // we only call 'before' hook when we have actual action (work) to perform
    if (work) {
        if (beforeHook) {
            // before hook should be called on instance with one param: callback
            beforeHook.call(inst, function () {
                // actual action also have one param: callback
                work.call(inst, next);
            }, data);
        } else {
            work.call(inst, next);
        }
    } else {
        next();
    }

    function next(done) {
        if (afterHook) {
            afterHook.call(inst, done);
        } else if (done) {
            done.call(this);
        }
    }
};

function capitalize(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}


text:
package com.founder.fix.fixflow.expand.rulescript.select;

import java.util.ArrayList;
import java.util.List;

import com.founder.fix.fixflow.core.db.pagination.Pagination;
import com.founder.fix.fixflow.core.impl.Context;
import com.founder.fix.fixflow.core.impl.Page;
import com.founder.fix.fixflow.core.impl.ProcessEngineConfigurationImpl;
import com.founder.fix.fixflow.core.impl.db.SqlCommand;
import com.founder.fix.fixflow.core.impl.runtime.TokenQueryImpl;
import com.founder.fix.fixflow.core.scriptlanguage.SelectRulesScript;

public class TokenQueryCountScript implements SelectRulesScript {

	protected TokenQueryImpl tokenQuery;
	protected Page page;
	protected SqlCommand sqlCommand;
	protected Pagination pagination;

	public Object execute(Object parameter, SqlCommand sqlCommand, ProcessEngineConfigurationImpl processEngineConfiguration) {

		this.tokenQuery = (TokenQueryImpl) parameter;

		this.sqlCommand = sqlCommand;
		this.pagination = Context.getProcessEngineConfiguration().getDbConfig().getPagination();

		return selectTokenCountByQueryCriteria(tokenQuery);
	}

	/**
	 * 根据查询对象查询结果个数
	 * @param tokenQuery
	 * @return
	 */
	public long selectTokenCountByQueryCriteria(TokenQueryImpl tokenQuery) {
		String sqlString="select count(*) ";
		List<Object> objectParamWhere = new ArrayList<Object>();

		TokenQueryScript tokenQueryScript=new TokenQueryScript();

		sqlString=tokenQueryScript.selectTokenByQueryCriteriaSql(sqlString,tokenQuery,null,objectParamWhere);
		Object returnObj=sqlCommand.queryForValue(sqlString, objectParamWhere);
		return Integer.parseInt(returnObj.toString());
	}

}


text:
/**
 * @fileoverview Tests for options.
 * @author Sindre Sorhus
 */

"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const assert = require("chai").assert,
    chalk = require("chalk"),
    proxyquire = require("proxyquire"),
    sinon = require("sinon");

// Chalk protects its methods so we need to inherit from it
// for Sinon to work.
const chalkStub = Object.create(chalk, {
    yellow: {
        value: function(str) {
            return chalk.yellow(str);
        },
        writable: true
    },
    red: {
        value: function(str) {
            return chalk.red(str);
        },
        writable: true
    }
});

chalkStub.yellow.bold = chalk.yellow.bold;
chalkStub.red.bold = chalk.red.bold;

const formatter = proxyquire("../../../lib/formatters/stylish", { chalk: chalkStub });

//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------

describe("formatter:stylish", function() {
    let sandbox;
    const colorsEnabled = chalk.enabled;

    beforeEach(function() {
        chalk.enabled = false;
        sandbox = sinon.sandbox.create();
        sandbox.spy(chalkStub.yellow, "bold");
        sandbox.spy(chalkStub.red, "bold");
    });

    afterEach(function() {
        sandbox.verifyAndRestore();
        chalk.enabled = colorsEnabled;
    });

    describe("when passed no messages", function() {
        const code = [{
            filePath: "foo.js",
            messages: []
        }];

        it("should not return message", function() {
            const result = formatter(code);

            assert.equal(result, "");
            assert.equal(chalkStub.yellow.bold.callCount, 0);
            assert.equal(chalkStub.red.bold.callCount, 0);
        });
    });

    describe("when passed a single message", function() {
        const code = [{
            filePath: "foo.js",
            messages: [{
                message: "Unexpected foo.",
                severity: 2,
                line: 5,
                column: 10,
                ruleId: "foo"
            }]
        }];

        it("should return a string in the correct format for errors", function() {
            const result = formatter(code);

            assert.equal(result, "\nfoo.js\n  5:10  error  Unexpected foo  foo\n\n\u2716 1 problem (1 error, 0 warnings)\n");
            assert.equal(chalkStub.yellow.bold.callCount, 0);
            assert.equal(chalkStub.red.bold.callCount, 1);
        });

        it("should return a string in the correct format for warnings", function() {
            code[0].messages[0].severity = 1;
            const result = formatter(code);

            assert.equal(result, "\nfoo.js\n  5:10  warning  Unexpected foo  foo\n\n\u2716 1 problem (0 errors, 1 warning)\n");
            assert.equal(chalkStub.yellow.bold.callCount, 1);
            assert.equal(chalkStub.red.bold.callCount, 0);
        });
    });

    describe("when passed a fatal error message", function() {
        const code = [{
            filePath: "foo.js",
            messages: [{
                fatal: true,
                message: "Unexpected foo.",
                line: 5,
                column: 10,
                ruleId: "foo"
            }]
        }];

        it("should return a string in the correct format", function() {
            const result = formatter(code);

            assert.equal(result, "\nfoo.js\n  5:10  error  Unexpected foo  foo\n\n\u2716 1 problem (1 error, 0 warnings)\n");
            assert.equal(chalkStub.yellow.bold.callCount, 0);
            assert.equal(chalkStub.red.bold.callCount, 1);
        });
    });

    describe("when passed multiple messages", function() {
        const code = [{
            filePath: "foo.js",
            messages: [{
                message: "Unexpected foo.",
                severity: 2,
                line: 5,
                column: 10,
                ruleId: "foo"
            }, {
                message: "Unexpected bar.",
                severity: 1,
                line: 6,
                column: 11,
                ruleId: "bar"
            }]
        }];

        it("should return a string with multiple entries", function() {
            const result = formatter(code);

            assert.equal(result, "\nfoo.js\n  5:10  error    Unexpected foo  foo\n  6:11  warning  Unexpected bar  bar\n\n\u2716 2 problems (1 error, 1 warning)\n");
            assert.equal(chalkStub.yellow.bold.callCount, 0);
            assert.equal(chalkStub.red.bold.callCount, 1);
        });
    });

    describe("when passed multiple files with 1 message each", function() {
        const code = [{
            filePath: "foo.js",
            messages: [{
                message: "Unexpected foo.",
                severity: 2,
                line: 5,
                column: 10,
                ruleId: "foo"
            }]
        }, {
            filePath: "bar.js",
            messages: [{
                message: "Unexpected bar.",
                severity: 1,
                line: 6,
                column: 11,
                ruleId: "bar"
            }]
        }];

        it("should return a string with multiple entries", function() {
            const result = formatter(code);

            assert.equal(result, "\nfoo.js\n  5:10  error  Unexpected foo  foo\n\nbar.js\n  6:11  warning  Unexpected bar  bar\n\n\u2716 2 problems (1 error, 1 warning)\n");
            assert.equal(chalkStub.yellow.bold.callCount, 0);
            assert.equal(chalkStub.red.bold.callCount, 1);
        });
    });

    describe("when passed one file not found message", function() {
        const code = [{
            filePath: "foo.js",
            messages: [{
                fatal: true,
                message: "Couldn't find foo.js."
            }]
        }];

        it("should return a string without line and column", function() {
            const result = formatter(code);

            assert.equal(result, "\nfoo.js\n  0:0  error  Couldn't find foo.js\n\n\u2716 1 problem (1 error, 0 warnings)\n");
            assert.equal(chalkStub.yellow.bold.callCount, 0);
            assert.equal(chalkStub.red.bold.callCount, 1);
        });
    });
});


text:
module Dyna
  class Exporter
    include Logger::ClientHelper
    include Filterable

    class << self
      def export(ddb, options = {})
        self.new(ddb, options).export
      end
    end

    def initialize(ddb, options = {})
      @ddb = ddb
      @options = options
    end

    def export
      result = {}
      @ddb.list_tables.map do |tables|
        tables.table_names
          .reject { |name| should_skip(name) }
          .sort
          .each do |table_name|
          result[table_name] = self.class.export_table(@ddb, table_name)
        end
      end
      result
    end

    def self.table_definition(describe_table)
      {
        table_name:               describe_table.table_name,
        key_schema:               key_schema(describe_table),
        attribute_definitions:    attribute_definitions(describe_table),
        billing_mode:             describe_table.billing_mode_summary&.billing_mode,
        provisioned_throughput:   {
          read_capacity_units:    describe_table.provisioned_throughput.read_capacity_units,
          write_capacity_units:   describe_table.provisioned_throughput.write_capacity_units,
        },
        local_secondary_indexes:  local_secondary_indexes(describe_table),
        global_secondary_indexes: global_secondary_indexes(describe_table),
        stream_specification:     stream_specification(describe_table),
        scalable_targets:         scalable_targets(describe_table),
        scaling_policies:         scaling_policies(describe_table),
      }
    end

    def self.aas(aas)
      @aas = aas
    end

    private
    def self.export_table(ddb, table_name)
      describe_table = ddb.describe_table(table_name: table_name).table
      table_definition(describe_table)
    end

    def self.key_schema(table)
      table.key_schema.map do |schema|
        {
          attribute_name: schema.attribute_name,
          key_type:       schema.key_type,
        }
      end
    end

    def self.attribute_definitions(table)
      table.attribute_definitions.map do |definition|
        {
          attribute_name: definition.attribute_name,
          attribute_type: definition.attribute_type,
        }
      end
    end

    def self.global_secondary_indexes(table)
      return nil unless table.global_secondary_indexes
      table.global_secondary_indexes.map do |index|
        {
          index_name:             index.index_name,
          key_schema:             key_schema(index),
          projection:             {
            projection_type:      index.projection.projection_type,
            non_key_attributes:   index.projection.non_key_attributes,
          },
          provisioned_throughput: {
            read_capacity_units:  index.provisioned_throughput.read_capacity_units,
            write_capacity_units: index.provisioned_throughput.write_capacity_units,
          },
        }
      end
    end

    def self.local_secondary_indexes(table)
      return nil unless table.local_secondary_indexes
      table.local_secondary_indexes.map do |index|
        {
          index_name:           index.index_name,
          key_schema:           key_schema(index),
          projection:           {
            projection_type:    index.projection.projection_type,
            non_key_attributes: index.projection.non_key_attributes,
          },
        }
      end
    end

    def self.stream_specification(table)
      stream_spec = table.stream_specification
      return nil unless stream_spec
      {
        stream_enabled: stream_spec.stream_enabled,
        stream_view_type: stream_spec.stream_view_type,
      }
    end

    def self.scalable_targets(table)
      scalable_targets_by_resource_id["table/#{table.table_name}"] || []
    end

    def self.scalable_targets_by_resource_id
      return {} unless @aas
      return @scalable_targets_by_resource_id if @scalable_targets_by_resource_id

      results = []
      next_token = nil
      begin
        resp = @aas.describe_scalable_targets(service_namespace: 'dynamodb', next_token: next_token)
        resp.scalable_targets.each do |target|
          results.push(target)
        end
        next_token = resp.next_token
      end while next_token
      @scalable_targets_by_resource_id = results.group_by(&:resource_id)
    end

    def self.scaling_policies(table)
      scaling_policies_by_resource_id["table/#{table.table_name}"] || []
    end

    def self.scaling_policies_by_resource_id
      return {} unless @aas
      return @scaling_policies_by_resource_id if @scaling_policies_by_resource_id

      results = []
      next_token = nil
      begin
        resp = @aas.describe_scaling_policies(service_namespace: 'dynamodb', next_token: next_token)
        resp.scaling_policies.each do |policy|
          results.push(policy)
        end
        next_token = resp.next_token
      end while next_token
      @scaling_policies_by_resource_id = results.group_by(&:resource_id)
    end
  end
end


text:
/* $Id$ */

#ifndef PHP_SESSION_H
#define PHP_SESSION_H

#include "ext/standard/php_var.h"

#if defined(HAVE_HASH_EXT) && !defined(COMPILE_DL_HASH)
# include "ext/hash/php_hash.h"
#endif

#define PHP_SESSION_API 20150121

#include "php_version.h"
#define PHP_SESSION_VERSION PHP_VERSION

/* save handler macros */
#define PS_NUM_APIS      9
#define PS_OPEN_ARGS     void **mod_data, const char *save_path, const char *session_name
#define PS_CLOSE_ARGS    void **mod_data
#define PS_READ_ARGS     void **mod_data, zend_string *key, zend_string **val, zend_long maxlifetime
#define PS_WRITE_ARGS    void **mod_data, zend_string *key, zend_string *val, zend_long maxlifetime
#define PS_DESTROY_ARGS  void **mod_data, zend_string *key
#define PS_GC_ARGS       void **mod_data, zend_long maxlifetime, int *nrdels
#define PS_CREATE_SID_ARGS void **mod_data
#define PS_VALIDATE_SID_ARGS void **mod_data, zend_string *key
#define PS_UPDATE_TIMESTAMP_ARGS void **mod_data, zend_string *key, zend_string *val, zend_long maxlifetime

typedef struct ps_module_struct {
	const char *s_name;
	int (*s_open)(PS_OPEN_ARGS);
	int (*s_close)(PS_CLOSE_ARGS);
	int (*s_read)(PS_READ_ARGS);
	int (*s_write)(PS_WRITE_ARGS);
	int (*s_destroy)(PS_DESTROY_ARGS);
	int (*s_gc)(PS_GC_ARGS);
	zend_string *(*s_create_sid)(PS_CREATE_SID_ARGS);
	int (*s_validate_sid)(PS_VALIDATE_SID_ARGS);
	int (*s_update_timestamp)(PS_UPDATE_TIMESTAMP_ARGS);
} ps_module;

#define PS_GET_MOD_DATA() *mod_data
#define PS_SET_MOD_DATA(a) *mod_data = (a)

#define PS_OPEN_FUNC(x) 	int ps_open_##x(PS_OPEN_ARGS)
#define PS_CLOSE_FUNC(x) 	int ps_close_##x(PS_CLOSE_ARGS)
#define PS_READ_FUNC(x) 	int ps_read_##x(PS_READ_ARGS)
#define PS_WRITE_FUNC(x) 	int ps_write_##x(PS_WRITE_ARGS)
#define PS_DESTROY_FUNC(x) 	int ps_delete_##x(PS_DESTROY_ARGS)
#define PS_GC_FUNC(x) 		int ps_gc_##x(PS_GC_ARGS)
#define PS_CREATE_SID_FUNC(x)	zend_string *ps_create_sid_##x(PS_CREATE_SID_ARGS)
#define PS_VALIDATE_SID_FUNC(x)	int ps_validate_sid_##x(PS_VALIDATE_SID_ARGS)
#define PS_UPDATE_TIMESTAMP_FUNC(x) 	int ps_update_timestamp_##x(PS_UPDATE_TIMESTAMP_ARGS)

/* Legacy save handler module definitions */
#define PS_FUNCS(x) \
	PS_OPEN_FUNC(x); \
	PS_CLOSE_FUNC(x); \
	PS_READ_FUNC(x); \
	PS_WRITE_FUNC(x); \
	PS_DESTROY_FUNC(x); \
	PS_GC_FUNC(x);	\
	PS_CREATE_SID_FUNC(x)

#define PS_MOD(x) \
	#x, ps_open_##x, ps_close_##x, ps_read_##x, ps_write_##x, \
	 ps_delete_##x, ps_gc_##x, php_session_create_id, \
	 php_session_validate_sid, php_session_update_timestamp

/* Legacy SID creation enabled save handler module definitions */
#define PS_FUNCS_SID(x) \
	PS_OPEN_FUNC(x); \
	PS_CLOSE_FUNC(x); \
	PS_READ_FUNC(x); \
	PS_WRITE_FUNC(x); \
	PS_DESTROY_FUNC(x); \
	PS_GC_FUNC(x); \
	PS_CREATE_SID_FUNC(x); \
	PS_VALIDATE_SID_FUNC(x); \
	PS_UPDATE_TIMESTAMP_FUNC(x);

#define PS_MOD_SID(x) \
	#x, ps_open_##x, ps_close_##x, ps_read_##x, ps_write_##x, \
	 ps_delete_##x, ps_gc_##x, ps_create_sid_##x, \
	 php_session_validate_sid, php_session_update_timestamp

/* Update timestamp enabled save handler module definitions
   New save handlers should use this API */
#define PS_FUNCS_UPDATE_TIMESTAMP(x) \
	PS_OPEN_FUNC(x); \
	PS_CLOSE_FUNC(x); \
	PS_READ_FUNC(x); \
	PS_WRITE_FUNC(x); \
	PS_DESTROY_FUNC(x); \
	PS_GC_FUNC(x); \
	PS_CREATE_SID_FUNC(x); \
	PS_VALIDATE_SID_FUNC(x); \
	PS_UPDATE_TIMESTAMP_FUNC(x);

#define PS_MOD_UPDATE_TIMESTAMP(x) \
	#x, ps_open_##x, ps_close_##x, ps_read_##x, ps_write_##x, \
	 ps_delete_##x, ps_gc_##x, ps_create_sid_##x, \
	 ps_validate_sid_##x, ps_update_timestamp_##x

typedef enum {
	php_session_disabled,
	php_session_none,
	php_session_active
} php_session_status;

typedef struct _php_session_rfc1867_progress {
	size_t    sname_len;
	zval      sid;
	smart_str key;

	zend_long      update_step;
	zend_long      next_update;
	double    next_update_time;
	zend_bool cancel_upload;
	zend_bool apply_trans_sid;
	size_t    content_length;

	zval      data;                 /* the array exported to session data */
	zval	 *post_bytes_processed; /* data["bytes_processed"] */
	zval      files;                /* data["files"] array */
	zval      current_file;         /* array of currently uploading file */
	zval	 *current_file_bytes_processed;
} php_session_rfc1867_progress;

typedef struct _php_ps_globals {
	char *save_path;
	char *session_name;
	zend_string *id;
	char *extern_referer_chk;
	char *entropy_file;
	char *cache_limiter;
	zend_long entropy_length;
	zend_long cookie_lifetime;
	char *cookie_path;
	char *cookie_domain;
	zend_bool  cookie_secure;
	zend_bool  cookie_httponly;
	ps_module *mod;
	ps_module *default_mod;
	void *mod_data;
	php_session_status session_status;
	zend_long gc_probability;
	zend_long gc_divisor;
	zend_long gc_maxlifetime;
	int module_number;
	zend_long cache_expire;
	union {
		zval names[PS_NUM_APIS];
		struct {
			zval ps_open;
			zval ps_close;
			zval ps_read;
			zval ps_write;
			zval ps_destroy;
			zval ps_gc;
			zval ps_create_sid;
			zval ps_validate_sid;
			zval ps_update_timestamp;
		} name;
	} mod_user_names;
	int mod_user_implemented;
	int mod_user_is_open;
	const struct ps_serializer_struct *serializer;
	zval http_session_vars;
	zend_bool auto_start;
	zend_bool use_cookies;
	zend_bool use_only_cookies;
	zend_bool use_trans_sid; /* contains the INI value of whether to use trans-sid */

	zend_long hash_func;
#if defined(HAVE_HASH_EXT) && !defined(COMPILE_DL_HASH)
	php_hash_ops *hash_ops;
#endif
	zend_long hash_bits_per_character;
	int send_cookie;
	int define_sid;

	php_session_rfc1867_progress *rfc1867_progress;
	zend_bool rfc1867_enabled; /* session.upload_progress.enabled */
	zend_bool rfc1867_cleanup; /* session.upload_progress.cleanup */
	char *rfc1867_prefix;  /* session.upload_progress.prefix */
	char *rfc1867_name;    /* session.upload_progress.name */
	zend_long rfc1867_freq;         /* session.upload_progress.freq */
	double rfc1867_min_freq;   /* session.upload_progress.min_freq */

	zend_bool use_strict_mode; /* whether or not PHP accepts unknown session ids */
	zend_bool lazy_write; /* omit session write when it is possible */
	zend_string *session_vars; /* serialized original session data */
} php_ps_globals;

typedef php_ps_globals zend_ps_globals;

extern zend_module_entry session_module_entry;
#define phpext_session_ptr &session_module_entry

#ifdef ZTS
#define PS(v) ZEND_TSRMG(ps_globals_id, php_ps_globals *, v)
#ifdef COMPILE_DL_SESSION
ZEND_TSRMLS_CACHE_EXTERN();
#endif
#else
#define PS(v) (ps_globals.v)
#endif

#define PS_SERIALIZER_ENCODE_ARGS void
#define PS_SERIALIZER_DECODE_ARGS const char *val, size_t vallen

typedef struct ps_serializer_struct {
	const char *name;
	zend_string *(*encode)(PS_SERIALIZER_ENCODE_ARGS);
	int (*decode)(PS_SERIALIZER_DECODE_ARGS);
} ps_serializer;

#define PS_SERIALIZER_ENCODE_NAME(x) ps_srlzr_encode_##x
#define PS_SERIALIZER_DECODE_NAME(x) ps_srlzr_decode_##x

#define PS_SERIALIZER_ENCODE_FUNC(x) \
	zend_string *PS_SERIALIZER_ENCODE_NAME(x)(PS_SERIALIZER_ENCODE_ARGS)
#define PS_SERIALIZER_DECODE_FUNC(x) \
	int PS_SERIALIZER_DECODE_NAME(x)(PS_SERIALIZER_DECODE_ARGS)

#define PS_SERIALIZER_FUNCS(x) \
	PS_SERIALIZER_ENCODE_FUNC(x); \
	PS_SERIALIZER_DECODE_FUNC(x)

#define PS_SERIALIZER_ENTRY(x) \
	{ #x, PS_SERIALIZER_ENCODE_NAME(x), PS_SERIALIZER_DECODE_NAME(x) }

/* default create id function */
PHPAPI zend_string *php_session_create_id(PS_CREATE_SID_ARGS);
/* Dummy PS module functions */
PHPAPI int php_session_validate_sid(PS_VALIDATE_SID_ARGS);
PHPAPI int php_session_update_timestamp(PS_UPDATE_TIMESTAMP_ARGS);

PHPAPI void session_adapt_url(const char *, size_t, char **, size_t *);

PHPAPI void php_add_session_var(zend_string *name);
PHPAPI zval *php_set_session_var(zend_string *name, zval *state_val, php_unserialize_data_t *var_hash);
PHPAPI zval *php_get_session_var(zend_string *name);

PHPAPI int php_session_register_module(ps_module *);

PHPAPI int php_session_register_serializer(const char *name,
	        zend_string *(*encode)(PS_SERIALIZER_ENCODE_ARGS),
	        int (*decode)(PS_SERIALIZER_DECODE_ARGS));

PHPAPI void php_session_set_id(char *id);
PHPAPI void php_session_start(void);

PHPAPI ps_module *_php_find_ps_module(char *name);
PHPAPI const ps_serializer *_php_find_ps_serializer(char *name);

PHPAPI int php_session_valid_key(const char *key);
PHPAPI void php_session_reset_id(void);

#define PS_ADD_VARL(name) do {										\
	php_add_session_var(name);							\
} while (0)

#define PS_ADD_VAR(name) PS_ADD_VARL(name)

#define PS_DEL_VARL(name) do {										\
	if (!Z_ISNULL(PS(http_session_vars))) {							\
		zend_hash_del(Z_ARRVAL(PS(http_session_vars)), name);		\
	}																\
} while (0)

#define PS_ENCODE_VARS 												\
	zend_string *key;												\
	zend_ulong num_key;													\
	zval *struc;

#define PS_ENCODE_LOOP(code) do {									\
	HashTable *_ht = Z_ARRVAL_P(Z_REFVAL(PS(http_session_vars)));	\
	ZEND_HASH_FOREACH_KEY(_ht, num_key, key) {						\
		if (key == NULL) {											\
			php_error_docref(NULL, E_NOTICE,				\
					"Skipping numeric key %pd", num_key);			\
			continue;												\
		}															\
		if ((struc = php_get_session_var(key))) {			\
			code;		 											\
		} 															\
	} ZEND_HASH_FOREACH_END();										\
} while(0)

PHPAPI ZEND_EXTERN_MODULE_GLOBALS(ps)

void php_session_auto_start(void *data);

#define PS_CLASS_NAME "SessionHandler"
extern zend_class_entry *php_session_class_entry;

#define PS_IFACE_NAME "SessionHandlerInterface"
extern zend_class_entry *php_session_iface_entry;

#define PS_SID_IFACE_NAME "SessionIdInterface"
extern zend_class_entry *php_session_id_iface_entry;

#define PS_UPDATE_TIMESTAMP_IFACE_NAME "SessionUpdateTimestampHandlerInterface"
extern zend_class_entry *php_session_update_timestamp_iface_entry;

extern PHP_METHOD(SessionHandler, open);
extern PHP_METHOD(SessionHandler, close);
extern PHP_METHOD(SessionHandler, read);
extern PHP_METHOD(SessionHandler, write);
extern PHP_METHOD(SessionHandler, destroy);
extern PHP_METHOD(SessionHandler, gc);
extern PHP_METHOD(SessionHandler, create_sid);
extern PHP_METHOD(SessionHandler, validateId);
extern PHP_METHOD(SessionHandler, updateTimestamp);

#endif


text:
import React from 'react';
import Title from 'react-title-component';

import CodeExample from '../../../CodeExample';
import PropTypeDescription from '../../../PropTypeDescription';
import MarkdownElement from '../../../MarkdownElement';

import iconMenuReadmeText from './README';
import IconMenuExampleSimple from './ExampleSimple';
import iconMenuExampleSimpleCode from '!raw!./ExampleSimple';
import IconMenuExampleControlled from './ExampleControlled';
import iconMenuExampleControlledCode from '!raw!./ExampleControlled';
import IconMenuExampleScrollable from './ExampleScrollable';
import iconMenuExampleScrollableCode from '!raw!./ExampleScrollable';
import IconMenuExampleNested from './ExampleNested';
import iconMenuExampleNestedCode from '!raw!./ExampleNested';
import iconMenuCode from '!raw!material-ui/lib/IconMenu/IconMenu';

const descriptions = {
  simple: 'Simple Icon Menus demonstrating some of the layouts possible using the `anchorOrigin` and `' +
  'targetOrigin` properties.',
  controlled: 'Three controlled examples, the first allowing a single selection, the second multiple selections,' +
    ' the third using internal state.',
  scrollable: 'The `maxHeight` property limits the height of the menu, above which it will be scrollable.',
  nested: 'Example of nested menus within an IconMenu.',
};

const IconMenusPage = () => (
  <div>
    <Title render={(previousTitle) => `Icon Menu - ${previousTitle}`} />
    <MarkdownElement text={iconMenuReadmeText} />
    <CodeExample
      title="Icon Menu positioning"
      description={descriptions.simple}
      code={iconMenuExampleSimpleCode}
    >
      <IconMenuExampleSimple />
    </CodeExample>
    <CodeExample
      title="Controlled Icon Menus"
      description={descriptions.controlled}
      code={iconMenuExampleControlledCode}
    >
      <IconMenuExampleControlled />
    </CodeExample>
    <CodeExample
      title="Scrollable Icon Menu"
      description={descriptions.scrollable}
      code={iconMenuExampleScrollableCode}
    >
      <IconMenuExampleScrollable />
    </CodeExample>
    <CodeExample
      title="Nested Icon Menus"
      description={descriptions.nested}
      code={iconMenuExampleNestedCode}
    >
      <IconMenuExampleNested />
    </CodeExample>
    <PropTypeDescription code={iconMenuCode} />
  </div>
);

export default IconMenusPage;


text:
/**
 * Run the migrations, creating the statistics table.
 *
 * @param  {Knex} knex  The Knex database instance
 * @return {Promise}
 */
exports.up = function (knex, Promise) {
    return Promise.all([
        knex.schema.createTable(app.constants.STATISTICS_TABLE_NAME, table => {
            table.bigInteger('respects');
            table.timestamps();
        }).then(() => {
            return knex(app.constants.STATISTICS_TABLE_NAME).insert([
                {
                    respects: 0,
                    created_at: new Date,
                    updated_at: new Date
                }
            ]);
        })
    ]);
};

/**
 * Reverse the migrations.
 *
 * @param  {Knex} knex  The Knex database instance
 * @return {Promise}
 */
exports.down = function (knex, Promise) {
    return Promise.all([
        knex.schema.dropTableIfExists(app.constants.STATISTICS_TABLE_NAME)
    ]);
};


text:
#ifndef glibc_sysdeps_llamaos_x86_bits_sigcontext_h
#define glibc_sysdeps_llamaos_x86_bits_sigcontext_h

// #include_next <bits/sigcontext.h>
/* Copyright (C) 2002-2012 Free Software Foundation, Inc.
   This file is part of the GNU C Library.

   The GNU C Library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   The GNU C Library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with the GNU C Library; if not, see
   <http://www.gnu.org/licenses/>.  */

#ifndef _BITS_SIGCONTEXT_H
#define _BITS_SIGCONTEXT_H  1

#if !defined _SIGNAL_H && !defined _SYS_UCONTEXT_H
# error "Never use <bits/sigcontext.h> directly; include <signal.h> instead."
#endif

#define FP_XSTATE_MAGIC1	0x46505853U
#define FP_XSTATE_MAGIC2	0x46505845U
#define FP_XSTATE_MAGIC2_SIZE	sizeof(FP_XSTATE_MAGIC2)

struct _fpx_sw_bytes
{
  __uint32_t magic1;
  __uint32_t extended_size;
  __uint64_t xstate_bv;
  __uint32_t xstate_size;
  __uint32_t padding[7];
};

struct _fpreg
{
  unsigned short significand[4];
  unsigned short exponent;
};

struct _fpxreg
{
  unsigned short significand[4];
  unsigned short exponent;
  unsigned short padding[3];
};

struct _xmmreg
{
  __uint32_t	element[4];
};

#ifndef __x86_64__

struct _fpstate
{
  /* Regular FPU environment.  */
  __uint32_t	cw;
  __uint32_t		sw;
  __uint32_t		tag;
  __uint32_t		ipoff;
  __uint32_t		cssel;
  __uint32_t		dataoff;
  __uint32_t		datasel;
  struct _fpreg	_st[8];
  unsigned short status;
  unsigned short magic;

  /* FXSR FPU environment.  */
  __uint32_t		_fxsr_env[6];
  __uint32_t		mxcsr;
  __uint32_t		reserved;
  struct _fpxreg	_fxsr_st[8];
  struct _xmmreg	_xmm[8];
  __uint32_t		padding[56];
};

#ifndef sigcontext_struct
/* Kernel headers before 2.1.1 define a struct sigcontext_struct, but
   we need sigcontext.  Some packages have come to rely on
   sigcontext_struct being defined on 32-bit x86, so define this for
   their benefit.  */
# define sigcontext_struct sigcontext
#endif

#define X86_FXSR_MAGIC		0x0000

struct sigcontext
{
  unsigned short gs, __gsh;
  unsigned short fs, __fsh;
  unsigned short es, __esh;
  unsigned short ds, __dsh;
  unsigned long edi;
  unsigned long esi;
  unsigned long ebp;
  unsigned long esp;
  unsigned long ebx;
  unsigned long edx;
  unsigned long ecx;
  unsigned long eax;
  unsigned long trapno;
  unsigned long err;
  unsigned long eip;
  unsigned short cs, __csh;
  unsigned long eflags;
  unsigned long esp_at_signal;
  unsigned short ss, __ssh;
  struct _fpstate * fpstate;
  unsigned long oldmask;
  unsigned long cr2;
};

#else /* __x86_64__ */

struct _fpstate
{
  /* FPU environment matching the 64-bit FXSAVE layout.  */
  __uint16_t		cwd;
  __uint16_t		swd;
  __uint16_t		ftw;
  __uint16_t		fop;
  __uint64_t		rip;
  __uint64_t		rdp;
  __uint32_t		mxcsr;
  __uint32_t		mxcr_mask;
  struct _fpxreg	_st[8];
  struct _xmmreg	_xmm[16];
  __uint32_t		padding[24];
};

struct sigcontext
{
  __uint64_t r8;
  __uint64_t r9;
  __uint64_t r10;
  __uint64_t r11;
  __uint64_t r12;
  __uint64_t r13;
  __uint64_t r14;
  __uint64_t r15;
  __uint64_t rdi;
  __uint64_t rsi;
  __uint64_t rbp;
  __uint64_t rbx;
  __uint64_t rdx;
  __uint64_t rax;
  __uint64_t rcx;
  __uint64_t rsp;
  __uint64_t rip;
  __uint64_t eflags;
  unsigned short cs;
  unsigned short gs;
  unsigned short fs;
  unsigned short __pad0;
  __uint64_t err;
  __uint64_t trapno;
  __uint64_t oldmask;
  __uint64_t cr2;
  __extension__ union
    {
      struct _fpstate * fpstate;
      __uint64_t __fpstate_word;
    };
  __uint64_t __reserved1 [8];
};

#endif /* __x86_64__ */

struct _xsave_hdr
{
  __uint64_t xstate_bv;
  __uint64_t reserved1[2];
  __uint64_t reserved2[5];
};

struct _ymmh_state
{
  __uint32_t ymmh_space[64];
};

struct _xstate
{
  struct _fpstate fpstate;
  struct _xsave_hdr xstate_hdr;
  struct _ymmh_state ymmh;
};

#endif /* _BITS_SIGCONTEXT_H */

#endif	// glibc_sysdeps_llamaos_x86_bits_sigcontext_h


text:
// * Name: Configuration.h
// * Project: Footfall
// * Author: David Haylock
// * Creation Date: 13/02/2017
// * Copyright: (c) 2017 by Watershed Arts Trust Ltd.

#ifndef Configuration_h
#define Configuration_h

struct Camera_Configuration
{
	int camerawidth;
	int cameraheight;
	int history;
	int mogThreshold;
	int threshold;
	int dilateAmount;
	int erodeAmount;
	int blur;

	float shadowPixelRatio;

	bool bTrackShadows;
	bool bFlipH;
	bool bFlipV;
	bool bUseMask;
	bool bShowShadowImage;

	vector<ofPoint> maskCoord;
};

struct Tracking_Configuration
{
	int threshold;
	int minarea;
	int maxarea;

	float blobdyingtime;
	int persistance;
	int maxdistance;
	int minsizeone;
	int minsizetwo;
	int minsizethree;
	int history;

	ofPoint startPos;
	ofPoint endPos;
	int camerawidth;
	int cameraheight;

	bool flipvertically;
	int offset;
};

struct HTTP_Configuration
{
	int port;
	string postserver;
	string postextension;
	string secretkey;
	int maxretries;
	bool keepbackups;
};

struct Configuration
{
	bool useHttp;
	bool useCsvLogging;
	Camera_Configuration cameraConfig;
	Tracking_Configuration trackingConfig;
	HTTP_Configuration httpConfig;
};

struct Post_Data
{
	Post_Data(string count,string timestamp)
	{
		_count = count;
		_timestamp = timestamp;
	}

	string _count;
	string _timestamp;
};

#endif /* Configuration_h */


text:
class AP_Limit_Geofence : public AP_Limit_Module {

public:
    AP_Limit_Geofence(uint16_t eeprom_fence_start, uint8_t fpsize, uint8_t max_fp, GPS *&gps, struct Location *home_loc, struct Location *current_loc);
    bool        init();
    bool        triggered();

    AP_Int8        fence_total();
    void        set_fence_point_with_index(Vector2l &point, uint8_t i);
    Vector2l        get_fence_point_with_index(uint8_t i);
    void            update_boundary();
    bool            boundary_correct();

    static const struct AP_Param::GroupInfo        var_info[];

protected:

    // pointers to gps, current location and home
    GPS *&                  _gps;
    struct Location *       _current_loc;
    struct Location *       _home;

    // Simple mode, just radius
    AP_Int8                 _simple;             // 1 = simple, 0 = complex
    AP_Int16                _radius;             // in meters, for simple mode

    // Complex mode, defined fence points
    AP_Int8                 _fence_total;
    AP_Int8                 _num_points;

private:
    const uint16_t          _eeprom_fence_start;
    const unsigned          _fence_wp_size;
    const unsigned          _max_fence_points;
    bool                    _boundary_uptodate;
    Vector2l                _boundary[MAX_FENCEPOINTS];      // complex mode fence

};

// Helper functions
uint32_t        get_distance_meters(struct Location *loc1, struct Location *loc2); // distance in meters between two locations

#endif // __AP_LIMIT_GEOFENCE_H__


text:
var startTime = Date.now();
import fs = require('fs');
import parameters = require('./core/parameters');

if (!fs.existsSync(__dirname+'/logs/')) fs.mkdirSync(__dirname+'/logs/');
if (!fs.existsSync(__dirname+'/logs/logs/')) fs.mkdirSync(__dirname+'/logs/logs/');
if (!fs.existsSync(__dirname+'/logs/access/')) fs.mkdirSync(__dirname+'/logs/access/');

var colors = require('colors/safe');
var numeral = require('numeral');
var cluster = require('cluster');

var clusterEnabled = parameters.getParameter('cluster');
var cpus = require('os').cpus().length;

if (!clusterEnabled || cluster.isMaster) {
    console.log(colors.yellow("          ____            _        _ _____ ____  "));
    console.log(colors.yellow("         |  _ \\ ___  _ __| |_ __ _| |_   _/ ___| "));
    console.log(colors.yellow("         | |_) / _ \\| '__| __/ _` | | | | \\___ \\ "));
    console.log(colors.yellow("         |  __/ (_) | |  | || (_| | | | |  ___) | "));
    console.log(colors.yellow("         |_|   \\___/|_|   \\__\\__,_|_| |_| |____/ "));
    console.log("\n");
    console.log(colors.bgRed(colors.white('                                                         ')));
    console.log(colors.bgRed(colors.white('                Loading required modules...              ')));
    console.log(colors.bgRed(colors.white('                                                         ')));
    console.log('\n');
}

import express = require('express');
import cookieParser = require('cookie-parser');
import bodyParser = require('body-parser');
import loader = require('./core/loader');

var portNumber = parameters.getParameter('port', 8080);
var server = express();

server.set('view engine', 'ejs');
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: false }));
server.use(cookieParser());
loader.Loader.init(server, __dirname);

export var onReadyCallback;

if (clusterEnabled && cluster.isMaster) {
    if (clusterEnabled!='auto' && clusterEnabled!==false && clusterEnabled!==true) {
        cpus = Number(clusterEnabled);
    }
    var s = "Starting in cluster mode ("+cpus+" processes)";
    console.log(colors.black(colors.bgWhite(s)));
    for (var i = 0; i < cpus; i++) {
        cluster.fork();
    }
}
else {
    server.listen(portNumber, () => {
        var endTime = Date.now();
        var elapsedTime = (endTime - startTime)/1000;
        var t = numeral(elapsedTime).format('0.00');
        console.log('\n');
        console.log(colors.bgGreen(colors.white('                                                         ')));
        console.log(colors.bgGreen(colors.white('           Startup completead in ' + t + ' seconds.           ')));
        console.log(colors.bgGreen(colors.white('                                                         ')));
        console.log('\n');
        console.log("Your application is in "+colors.green(server.get('env'))+" mode on port "+colors.green(portNumber));
        if (onReadyCallback) onReadyCallback();
    });
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycotaxon 34(2): 452 (1989)

#### Original name
Erynia formicae Humber & Balazy, 1981

### Remarks
null


text:
class RxSchema::XSD::Schema < RxSchema::XSD::XMLElement

  attr_accessor :namespaces

  def initialize
    @namespaces = {}.with_indifferent_access
    super
  end

  def add_xmlns(prefix, uri)
    @namespaces[prefix] = uri unless @namespaces.has_key?(prefix)
  end

  def namespaces
    @namespaces
  end

  def get_uri_by_prefix(prefix)
    @namespaces[prefix]
  end

  class ::XSDSpecification
    # attr_accessor :id #optional
    # attr_accessor :attribute_form_default #optional ( qualified|unqualified )
    # attr_accessor :element_form_default #optional ( qualified|unqualified )
    # attr_accessor :block_default #optional (#all|list of (extension|restriction|substitution))
    # attr_accessor :final_default #optional (#all|list of (extension|restriction|list|union))
    # attr_accessor :target_namespace #optional only URI
    # attr_accessor :version #optional
  end
end


text:
var Complex = function(real, imag) {
    this.real = real;
    this.imag = imag;
};

Complex.prototype = function () {
    var add = function (b) {
            return new Complex(this.real + b.real, this.imag + b.imag);
        },
        substract = function (b) {
            return new Complex(this.real - b.real, this.imag - b.imag);
        },
        square = function () {
            return new Complex(this.real * this.real - this.imag * this.imag, 2 * this.real * this.imag);
        },
        abs = function () {
            return Math.sqrt(this.real * this.real + this.imag * this.imag);
        },
        abs2 = function () {
            return this.real * this.real + this.imag * this.imag;
        },
        multiply = function (b) {
            return new Complex(this.real * b.real - this.imag * b.imag, this.real * b.imag + this.imag * b.real);
        };

    return {
        add: add,
        subtract: substract,
        square: square,
        multiply: multiply,
        abs: abs,
        abs2: abs2
    };
} ();


text:
module Azure::DataMigration::Mgmt::V2018_04_19
  module Models
    #
    # Defines values for MigrationState
    #
    module MigrationState
      None = "None"
      InProgress = "InProgress"
      Failed = "Failed"
      Warning = "Warning"
      Completed = "Completed"
      Skipped = "Skipped"
      Stopped = "Stopped"
    end
  end
end


text:
package terminal

import (
	"bufio"
	"fmt"
	"io"
	"strings"

	"github.com/cloudfoundry-incubator/lattice/ltc/terminal/password_reader"
)

type UI interface {
	io.ReadWriter
	password_reader.PasswordReader

	Prompt(promptText string, args ...interface{}) string
	PromptWithDefault(promptText, defaultValue string, args ...interface{}) string
	Say(format string, args ...interface{})
	SayIncorrectUsage(message string)
	SayLine(format string, args ...interface{})
	SayNewLine()
}

type terminalUI struct {
	io.Reader
	io.Writer
	password_reader.PasswordReader
}

func NewUI(input io.Reader, output io.Writer, passwordReader password_reader.PasswordReader) UI {
	return &terminalUI{
		input,
		output,
		passwordReader,
	}
}

func (t *terminalUI) Prompt(promptText string, args ...interface{}) string {
	reader := bufio.NewReader(t)
	fmt.Fprintf(t.Writer, promptText+": ", args...)

	result, _ := reader.ReadString('\n')
	return strings.TrimSuffix(result, "\n")
}

func (t *terminalUI) PromptWithDefault(promptText, defaultValue string, args ...interface{}) string {
	reader := bufio.NewReader(t)
	fmt.Fprintf(t.Writer, promptText+fmt.Sprintf(" [%s]: ", defaultValue), args...)

	result, _ := reader.ReadString('\n')
	result = strings.TrimSuffix(result, "\n")

	if result == "" {
		return defaultValue
	}

	return result
}

func (t *terminalUI) Say(format string, args ...interface{}) {
	t.say(format, args...)
}

func (t *terminalUI) SayIncorrectUsage(message string) {
	if len(message) > 0 {
		t.say("Incorrect Usage: %s\n", message)
	} else {
		t.say("Incorrect Usage\n")
	}
}

func (t *terminalUI) SayLine(format string, args ...interface{}) {
	t.say(format+"\n", args...)
}

func (t *terminalUI) SayNewLine() {
	t.say("\n")
}

func (t *terminalUI) say(format string, args ...interface{}) {
	if len(args) > 0 {
		t.Write([]byte(fmt.Sprintf(format, args...)))
		return
	}
	t.Write([]byte(format))
}


text:
import mock
from neutron_lib.callbacks import events
from neutron_lib import fixture

from neutron.common import exceptions
from neutron.services.logapi.common import constants as log_const
from neutron.services.logapi.common import exceptions as log_exc
from neutron.services.logapi.drivers import base as log_driver_base
from neutron.services.logapi.drivers import manager as driver_mgr
from neutron.tests import tools
from neutron.tests.unit.services.logapi import base

class TestGetParameter(base.BaseLogTestCase):

    def test__get_param_missing_parameter(self):
        kwargs = {'context': mock.sentinel.context}
        self.assertRaises(log_exc.LogapiDriverException,
                          driver_mgr._get_param,
                          args=[], kwargs=kwargs,
                          name='log_obj', index=1)
        self.assertRaises(log_exc.LogapiDriverException,
                          driver_mgr._get_param,
                          args=[mock.sentinel.context], kwargs={},
                          name='log_obj', index=1)
        self.assertRaises(log_exc.LogapiDriverException,
                          driver_mgr._get_param,
                          args=[], kwargs={'log_obj': mock.sentinel.log_obj},
                          name='context', index=0)

class TestLogDriversManagerBase(base.BaseLogTestCase):

    def setUp(self):
        super(TestLogDriversManagerBase, self).setUp()
        self.config_parse()
        self.setup_coreplugin(load_plugins=False)

    @staticmethod
    def _create_manager_with_drivers(drivers_details):
        for name, driver_details in drivers_details.items():
            class LogDriver(log_driver_base.DriverBase):
                @property
                def is_loaded(self):
                    return driver_details['is_loaded']

            LogDriver(name,
                      driver_details.get('vif_types', []),
                      driver_details.get('vnic_types', []),
                      driver_details.get('supported_logging_types', []))

        return driver_mgr.LoggingServiceDriverManager()

class TestLogDriversManagerMulti(TestLogDriversManagerBase):
    """Test calls happen to all drivers"""
    def test_driver_manager_empty_with_no_drivers(self):
        driver_manager = self._create_manager_with_drivers({})
        self.assertEqual(0, len(driver_manager.drivers))

    def test_driver_manager_empty_with_no_loaded_drivers(self):
        driver_manager = self._create_manager_with_drivers(
            {'driver-A': {'is_loaded': False}})
        self.assertEqual(0, len(driver_manager.drivers))

    def test_driver_manager_with_one_loaded_driver(self):
        driver_manager = self._create_manager_with_drivers(
            {'driver-A': {'is_loaded': True}})
        self.assertEqual(1, len(driver_manager.drivers))

    def test_driver_manager_with_two_loaded_drivers(self):
        driver_manager = self._create_manager_with_drivers(
            {'driver-A': {'is_loaded': True},
             'driver-B': {'is_loaded': True}})
        self.assertEqual(2, len(driver_manager.drivers))

class TestLogDriversManagerLoggingTypes(TestLogDriversManagerBase):
    """Test supported logging types"""
    def test_available_logging_types(self):
        driver_manager = self._create_manager_with_drivers(
            {'driver-A': {'is_loaded': True,
                          'supported_logging_types': ['security_group']},
             'driver-B': {'is_loaded': True,
                          'supported_logging_types':
                              ['security_group', 'firewall']}
             })
        self.assertEqual(set(['security_group', 'firewall']),
                         driver_manager.supported_logging_types)

class TestLogDriversCalls(TestLogDriversManagerBase):
    """Test log driver calls"""

    def setUp(self):
        super(TestLogDriversCalls, self).setUp()
        self.driver_manager = self._create_manager_with_drivers(
            {'driver-A': {'is_loaded': True}})

    def test_implemented_call_methods(self):
        for method in log_const.LOG_CALL_METHODS:
            with mock.patch.object(log_driver_base.DriverBase, method) as \
                    method_fnc:
                context = mock.sentinel.context
                log_obj = mock.sentinel.log_obj
                self.driver_manager.call(
                    method, context=context, log_objs=[log_obj])
                method_fnc.assert_called_once_with(
                    context=context, log_objs=[log_obj])

    def test_not_implemented_call_methods(self):
        context = mock.sentinel.context
        log_obj = mock.sentinel.log_obj
        self.assertRaises(exceptions.DriverCallError, self.driver_manager.call,
                          'wrong_method', context=context, log_objs=[log_obj])

class TestHandleResourceCallback(TestLogDriversManagerBase):
    """Test handle resource callback"""

    def setUp(self):
        super(TestHandleResourceCallback, self).setUp()
        self._cb_mgr = mock.Mock()
        self.useFixture(fixture.CallbackRegistryFixture(
            callback_manager=self._cb_mgr))
        self.driver_manager = driver_mgr.LoggingServiceDriverManager()

    def test_subscribe_resources_cb(self):

        class FakeResourceCB1(driver_mgr.ResourceCallBackBase):
            def handle_event(self, resource, event, trigger, **kwargs):
                pass

        class FakeResourceCB2(driver_mgr.ResourceCallBackBase):
            def handle_event(self, resource, event, trigger, **kwargs):
                pass

        driver_mgr.RESOURCE_CB_CLASS_MAP = {'fake_resource1': FakeResourceCB1,
                                            'fake_resource2': FakeResourceCB2}

        self.driver_manager._setup_resources_cb_handle()

        fake_resource_cb1 = FakeResourceCB1(
            'fake_resource1', self.driver_manager.call)
        fake_resource_cb2 = FakeResourceCB2(
            'fake_resource2', self.driver_manager.call)
        assert_calls = [
            mock.call(
                *tools.get_subscribe_args(
                    fake_resource_cb1.handle_event,
                    'fake_resource1', events.AFTER_CREATE)),
            mock.call(
                *tools.get_subscribe_args(
                    fake_resource_cb1.handle_event,
                    'fake_resource1', events.AFTER_UPDATE)),
            mock.call(
                *tools.get_subscribe_args(
                    fake_resource_cb1.handle_event,
                    'fake_resource1', events.AFTER_DELETE)),
            mock.call(
                *tools.get_subscribe_args(
                    fake_resource_cb2.handle_event,
                    'fake_resource2', events.AFTER_CREATE)),
            mock.call(
                *tools.get_subscribe_args(
                    fake_resource_cb2.handle_event,
                    'fake_resource2', events.AFTER_UPDATE)),
            mock.call(
                *tools.get_subscribe_args(
                    fake_resource_cb2.handle_event,
                    'fake_resource2', events.AFTER_DELETE)),
        ]
        self._cb_mgr.subscribe.assert_has_calls(assert_calls)


text:
from queue import Queue
from graphs import Graph, Vertex

def bfs(g, start):
    # start is the starting vertex of the graph,
    # as it's the starting point, set distance to zero
    # also predecessor to 'None' as this was the starting
    # point.
    start.setDistance(0)
    start.setPred(None)
    # initialize an empty Queue to hold the vertices.
    # enuqeue `start` in the Queue
    vertQueue = Queue()
    vertQueue.enqueue(start)
    # check if vertices Queue has any Queue items to be explored.
    # if there are any items that need to be explored we have
    # not searched far enough.
    while (vertQueue.size() > 0):
        # take out `dequeue` the first Item in the vertices Queue.
        # and assign it to  `currentVert`.
        # for loop now goes over all the connections for this vertex
        currentVert = vertQueue.dequeue()
        for nbr in currentVert.getConnections():
            # nbr is the current node in question,
            # if it was marked white, which means that it was
            # never discovered and as a flag mark it was `grey`
            if (nbr.getColor == 'white'):
                nbr.setColor('grey')
                # set distance for nbr vertex to be +1 from `currentVertex`
                nbr.setDistance(currentVert.getDistance()+1)
                # now set nbr predecessor to be current vertex
                # and then we need to put `nbr` in  vertQueue as
                # nbr needs to be explored as well for nodes.
                nbr.setPred(currentVert)
                vertQueue.enqueue(nbr)
        # when we reach here it means that currentVert connections have been completley explored.
        # and set the color to black as a marker.
        currentVert.setColor('black')


text:
package org.apache.coyote.http11.filters;

import java.io.IOException;
import java.nio.ByteBuffer;

import org.apache.coyote.InputBuffer;
import org.apache.coyote.http11.InputFilter;
import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.net.ApplicationBufferHandler;

/**
 * Input filter responsible for replaying the request body when restoring the
 * saved request after FORM authentication.
 */
public class SavedRequestInputFilter implements InputFilter {

    /**
     * The original request body.
     */
    protected ByteChunk input = null;

    /**
     * Create a new SavedRequestInputFilter.
     *
     * @param input The saved request body to be replayed.
     */
    public SavedRequestInputFilter(ByteChunk input) {
        this.input = input;
    }

    /**
     * @deprecated Unused. Will be removed in Tomcat 9. Use
     *             {@link #doRead(ApplicationBufferHandler)}
     */
    @Deprecated
    @Override
    public int doRead(ByteChunk chunk) throws IOException {
        if(input.getOffset()>= input.getEnd())
            return -1;

        int writeLength = 0;

        if (chunk.getLimit() > 0 && chunk.getLimit() < input.getLength()) {
            writeLength = chunk.getLimit();
        } else {
            writeLength = input.getLength();
        }

        input.substract(chunk.getBuffer(), 0, writeLength);
        chunk.setOffset(0);
        chunk.setEnd(writeLength);

        return writeLength;
    }

    @Override
    public int doRead(ApplicationBufferHandler handler) throws IOException {
        if(input.getOffset()>= input.getEnd())
            return -1;

        ByteBuffer byteBuffer = handler.getByteBuffer();
        byteBuffer.position(byteBuffer.limit()).limit(byteBuffer.capacity());
        input.substract(byteBuffer);

        return byteBuffer.remaining();
    }

    /**
     * Set the content length on the request.
     */
    @Override
    public void setRequest(org.apache.coyote.Request request) {
        request.setContentLength(input.getLength());
    }

    /**
     * Make the filter ready to process the next request.
     */
    @Override
    public void recycle() {
        input = null;
    }

    /**
     * Return the name of the associated encoding; here, the value is null.
     */
    @Override
    public ByteChunk getEncodingName() {
        return null;
    }

    /**
     * Set the next buffer in the filter pipeline (has no effect).
     */
    @Override
    public void setBuffer(InputBuffer buffer) {
        // NOOP since this filter will be providing the request body
    }

    /**
     * Amount of bytes still available in a buffer.
     */
    @Override
    public int available() {
        return input.getLength();
    }

    /**
     * End the current request (has no effect).
     */
    @Override
    public long end() throws IOException {
        return 0;
    }

    @Override
    public boolean isFinished() {
        return input.getOffset() >= input.getEnd();
    }
}


text:
package io.shaoshuai.common.service;

import io.shaoshuai.common.exception.BusinessException;
import io.shaoshuai.common.po.BasePO;

import java.io.Serializable;

/**
 * @author guoqiang
 * @version 1.0
 * @created 5/27/2016 3:33 PM
 */
public interface IBaseService<PO extends Serializable, ID extends Serializable> {

    ID save(PO record) throws BusinessException;

    boolean delete(ID id) throws BusinessException;

    boolean update(PO record) throws BusinessException;

    PO findById(ID id);

}


text:
#ifndef FIREFUSE_HPP
#define FIREFUSE_HPP
#ifdef __cplusplus
extern "C" {
#endif

//////////////////////////////// C DECLARATIONS ////////////////////////////////
#define FUSE_USE_VERSION 26
#include <fuse.h>
#include <FireLog.h>

#define MAX_GCODE_LEN 255 /* maximum characters in a gcode instruction */

#define STATUS_PATH "/status"
#define HOLES_PATH "/holes"
#define FIRESTEP_PATH "/firestep"
#define FIRELOG_PATH "/firelog"
#define CONFIG_PATH "/config.json"
#define ECHO_PATH "/echo"

// FireREST JSON network response sizes are obtained from FUSE file size.
// We provide a minimum size for sync requests that don't know actual response size in cve_getattr()
// Large values waste bandwidth, small values run the risk of clipping the returned JSON.
// To match the minimum size constraint, JSON text is padded with trailing spaces
#define MIN_SAVE_SIZE ((size_t) 256)
#define MIN_PROCESS_SIZE ((size_t) 2048)

#ifndef bool
#define bool int
#define TRUE 1
#define FALSE 0
#endif

    typedef struct {
        char *pData;
        int length;
        long reserved;
    } FuseDataBuffer;

    extern const char * fuse_root;
    extern FuseDataBuffer headcam_image;     // perpetually changing image
    extern FuseDataBuffer headcam_image_fstat;  // image at time of most recent fstat()

    extern FuseDataBuffer* firefuse_allocImage(const char *path, int *pResult);
    extern FuseDataBuffer* firefuse_allocDataBuffer(const char *path, int *pResult, const char *pData, size_t length);
    bool firefuse_isFile(const char *value, const char * suffix);
    extern void firefuse_freeDataBuffer(const char *path, struct fuse_file_info *fi);
    extern const char* firepick_status();
    extern const void* firepick_holes(FuseDataBuffer *pJPG);
    extern int background_worker();
    extern bool is_cv_path(const char * path);
    extern bool is_cnc_path(const char *path);
    int firefuse_getattr_file(const char *path, struct stat *stbuf, size_t length, int perm);
    int firefuse_getattr(const char *path, struct stat *stbuf);
    int firefuse_open(const char *path, struct fuse_file_info *fi);
    int firefuse_read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fi);
    int firefuse_write(const char *path, const char *buf, size_t bufsize, off_t offset, struct fuse_file_info *fi);
    int firefuse_release(const char *path, struct fuse_file_info *fi);
    int firefuse_main(int argc, char *argv[]);

    int firerest_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi);
    int firerest_getattr_default(const char *path, struct stat *stbuf);
    char * firerest_config(const char *path);

    static inline int firefuse_readBuffer(char *pDst, const char *pSrc, size_t size, off_t offset, size_t len) {
        size_t sizeOut = size;
        if (offset < len) {
            if (offset + sizeOut > len) {
                sizeOut = len - offset;
            }
            memcpy(pDst, pSrc + offset, sizeOut);
        } else {
            sizeOut = 0;
        }

        return sizeOut;
    }

#define FIREREST_1 "/1"
#define FIREREST_GRAY "/gray"
#define FIREREST_BGR "/bgr"
#define FIREREST_CAMERA_JPG "/camera.jpg"
#define FIREREST_CAMERA_JPG_TILDE "/camera.jpg~"
#define FIREREST_CV "/cv"
#define FIREREST_SYNC "/sync"
#define FIREREST_CVE "/cve"
#define FIREREST_CNC "/cnc"
#define FIREREST_FIRESIGHT_JSON "/firesight.json"
#define FIREREST_PROPERTIES_JSON "/properties.json"
#define FIREREST_MONITOR_JPG "/monitor.jpg"
#define FIREREST_OUTPUT_JPG "/output.jpg"
#define FIREREST_PROCESS_FIRE "/process.fire"
#define FIREREST_GCODE_FIRE "/gcode.fire"
#define FIREREST_SAVED_PNG "/saved.png"
#define FIREREST_SAVE_FIRE "/save.fire"

#define FIREREST_VAR "/var/firefuse"

    bool cve_isPathSuffix(const char *path, const char *suffix);
    int cve_save(FuseDataBuffer *pBuffer, const char *path);
    int cve_getattr(const char *path, struct stat *stbuf);
    int cve_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi);
    int cve_open(const char *path, struct fuse_file_info *fi);
    int cve_read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fi);
    int cve_write(const char *path, const char *buf, size_t bufsize, off_t offset, struct fuse_file_info *fi);
    int cve_release(const char *path, struct fuse_file_info *fi);
    int cve_truncate(const char *path, off_t size);
    int cve_rename(const char *path1, const char * path2);
    int cnc_getattr(const char *path, struct stat *stbuf);
    int cnc_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi);
    int cnc_open(const char *path, struct fuse_file_info *fi);
    int cnc_read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fi);
    int cnc_write(const char *path, const char *buf, size_t bufsize, off_t offset, struct fuse_file_info *fi);
    int cnc_release(const char *path, struct fuse_file_info *fi);
    int cnc_truncate(const char *path, off_t size);

    inline bool verifyOpenR_(const char *path, struct fuse_file_info *fi, int *pResult) {
        switch (fi->flags & 3) {
        case O_RDONLY:
            LOGTRACE1("verifyOpenR_(%s) O_RDONLY", path);
            break;
        case O_WRONLY:
        case O_RDWR:
        default:
            LOGERROR2("verifyOpenR_(%s) EACCESS %o", path, fi->flags);
            (*pResult) = -EACCES;
            break;
        }
        return (*pResult) == 0;
    }

    inline bool verifyOpenRW(const char *path, struct fuse_file_info *fi, int *pResult) {
        if ((fi->flags & O_DIRECTORY)) {
            LOGERROR2("verifyOpenRW(%s) DIRECTORY EACCESS %o", path, fi->flags);
            (*pResult) = -EACCES;
        } else {
            switch (fi->flags & 3) {
            case O_RDONLY:
                LOGTRACE1("verifyOpenRW(%s) O_RDONLY", path);
                break;
            case O_WRONLY:
                LOGTRACE1("verifyOpenRW(%s) O_WRONLY", path);
                break;
            case O_RDWR: // Simultaneous read/write not allowed
                LOGERROR2("verifyOpenRW(%s) EACCESS %o", path, fi->flags);
                (*pResult) = -EACCES;
                break;
            default:
                LOGERROR2("verifyOpenRW(%s) UNKNOWN EACCESS %o", path, fi->flags);
                (*pResult) = -EACCES;
                break;
            }
        }
        return (*pResult) == 0;
    }

    int firestep_init();
    void firestep_destroy();
    int firestep_write(const char *buf, size_t bufsize);
    const char * firestep_json();
    int tinyg_hash(const char *value, size_t len);

#ifdef __cplusplus
//////////////////////////////// C++ DECLARATIONS ///////////////////////////////////////////////////
} // extern C
#include "LIFOCache.hpp"
#include <vector>
#include <map>
#include <string.h>
#include <signal.h>
#include "FireUtils.hpp"

extern int cameraWidth; // config.json provided camera width
extern int cameraHeight; // config.json provided camera height
extern string cameraSourceName; // config.json provided camera source name
extern string cameraSourceConfig; // config.json provided camera souce config

void 	cve_process(const char *path, int *pResult);
class BackgroundWorker;

// firerest.cpp
string hexFromRFC4648(const char *rfc);
string hexToRFC4648(const char *hex);

// background.cpp
SmartPointer<char> loadFile(const char *path, int suffixBytes=0); //Return allocated memory with contents

// ****************************************************************************
// cv.cpp - Implementation of Computer Vision Endpoint (https://github.com/firepick1/FireREST/wiki/FireREST-CV)
// There will be one CVE element for each endpoint in /dev/firefuse.
typedef class CVE {
    private:
        string name;                                        //
    private:
        bool _isColor;                                      // TRUE if CVE is a color endpoint, or FALSE if endpoint is grayscale

    public:
        LIFOCache<SmartPointer<char> > src_saved_png;        // Pointer to https://github.com/firepick1/FireREST/wiki/saved.png
    public:
        LIFOCache<SmartPointer<char> > src_save_fire;        // Pointer to https://github.com/firepick1/FireREST/wiki/save.fire (grab saved.png when accessed)
    public:
        LIFOCache<SmartPointer<char> > src_process_fire;     // Pointer to https://github.com/firepick1/FireREST/wiki/process.fire
    public:
        LIFOCache<SmartPointer<char> > src_firesight_json;   // Pointer to https://github.com/firepick1/FireREST/wiki/firesight.json
    public:
        LIFOCache<SmartPointer<char> > src_properties_json;  // Pointer to https://github.com/firepick1/FireREST/wiki/properties.json
    public:
        static string cve_path(const char *pPath);          // String containing path to Computer Vision Endpoint
    public:
        CVE(string name);                                    // Constructor
    public:
        ~CVE();                                              // Destructor
    public:
        inline string getName() {
            return name;
        }
    public:
        int save(BackgroundWorker *pWorker);
    public:
        int process(BackgroundWorker *pWorker);
    public:
        inline bool isColor() {
            return _isColor;    // TRUE if CVE is a color endpoint, or FALSE if endpoint is grayscale
        }
} CVE, *CVEPtr;

// ****************************************************************************
// cnc.cpp - Implementation of Device Control Endpoint (https://github.com/firepick1/FireREST/wiki/FireREST-CNC)
typedef class DCE {
    private:
        string name;
    private:
        int serial_fd;
    private:
        bool is_sync;
    private:
        string serial_path;
    private:
        string serial_stty;
	private:
		string serial_ack;
    private:
        pthread_t tidReader;
    public:
        vector<string> serial_device_config;
    private:
        char *jsonBuf;
    private:
        int activeRequests;
    private:
        int jsonLen;
    private:
        int jsonDepth;
    private:
        string gcode_finish;	// Complete current operations and await further instructions (e.g., G4P0)
    private:
        char *inbuf;
    private:
        int inbuflen;
    private:
        int inbufEmptyLine;
    private:
        string serial_reader_buf;
    private:
        int serial_send_eol(const char *buf, size_t bufsize);
    private:
        int serial_send(const char *data, size_t length);
    private:
        int serial_read_char(int c);
    private:
        int post_serial_status(const char *line);
    private:
        static void * serial_reader_thread(void *arg);
    private:
        const char * read_json();

    protected:
        virtual void send_line(string request, json_t*response);

        // Common data
    public:
        LIFOCache<SmartPointer<char> > snk_gcode_fire;
    public:
        LIFOCache<SmartPointer<char> > src_gcode_fire;
        //public: LIFOCache<SmartPointer<char> > src_properties_json;

    public:
        static vector<std::string> gcode_lines(const string &gcode);
    public:
        static string dce_path(const char *pPath);
    public:
        DCE(string name);
    public:
        ~DCE();
    public:
        void init();
	public:
		void send_request(SmartPointer<char> &data);
    public:
        inline bool isSync() {
            return is_sync;
        }
	public:
		void setSync(bool value);
    public:
        inline void set_gcode_finish(const char *value="G4P0") {
            gcode_finish = value;
        }
    public:
        inline const char * get_gcode_finish() {
            return gcode_finish.c_str();
        }
	public:
		inline void set_serial_ack(const char * value="ok") {
			serial_ack = value;
		}
	public:
		inline const char *get_serial_ack() {
			return serial_ack.c_str();
		}
    public:
        int serial_init();
    public:
        inline string getName() {
            return name;
        }
    public:
        int gcode(BackgroundWorker *pWorker);
    public:
        inline string getSerialStty() {
            return serial_stty;
        }
    public:
        inline void setSerialStty(const char * value) {
            serial_stty = value;
        }
    public:
        inline string getSerialPath() {
            return serial_path;
        }
    public:
        inline void setSerialPath(const char * value) {
            serial_path = value;
        }
    public:
        inline vector<string> getSerialDeviceConfig() {
            return serial_device_config;
        }
} DCE, *DCEPtr;

// ****************************************************************************
// background.cpp - Gets called whenever cve_open() is called.
// During cve_open (cv.cpp), worker.cameras[] will be populated with a CameraNode object for each camera present.
typedef class CameraNode {
    private:
        double camera_idle_capture_seconds;
    private:
        double camera_seconds; // time of last camera update
    private:
        double output_seconds; // time of last FireSight pipeline completion
    private:
        double monitor_duration; // number of seconds to show last output
    private:
        int min_capture_ms; // minimum number of milliseconds between captures
    private:
        bool captureActive;
    private:
        pid_t raspistillPID;
    private:
        long msCapture; // earliest time of next capture

        // Common data
    public:
        LIFOCache<SmartPointer<char> > src_camera_jpg;
    public:
        LIFOCache<Mat> src_camera_mat_gray;
    public:
        LIFOCache<Mat> src_camera_mat_bgr;
    public:
        LIFOCache<SmartPointer<char> > src_monitor_jpg;
    public:
        LIFOCache<SmartPointer<char> > src_output_jpg;

        // General use
    public:
        bool capture();

	public:
		bool isCapturing();

        // For BackgroundWorker use
    public:
        CameraNode();
    public:
        ~CameraNode();
    public:
        void init();                                     //Inits camera.  Starts Raspistill, etc..
    public:
        void clear();
    public:
        void endCapture();
    public:
        int async_update_camera_jpg();
    public:
        int accept_new_image(SmartPointer<char> jpg);
    public:
        int async_update_monitor_jpg();
    public:
        void setOutput(Mat image);
    public:
        inline int get_min_capture_ms() {
            return min_capture_ms;
        }
    public:
        void set_min_capture_ms(int value = 500);
} CameraNode;

#define MAX_CAMERAS 1 /* TODO: Make code actually work for multiple cameras */

// ****************************************************************************
// background.cpp - singleton class
typedef class BackgroundWorker {
    private:
        double idle_period; // minimum seconds between idle() execution. Gets set by config.json.
    private:
        std::map<string, CVEPtr> cveMap;
    private:
        std::map<string, DCEPtr> dceMap;
    private:
        std::map<string, DCEPtr> serialMap;
    private:
        double idle_seconds; // time of last idle() execution
    private:
        int async_save_fire();
    private:
        int async_process_fire();
    private:
        int async_gcode_fire();

    public:
        CameraNode cameras[MAX_CAMERAS];
    public:
        static double seconds();

    public:
        BackgroundWorker();
    public:
        ~BackgroundWorker();
    public:
        static int callSystem(char *cmdbuf); //Execute a system shell command
    public:
        CVE& cve(string path, bool create=FALSE);
    public:
        DCE& dce(string path, bool create=FALSE);
    public:
        vector<string> getCveNames();
    public:
        vector<string> getDceNames();
    public:
        void clear();
    public:
        void process();
    public:
        inline void setIdlePeriod(double value) {
            idle_period = value;
        }
    public:
        inline double getIdlePeriod() {
            return idle_period;
        }
    public:
        inline DCEPtr getSerialDCE(string serialPath) {
            return serialMap[serialPath];
        }
    public:
        inline void setSerialDCE(string serialPath, DCEPtr pDce) {
            serialMap[serialPath] = pDce;
        }

        // TESTING ONLY
    public:
        void processInit();
    public:
        int processLoop();
    public:
        void idle();
} BackgroundWorker;

extern BackgroundWorker worker; // BackgroundWorker singleton background worker

// ****************************************************************************
// firerest.cpp
typedef class JSONFileSystem {
    private:
        std::map<string, json_t *> dirMap;
    private:
        std::map<string, json_t *> fileMap;
    private:
        json_t *resolve_file(const char *path);

    public:
        JSONFileSystem();
    public:
        ~JSONFileSystem();

    public:
        static vector<string> splitPath(const char *path);
    public:
        void clear();
    public:
        json_t *get(const char *path);
    public:
        void create_file(const char *path, int perm);
    public:
        inline void create_file(string path, int perm) {
            create_file(path.c_str(), perm);
        }
    public:
        vector<string> fileNames(const char *path);
    public:
        bool isFile(const char *path);
    public:
        bool isDirectory(const char *path);
    public:
        int perms(const char *path);
} JSONFileSystem;

// ****************************************************************************
// firerest.cpp - read/write/modify of config.json (shared with FireREST et. al.)
typedef class FireREST {
    private:
        pthread_mutex_t processMutex;
    private:
        int processCount;
    private:
        JSONFileSystem files;
    private:
        string config_camera(const char* cv_path, json_t *pCamera, const char *pCameraName, json_t *pCveMap);
    private:
        string config_cv(const char* root_path, json_t *pConfig);
    private:
        string config_cnc(const char* root_path, json_t *pConfig);
    private:
        string config_cnc_serial(string dcePath, json_t *pSerial);
    private:
        string config_dce(string dcePath, json_t *pConfig);
    private:
        void create_resource(string path, int perm);

    public:
        FireREST();
    public:
        ~FireREST();

    public:
        int incrementProcessCount();
    public:
        int decrementProcessCount();
    public:
        char * configure_path(const char *path);
    public:
        void configure_json(const char *pJson);
    public:
        int perms(const char *path) {
            return files.perms(path);
        }
    public:
        bool isDirectory(const char *path) {
            return files.isDirectory(path);
        }
    public:
        bool isFile(const char *path) {
            return files.isFile(path);
        }
    public:
        static bool isSync(const char *path);
    public:
        vector<string> fileNames(const char *path) {
            return files.fileNames(path);
        }
} FireREST;

extern FireREST firerest;

// ****************************************************************************
// Calibrate.cpp
typedef class SpiralIterator { // simpler than a C++ <iterator>
    private:
        int x;
    private:
        int y;
    private:
        int mx;
    private:
        int my;
    private:
        int dx;
    private:
        int dy;
    private:
        int state;
    private:
        int xMax;
    private:
        int yMax;
    private:
        float xScale;
    private:
        float yScale;
    private:
        float xOffset;
    private:
        float yOffset;
    private:
        void reset();

    public:
        SpiralIterator(int xSteps=21, int ySteps=0);
    public:
        inline void setScale(float xScale, float yScale) {
            this->xScale = xScale;
            this->yScale = yScale;
        }
    public:
        inline void setOffset(float xOffset, float yOffset) {
            this->xOffset = xOffset;
            this->yOffset = yOffset;
        }
    public:
        inline float getX() {
            return x*xScale + xOffset;
        }
    public:
        inline float getY() {
            return y*yScale + yOffset;
        }
    public:
        bool next();
} SpiralIterator;

extern long millis();

#endif // __cplusplus
//////////////////////////////////// FIREFUSE_H ////////////////////////////////////////////////////////
#endif // FIREFUSE_HPP


text:
__version__ = '1.1.3-p1'

from breadcrumbs import Breadcrumb


text:
import {Injectable} from '@angular/core'
import * as Fuse from 'fuse.js'
import FuseOptions = Fuse.FuseOptions;

import _set = require('lodash.set');
import _get = require('lodash.get');

export interface AngularFusejsOptions extends FuseOptions {
  supportHighlight?: boolean;
  fusejsHighlightKey?: string;
  fusejsScoreKey?: string;
  minSearchTermLength?: number;
  maximumScore?: number;
}

@Injectable()
export class FusejsService {
  private defaultOptions: AngularFusejsOptions = {
    supportHighlight: true,
    shouldSort: false,
    threshold: 0.6,
    location: 0,
    distance: 100,
    maxPatternLength: 32,
    minMatchCharLength: 2,
    includeScore: true,
    minSearchTermLength: 3,
    fusejsHighlightKey: 'fuseJsHighlighted',
    fusejsScoreKey: 'fuseJsScore',
  };

  searchList(list: Array<any>, searchTerms: string, options: AngularFusejsOptions = {}) {
    const fuseOptions: AngularFusejsOptions = Object.assign({}, this.defaultOptions, options);
    let result = [];

    if (searchTerms && searchTerms.length >= fuseOptions.minSearchTermLength) {
      if (fuseOptions.supportHighlight) {
        fuseOptions.includeMatches = true;
      }

      let fuse = new Fuse(list, fuseOptions);
      result = fuse.search(searchTerms);
      if (fuseOptions.supportHighlight) {
        result = this.handleHighlight(result, fuseOptions);
      }
    } else {
      result = this.deepClone(list);

      if (fuseOptions.supportHighlight) {
        result.forEach((element) => {
          element[fuseOptions.fusejsHighlightKey] = this.deepClone(element);
        });
      }
    }

    return result;
  }

  private deepClone(o) {
    var _out, v, _key;
    _out = Array.isArray(o) ? [] : {};
    for (_key in o) {
      v = o[_key];
      _out[_key] = (typeof v === "object") ? this.deepClone(v) : v;
    }
    return _out;
  }

  private handleHighlight(result, options: AngularFusejsOptions) {
    if (options.maximumScore && options.includeScore) {
      result = result.filter((matchObject) => {
        return matchObject.score <= options.maximumScore;
      })
    }

    return result.map((matchObject) => {
      const item = this.deepClone(matchObject.item);
      item[options.fusejsHighlightKey] = this.deepClone(item);
      item[options.fusejsScoreKey] = matchObject.score;
      for (let match of matchObject.matches) {
        const indices: number[][] = match.indices;

        let highlightOffset: number = 0;

        let key: string = match.key;
        if(_get(item[options.fusejsHighlightKey], key).constructor === Array) {
          key += `[${match.arrayIndex}]`
        }

        for (let indice of indices) {
          let initialValue: string = _get(item[options.fusejsHighlightKey], key) as string;

          const startOffset = indice[0] + highlightOffset;
          const endOffset = indice[1] + highlightOffset + 1;
          let highlightedTerm = initialValue.substring(startOffset, endOffset);
          let newValue = initialValue.substring(0, startOffset) + '' + highlightedTerm + '' + initialValue.substring(endOffset);
          highlightOffset += ''.length;
          _set(item[options.fusejsHighlightKey], key, newValue);
        }
      }

      return item;
    });
  }
}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" type="text/css" href="./css/bootstrap.css">
        <link rel="stylesheet" type="text/css" href="./css/user.css">

										<input type="button" ng-value="'下载'" ng-click="upload(data[0],data[1])"/>