text:
#ifndef ARGRIPPER_H
#define ARGRIPPER_H

#include "ariaTypedefs.h"
#include "ArRobot.h"

/// Constains gripper command numbers
/**
   A class with an enum of the commands for the gripper, see the Pioneer operations
   manual and the gripper guide for more detailed descriptions.  The enum
   values which start with GRIP are for the gripper paddles, the ones which
   start with LIFT are the for the lift, and the ones which start with GRIPPER
   are for the entire unit.
*/
class ArGripperCommands
{
public:
  enum Commands {
    GRIP_OPEN = 1, ///< open the gripper paddles fully
    GRIP_CLOSE = 2, ///< close the gripper paddles all the way
    GRIP_STOP = 3, ///< stop the gripper paddles where they are
    LIFT_UP = 4, ///< raises the lift to the top of its range
    LIFT_DOWN = 5, ///< lowers the lift to the bottom of its range
    LIFT_STOP = 6, ///< stops the lift where it is
    GRIPPER_STORE = 7, /**<
		       closes the paddles and raises the lift simultaneously,
		       this is for storage not for grasping/carrying an object
		    */
    GRIPPER_DEPLOY = 8, /**<
			opens the paddles and lowers the lieft simultaneously,
			this is for getting ready to grasp an object, not for
			object drops
		     */
    GRIPPER_HALT = 15, ///< stops the gripper paddles and lift from moving
    GRIP_PRESSURE = 16, /**<
			sets the time delay in 20 msec increments after the
			gripper paddles first grasp an object before they stop
			moving, regulates grasp pressure
		     */
    LIFT_CARRY = 17 /**<
		       raises or lowers the lieft, the argument is the number
		       of 20 msec increments to raise or lower the lift,
		       poseitive arguments for raise, negative for lower
		    */
  };
};

/// Provides an interface to the Pioneer gripper device
class ArGripper
{
public:
  /// Constructor
  AREXPORT ArGripper(ArRobot *robot, int gripperType = QUERYTYPE);
  /// Destructor
  AREXPORT virtual ~ArGripper();
  /// Opens the gripper paddles
  AREXPORT bool gripOpen(void);
  /// Closes the gripper paddles
  AREXPORT bool gripClose(void);
  /// Stops the gripper paddles
  AREXPORT bool gripStop(void);
  /// Raises the lift to the top
  AREXPORT bool liftUp(void);
  /// Lowers the lift to the bottom
  AREXPORT bool liftDown(void);
  /// Stops the lift
  AREXPORT bool liftStop(void);
  /// Puts the gripper in a storage position
  AREXPORT bool gripperStore(void);
  /// Puts the gripper in a deployed position, ready for use
  AREXPORT bool gripperDeploy(void);
  /// Halts the lift and the gripper paddles
  AREXPORT bool gripperHalt(void);
  /// Sets the amount of pressure the gripper applies
  AREXPORT bool gripPressure(int mSecIntervals);
  /// Raises the lift by a given amount of time
  AREXPORT bool liftCarry(int mSecIntervals);
  /// Returns true if the gripper paddles are moving
  AREXPORT bool isGripMoving(void) const;
  /// Returns true if the lift is moving
  AREXPORT bool isLiftMoving(void) const;
  /// Returns the state of the gripper paddles
  AREXPORT int getGripState(void) const;
  /// Returns the state of each gripper paddle
  AREXPORT int getPaddleState(void) const;
  /// Returns the state of the gripper's breakbeams
  AREXPORT int getBreakBeamState(void) const;
  /// Returns the state of the lift
  AREXPORT bool isLiftMaxed(void) const;
  /// Gets the type of the gripper
  AREXPORT int getType(void) const;
  /// Sets the type of the gripper
  AREXPORT void setType(int type);
  /// Gets the number of mSec since the last gripper packet
  AREXPORT long getMSecSinceLastPacket(void) const;
  /// Gets the grasp time
  AREXPORT int getGraspTime(void) const;
  /// logs the gripper state
  AREXPORT void logState(void) const;
  /// Parses the gripper packet
  AREXPORT bool packetHandler(ArRobotPacket *packet);
  /// The handler for when the robot connects
  AREXPORT void connectHandler(void);
  /// These are the types for the gripper
  enum Type {
    QUERYTYPE, ///< Finds out what type from the robot, default
    GENIO, ///< Uses general IO
    USERIO, ///< Uses the user IO
    GRIPPAC, ///< Uses a packet requested from the robot
    NOGRIPPER ///< There isn't a gripper
  };
protected:
  ArRobot *myRobot;
  int myType;
  unsigned char myState;
  unsigned char mySwitches;
  unsigned char myGraspTime;
  ArTime myLastDataTime;
  ArFunctorC<ArGripper> myConnectCB;
  ArRetFunctor1C<bool, ArGripper, ArRobotPacket *> myPacketHandlerCB;
};

#endif // ARGRIPPER_H


text:
/*
 * generated by Xtext 2.9.2
 */
package org.wso2.vihanga.example.student.idea;

import com.intellij.openapi.extensions.ExtensionFactory;
import org.wso2.vihanga.example.student.idea.lang.StudentLanguage;

public class StudentExtensionFactory implements ExtensionFactory {
	@Override
	public Object createInstance(String factoryArgument, String implementationClass) {
		Class<?> clazz;
		try {
			clazz = Class.forName(implementationClass);
		} catch (ClassNotFoundException e) {
			throw new IllegalArgumentException("Couldn't load "+implementationClass, e);
		}
		return StudentLanguage.INSTANCE.<Object> getInstance(clazz);
	}
}

redpajama_set_name: RedPajamaGithub


text:
Listen to git hooks, and trigger your functions simply with gitTA.
```
import gitTA as git

@git.listen('pre-push')
def run_tests(*args, **kwargs):
	import test
    test.all_your_things()
    if test.failed:
    	raise BaseException('abort the push' + test.feedback)
```
With the above code in main.py, the function **run_tests** will trigger each time **git push** is called, with the option to abort the push by raising an error.
In fact, you can listen to **all** local git hooks, including:

1. **pre-commit**
2. **commit-msg**
3. **post-commit**
4. **post-checkout**
5. .... and many more!

With these hooks, its possible to:

1. Encrypt a commit message after user input
2. Abort pushes if the branch is master
3. Correct file-permissions after branch changes
4. Undo branch changes to always stay on master
5. Change files after committing
6. Most anything good or evil... use your powers responsibly

To install gitTA, copy gitTA into a local git repo of your choice. Edit main.py to your liking, then run the install script (located in ./bash/install_githooks.sh), which will move gitTA into your .git directory, overwriting any current hooks with its own.
gitTA is local only -- the install script MUST be run each time another user clones your repository.  In short, it's a local tool that must be installed by the user; there is no way to have gitTA pre-installed in a repository, short of passing it around in a zipfile or setting it up as a git template. You can, however, include gitTA in your repository as a visible folder and ask that the user run the install script prior to using it.


text:
(function(angular) {
    'use strict';

    // Global service for global variables
    var GlobalFactory = [
        function() {
            var _this = this;
            _this._data = {
                user: window.user,
                authenticated: !! window.user
            };

            return _this._data;
        }
    ];

    angular.module('startupwichita.services').factory('Global', GlobalFactory);
})(window.angular);


text:
`cssnano` can compress only CSS files.

[https://github.com/cssnano/cssnano](https://github.com/cssnano/cssnano)

## Usage

```js
const minify = require('@node-minify/core');
const cssnano = require('@node-minify/cssnano');

minify({
  compressor: cssnano,
  input: 'foo.css',
  output: 'bar.css',
  callback: function(err, min) {}
});
```


text:
package com.akiban.sql.parser;

import com.akiban.sql.StandardException;

/**
 * An Aggregate Node is a node that reprsents a set function/aggregate.
 * It used for all system aggregates as well as user defined aggregates.
 *
 */

public class AggregateNode extends UnaryOperatorNode
{
    private String aggregateName;
    private String aggregateDefinitionClassName;
    private boolean distinct;

    /**
     * Intializer.  Used for user defined and internally defined aggregates.
     * Called when binding a StaticMethodNode that we realize is an aggregate.
     *
     * @param operand   the value expression for the aggregate
     * @param uadClass  the class name for user aggregate definition for the aggregate
     *                  or internal aggregate type.
     * @param distinct  boolean indicating whether this is distinct
     *                  or not.
     * @param aggregateName the name of the aggregate from the user's perspective,
     *                      e.g. MAX
     *
     * @exception StandardException on error
     */
    public void init(Object operand,
                     Object uadClass,
                     Object distinct,
                     Object aggregateName)
            throws StandardException {
        super.init(operand);
        this.aggregateDefinitionClassName = (String)uadClass;
        this.aggregateName = (String)aggregateName;
        this.distinct = ((Boolean)distinct).booleanValue();
    }

    /**
     * Fill this node with a deep copy of the given node.
     */
    public void copyFrom(QueryTreeNode node) throws StandardException {
        super.copyFrom(node);

        AggregateNode other = (AggregateNode)node;
        this.aggregateDefinitionClassName = other.aggregateDefinitionClassName;
        this.aggregateName = other.aggregateName;
        this.distinct = other.distinct;
    }

    /**
     * Get the name of the aggregate.
     *
     * @return the aggregate name
     */
    public String getAggregateName() {
        return aggregateName;
    }

    /**
     * Indicate whether this aggregate is distinct or not.
     *
     * @return true/false
     */
    public boolean isDistinct() {
        return distinct;
    }

    /**
     * Convert this object to a String.  See comments in QueryTreeNode.java
     * for how this should be done for tree printing.
     *
     * @return This object as a String
     */

    public String toString() {
        return "aggregateName: " + aggregateName + "\n" +
            super.toString();
    }

}


text:
package com.ait.lienzo.client.core.palette;

import com.ait.lienzo.client.core.shape.json.validators.ValidationContext;
import com.ait.lienzo.client.core.shape.json.validators.ValidationException;
import com.ait.lienzo.shared.core.types.PaletteType;
import com.google.gwt.json.client.JSONObject;

public final class PaletteItem extends AbstractPaletteBase<PaletteItem>
{
    public PaletteItem()
    {
        super(PaletteType.PALETTE_ITEM);
    }

    protected PaletteItem(final JSONObject node, final ValidationContext ctx) throws ValidationException
    {
        super(PaletteType.PALETTE_ITEM, node, ctx);
    }

    public static final class PaletteItemFactory extends AbstractPalettebaseFactory<PaletteItem>
    {
        public PaletteItemFactory()
        {
            super(PaletteType.PALETTE_ITEM);
        }

        @Override
        public PaletteItem create(final JSONObject node, final ValidationContext ctx) throws ValidationException
        {
            return new PaletteItem(node, ctx);
        }
    }
}


text:
require 'togostanza'
require_relative '../stanza'

EnvironmentOrganismDistributionOnTemperatureNanoStanza.root = File.expand_path('../..', __FILE__)

TogoStanza.sprockets.append_path File.expand_path('../../assets', __FILE__)


text:
<?php
namespace core;
class CoreLostPetPost extends CorePost{
	private $uniqueApperance;
	private $timeLost;
	private $dateLost;

	public function getUniqueApperance(){
		return $this->uniqueApperance;
	}

	public function getTimeLost(){
		return $this->timeLost;
	}

	public function getDateLost(){
		return $this->dateLost;
	}

	public function setUniqueApperance($uniqueApperanceIn){
		$this->uniqueApperance = $uniqueApperanceIn;
	}

	public function setTimeLOst($timeLostIn){
		$this->timeLost = $timeLostIn;
	}

	public function setDateLost($dateLostIn){
		$this->dateLost = $dateLostIn;
	}
}

?>


text:
require "test_helper"
require "helpers/rate_limit_helpers"

class RackAttackTest < ActionDispatch::IntegrationTest
  include RateLimitHelpers

  setup do
    Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new
    Rails.cache.clear

    @ip_address = "1.2.3.4"
    @user = create(:user, email: "nick@example.com", password: PasswordHelpers::SECURE_TEST_PASSWORD,
                   remember_token_expires_at: Gemcutter::REMEMBER_FOR.from_now)
  end

  context "requests is lower than limit" do
    should "allow sign in" do
      stay_under_limit_for("clearance/ip")

      post "/session",
        params: { session: { who: @user.email, password: @user.password } },
        headers: { REMOTE_ADDR: @ip_address }
      follow_redirect!

      assert_response :success
    end

    should "allow sign up" do
      stay_under_limit_for("clearance/ip")

      user = build(:user)
      post "/users",
        params: { user: { email: user.email, password: user.password } },
        headers: { REMOTE_ADDR: @ip_address }
      follow_redirect!

      assert_response :success
    end

    should "allow forgot password" do
      stay_under_limit_for("clearance/ip")
      stay_under_email_limit_for("password/email")

      post "/passwords",
        params: { password: { email: @user.email } },
        headers: { REMOTE_ADDR: @ip_address }

      assert_response :success
    end

    should "allow email confirmation resend" do
      stay_under_limit_for("clearance/ip/1")
      stay_under_email_limit_for("email_confirmations/email")

      post "/email_confirmations",
        params: { email_confirmation: { email: @user.email } },
        headers: { REMOTE_ADDR: @ip_address }
      follow_redirect!
      assert_response :success
    end

    context "owners requests" do
      setup do
        post session_path(session: { who: @user.handle, password: PasswordHelpers::SECURE_TEST_PASSWORD })
        @rubygem = create(:rubygem)
        create(:ownership, :unconfirmed, rubygem: @rubygem, user: @user)
      end

      teardown do
        delete sign_out_path
      end

      should "allow resending ownership confirmation" do
        stay_under_limit_for("owners/ip")
        stay_under_email_limit_for("owners/email")

        get "/gems/#{@rubygem.name}/owners/resend_confirmation",
            headers: { REMOTE_ADDR: @ip_address }
        follow_redirect!
        assert_response :success
      end
    end

    context "api requests" do
      setup do
        @rubygem = create(:rubygem, name: "test", number: "0.0.1")
        create(:ownership, user: @user, rubygem: @rubygem)
        create(:api_key, key: "12334", push_rubygem: true, user: @user)
      end

      should "allow gem push by ip" do
        stay_under_push_limit_for("api/push/ip")

        post "/api/v1/gems",
          params: gem_file("test-1.0.0.gem").read,
          headers: { REMOTE_ADDR: @ip_address, HTTP_AUTHORIZATION: "12334", CONTENT_TYPE: "application/octet-stream" }

        assert_response :success
      end
    end

    context "params" do
      should "return 400 for bad request" do
        post "/session"

        assert_response :bad_request
      end

      should "return 401 for unauthorized request" do
        post "/session", params: { session: { password: @user.password } }

        assert_response :unauthorized
      end
    end

    context "expontential backoff" do
      context "with successful gem push" do
        setup do
          Rack::Attack::EXP_BACKOFF_LEVELS.each do |level|
            under_backoff_limit = (Rack::Attack::EXP_BASE_REQUEST_LIMIT * level) - 1
            @push_exp_throttle_level_key = "#{Rack::Attack::PUSH_EXP_THROTTLE_KEY}/#{level}:#{@ip_address}"
            under_backoff_limit.times { Rack::Attack.cache.count(@push_exp_throttle_level_key, exp_base_limit_period**level) }
          end

          create(:api_key, key: "12334", push_rubygem: true, user: @user)
          post "/api/v1/gems",
            params: gem_file("test-0.0.0.gem").read,
            headers: { REMOTE_ADDR: @ip_address, HTTP_AUTHORIZATION: "12334", CONTENT_TYPE: "application/octet-stream" }
        end

        should "reset gem push rate limit rack attack key" do
          Rack::Attack::EXP_BACKOFF_LEVELS.each do |level|
            period = exp_base_limit_period**level

            time_counter = (Time.now.to_i / period).to_i
            prev_time_counter = time_counter - 1

            assert_nil Rack::Attack.cache.read("#{time_counter}:#{@push_exp_throttle_level_key}")
            assert_nil Rack::Attack.cache.read("#{prev_time_counter}:#{@push_exp_throttle_level_key}")
          end
        end

        should "not rate limit successive requests" do
          post "/api/v1/gems",
            params: gem_file("test-1.0.0.gem").read,
            headers: { REMOTE_ADDR: @ip_address, HTTP_AUTHORIZATION: "12334", CONTENT_TYPE: "application/octet-stream" }

          assert_response :ok
        end
      end

      context "ui requests" do
        setup do
          @user.enable_mfa!(ROTP::Base32.random_base32, :ui_only)
          stay_under_exponential_limit("clearance/ip")
        end

        should "allow for mfa sign in" do
          post "/session", params: { session: { who: @user.handle, password: @user.password } } # sets session[:mfa_user]

          post "/session/mfa_create",
            params: { otp: ROTP::TOTP.new(@user.mfa_seed).now },
            headers: { REMOTE_ADDR: @ip_address }

          assert_redirected_to "/dashboard"
        end

        should "allow mfa forgot password" do
          @user.forgot_password!
          post "/users/#{@user.id}/password/mfa_edit",
            params: { token: @user.confirmation_token, otp: ROTP::TOTP.new(@user.mfa_seed).now },
            headers: { REMOTE_ADDR: @ip_address }

          assert_response :ok
        end

        should "allow reverse_dependencies index" do
          rubygem = create(:rubygem, name: "test", number: "0.0.1")
          get "/gems/#{rubygem.name}/reverse_dependencies",
            headers: { REMOTE_ADDR: @ip_address }

          assert_response :ok
        end
      end

      context "api requests" do
        setup do
          @user.enable_mfa!(ROTP::Base32.random_base32, :ui_and_api)
          stay_under_exponential_limit("api/ip")

          create(:api_key, key: "12334", add_owner: true, yank_rubygem: true, remove_owner: true, user: @user)
          @rubygem = create(:rubygem, name: "test", number: "0.0.1")
          create(:ownership, user: @user, rubygem: @rubygem)
        end

        should "allow gem yank by ip" do
          delete "/api/v1/gems/yank",
            params: { gem_name: @rubygem.to_param, version: @rubygem.latest_version.number },
            headers: { REMOTE_ADDR: @ip_address, HTTP_AUTHORIZATION: "12334", HTTP_OTP: ROTP::TOTP.new(@user.mfa_seed).now }

          assert_response :success
        end

        should "allow owner add by ip" do
          second_user = create(:user)

          post "/api/v1/gems/#{@rubygem.name}/owners",
            params: { rubygem_id: @rubygem.to_param, email: second_user.email },
            headers: { REMOTE_ADDR: @ip_address, HTTP_AUTHORIZATION: "12334", HTTP_OTP: ROTP::TOTP.new(@user.mfa_seed).now }

          assert_response :success
        end

        should "allow owner remove by ip" do
          second_user = create(:user)
          create(:ownership, user: second_user, rubygem: @rubygem)

          delete "/api/v1/gems/#{@rubygem.name}/owners",
            params: { rubygem_id: @rubygem.to_param, email: second_user.email },
            headers: { REMOTE_ADDR: @ip_address, HTTP_AUTHORIZATION: "12334", HTTP_OTP: ROTP::TOTP.new(@user.mfa_seed).now }

          assert_response :success
        end
      end
    end

    context "ownership requests" do
      setup do
        sign_in_as(@user)
        @rubygem = create(:rubygem, name: "test", downloads: 2_000)
        create(:version, rubygem: @rubygem, created_at: 2.years.ago)
        stay_under_ownership_request_limit_for("ownership_requests/email")
        post "/gems/#{@rubygem.name}/ownership_requests", params: { rubygem_id: @rubygem.name, note: "small note" }
      end

      should "allow creating new requests" do
        assert_redirected_to "/gems/test/adoptions"
        assert_equal "small note", @rubygem.ownership_requests.last.note
      end
    end
  end

  context "requests is higher than limit" do
    should "throttle sign in" do
      exceed_limit_for("clearance/ip")

      post "/session",
        params: { session: { who: @user.email, password: @user.password } },
        headers: { REMOTE_ADDR: @ip_address }

      assert_response :too_many_requests
    end

    should "throttle sign up" do
      exceed_limit_for("clearance/ip")

      user = build(:user)
      post "/users",
        params: { user: { email: user.email, password: user.password } },
        headers: { REMOTE_ADDR: @ip_address }

      assert_response :too_many_requests
    end

    should "throttle forgot password" do
      exceed_limit_for("clearance/ip")

      post "/passwords",
        params: { password: { email: @user.email } },
        headers: { REMOTE_ADDR: @ip_address }

      assert_response :too_many_requests
    end

    should "throttle verify password" do
      exceed_limit_for("clearance/ip")

      post "/session/authenticate",
           params: { verify_password: { password: "password" } },
           headers: { REMOTE_ADDR: @ip_address }

      assert_response :too_many_requests
    end

    should "throttle profile update" do
      post session_path(session: { who: @user.handle, password: PasswordHelpers::SECURE_TEST_PASSWORD })

      exceed_limit_for("clearance/ip")
      patch "/profile",
        headers: { REMOTE_ADDR: @ip_address }

      assert_response :too_many_requests
    end

    should "throttle profile delete" do
      post session_path(session: { who: @user.handle, password: PasswordHelpers::SECURE_TEST_PASSWORD })

      exceed_limit_for("clearance/ip")
      delete "/profile",
        headers: { REMOTE_ADDR: @ip_address }

      assert_response :too_many_requests
    end

    should "throttle reverse_dependencies index" do
      exceed_limit_for("clearance/ip")
      rubygem = create(:rubygem, name: "test", number: "0.0.1")
      get "/gems/#{rubygem.name}/reverse_dependencies",
        headers: { REMOTE_ADDR: @ip_address }

      assert_response :too_many_requests
    end

    context "owners requests" do
      setup do
        post session_path(session: { who: @user.handle, password: PasswordHelpers::SECURE_TEST_PASSWORD })
        @rubygem = create(:rubygem)
        create(:ownership, :unconfirmed, rubygem: @rubygem, user: @user)
      end

      teardown do
        delete sign_out_path
      end

      should "throttle ownership confirmation resend" do
        exceed_limit_for("owners/ip")
        get "/gems/#{@rubygem.name}/owners/resend_confirmation", headers: { REMOTE_ADDR: @ip_address }

        assert_response :too_many_requests
      end

      should "throttle adding owner" do
        exceed_limit_for("owners/ip")
        new_user = create(:user)
        post "/gems/#{@rubygem.name}/owners", params: { owner: new_user.name },
             headers: { REMOTE_ADDR: @ip_address }

        assert_response :too_many_requests
      end

      should "throttle removing owner" do
        exceed_limit_for("owners/ip")
        delete "/gems/#{@rubygem.name}/owners/#{@user.id}", headers: { REMOTE_ADDR: @ip_address }

        assert_response :too_many_requests
      end
    end

    context "email confirmation" do
      should "throttle by ip" do
        exceed_limit_for("clearance/ip")

        post "/email_confirmations",
          params: { email_confirmation: { email: @user.email } },
          headers: { REMOTE_ADDR: @ip_address }
        assert_response :too_many_requests
      end

      should "throttle by email" do
        exceed_email_limit_for("email_confirmations/email")

        post "/email_confirmations", params: { email_confirmation: { email: @user.email } }
        assert_response :too_many_requests
      end
    end

    context "password update" do
      should "throttle by ip" do
        exceed_limit_for("clearance/ip")

        post "/passwords",
          params: { password: { email: @user.email } },
          headers: { REMOTE_ADDR: @ip_address }

        assert_response :too_many_requests
      end

      should "throttle by email" do
        exceed_email_limit_for("password/email")

        post "/passwords", params: { password: { email: @user.email } }
        assert_response :too_many_requests
      end
    end

    context "api requests" do
      setup do
        @rubygem = create(:rubygem, name: "test", number: "0.0.1")
        @rubygem.ownerships.create(user: @user)
      end

      should "throttle gem push by ip" do
        exceed_push_limit_for("api/push/ip")
        create(:api_key, key: "12334", push_rubygem: true, user: @user)

        post "/api/v1/gems",
          params: gem_file("test-1.0.0.gem").read,
          headers: { REMOTE_ADDR: @ip_address, HTTP_AUTHORIZATION: "12334", CONTENT_TYPE: "application/octet-stream" }

        assert_response :too_many_requests
      end
    end

    context "exponential backoff" do
      setup { @mfa_max_period = { 1 => 300, 2 => 90_000 } }

      Rack::Attack::EXP_BACKOFF_LEVELS.each do |level|
        should "throttle for mfa sign in at level #{level}" do
          freeze_time do
            exceed_exponential_limit_for("clearance/ip/#{level}", level)
            post "/session/mfa_create", headers: { REMOTE_ADDR: @ip_address }

            assert_throttle_at(level)
          end
        end

        should "throttle gem push at level #{level}" do
          freeze_time do
            exceed_exponential_limit_for("#{Rack::Attack::PUSH_EXP_THROTTLE_KEY}/#{level}", level)

            post "/api/v1/gems",
              params: gem_file("test-0.0.0.gem").read,
              headers: { REMOTE_ADDR: @ip_address, HTTP_AUTHORIZATION: @user.api_key, CONTENT_TYPE: "application/octet-stream" }

            assert_throttle_at(level)
          end
        end

        should "throttle mfa create at level #{level}" do
          freeze_time do
            exceed_exponential_limit_for("clearance/ip/#{level}", level)
            post "/multifactor_auth", headers: { REMOTE_ADDR: @ip_address }

            assert_throttle_at(level)
          end
        end

        should "throttle mfa update at level #{level}" do
          freeze_time do
            exceed_exponential_limit_for("clearance/ip/#{level}", level)
            put "/multifactor_auth", headers: { REMOTE_ADDR: @ip_address }

            assert_throttle_at(level)
          end
        end

        should "throttle api key show at level #{level}" do
          freeze_time do
            exceed_exponential_limit_for("api/ip/#{level}", level)
            get "/api/v1/api_key.json", headers: { REMOTE_ADDR: @ip_address }

            assert_throttle_at(level)
          end
        end

        should "throttle mfa forgot password at level #{level}" do
          freeze_time do
            exceed_exponential_limit_for("clearance/ip/#{level}", level)
            post "/users/#{@user.id}/password/mfa_edit", headers: { REMOTE_ADDR: @ip_address }

            assert_throttle_at(level)
          end
        end

        should "throttle gem yank by ip #{level}" do
          freeze_time do
            exceed_exponential_limit_for("api/ip/#{level}", level)
            delete "/api/v1/gems/yank", headers: { REMOTE_ADDR: @ip_address }

            assert_throttle_at(level)
          end
        end

        should "throttle owner add by ip #{level}" do
          freeze_time do
            exceed_exponential_limit_for("api/ip/#{level}", level)
            post "/api/v1/gems/somegem/owners", headers: { REMOTE_ADDR: @ip_address }

            assert_throttle_at(level)
          end
        end

        should "throttle owner remove by ip #{level}" do
          freeze_time do
            exceed_exponential_limit_for("api/ip/#{level}", level)
            delete "/api/v1/gems/somegem/owners", headers: { REMOTE_ADDR: @ip_address }

            assert_throttle_at(level)
          end
        end
      end
    end

    context "with per email limits" do
      context "for sign in" do
        setup { update_limit_for("password/email:#{@user.email}", exceeding_limit) }

        should "throttle for sign in ignoring case" do
          post "/passwords",
               params: { password: { email: "Nick@example.com" } }

          assert_response :too_many_requests
        end

        should "throttle for sign in ignoring spaces" do
          post "/passwords",
               params: { password: { email: "n ick@example.com" } }

          assert_response :too_many_requests
        end
      end

      context "for ownerships" do
        setup do
          @rubygem = create(:rubygem)
          create(:ownership, rubygem: @rubygem, user: @user)
        end

        teardown do
          delete sign_out_path
        end

        should "throttle resending ownership confirmation" do
          other_user = create(:user)
          set_owners_session(@rubygem, other_user)
          create(:ownership, :unconfirmed, rubygem: @rubygem, user: other_user)
          update_limit_for("owners/email:#{other_user.email}", exceeding_email_limit)
          get "/gems/#{@rubygem.name}/owners/resend_confirmation"

          assert_response :too_many_requests
        end

        should "throttle adding owner" do
          set_owners_session(@rubygem, @user)
          new_user = create(:user)
          exceed_email_limit_for("owners/email")
          post "/gems/#{@rubygem.name}/owners", params: { handle: new_user.display_id }

          assert_response :too_many_requests
        end

        should "throttle removing owner" do
          set_owners_session(@rubygem, @user)
          exceed_email_limit_for("owners/email")
          delete "/gems/#{@rubygem.name}/owners/#{@user.display_id}"

          assert_response :too_many_requests
        end
      end
    end

    context "ownership requests" do
      setup do
        sign_in_as(@user)
        @rubygem = create(:rubygem, name: "test", downloads: 2_000)
        create(:version, rubygem: @rubygem, created_at: 2.years.ago)
        exceed_ownership_request_limit_for("ownership_requests/email")
        post "/gems/#{@rubygem.name}/ownership_requests", params: { rubygem_id: @rubygem.name, note: "small note" }
      end

      should "throttle creating new requests" do
        assert_response :too_many_requests
        assert_empty @rubygem.ownership_requests
      end
    end
  end

  private

  def sign_in_as(user)
    post session_path(session: { who: user.handle, password: PasswordHelpers::SECURE_TEST_PASSWORD })
  end

  def set_owners_session(_rubygem, user)
    sign_in_as(user)
    post authenticate_session_path(verify_password: { password: PasswordHelpers::SECURE_TEST_PASSWORD })
  end
end


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

namespace DevAchievements.Infrastructure.Web.UI.FluentUI
{
	public interface IHtmlCreator : IFluentUI
    {
		#region Properties
		string Id { get; }
		IHtmlCreator Parent { get; set; }
		IList<IHtmlCreator> Children { get; set; }
		bool HtmlCreated { get; }
		 string CreateHtml ();
		#endregion
    }
}


text:
<?php

require_once('../config.php');
require_once('../JWT/JWT.php');

define('ACCEPTED_INVITATION_LOG_PATH', '../log/accepted_invitation.log');

global $CLIENT_SECRETS;
error_log('Accepted Invitation Notification has come !!' . "\n", 3, ERROR_LOG_PATH);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json; charset=utf-8');

    // load json from request body
    $jwt_body = file_get_contents('php://input');
    if (empty($jwt_body)) {
        echo json_encode([ 'result' => false ]);
        return;
    }

    // decode JSON Web Token
    try {
        $jwt_claims = JWT::decode($jwt_body, PUBLIC_KEY, array('RS256'));
    } catch (Exception $e) {
        error_log('jwt_decode failed because ' . $e . "\n", 3, ERROR_LOG_PATH);
        render_error_json();
    }

    //----------------------
    // Validate JSON Web Token

    $unixtime = time();
    // validate 'iss'(Issuer Claim)
    if (!($jwt_claims->iss === ISSUER_FOR_ASYNC_CONFIRMATION)) {
        error_log('Issuer Claim is invalid. ' .
            'iss=' . $jwt_claims->iss . ', ISSUER=' . ISSUER_FOR_ASYNC_CONFIRMATION . "\n", 3, ERROR_LOG_PATH);
        render_error_json();
    }
    // validate 'aud'(Audience Claim)
    if (!(isset($CLIENT_SECRETS[$jwt_claims->aud]))) {
        error_log('Audience Claim is invalid. ' .
            'aud=' . $jwt_claims->aud . "\n", 3, ERROR_LOG_PATH);
        render_error_json();
    }
    // validate 'iat'(Issued At)
    if (!($jwt_claims->iat <= $unixtime)) {
        error_log('Issed At is newer than now. ' .
            'iat=' . $jwt_claims->iat . ', now=' . $unixtime . "\n", 3, ERROR_LOG_PATH);
        render_error_json();
    }

    $result = [
        'inviterUserId' => $jwt_claims->event->inviterUserId,
        'inviteeUserId' => $jwt_claims->event->inviteeUserId
    ];

    error_log(json_encode($result) . "\n", 3, ACCEPTED_INVITATION_LOG_PATH);

    render_json([ 'success' => true ]);
}

function render_json($params) {
    echo json_encode($params);
    exit;
}

function render_error_json() {
    http_response_code(400);
    return render_json([ 'success' => false ]);
}


text:
/*global window, document*/

var EyeballControllersTestPage = function() {

    var Q = require('q');
    var _ = require('lodash');

    function setupPage(page) {
        page.timestamp = new Date();
        page.resources = [];
        page.libraryPath = "../";
        page.settings = {
            resourceTimeout : 5000
        };
        page.errors = {
            js : [],
            resources : []
        };
        page.issues = {
            alert : [],
            console : []
        };
        page.resourceCount = 0;

        page.finished = Q.defer();
        page.received = [];

        page.onResourceRequested = function (req) {
            page.resourceCount++;
            page.resources[req[0].id] = {
                url : req[0].url,
                request: req[0],
                startReply: null,
                endReply: null,
                eyeballSize : null,
                complete : Q.defer()
            };
            page.received.push(page.resources[req[0].id].promise);
        };

        page.onResourceReceived = function (res) {

            if(!page.resources[res.id]) {
                return;
            }
            var eyeballSize = _.find(res.headers,{name : 'x-eyeball-size'});
            var eyeballStatus = _.find(res.headers,{name : 'x-eyeball-status'});
            if(eyeballSize) {
                page.resources[res.id].eyeballSize = Number(eyeballSize.value);
            }
            if(eyeballStatus) {
                page.resources[res.id].eyeballStatus = Number(eyeballStatus.value);
            }
            if (res.stage === 'start') {
                page.resources[res.id].startReply = res;
            }
            if (res.stage === 'end') {
                page.resources[res.id].endReply = res;
                page.resources[res.id].complete.resolve();
            }

        };

        page.onLoadFinished = function() {
            setTimeout(page.finished.resolve,
            1000);
        };

        page.setFn('onCallback',function(msg) {
            if(msg === "DOMContentLoaded") {
                page.evaluate(function(){
                    window.DOMContentLoaded = new Date().getTime();
                });
            }
        });

        page.setFn('onInitialized',function(){
            page.evaluate(function() {
                document.addEventListener('DOMContentLoaded', function() {
                    window.callPhantom('DOMContentLoaded');
                }, false);
            });
        });

        page.onError = function(err) {
            page.errors.js.push(err);
        };

        page.onResourceError = function(err) {
            page.errors.resources.push(err);
        };

        page.onResourceTimeout = page.onResourceError;

        page.onAlert = function(msg) {
            page.issues.alert.push(msg);
        };

        page.onConsoleMessage = function(msg) {
            page.issues.console.push(msg);
        };

        return page;
    }

    return {
        setup : setupPage
    };

};

module.exports = EyeballControllersTestPage();


text:
import { ViewportRuler } from './viewport-ruler';
import { ConnectedPositionStrategy } from './connected-position-strategy';
import { ElementRef, Injectable } from '@angular/core';
import { GlobalPositionStrategy } from './global-position-strategy';
import { IOverlayConnectionPosition, IOriginConnectionPosition } from './connected-position';

/**
 * builder for overlay position strategy.
 */
@Injectable()
export class OverlayPositionBuilder
{
  constructor(private f_viewportRuler: ViewportRuler) { }

  /** Creates a global position strategy. */
  global()
  {
    return new GlobalPositionStrategy();
  }

  /**
   * creates a relative position strategy.
   */
  connectedTo(
    a_elementRef: ElementRef,
    a_originPos: IOriginConnectionPosition,
    a_overlayPos: IOverlayConnectionPosition)
  {
    return new ConnectedPositionStrategy(a_elementRef, a_originPos, a_overlayPos, this.f_viewportRuler);
  } // connectedTo()

} // class OverlayPositionBuilder


text:
var eventproxy = require('eventproxy');
var Message    = require('../../proxy').Message;
var _          = require('lodash');

var index = function (req, res, next) {
  var user_id = req.user._id;
  var ep = new eventproxy();
  ep.fail(next);

  ep.all('has_read_messages', 'hasnot_read_messages', function (has_read_messages, hasnot_read_messages) {
    res.send({
      data: {
        has_read_messages: has_read_messages,
        hasnot_read_messages: hasnot_read_messages
      }
    });
  });

  ep.all('has_read', 'unread', function (has_read, unread) {
    [has_read, unread].forEach(function (msgs, idx) {
      var epfill = new eventproxy();
      epfill.fail(next);
      epfill.after('message_ready', msgs.length, function (docs) {
        docs = docs.filter(function (doc) {
          return !doc.is_invalid;
        });
        docs = docs.map(function (doc) {
          doc.author = _.pick(doc.author, ['loginname', 'avatar_url']);
          doc.topic  = _.pick(doc.topic, ['id', 'author', 'title', 'last_reply_at']);
          doc.reply  = _.pick(doc.reply, ['id', 'content', 'ups', 'create_at']);
          doc        = _.pick(doc, ['id', 'type', 'has_read', 'author', 'topic', 'reply']);

          return doc;
        });
        ep.emit(idx === 0 ? 'has_read_messages' : 'hasnot_read_messages', docs);
      });
      msgs.forEach(function (doc) {
        Message.getMessageById(doc._id, epfill.group('message_ready'));
      });
    });
  });

  Message.getReadMessagesByUserId(user_id, ep.done('has_read'));

  Message.getUnreadMessageByUserId(user_id, ep.done('unread'));
};

exports.index = index;

var markAll = function (req, res, next) {
  var user_id = req.user._id;
  var ep = new eventproxy();
  ep.fail(next);
  Message.getUnreadMessageByUserId(user_id, ep.done('unread', function (docs) {
    docs.forEach(function (doc) {
      doc.has_read = true;
      doc.save();
    });
    return docs;
  }));

  ep.all('unread', function (unread) {
    unread = unread.map(function (doc) {
      doc = _.pick(doc, ['id']);
      return doc;
    });
    res.send({
      success: true,
      marked_msgs: unread,
    });
  });
};

exports.markAll = markAll;

var count = function (req, res, next) {
  var userId = req.user.id;

  var ep = new eventproxy();
  ep.fail(next);

  Message.getMessagesCount(userId, ep.done(function (count) {
    res.send({data: count});
  }));
};

exports.count = count;


text:
All notable changes to this project will be documented in this file. This
project adheres to [Semantic Versioning](http://semver.org/).

## [1.0.2] - 2016-01-15
### Fixed
- Fixed "Stack level too deep" error when inspecting complicated
  AhoCorasickMatcher instances from @mudge.

## [1.0.1] - 2015-06-26
### Changed
- Add compatibility with Ruby 1.8.7 from @mudge;
- Speed up matching by avoiding Object#tap and Object#nil? from @mudge.

## [1.0.0] - 2015-06-15
### Added
- First stable version of Aho-Corasick Matcher.

[1.0.2]: https://github.com/altmetric/aho_corasick_matcher/releases/tag/v1.0.2
[1.0.1]: https://github.com/altmetric/aho_corasick_matcher/releases/tag/v1.0.1
[1.0.0]: https://github.com/altmetric/aho_corasick_matcher/releases/tag/v1.0.0


text:
package com.sun.xacml.combine;

import com.sun.xacml.AbstractPolicy;
import com.sun.xacml.EvaluationCtx;
import com.sun.xacml.MatchResult;

import com.sun.xacml.ctx.Result;
import com.sun.xacml.ctx.Status;

import java.net.URI;
import java.net.URISyntaxException;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * This is the standard Permit Overrides policy combining algorithm. It
 * allows a single evaluation of Permit to take precedence over any number
 * of deny, not applicable or indeterminate results. Note that since
 * this implementation does an ordered evaluation, this class also
 * supports the Ordered Permit Overrides algorithm.
 *
 * @since 1.0
 * @author Seth Proctor
 */
public class PermitOverridesPolicyAlg extends PolicyCombiningAlgorithm
{

    /**
     * The standard URN used to identify this algorithm
     */
    public static final String algId =
        "urn:oasis:names:tc:xacml:1.0:policy-combining-algorithm:" +
        "permit-overrides";

    // a URI form of the identifier
    private static URI identifierURI;
    // exception if the URI was invalid, which should never be a problem
    private static RuntimeException earlyException;

    static {
        try {
            identifierURI = new URI(algId);
        } catch (URISyntaxException se) {
            earlyException = new IllegalArgumentException();
            earlyException.initCause(se);
        }
    }

    /**
     * Standard constructor.
     */
    public PermitOverridesPolicyAlg() {
        super(identifierURI);

        if (earlyException != null)
            throw earlyException;
    }

    /**
     * Protected constructor used by the ordered version of this algorithm.
     *
     * @param identifier the algorithm's identifier
     */
    protected PermitOverridesPolicyAlg(URI identifier) {
        super(identifier);
    }

    /**
     * Applies the combining rule to the set of policies based on the
     * evaluation context.
     *
     * @param context the context from the request
     * @param policies the policies to combine
     *
     * @return the result of running the combining algorithm
     */
    public Result combine(EvaluationCtx context, List policies) {
        boolean atLeastOneError = false;
        boolean atLeastOneDeny = false;
        Set denyObligations = new HashSet();
        Status firstIndeterminateStatus = null;
        Iterator it = policies.iterator();

        while (it.hasNext()) {
            AbstractPolicy policy = (AbstractPolicy)(it.next());

            // make sure that the policy matches the context
            MatchResult match = policy.match(context);

            if (match.getResult() == MatchResult.INDETERMINATE) {
                atLeastOneError = true;

                // keep track of the first error, regardless of cause
                if (firstIndeterminateStatus == null)
                    firstIndeterminateStatus = match.getStatus();
            } else if (match.getResult() == MatchResult.MATCH) {
                // now we evaluate the policy
                Result result = policy.evaluate(context);
                int effect = result.getDecision();

                // this is a little different from DenyOverrides...

                if (effect == Result.DECISION_PERMIT)
                    return result;

                if (effect == Result.DECISION_DENY) {
                    atLeastOneDeny = true;
                    denyObligations.addAll(result.getObligations());
                } else if (effect == Result.DECISION_INDETERMINATE) {
                    atLeastOneError = true;

                    // keep track of the first error, regardless of cause
                    if (firstIndeterminateStatus == null)
                        firstIndeterminateStatus = result.getStatus();
                }
            }
        }

        // if we got a DENY, return it
        if (atLeastOneDeny)
            return new Result(Result.DECISION_DENY,
                              context.getResourceId().encode(),
                              denyObligations);

        // if we got an INDETERMINATE, return it
        if (atLeastOneError)
            return new Result(Result.DECISION_INDETERMINATE,
                              firstIndeterminateStatus,
                              context.getResourceId().encode());

        // if we got here, then nothing applied to us
        return new Result(Result.DECISION_NOT_APPLICABLE,
                          context.getResourceId().encode());
    }

}


text:
<!DOCTYPE html>
<html>

<button id = "ButtonX">Rotate X</button>
<button id = "ButtonY">Rotate Y</button>
<button id = "ButtonZ">Rotate Z</button>
<button id = "ButtonT">Toggle Rotation</button>

<script id="vertex-shader" type="x-shader/x-vertex">

varying vec3 R;
attribute vec4 vPosition;
attribute vec3 vNormal;

uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;
uniform mat3 normalMatrix;

void main()
{
    gl_Position = projectionMatrix*modelViewMatrix*vPosition;

    //vec3 eyePos  = normalize((modelViewMatrix*vPosition).xyz);
    vec3 eyePos  = (modelViewMatrix*vPosition).xyz;

    vec3 N = normalize(normalMatrix*vNormal);
    //vec3 N = normalMatrix*vNormal;

    R = reflect(eyePos, N);

}
</script>

<script id="fragment-shader" type="x-shader/x-fragment">

precision mediump float;

varying vec3 R;
uniform samplerCube texMap;

void main()
{
    vec4 texColor = textureCube(texMap, R);

    gl_FragColor = texColor;
}
</script>

<script type="text/javascript" src="../Common/webgl-utils.js"></script>
<script type="text/javascript" src="../Common/initShaders.js"></script>
<script type="text/javascript" src="../Common/MV.js"></script>
<script type="text/javascript" src="reflectionMap2.js"></script>

<body>
<canvas id="gl-canvas" width="512" height="512">
Oops ... your browser doesn't support the HTML5 canvas element
</canvas>
</body>
</html>


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/take_photo"
    android:title="@string/take_photo"
    />
    <item android:id="@+id/select_photo"
        android:title="@string/select_photo"/>
</menu>


text:
namespace ParquetSharp.IO
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using ParquetSharp.Column;
    using ParquetSharp.Column.Impl;
    using ParquetSharp.Column.Page;
    using ParquetSharp.External;
    using ParquetSharp.Filter;
    using ParquetSharp.Filter2.Compat;
    using ParquetSharp.Filter2.Predicate;
    using ParquetSharp.Filter2.RecordLevel;
    using ParquetSharp.IO.Api;
    using ParquetSharp.Schema;

    /**
     * Message level of the IO structure
     *
     *
     * @author Julien Le Dem
     */
    public class MessageColumnIO : GroupColumnIO
    {
        private static readonly Log logger = Log.getLog(typeof(MessageColumnIO));

        private static readonly bool DEBUG = Log.DEBUG;

        private List<PrimitiveColumnIO> leaves;

        private readonly bool validating;
        private readonly string createdBy;

        internal MessageColumnIO(MessageType messageType, bool validating, string createdBy)
            : base(messageType, null, 0)
        {
            this.validating = validating;
            this.createdBy = createdBy;
        }

        internal override List<string[]> getColumnNames()
        {
            return base.getColumnNames();
        }

        public RecordReader<T> getRecordReader<T>(PageReadStore columns,
                                                   RecordMaterializer<T> recordMaterializer)
        {
            return getRecordReader(columns, recordMaterializer, FilterCompat.NOOP);
        }

        /**
         * @deprecated use {@link #getRecordReader(PageReadStore, RecordMaterializer, Filter)}
         */
        [Obsolete]
        public RecordReader<T> getRecordReader<T>(PageReadStore columns,
                                                   RecordMaterializer<T> recordMaterializer,
                                                   UnboundRecordFilter filter)
        {
            return getRecordReader(columns, recordMaterializer, FilterCompat.get(filter));
        }

        public RecordReader<T> getRecordReader<T>(PageReadStore columns,
                                                   RecordMaterializer<T> recordMaterializer,
                                                   FilterCompat.Filter filter)
        {
            Preconditions.checkNotNull(columns, "columns");
            Preconditions.checkNotNull(recordMaterializer, "recordMaterializer");
            Preconditions.checkNotNull(filter, "filter");

            if (leaves.Count == 0)
            {
                return new EmptyRecordReader<T>(recordMaterializer);
            }

            return filter.accept(new RecordReaderVisitor<T>(this, columns, recordMaterializer));
        }

        class RecordReaderVisitor<T> : FilterCompat.Visitor<RecordReader<T>>
        {
            private readonly MessageColumnIO parent;
            private readonly PageReadStore columns;
            private readonly RecordMaterializer<T> recordMaterializer;

            public RecordReaderVisitor(MessageColumnIO parent, PageReadStore columns, RecordMaterializer<T> recordMaterializer)
            {
                this.parent = parent;
                this.columns = columns;
                this.recordMaterializer = recordMaterializer;
            }

            public RecordReader<T> visit(FilterCompat.FilterPredicateCompat filterPredicateCompat)
            {
                FilterPredicate predicate = filterPredicateCompat.getFilterPredicate();
                IncrementallyUpdatedFilterPredicateBuilder builder = new IncrementallyUpdatedFilterPredicateBuilder();
                IncrementallyUpdatedFilterPredicate streamingPredicate = builder.build(predicate);
                RecordMaterializer<T> filteringRecordMaterializer = new FilteringRecordMaterializer<T>(
                    recordMaterializer,
                    parent.leaves,
                    builder.getValueInspectorsByColumn(),
                    streamingPredicate);

                return new RecordReaderImplementation<T>(
                    parent,
                    filteringRecordMaterializer,
                    parent.validating,
                    new ColumnReadStoreImpl(columns, filteringRecordMaterializer.getRootConverter(), parent.getMessageType(), parent.createdBy));
            }

            public RecordReader<T> visit(FilterCompat.UnboundRecordFilterCompat unboundRecordFilterCompat)
            {
                return new FilteredRecordReader<T>(
                    parent,
                    recordMaterializer,
                    parent.validating,
                    new ColumnReadStoreImpl(columns, recordMaterializer.getRootConverter(), parent.getMessageType(), parent.createdBy),
                    unboundRecordFilterCompat.getUnboundRecordFilter(),
                    columns.getRowCount()
                );
            }

            public RecordReader<T> visit(FilterCompat.NoOpFilter noOpFilter)
            {
                return new RecordReaderImplementation<T>(
                    parent,
                    recordMaterializer,
                    parent.validating,
                    new ColumnReadStoreImpl(columns, recordMaterializer.getRootConverter(), parent.getMessageType(), parent.createdBy));
            }
        }

        /**
         * To improve null writing performance, we cache null values on group nodes. We flush nulls when a
         * non-null value hits the group node.
         *
         * Intuitively, when a group node hits a null value, all the leaves underneath it should be null.
         * A direct way of doing it is to write nulls for all the leaves underneath it when a group node
         * is null. This approach is not optimal, consider following case:
         *
         *    - When the schema is really wide where for each group node, there are thousands of leaf
         *    nodes underneath it.
         *    - When the data being written is really sparse, group nodes could hit nulls frequently.
         *
         * With the direct approach, if a group node hit null values a thousand times, and there are a
         * thousand nodes underneath it.
         * For each null value, it iterates over a thousand leaf writers to write null values and it
         *  will do it for a thousand null values.
         *
         * In the above case, each leaf writer maintains it's own buffer of values, calling thousands of
         * them in turn is very bad for memory locality. Instead each group node can remember the null values
         * encountered and flush only when a non-null value hits the group node. In this way, when we flush
         * null values, we only iterate through all the leaves 1 time and multiple cached null values are
         * flushed to each leaf in a tight loop. This implementation has following characteristics.
         *
         *    1. When a group node hits a null value, it adds the repetition level of the null value to
         *    the groupNullCache. The definition level of the cached nulls should always be the same as
         *    the definition level of the group node so there is no need to store it.
         *
         *    2. When a group node hits a non null value and it has null value cached, it should flush null
         *    values and start from his children group nodes first. This make sure the order of null values
         *     being flushed is correct.
         *
         */
        private class MessageColumnIORecordConsumer : RecordConsumer
        {
            private readonly MessageColumnIO parent;
            private ColumnIO currentColumnIO;
            private int currentLevel = 0;

            private class FieldsMarker
            {
                private BitArray visitedIndexes = null;

                public override string ToString()
                {
                    return "VistedIndex{" +
                        "vistedIndexes=" + visitedIndexes +
                        '}';
                }

                public void reset(int fieldsCount)
                {
                    // TODO:
                    this.visitedIndexes = new BitArray(fieldsCount);
                }

                public void markWritten(int i)
                {
                    visitedIndexes.Set(i, true);
                }

                public bool isWritten(int i)
                {
                    return visitedIndexes.Get(i);
                }
            }

            //track at each level of depth, which fields are written, so nulls can be inserted for the unwritten fields
            private readonly FieldsMarker[] fieldsWritten;
            private readonly int[] r;
            private readonly ColumnWriter[] columnWriter;

            /**
             * Maintain a map of groups and all the leaf nodes underneath it. It's used to optimize writing null for a group node.
             * Instead of using recursion calls, all the leaves can be called directly without traversing the sub tree of the group node
             */
            private Dictionary<GroupColumnIO, List<ColumnWriter>> groupToLeafWriter = new Dictionary<GroupColumnIO, List<ColumnWriter>>();

            /*
             * Cache nulls for each group node. It only stores the repetition level, since the definition level
             * should always be the definition level of the group node.
             */
            private Dictionary<GroupColumnIO, List<int>> groupNullCache = new Dictionary<GroupColumnIO, List<int>>();
            private readonly ColumnWriteStore columns;
            private bool emptyField = true;

            private void buildGroupToLeafWriterMap(PrimitiveColumnIO primitive, ColumnWriter writer)
            {
                GroupColumnIO parent = primitive.getParent();
                do
                {
                    getLeafWriters(parent).Add(writer);
                    parent = parent.getParent();
                } while (parent != null);
            }

            private List<ColumnWriter> getLeafWriters(GroupColumnIO group)
            {
                List<ColumnWriter> writers;
                if (!groupToLeafWriter.TryGetValue(group, out writers))
                {
                    writers = new List<ColumnWriter>();
                    groupToLeafWriter.Add(group, writers);
                }
                return writers;
            }

            public MessageColumnIORecordConsumer(MessageColumnIO parent, ColumnWriteStore columns)
            {
                this.parent = parent;
                this.columns = columns;
                int maxDepth = 0;
                this.columnWriter = new ColumnWriter[parent.getLeaves().Count];

                foreach (PrimitiveColumnIO primitiveColumnIO in parent.getLeaves())
                {
                    ColumnWriter w = columns.getColumnWriter(primitiveColumnIO.getColumnDescriptor());
                    maxDepth = Math.Max(maxDepth, primitiveColumnIO.getFieldPath().Length);
                    columnWriter[primitiveColumnIO.getId()] = w;
                    buildGroupToLeafWriterMap(primitiveColumnIO, w);
                }

                fieldsWritten = new FieldsMarker[maxDepth];
                for (int i = 0; i < maxDepth; i++)
                {
                    fieldsWritten[i] = new FieldsMarker();
                }
                r = new int[maxDepth];
            }

            public void printState()
            {
                log(currentLevel + ", " + fieldsWritten[currentLevel] + ": " + Arrays.toString(currentColumnIO.getFieldPath()) + " r:" + r[currentLevel]);
                if (r[currentLevel] > currentColumnIO.getRepetitionLevel())
                {
                    // sanity check
                    throw new InvalidRecordException(r[currentLevel] + "(r) > " + currentColumnIO.getRepetitionLevel() + " ( schema r)");
                }
            }

            private void log(object m)
            {
                string indent = "";
                for (int i = 0; i < currentLevel; ++i)
                {
                    indent += "  ";
                }
                logger.debug(indent + m);
            }

            public override void startMessage()
            {
                if (Log.DEBUG) log("< MESSAGE START >");
                currentColumnIO = parent;
                r[0] = 0;
                int numberOfFieldsToVisit = ((GroupColumnIO)currentColumnIO).getChildrenCount();
                fieldsWritten[0].reset(numberOfFieldsToVisit);
                if (Log.DEBUG) printState();
            }

            public override void endMessage()
            {
                writeNullForMissingFieldsAtCurrentLevel();
                columns.endRecord();
                if (Log.DEBUG) log("< MESSAGE END >");
                if (Log.DEBUG) printState();
            }

            public override void startField(string field, int index)
            {
                try
                {
                    if (Log.DEBUG) log("startField(" + field + ", " + index + ")");
                    currentColumnIO = ((GroupColumnIO)currentColumnIO).getChild(index);
                    emptyField = true;
                    if (Log.DEBUG) printState();
                }
                catch (RuntimeException e)
                {
                    throw new ParquetEncodingException("error starting field " + field + " at " + index, e);
                }
            }

            public override void endField(string field, int index)
            {
                if (Log.DEBUG) log("endField(" + field + ", " + index + ")");
                currentColumnIO = currentColumnIO.getParent();
                if (emptyField)
                {
                    throw new ParquetEncodingException("empty fields are illegal, the field should be ommited completely instead");
                }
                fieldsWritten[currentLevel].markWritten(index);
                r[currentLevel] = currentLevel == 0 ? 0 : r[currentLevel - 1];
                if (Log.DEBUG) printState();
            }

            private void writeNullForMissingFieldsAtCurrentLevel()
            {
                int currentFieldsCount = ((GroupColumnIO)currentColumnIO).getChildrenCount();
                for (int i = 0; i < currentFieldsCount; i++)
                {
                    if (!fieldsWritten[currentLevel].isWritten(i))
                    {
                        try
                        {
                            ColumnIO undefinedField = ((GroupColumnIO)currentColumnIO).getChild(i);
                            int d = currentColumnIO.getDefinitionLevel();
                            if (Log.DEBUG)
                                log(Arrays.toString(undefinedField.getFieldPath()) + ".writeNull(" + r[currentLevel] + "," + d + ")");
                            writeNull(undefinedField, r[currentLevel], d);
                        }
                        catch (RuntimeException e)
                        {
                            throw new ParquetEncodingException("error while writing nulls for fields of indexes " + i + " . current index: " + fieldsWritten[currentLevel], e);
                        }
                    }
                }
            }

            private void writeNull(ColumnIO undefinedField, int r, int d)
            {
                if (undefinedField.getType().isPrimitive())
                {
                    columnWriter[((PrimitiveColumnIO)undefinedField).getId()].writeNull(r, d);
                }
                else
                {
                    GroupColumnIO groupColumnIO = (GroupColumnIO)undefinedField;
                    // only cache the repetition level, the definition level should always be the definition level of the parent node
                    cacheNullForGroup(groupColumnIO, r);
                }
            }

            private void cacheNullForGroup(GroupColumnIO group, int r)
            {
                List<int> nulls;
                if (!groupNullCache.TryGetValue(group, out nulls))
                {
                    nulls = new List<int>();
                    groupNullCache.Add(group, nulls);
                }
                nulls.Add(r);
            }

            private void writeNullToLeaves(GroupColumnIO group)
            {
                List<int> nullCache;
                if (!groupNullCache.TryGetValue(group, out nullCache) || nullCache.Count == 0)
                {
                    return;
                }

                int parentDefinitionLevel = group.getParent().getDefinitionLevel();
                foreach (ColumnWriter leafWriter in groupToLeafWriter[group])
                {
                    foreach (int repetitionLevel in nullCache)
                    {
                        leafWriter.writeNull(repetitionLevel, parentDefinitionLevel);
                    }
                }
                nullCache.Clear();
            }

            private void setRepetitionLevel()
            {
                r[currentLevel] = currentColumnIO.getRepetitionLevel();
                if (Log.DEBUG) log("r: " + r[currentLevel]);
            }

            public override void startGroup()
            {
                if (Log.DEBUG) log("startGroup()");
                GroupColumnIO group = (GroupColumnIO)currentColumnIO;

                // current group is not null, need to flush all the nulls that were cached before
                if (hasNullCache(group))
                {
                    flushCachedNulls(group);
                }

                ++currentLevel;
                r[currentLevel] = r[currentLevel - 1];

                int fieldsCount = ((GroupColumnIO)currentColumnIO).getChildrenCount();
                fieldsWritten[currentLevel].reset(fieldsCount);
                if (Log.DEBUG) printState();
            }

            private bool hasNullCache(GroupColumnIO group)
            {
                List<int> nulls;
                return groupNullCache.TryGetValue(group, out nulls) && nulls.Count > 0;
            }

            private void flushCachedNulls(GroupColumnIO group)
            {
                //flush children first
                for (int i = 0; i < group.getChildrenCount(); i++)
                {
                    ColumnIO child = group.getChild(i);
                    if (child is GroupColumnIO)
                    {
                        flushCachedNulls((GroupColumnIO)child);
                    }
                }
                //then flush itself
                writeNullToLeaves(group);
            }

            public override void endGroup()
            {
                if (Log.DEBUG) log("endGroup()");
                emptyField = false;
                writeNullForMissingFieldsAtCurrentLevel();
                --currentLevel;

                setRepetitionLevel();
                if (Log.DEBUG) printState();
            }

            private ColumnWriter getColumnWriter()
            {
                return columnWriter[((PrimitiveColumnIO)currentColumnIO).getId()];
            }

            public override void addInteger(int value)
            {
                if (Log.DEBUG) log("addInt(" + value + ")");
                emptyField = false;
                getColumnWriter().write(value, r[currentLevel], currentColumnIO.getDefinitionLevel());

                setRepetitionLevel();
                if (Log.DEBUG) printState();
            }

            public override void addLong(long value)
            {
                if (Log.DEBUG) log("addLong(" + value + ")");
                emptyField = false;
                getColumnWriter().write(value, r[currentLevel], currentColumnIO.getDefinitionLevel());

                setRepetitionLevel();
                if (Log.DEBUG) printState();
            }

            public override void addBoolean(bool value)
            {
                if (Log.DEBUG) log("addBoolean(" + value + ")");
                emptyField = false;
                getColumnWriter().write(value, r[currentLevel], currentColumnIO.getDefinitionLevel());

                setRepetitionLevel();
                if (Log.DEBUG) printState();
            }

            public override void addBinary(Binary value)
            {
                if (Log.DEBUG) log("addBinary(" + value.length() + " bytes)");
                emptyField = false;
                getColumnWriter().write(value, r[currentLevel], currentColumnIO.getDefinitionLevel());

                setRepetitionLevel();
                if (Log.DEBUG) printState();
            }

            public override void addFloat(float value)
            {
                if (Log.DEBUG) log("addFloat(" + value + ")");
                emptyField = false;
                getColumnWriter().write(value, r[currentLevel], currentColumnIO.getDefinitionLevel());

                setRepetitionLevel();
                if (Log.DEBUG) printState();
            }

            public override void addDouble(double value)
            {
                if (Log.DEBUG) log("addDouble(" + value + ")");
                emptyField = false;
                getColumnWriter().write(value, r[currentLevel], currentColumnIO.getDefinitionLevel());

                setRepetitionLevel();
                if (Log.DEBUG) printState();
            }

            //should flush null for all groups
            public override void flush()
            {
                flushCachedNulls(parent);
            }
        }

        public RecordConsumer getRecordWriter(ColumnWriteStore columns)
        {
            RecordConsumer recordWriter = new MessageColumnIORecordConsumer(this, columns);
            if (Log.DEBUG) recordWriter = new RecordConsumerLoggingWrapper(recordWriter);
            return validating ? new ValidatingRecordConsumer(recordWriter, getMessageType()) : recordWriter;
        }

        internal void setLevels()
        {
            setLevels(0, 0, new string[0], new int[0], new List<ColumnIO> { this }, new List<ColumnIO> { this });
        }

        internal void setLeaves(List<PrimitiveColumnIO> leaves)
        {
            this.leaves = leaves;
        }

        public List<PrimitiveColumnIO> getLeaves()
        {
            return this.leaves;
        }

        internal MessageType getMessageType()
        {
            return (MessageType)base.getType();
        }
    }
}


text:
<?php

/**
 * @file
 * Definition of Drupal\node\Plugin\views\row\Rss.
 */

namespace Drupal\node\Plugin\views\row;

use Drupal\Component\Annotation\Plugin;
use Drupal\Core\Annotation\Translation;
use Drupal\views\Plugin\views\row\RowPluginBase;

/**
 * Plugin which performs a node_view on the resulting object
 * and formats it as an RSS item.
 *
 * @Plugin(
 *   id = "node_rss",
 *   title = @Translation("Content"),
 *   help = @Translation("Display the content with standard node view."),
 *   theme = "views_view_row_rss",
 *   base = {"node"},
 *   display_types = {"feed"},
 *   module = "node"
 * )
 */
class Rss extends RowPluginBase {

  // Basic properties that let the row style follow relationships.
  var $base_table = 'node';

  var $base_field = 'nid';

  // Stores the nodes loaded with preRender.
  var $nodes = array();

  protected function defineOptions() {
    $options = parent::defineOptions();

    $options['item_length'] = array('default' => 'default');
    $options['links'] = array('default' => FALSE, 'bool' => TRUE);

    return $options;
  }

  public function buildOptionsForm(&$form, &$form_state) {
    parent::buildOptionsForm($form, $form_state);

    $form['item_length'] = array(
      '#type' => 'select',
      '#title' => t('Display type'),
      '#options' => $this->buildOptionsForm_summary_options(),
      '#default_value' => $this->options['item_length'],
    );
    $form['links'] = array(
      '#type' => 'checkbox',
      '#title' => t('Display links'),
      '#default_value' => $this->options['links'],
    );
  }

  /**
   * Return the main options, which are shown in the summary title.
   */
  public function buildOptionsForm_summary_options() {
    $view_modes = entity_get_view_modes('node');
    $options = array();
    foreach ($view_modes as $mode => $settings) {
      $options[$mode] = $settings['label'];
    }
    $options['title'] = t('Title only');
    $options['default'] = t('Use site default RSS settings');
    return $options;
  }

  public function summaryTitle() {
    $options = $this->buildOptionsForm_summary_options();
    return check_plain($options[$this->options['item_length']]);
  }

  public function preRender($values) {
    $nids = array();
    foreach ($values as $row) {
      $nids[] = $row->{$this->field_alias};
    }
    if (!empty($nids)) {
      $this->nodes = node_load_multiple($nids);
    }
  }

  public function render($row) {
    // For the most part, this code is taken from node_feed() in node.module
    global $base_url;

    $nid = $row->{$this->field_alias};
    if (!is_numeric($nid)) {
      return;
    }

    $display_mode = $this->options['item_length'];
    if ($display_mode == 'default') {
      $display_mode = config('system.rss')->get('items.view_mode');
    }

    // Load the specified node:
    $node = $this->nodes[$nid];
    if (empty($node)) {
      return;
    }

    $item_text = '';

    $uri = $node->uri();
    $node->link = url($uri['path'], $uri['options'] + array('absolute' => TRUE));
    $node->rss_namespaces = array();
    $node->rss_elements = array(
      array(
        'key' => 'pubDate',
        'value' => gmdate('r', $node->created),
      ),
      array(
        'key' => 'dc:creator',
        'value' => $node->name,
      ),
      array(
        'key' => 'guid',
        'value' => $node->id() . ' at ' . $base_url,
        'attributes' => array('isPermaLink' => 'false'),
      ),
    );

    // The node gets built and modules add to or modify $node->rss_elements
    // and $node->rss_namespaces.

    $build_mode = $display_mode;

    $build = node_view($node, $build_mode);
    unset($build['#theme']);

    if (!empty($node->rss_namespaces)) {
      $this->view->style_plugin->namespaces = array_merge($this->view->style_plugin->namespaces, $node->rss_namespaces);
    }
    elseif (function_exists('rdf_get_namespaces')) {
      // Merge RDF namespaces in the XML namespaces in case they are used
      // further in the RSS content.
      $xml_rdf_namespaces = array();
      foreach (rdf_get_namespaces() as $prefix => $uri) {
        $xml_rdf_namespaces['xmlns:' . $prefix] = $uri;
      }
      $this->view->style_plugin->namespaces += $xml_rdf_namespaces;
    }

    // Hide the links if desired.
    if (!$this->options['links']) {
      hide($build['links']);
    }

    if ($display_mode != 'title') {
      // We render node contents and force links to be last.
      $build['links']['#weight'] = 1000;
      $item_text .= drupal_render($build);
    }

    $item = new \stdClass();
    $item->description = $item_text;
    $item->title = $node->label();
    $item->link = $node->link;
    $item->elements = $node->rss_elements;
    $item->nid = $node->id();
    $theme_function = array(
      '#theme' => $this->themeFunctions(),
      '#view' => $this->view,
      '#options' => $this->options,
      '#row' => $item,
    );
    return drupal_render($theme_function);
  }

}


text:
var Backbone = require('backbone');
var CreateComponent = require('./CreateComponent');

module.exports = _.extend({}, CreateComponent, {

  /**
   * This event is triggered at the beginning of a draw operation
   * @param   {Object}   component  Object component before creation
   * @private
   * */
  beforeDraw(component) {
    component.type = 'text';
    if(!component.style)
      component.style  = {};
    component.style.padding = '10px';
  },

  /**
   * This event is triggered at the end of a draw operation
   * @param   {Object}  model  Component model created
   * @private
   * */
  afterDraw(model) {
    if(!model || !model.set)
      return;
    model.trigger('focus');
    if(this.sender)
      this.sender.set('active', false);
  },

});


text:
<?xml version="1.0" encoding="UTF-8"?>
<container>
  <alias id=".alias_2" service=".service_2" public="false"/>
  <definition id=".definition_2" class="Full\Qualified\Class2" public="false" synthetic="true" lazy="false" shared="true" abstract="false" autowired="false" autoconfigured="false" deprecated="false" file="/path/to/file">
    <factory service="factory.service" method="get"/>
    <calls>
      <call method="setMailer"/>
    </calls>
    <tags>
      <tag name="tag1">
        <parameter name="attr1">val1</parameter>
        <parameter name="attr2">val2</parameter>
      </tag>
      <tag name="tag1">
        <parameter name="attr3">val3</parameter>
      </tag>
      <tag name="tag2"/>
    </tags>
  </definition>
</container>


text:
package android.content;

import android.annotation.TargetApi;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.ShadowResources;
import android.os.Build;
import android.os.Environment;
import android.util.DisplayMetrics;

import net.kb.test.library.CGLibProxy;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.File;
import java.io.IOException;

/**
 * Created by kkmike999 on 2017/06/15.
 */
public class ContextTest {

    Context       context;
    ShadowContext shadowContext;

    @Before
    public void setUp() throws Exception {
        Resources resources = new CGLibProxy().proxy(Resources.class, new ShadowResources(), new Class[]{AssetManager.class, DisplayMetrics.class, Configuration.class}, new Object[]{null, null, null});
        context = new CGLibProxy().proxy(Context.class, shadowContext = new ShadowContext(resources));
    }

    @After
    public void tearDown() throws Exception {
        shadowContext.deleteAllTempDir();
    }

    @TargetApi(Build.VERSION_CODES.N)
    @Test
    public void getFileDir() throws IOException {

        displayPath(context.getDataDir());
        displayPath(context.getFilesDir());
        displayPath(context.getFileStreamPath("stream"));
        displayPath(context.getCacheDir());

        System.out.println("\n----\n");

        displayPath(context.getCodeCacheDir());
        displayPath(context.getNoBackupFilesDir());

        System.out.println(context.getPackageCodePath());
        System.out.println(context.getPackageResourcePath());
//        displayPath(context.getObbDir());
//        displayPath(context.getObbDirs());

        System.out.println("\n----\n");

        displayPath(context.getExternalCacheDir());
        displayPath(context.getExternalFilesDir(Environment.DIRECTORY_MUSIC));
        displayPath(context.getExternalFilesDir(Environment.DIRECTORY_MOVIES));
//        displayPath(context.getExternalMediaDirs());
//        displayPath(context.getExternalCacheDirs());

        System.out.println("\n-- fileList --\n");

        // 创建临时文件
        File tmpFile = new File(context.getFilesDir(), "tmp.txt");
        tmpFile.getParentFile().mkdirs();
        tmpFile.createNewFile();

        for (String f : context.fileList()) {
            System.out.println(f);
        }

        System.out.println("\n-- databaseList --\n");

        // 创建数据库
        context.openOrCreateDatabase("test.db", 0, null);

        for (String db : context.databaseList()) {
            System.out.println(db);
        }

        System.out.println("\n-- getDatabasePath --\n");

        System.out.println(context.getDatabasePath("mydb"));
    }

    private void displayPath(File... files) {
        for (File file : files) {
            System.out.println(file.getAbsolutePath());
        }
    }
}


text:
import pytest

from democracy.factories.hearing import HearingFactory
from democracy.models import Hearing

@pytest.mark.django_db
def test_manager_exclude_deleted():
    for _ in range(10):
        HearingFactory()
    for _ in range(3):
        Hearing.objects.first().soft_delete()
    assert Hearing.objects.count() == 7
    assert Hearing.objects.deleted().count() == 3

@pytest.mark.django_db
def test_cant_delete():
    hearing = HearingFactory()
    with pytest.raises(NotImplementedError):
        hearing.delete()
    assert hearing.pk

@pytest.mark.django_db
def test_unpublished():
    # the story of an unpublished hearing
    hearing = Hearing.objects.create(published=False)
    assert not Hearing.objects.public(pk=hearing.pk).exists()  # not in the regular qs
    assert Hearing.objects.with_unpublished(pk=hearing.pk).exists()  # but in the unpub qs
    assert Hearing.objects.everything(pk=hearing.pk).exists()  # and the everything qs
    assert not Hearing.objects.deleted(pk=hearing.pk).exists()  # not deleted yet
    hearing.soft_delete()
    assert not Hearing.objects.with_unpublished(pk=hearing.pk).exists()  # deleted, not in unpub anymore
    assert Hearing.objects.everything(pk=hearing.pk).exists()  # but still in everything
    assert Hearing.objects.deleted(pk=hearing.pk).exists()  # and now also in deleted


text:
const request = require('request-promise');
var secretConfig;

module.exports = function(app) {

  var config = app.web.services.get('google');

  if(!config){
    return;
  }

  if (!secretConfig) {
    secretConfig = app.secrets.get('google');
  }

  //---------------------------------------------------
  // Recaptcha

  if (!config.recaptcha) {
    console.warn('Could not find Recaptcha configuration');
    return;
  }

  app.recaptcha = {
    verify: function(response) {

      var verificationUrl = 'https://www.google.com/recaptcha/api/siteverify?secret=' + secretConfig.recaptcha.secretKey + '&response=' + response;

      return request({
        uri: verificationUrl,
        json: true
      });

    }
  };

};


text:
<?php
Yii::setAlias('common', dirname(__DIR__));
Yii::setAlias('frontend', dirname(dirname(__DIR__)) . '/frontend');
Yii::setAlias('backend', dirname(dirname(__DIR__)) . '/backend');
Yii::setAlias('console', dirname(dirname(__DIR__)) . '/console');
Yii::setAlias('vendor', dirname(dirname(__DIR__)) . '/vendor');
Yii::setAlias('api', dirname(dirname(__DIR__)) . '/api');
Yii::setAlias('media', dirname(dirname(__DIR__)) . '/media');


text:
package liulx.domain;

import org.mongodb.morphia.annotations.Embedded;

/**
 * Created by Liu Lixiang on 2017/5/2.
 */
@Embedded
public class Post {
    private Long id;
    private String title;
    private String body;

    public Long getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }
}


text:
class Swiftplate < Formula
  desc "Cross-platform Swift framework templates from the command-line"
  homepage "https://github.com/JohnSundell/SwiftPlate"
  url "https://github.com/JohnSundell/SwiftPlate/archive/1.3.0.tar.gz"
  sha256 "edd0329dd04e579e17b71d3b9624781fda2fdb046eb9a5ea1a7a391144b900a8"
  head "https://github.com/JohnSundell/SwiftPlate.git"

  bottle do
    cellar :any_skip_relocation
    sha256 "08c2ec29bd298efa3c3634c218667307dcd0bac874bc23a80e04262749d4e30b" => :sierra
    sha256 "60af116ef0834a8e610288caf3ed28d53bf9144cbb3637e6836d55a617347c9a" => :el_capitan
  end

  depends_on :xcode => "8.2"

  def install
    xcodebuild "-project",
        "SwiftPlate.xcodeproj",
        "-scheme", "SwiftPlate",
        "-configuration", "Release",
        "CONFIGURATION_BUILD_DIR=build",
        "SYMROOT=."
    bin.install "build/swiftplate"
  end

  test do
    system "#{bin}/swiftplate", "--destination", ".",
      "--project", "test", "--name", "testUser",
      "--email", "test@example.com", "--url", "https://github.com/johnsundell/swiftplate",
      "--organization", "exampleOrg", "--force"
    assert File.exist?("test.xcodeproj"), "Failed to generate test.xcodeproj"
  end
end


text:
from django import template

from pinax.blog.models import Post

register = template.Library()

class LatestSectionPostsNode(template.Node):

    def __init__(self, section, context_var):
        self.section = template.Variable(section)
        self.context_var = context_var

    def render(self, context):
        try:
            section = self.section.resolve(context)
            posts = Post.objects.section(section,
                                         queryset=Post.objects.current())
            context[self.context_var] = posts
        except Exception:
            pass
        return u""

@register.tag
def latest_section_posts(parser, token):
    """
        {% latest_section_posts "articles" as latest_article_posts %}
    """
    bits = token.split_contents()
    return LatestSectionPostsNode(bits[1], bits[3])


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Hyak.Common;
using Microsoft.Azure.Insights.Models;

namespace Microsoft.Azure.Insights.Models
{
    /// <summary>
    /// The collection of metric value sets.
    /// </summary>
    public partial class MetricCollection
    {
        private IList<Metric> _value;

        /// <summary>
        /// Optional. The value of the collection.
        /// </summary>
        public IList<Metric> Value
        {
            get { return this._value; }
            set { this._value = value; }
        }

        /// <summary>
        /// Initializes a new instance of the MetricCollection class.
        /// </summary>
        public MetricCollection()
        {
            this.Value = new LazyList<Metric>();
        }
    }
}


text:
import React from 'react';
import { View, Text } from 'native-base';
import { textStyles, colors } from '../../application/styles';
import { TouchableOpacity } from 'react-native';
import { EmptyComponent } from '../empty_component/empty_component';
import { UxTheme } from '../../application/ux_themes';

interface Props {
    readonly isVisible: boolean;
    readonly messageText: JSX.Element;
    readonly linkText: JSX.Element;
    readonly theme: UxTheme;
    readonly onLinkPress: () => void;
}

export const MessageComponent = (props: Props): JSX.Element => {
    if (!props.isVisible) {
        return <EmptyComponent />;
    }

    return (
        <View style={{ backgroundColor: colors.lightGrey }}>
            <View style={{ backgroundColor: colors.white, padding: 20, marginBottom: 8 }}>
                <Message text={props.messageText} />
                <Link text={props.linkText} theme={props.theme} onPress={props.onLinkPress}/>
            </View>
        </View>
    );
};

const Message = (props: { readonly text: Props['messageText'] }): JSX.Element => (
    <View>
        <Text style={textStyles.listItemDetail}>
            {props.text}
        </Text>
    </View>
);

const Link = (props: { readonly onPress: Props['onLinkPress'], readonly text: Props['linkText'], readonly theme: UxTheme}): JSX.Element => (
    <View style={{ marginTop: 16, flexDirection: 'row-reverse' }}>
        <TouchableOpacity onPress={props.onPress}>
            <Text style={[textStyles.messageLink, { fontSize: 16, color: props.theme.mainColour }]}>
                {props.text}
            </Text>
        </TouchableOpacity>
    </View>
);


text: Sample application to test Deployment AWS Tools


text:
var tmpVec = new pc.Vec3();

pc.script.create('snakeAction', function (context) {
    // Creates a new SnakeAction instance
    var SnakeAction = function (entity) {
        this.entity = entity;
        //this.movePoint = new pc.Vec3();
        this.timer = this.maxTimer = 0.5;
        this.snakeHead;
        this.player;
        this.movementVar = 1;
        this.stopMove = false;
        //this.client = context.root.getChildren()[0].script.client;
        this.clientid = 0;
        this.snake;//= context.root.findByName('snake_' + this.client.id);
        this.direction = 1;
    };

    SnakeAction.prototype = {
        // Called once after all resources are loaded and before the first update
        initialize: function () {

        },

        // Called every frame, dt is time in seconds since last update
        update: function (dt) {

            this.snake = context.root.findByName('snake_' + this.clientid);
            this.snakeHead = this.snake.getChildren()[0];

            //this.direction = this.client.currentDirection;
            this.timer -= dt;
            if(this.timer < 0){
                this.timer = this.maxTimer;

                var currentHeadPosition = this.snakeHead.getPosition();
                var nextPos = currentHeadPosition;

                switch(this.direction){
                    case 1://Up
                        this.snakeHead.translate(0, 0, -this.movementVar);
                        break;
                    case 2://Right
                        this.snakeHead.translate(this.movementVar, 0, 0);
                        break;
                    case 3://Down
                        this.snakeHead.translate(0, 0, this.movementVar);
                        break;
                    case 4://Left
                        this.snakeHead.translate(-this.movementVar, 0, 0);
                        break;
                }

                var len = this.snake.getChildren().length;//-1;

                for(var i = 1; i < len; i++)
                {
                    var previousPos = this.snake.getChildren()[i].getPosition();
                    this.snake.getChildren()[i].setPosition(nextPos);
                    nextPos = previousPos;

                }
            }

        },
        addBody: function (pos, parent) {
            var entity = new pc.fw.Entity();

            context.systems.model.addComponent(entity, {
                type: 'box',
            });

            context.root.findByName(parent).addChild(entity);

            entity.setPosition(pos[0],pos[1],pos[2]);
        },
        moveToAction: function(pos) {

        },
        changeMoveDirection: function(dir){
            this.direction = dir;
        },
        link: function(snakeid) {
            this.clientid = snakeid;
        }
    };

    return SnakeAction;
});


text:
#include "UnitTest.h"

using namespace Jinx;

TEST_CASE("Test Core Library", "[Core]")
{

	SECTION("Test write functions")
	{
		const char * scriptText =
			u8R"(

			import core

			write "test 1, ", "test 2, ", "test 3", newline
			write line "test 1, ", "test 2 ", "test 3"

			)";

		auto script = TestExecuteScript(scriptText);
		REQUIRE(script);

	}

	SECTION("Test size functions")
	{
		const char * scriptText =
			u8R"(

			import core

			set a to 1, 2, 3
			set b to "test"

			set c to a size
			set d to b get size

			)";

		auto script = TestExecuteScript(scriptText);
		REQUIRE(script);
		REQUIRE(script->GetVariable("c") == 3);
		REQUIRE(script->GetVariable("d") == 4);
	}

	SECTION("Test UTF-8 string size")
	{
		const char * scriptText =
			u8R"(

			import core

			set a to "いろは"
			set b to a's size

			)";

		auto script = TestExecuteScript(scriptText);
		REQUIRE(script);
		REQUIRE(script->GetVariable("a") == u8"いろは");
		REQUIRE(script->GetVariable("b") == 3);
	}

	SECTION("Test empty function")
	{
		const char * scriptText =
			u8R"(

			import core

			set a to []
			set b to ""

			set c to a empty
			set d to b is empty

			)";

		auto script = TestExecuteScript(scriptText);
		REQUIRE(script);
		REQUIRE(script->GetVariable("c") == true);
		REQUIRE(script->GetVariable("d") == true);
	}

	SECTION("Test get call stack function with local functions")
	{
		const char * scriptText =
			u8R"(

			import core

			function func4 {integer a}
				return call stack
			end

			function func3 {a}
				return func4 a
			end

			function func2/func22 (opt1/opt2)
				return func3 123
			end

			function func1/func11 (optional)
				return func2
			end

			set a to func1

			)";

		auto script = TestExecuteScript(scriptText);
		REQUIRE(script);
		REQUIRE(script->GetVariable("a").IsCollection());
		REQUIRE(script->GetVariable("a").GetCollection()->at(1) == "root");
		REQUIRE(script->GetVariable("a").GetCollection()->at(2) == "func1/func11 (optional)");
		REQUIRE(script->GetVariable("a").GetCollection()->at(3) == "func2/func22 (opt1/opt2)");
		REQUIRE(script->GetVariable("a").GetCollection()->at(4) == "func3 {}");
		REQUIRE(script->GetVariable("a").GetCollection()->at(5) == "func4 {integer}");
	}

	SECTION("Test get call stack function with local functions")
	{
		const char * scriptText =
			u8R"(

			import core

			library test

			function func one
				return call stack
			end

			set a to func one

			)";

		auto script = TestExecuteScript(scriptText);
		REQUIRE(script);
		REQUIRE(script->GetVariable("a").IsCollection());
		REQUIRE(script->GetVariable("a").GetCollection()->at(1) == "root");
		REQUIRE(script->GetVariable("a").GetCollection()->at(2) == "test func one");
	}

	SECTION("Test 'call' no-arg no-return function with local function variable")
	{
		static const char * scriptText =
			u8R"(

			import core

			set public a to 0
			function test
				set a to 123
			end

			set f to function test
			call f

			)";

		auto script = TestExecuteScript(scriptText);
		REQUIRE(script);
		REQUIRE(script->GetVariable("f").IsFunction());
		auto library = script->GetLibrary();
		REQUIRE(library->GetProperty("a") == 123);
	}

	SECTION("Test 'call' no-arg function")
	{
		static const char * scriptText =
			u8R"(

			import core

			function test
				return 123
			end

			set f to function test
			set a to call f

			)";

		auto script = TestExecuteScript(scriptText);
		REQUIRE(script);
		REQUIRE(script->GetVariable("f").IsFunction());
		REQUIRE(script->GetVariable("a") == 123);
	}

	SECTION("Test 'call with' one-arg function")
	{
		static const char * scriptText =
			u8R"(

			import core

			function test {x}
				return x
			end

			set f to function test {}
			set a to call f with 123

			)";

		auto script = TestExecuteScript(scriptText);
		REQUIRE(script);
		REQUIRE(script->GetVariable("f").IsFunction());
		REQUIRE(script->GetVariable("a") == 123);
	}

	SECTION("Test 'call with' two-arg function")
	{
		static const char * scriptText =
			u8R"(

			import core

			function test {x} and {y}
				return x, y
			end

			set f to function test {} and {}
			set a to call f with 12, 34

			)";

		auto script = TestExecuteScript(scriptText);
		REQUIRE(script);
		REQUIRE(script->GetVariable("f").IsFunction());
		REQUIRE(script->GetVariable("a").IsCollection());
		REQUIRE(script->GetVariable("a").GetCollection()->at(1) == 12);
		REQUIRE(script->GetVariable("a").GetCollection()->at(2) == 34);
	}

	SECTION("Test 'call' function from library")
	{
		static const char * libText =
			u8R"(

			library lib

			public function test
				return 123
			end

			)";

		static const char * scriptText =
			u8R"(

			import core
			import lib

			set f to function test
			set a to call f

			)";

		auto runtime = TestCreateRuntime();
		auto libScript = TestExecuteScript(libText, runtime);
		auto script = TestExecuteScript(scriptText, runtime);
		REQUIRE(libScript);
		REQUIRE(script);
		REQUIRE(script->GetVariable("f").IsFunction());
		REQUIRE(script->GetVariable("a") == 123);
	}

	SECTION("Test 'call with' function from library")
	{
		static const char * libText =
			u8R"(

			library lib

			public function {x} test {y}
				return x + y
			end

			)";

		static const char * scriptText =
			u8R"(

			import core
			import lib

			set f to function {} test {}
			set a to call f with "Hello ", "world!"

			)";

		auto runtime = TestCreateRuntime();
		auto libScript = TestExecuteScript(libText, runtime);
		auto script = TestExecuteScript(scriptText, runtime);
		REQUIRE(libScript);
		REQUIRE(script);
		REQUIRE(script->GetVariable("f").IsFunction());
		REQUIRE(script->GetVariable("a") == "Hello world!");
	}

	SECTION("Test 'call with' function with wait")
	{
		static const char * scriptText =
			u8R"(

			import core

			function test {x}
				set z to 0
				loop i from 1 to x
					increment z by i
					wait
				end
				return z
			end

			set f to function test {}
			set a to call f with 4

			)";

		auto script = TestCreateScript(scriptText);
		REQUIRE(script);
		REQUIRE(script->Execute());
		REQUIRE(!script->IsFinished());
		while (!script->IsFinished())
		{
			REQUIRE(script->Execute());
		}
		REQUIRE(script->GetVariable("f").IsFunction());
		REQUIRE(script->GetVariable("a") == 10);
	}

}


text:
namespace unvell.ReoGrid.Main
{
	[System.Obsolete("use unvell.ReoGrid.Interaction.CursorStyle instead")]
	public enum RGCursor : byte
	{ }
}

namespace unvell.ReoGrid.Interaction
{
	/// <summary>
	/// Cursor style
	/// </summary>
	public enum CursorStyle : byte
	{
		/// <summary>
		/// Default (Auto)
		/// </summary>
		PlatformDefault,

		/// <summary>
		/// Hand
		/// </summary>
		Hand,

		/// <summary>
		/// Range Selection
		/// </summary>
		Selection,

		/// <summary>
		/// Full Row Selector
		/// </summary>
		FullRowSelect,

		/// <summary>
		/// Full Column Selector
		/// </summary>
		FullColumnSelect,

		/// <summary>
		/// Entire worksheet Selector
		/// </summary>
		EntireSheet,

		/// <summary>
		/// Move object
		/// </summary>
		Move,

		/// <summary>
		/// Copy object
		/// </summary>
		Copy,

		/// <summary>
		/// Change Column Width
		/// </summary>
		ChangeColumnWidth,

		/// <summary>
		/// Change Row Height
		/// </summary>
		ChangeRowHeight,

		/// <summary>
		/// Horizontal Resize
		/// </summary>
		ResizeHorizontal,

		/// <summary>
		/// Vertical Resize
		/// </summary>
		ResizeVertical,

		/// <summary>
		/// Busy (Waiting)
		/// </summary>
		Busy,

		/// <summary>
		/// Cross Cursor
		/// </summary>
		Cross,
	}
}


text:
SPI::SPI() {
	mspi = NULL;
}

void SPI::begin(int busNo) {
	mspi = new mraa::Spi(busNo); // init mraa spi bus, it will handle chip select internally. For CS pin wiring user must check SPI details in hardware manual

	mspi->mode(mraa::SPI_MODE0);
	mspi->bitPerWord(8);
	mspi->frequency(8000000); // Prophet: this will try to set 8MHz, however MRAA will reset to max platform speed and syslog a message of it
}

void SPI::end() {
	// Prophet: we should check for existence of mspi before deleting it
	if (mspi != NULL)
		delete mspi;
}

void SPI::setBitOrder(uint8_t bit_order) {
	if (mspi != NULL)
		mspi->lsbmode((mraa_boolean_t)bit_order); // Prophet: bit_order
}

void SPI::setDataMode(uint8_t data_mode) {
	if (mspi != NULL)
		mspi->mode((mraa::Spi_Mode)data_mode);
}

void SPI::setClockDivider(uint32_t spi_speed) {
	if (mspi != NULL)
		mspi->frequency(spi_speed);
}

void SPI::chipSelect(int csn_pin){

}

SPI::~SPI() {
	// Prophet: we should call end here to free used memory and unexport SPI interface
	this->end();
}


text:
	<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

重置密码

<form method="post" action="/admin/users/reset_password/<?=$user->id?>" class="ajaxForm">

		<?php
		if(isset($message))
			echo $message;
		?>

		<input type="hidden" name="id" value="<?=$user->id?>">
		确定要重置密吗?

		<input type="submit" class="btn btn-danger submitButton" value="确定" onclick="return submitAjax(1)" <?=isset($message)?"disabled":""?>>
		<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>

</form>


text:
Post Installation Configuration
=================================

* Navigate to Administer->BizSense Status->File Permissions. Verify the file permissions
* Configure email settings at Administer->Email Settings
* Set up cron. Have the command::

         php application/modules/default/services/cli.php --service=Core_Service_Cron

    in your crontab entry
* Set your organization details
* Add the site logo. This logo appears in the top left corner of the application
* Add the Document logo. This logo appears in the PDF and other documents
* Save newsletter settings at Marketing->Settings->Message Queue Settings
* Improve performance by setting Expires header in your Apache virutal host directive or .htaccess. Example::

    <FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">
        Header set Expires "Fri, 31 Dec 2011 20:00:00 GMT"
    </FilesMatch>