text:
struct a2dp_sep;
struct a2dp_setup;

typedef void (*a2dp_endpoint_select_t) (struct a2dp_setup *setup, void *ret,
					int size);
typedef void (*a2dp_endpoint_config_t) (struct a2dp_setup *setup, gboolean ret);

struct a2dp_endpoint {
	const char *(*get_name) (struct a2dp_sep *sep, void *user_data);
	size_t (*get_capabilities) (struct a2dp_sep *sep,
						uint8_t **capabilities,
						void *user_data);
	int (*select_configuration) (struct a2dp_sep *sep,
						uint8_t *capabilities,
						size_t length,
						struct a2dp_setup *setup,
						a2dp_endpoint_select_t cb,
						void *user_data);
	int (*set_configuration) (struct a2dp_sep *sep,
						uint8_t *configuration,
						size_t length,
						struct a2dp_setup *setup,
						a2dp_endpoint_config_t cb,
						void *user_data);
	void (*clear_configuration) (struct a2dp_sep *sep, void *user_data);
	void (*set_delay) (struct a2dp_sep *sep, uint16_t delay,
							void *user_data);
};

typedef void (*a2dp_select_cb_t) (struct avdtp *session,
					struct a2dp_sep *sep, GSList *caps,
					void *user_data);
typedef void (*a2dp_config_cb_t) (struct avdtp *session, struct a2dp_sep *sep,
					struct avdtp_stream *stream,
					struct avdtp_error *err,
					void *user_data);
typedef void (*a2dp_stream_cb_t) (struct avdtp *session,
					struct avdtp_error *err,
					void *user_data);

struct a2dp_sep *a2dp_add_sep(struct btd_adapter *adapter, uint8_t type,
				uint8_t codec, gboolean delay_reporting,
				struct a2dp_endpoint *endpoint,
				void *user_data, GDestroyNotify destroy,
				int *err);
void a2dp_remove_sep(struct a2dp_sep *sep);

unsigned int a2dp_select_capabilities(struct avdtp *session,
					uint8_t type, const char *sender,
					a2dp_select_cb_t cb,
					void *user_data);
unsigned int a2dp_config(struct avdtp *session, struct a2dp_sep *sep,
				a2dp_config_cb_t cb, GSList *caps,
				void *user_data);
unsigned int a2dp_resume(struct avdtp *session, struct a2dp_sep *sep,
				a2dp_stream_cb_t cb, void *user_data);
unsigned int a2dp_suspend(struct avdtp *session, struct a2dp_sep *sep,
				a2dp_stream_cb_t cb, void *user_data);
gboolean a2dp_cancel(unsigned int id);

gboolean a2dp_sep_lock(struct a2dp_sep *sep, struct avdtp *session);
gboolean a2dp_sep_unlock(struct a2dp_sep *sep, struct avdtp *session);
struct avdtp_stream *a2dp_sep_get_stream(struct a2dp_sep *sep);
struct btd_device *a2dp_setup_get_device(struct a2dp_setup *setup);


text:
Rails.application.routes.draw do

  resources :albums do
    member do
      patch :upload_photos
    end
  end

  devise_for :users
  get 'sessions/login'

  root 'home#index', as: :home

  delete 'photo/:id' => 'albums#delete_photo', as: :delete_photo
  delete 'avatar/:id' => 'albums#delete_avatar', as: :delete_avatar

  # get 'album/:id' =>

  # Example of regular route:
  #   get 'products/:id' => 'catalog#view'

  # Example of named route that can be invoked with purchase_url(id: product.id)
  #   get 'products/:id/purchase' => 'catalog#purchase', as: :purchase

  # Example resource route (maps HTTP verbs to controller actions automatically):
  #   resources :products

  # Example resource route with options:
  #   resources :products do
  #     member do
  #       get 'short'
  #       post 'toggle'
  #     end
  #
  #     collection do
  #       get 'sold'
  #     end
  #   end

  # Example resource route with sub-resources:
  #   resources :products do
  #     resources :comments, :sales
  #     resource :seller
  #   end

  # Example resource route with more complex sub-resources:
  #   resources :products do
  #     resources :comments
  #     resources :sales do
  #       get 'recent', on: :collection
  #     end
  #   end

  # Example resource route with concerns:
  #   concern :toggleable do
  #     post 'toggle'
  #   end
  #   resources :posts, concerns: :toggleable
  #   resources :photos, concerns: :toggleable

  # Example resource route within a namespace:
  #   namespace :admin do
  #     # Directs /admin/products/* to Admin::ProductsController
  #     # (app/controllers/admin/products_controller.rb)
  #     resources :products
  #   end
end

redpajama_set_name: RedPajamaGithub


text:
package com.allvu.web.config.core;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

import com.allvu.web.config.security.SecurityConfig;

/**
 * Configuration: Indicates to "Spring framework" that this class can be used as
 * a source of bean definitions. EnableWebMvc: Imports the Spring MVC
 * configuration ComponentScan: Directs "Spring framework" to scan the base
 * packages for controllers, dispatchers, resolvers, ...
 *
 * @author dantullis
 *
 */
@EnableWebMvc
@Configuration
@ComponentScan({ "com.allvu.web.*" })
@Import({ SecurityConfig.class })
public class ApplicationConfig {

	@Bean
	/**
	 * Sets the view resolver to use JSP pages/views
	 *
	 * @return
	 */
	public InternalResourceViewResolver viewResolver() {
		InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
		viewResolver.setViewClass(JstlView.class);
		viewResolver.setPrefix("/WEB-INF/pages/");
		viewResolver.setSuffix(".jsp");
		return viewResolver;
	}
}


text:
from django.apps import AppConfig

class NetConfig(AppConfig):
    name = "net"


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Matrix3 (libgdx API)</title>
<meta name="date" content="2013-05-14">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

				libgdx API

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.badlogic.gdx.math

Class Matrix3

java.lang.Object

com.badlogic.gdx.math.Matrix3

All Implemented Interfaces:

java.io.Serializable

public class Matrix3
extends java.lang.Object
implements java.io.Serializable

A 3x3 column major matrix; useful for 2D transforms.

Author:

mzechner

See Also:

Serialized Form

Field Summary

Fields

Modifier and Type
Field and Description

static int
M00

static int
M01

static int
M02

static int
M10

static int
M11

static int
M12

static int
M20

static int
M21

static int
M22

float[]
val

Constructor Summary

Constructors

Constructor and Description

Matrix3()

Matrix3(Matrix3 matrix)

Method Summary

Methods

Modifier and Type
Method and Description

float
det()

float[]
getValues()

Get the values in this matrix.

Matrix3
idt()

Sets this matrix to the identity matrix

Matrix3
inv()

Inverts this matrix given that the determinant is !

Matrix3
mul(Matrix3 m)

Multiplies this matrix with the provided matrix and stores the result in this matrix.

Matrix3
rotate(float angle)

Postmultiplies this matrix with a (counter-clockwise) rotation matrix.

Matrix3
scale(float scaleX,
     float scaleY)

Postmultiplies this matrix with a scale matrix.

Matrix3
scale(Vector2 scale)

Postmultiplies this matrix with a scale matrix.

Matrix3
scl(float scale)

Scale the matrix in the both the x and y components by the scalar value.

Matrix3
scl(Vector2 scale)

Scale this matrix using the x and y components of the vector but leave the rest of the matrix alone.

Matrix3
scl(Vector3 scale)

Scale this matrix using the x and y components of the vector but leave the rest of the matrix alone.

Matrix3
set(Matrix3 mat)

Copies the values from the provided matrix to this matrix.

Matrix3
set(Matrix4 mat)

Sets this 3x3 matrix to the top left 3x3 corner of the provided 4x4 matrix.

Matrix3
setToRotation(float degrees)

Sets this matrix to a rotation matrix that will rotate any vector in counter-clockwise order around the z-axis.

Matrix3
setToScaling(float scaleX,
            float scaleY)

Sets this matrix to a scaling matrix.

Matrix3
setToTranslation(float x,
                float y)

Sets this matrix to a translation matrix.

Matrix3
setToTranslation(Vector2 translation)

Sets this matrix to a translation matrix.

java.lang.String
toString()

Matrix3
translate(float x,
         float y)

Postmultiplies this matrix by a translation matrix.

Matrix3
translate(Vector2 translation)

Postmultiplies this matrix by a translation matrix.

Matrix3
transpose()

Transposes the current matrix.

Matrix3
trn(float x,
   float y)

Adds a translational component to the matrix in the 3rd column.

Matrix3
trn(Vector2 vector)

Adds a translational component to the matrix in the 3rd column.

Matrix3
trn(Vector3 vector)

Adds a translational component to the matrix in the 3rd column.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

M00

public static final int M00

See Also:

Constant Field Values

M01

public static final int M01

See Also:

Constant Field Values

M02

public static final int M02

See Also:

Constant Field Values

M10

public static final int M10

See Also:

Constant Field Values

M11

public static final int M11

See Also:

Constant Field Values

M12

public static final int M12

See Also:

Constant Field Values

M20

public static final int M20

See Also:

Constant Field Values

M21

public static final int M21

See Also:

Constant Field Values

M22

public static final int M22

See Also:

Constant Field Values

val

public float[] val

Constructor Detail

Matrix3

public Matrix3()

Matrix3

public Matrix3(Matrix3 matrix)

Method Detail

idt

public Matrix3 idt()

Sets this matrix to the identity matrix

Returns:

This matrix for the purpose of chaining operations.

mul

public Matrix3 mul(Matrix3 m)

Multiplies this matrix with the provided matrix and stores the result in this matrix. For example:

 A.mul(B) results in A := AB

Parameters:

m - Matrix to multiply by.

Returns:

This matrix for the purpose of chaining operations together.

setToRotation

public Matrix3 setToRotation(float degrees)

Sets this matrix to a rotation matrix that will rotate any vector in counter-clockwise order around the z-axis.

Parameters:

degrees - the angle in degrees.

Returns:

This matrix for the purpose of chaining operations.

setToTranslation

public Matrix3 setToTranslation(float x,
                       float y)

Sets this matrix to a translation matrix.

Parameters:

x - the translation in x

y - the translation in y

Returns:

This matrix for the purpose of chaining operations.

setToTranslation

public Matrix3 setToTranslation(Vector2 translation)

Sets this matrix to a translation matrix.

Parameters:

translation - The translation vector.

Returns:

This matrix for the purpose of chaining operations.

setToScaling

public Matrix3 setToScaling(float scaleX,
                   float scaleY)

Sets this matrix to a scaling matrix.

Parameters:

scaleX - the scale in x

scaleY - the scale in y

Returns:

This matrix for the purpose of chaining operations.

toString

public java.lang.String toString()

Overrides:

toString in class java.lang.Object

det

public float det()

Returns:

The determinant of this matrix

inv

public Matrix3 inv()

Inverts this matrix given that the determinant is != 0.

Returns:

This matrix for the purpose of chaining operations.

set

public Matrix3 set(Matrix3 mat)

Copies the values from the provided matrix to this matrix.

Parameters:

mat - The matrix to copy.

Returns:

This matrix for the purposes of chaining.

set

public Matrix3 set(Matrix4 mat)

Sets this 3x3 matrix to the top left 3x3 corner of the provided 4x4 matrix.

Parameters:

mat - The matrix whose top left corner will be copied. This matrix will not be modified.

Returns:

This matrix for the purpose of chaining operations.

trn

public Matrix3 trn(Vector2 vector)

Adds a translational component to the matrix in the 3rd column. The other columns are untouched.

Parameters:

vector - The translation vector.

Returns:

This matrix for the purpose of chaining.

trn

public Matrix3 trn(float x,
          float y)

Adds a translational component to the matrix in the 3rd column. The other columns are untouched.

Parameters:

x - The x-component of the translation vector.

y - The y-component of the translation vector.

Returns:

This matrix for the purpose of chaining.

trn

public Matrix3 trn(Vector3 vector)

Adds a translational component to the matrix in the 3rd column. The other columns are untouched.

Parameters:

vector - The translation vector. (The z-component of the vector is ignored because this is a 3x3 matrix)

Returns:

This matrix for the purpose of chaining.

translate

public Matrix3 translate(float x,
                float y)

Postmultiplies this matrix by a translation matrix. Postmultiplication is also used by OpenGL ES' 1.x
 glTranslate/glRotate/glScale.

Parameters:

x - The x-component of the translation vector.

y - The y-component of the translation vector.

Returns:

This matrix for the purpose of chaining.

translate

public Matrix3 translate(Vector2 translation)

Postmultiplies this matrix by a translation matrix. Postmultiplication is also used by OpenGL ES' 1.x
 glTranslate/glRotate/glScale.

Parameters:

translation - The translation vector.

Returns:

This matrix for the purpose of chaining.

rotate

public Matrix3 rotate(float angle)

Postmultiplies this matrix with a (counter-clockwise) rotation matrix. Postmultiplication is also used by OpenGL ES' 1.x
 glTranslate/glRotate/glScale.

Parameters:

angle - The angle in degrees

Returns:

This matrix for the purpose of chaining.

scale

public Matrix3 scale(float scaleX,
            float scaleY)

Postmultiplies this matrix with a scale matrix. Postmultiplication is also used by OpenGL ES' 1.x
 glTranslate/glRotate/glScale.

Parameters:

scaleX - The scale in the x-axis.

scaleY - The scale in the y-axis.

Returns:

This matrix for the purpose of chaining.

scale

public Matrix3 scale(Vector2 scale)

Postmultiplies this matrix with a scale matrix. Postmultiplication is also used by OpenGL ES' 1.x
 glTranslate/glRotate/glScale.

Parameters:

scale - The vector to scale the matrix by.

Returns:

This matrix for the purpose of chaining.

getValues

public float[] getValues()

Get the values in this matrix.

Returns:

The float values that make up this matrix in column-major order.

scl

public Matrix3 scl(float scale)

Scale the matrix in the both the x and y components by the scalar value.

Parameters:

scale - The single value that will be used to scale both the x and y components.

Returns:

This matrix for the purpose of chaining methods together.

scl

public Matrix3 scl(Vector2 scale)

Scale this matrix using the x and y components of the vector but leave the rest of the matrix alone.

Parameters:

scale - The Vector3 to use to scale this matrix.

Returns:

This matrix for the purpose of chaining methods together.

scl

public Matrix3 scl(Vector3 scale)

Scale this matrix using the x and y components of the vector but leave the rest of the matrix alone.

Parameters:

scale - The Vector3 to use to scale this matrix. The z component will be ignored.

Returns:

This matrix for the purpose of chaining methods together.

transpose

public Matrix3 transpose()

Transposes the current matrix.

Returns:

This matrix for the purpose of chaining methods together.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

libgdx API

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

				Copyright © 2010-2013 Mario Zechner (contact@badlogicgames.com), Nathan Sweet (admin@esotericsoftware.com)


text:
OAuth2
======

This is a summary of the main features of OAuth2 as they are supported by this extension.
You can read all the details in [RFC 6749](http://tools.ietf.org/html/rfc6749).

## Overview

The main idea is that a **resource owner** (a.k.a. end user) hosts some data at a **server**,
and can grant permission to a **client** (a.k.a. a third party) to access this data or parts of it.
Therefore the client can obtain an **access token** which represents this permission.

So we have three roles involved:

 * **User**: The end user that has a `username` and `password` at the server.
 * **Server**: A website where the end user has an account and stored data.
 * **Client**: A third party website that wants to access user data from the server.
   Clients have to register with the server first and receive a `client_id` and `client_secret`.

## Grant Types

OAuth2 defines four different flows or *grant types* for how to get an access token. All four
are supported by this extension. Let's look at each of them.

### 1. Authorization Code

This is the famous *"Login with your FB account"* type: A client site wants to authenticate its
users through another server and access the users data on that other website.

The basic flow here is:

 1. Client site redirects the user to the server site
 1. User logs in there and is asked to grant permission to the client
 1. User is redirected back to client site with an *authorization code* in the URL
 1. Client site can use this *authorization token*  to request an *access token* directly from the server
 1. Client site also receives the expiry time of the access token and optionally a *refresh token*
 1. With the *access token* the client can now access some of the user's data on the server
 1. Client can request a new access token with the refresh token

The server here has to provide two main actions:

 * **authorize**: This is a page, where the user first has to login and is then asked for permission
   to grant access to the client. This can either be a simple question like *"Do you allow website
   Foo to authenticate with us?"* or involve the selection of **scopes** like *"Which of the following
   permissions do you want to grant to website Foo?"*. After this, the action will redirect the
   user back to the client and append an *authorization code* to the client's redirect URL.
 * **token**: This is the action where the client can exchange the *authorization code* against the
   final *access token*.

### 2. Implicit

This is for pure Javascript applications that run in a browser. Note, that this grant type is considered
to be insecure and should be avoided. There's no client involved in the communication to the server.

 1. User is redirected to the server site via javascript
 1. User logs in there and is asked to grant permission to the application
 1. User is redirected back to client site with an *access token* as URL parameter

The server here has to provide only one action:

 * **authorize**: This is the same page as in the step above, asking the user for permission.
   This time the URL that the user is redirect to afterwards will contain the *access token*
   right away. But it's a URL hash parameter so that the client server can't read it.

### 3. Resource Owner Password

If the client is a trusted entity, e.g. part of the providers enterprise then it can be
trusted to ask the users for their credentials.

 1. Client POSTs the user's credentials directly to the authorization provider
 1. Client recieves an *access token* in response and optionally a refresh token

The server here again has to provide only one action:

 * **token**: The client will send the username and password to this action and receive an
   access token in return.

### 4. Client Credentials

The last grant type is used if the client has to authenticate itself against the server
to manage it's own data. Here no user is involved and the access token only allow the
client to access its own data.

 1. Client POSTs its own credentials directly to the authorization provider
 1. Client recieves an access token in response

The server here again has to provide only one action:

 * **token**: The client will send his client_id and client_secret to this action and receive an
   access token in return.


text:
<ul>
    <li *ngFor="#person of persons" (click)="personSelected(person)" [class.clicked]="showDetail">
        {{person.name}}
    </li>
</ul>
<contact [c]="selectedPerson"></contact>


text:
#if !defined(CY_STATUS_REG_FF_STATUS_H) /* CY_STATUS_REG_FF_STATUS_H */
#define CY_STATUS_REG_FF_STATUS_H

#include "cyfitter.h"

#if ((CYDEV_CHIP_FAMILY_USED == CYDEV_CHIP_FAMILY_PSOC3) || \
     (CYDEV_CHIP_FAMILY_USED == CYDEV_CHIP_FAMILY_PSOC4) || \
     (CYDEV_CHIP_FAMILY_USED == CYDEV_CHIP_FAMILY_PSOC5))
    #include "cytypes.h"
    #include "CyLib.h"
#else
    #include "syslib/cy_syslib.h"
#endif

/***************************************
*     Data Struct Definitions
***************************************/

/* Sleep Mode API Support */
typedef struct
{
    uint8 statusState;

} FF_STATUS_BACKUP_STRUCT;

/***************************************
*        Function Prototypes
***************************************/

uint8 FF_STATUS_Read(void) ;
void FF_STATUS_InterruptEnable(void) ;
void FF_STATUS_InterruptDisable(void) ;
void FF_STATUS_WriteMask(uint8 mask) ;
uint8 FF_STATUS_ReadMask(void) ;

/***************************************
*           API Constants
***************************************/

#define FF_STATUS_STATUS_INTR_ENBL    0x10u

/***************************************
*         Parameter Constants
***************************************/

/* Status Register Inputs */
#define FF_STATUS_INPUTS              1

/***************************************
*             Registers
***************************************/

/* Status Register */
#define FF_STATUS_Status             (* (reg8 *) FF_STATUS_sts_sts_reg__STATUS_REG )
#define FF_STATUS_Status_PTR         (  (reg8 *) FF_STATUS_sts_sts_reg__STATUS_REG )
#define FF_STATUS_Status_Mask        (* (reg8 *) FF_STATUS_sts_sts_reg__MASK_REG )
#define FF_STATUS_Status_Aux_Ctrl    (* (reg8 *) FF_STATUS_sts_sts_reg__STATUS_AUX_CTL_REG )

#endif /* End CY_STATUS_REG_FF_STATUS_H */

/* [] END OF FILE */


text:
package interfaces;

public interface IDeck {

    public void shuffle();

    public ICard dealCard();
}


text:
<link rel="import" href="../polymer/polymer.html">

<link rel="import" href="../iron-a11y-keys-behavior/iron-a11y-keys-behavior.html">
<link rel="import" href="../iron-behaviors/iron-control-state.html">
<link rel="import" href="../iron-form-element-behavior/iron-form-element-behavior.html">
<link rel="import" href="../iron-input/iron-input.html">
<link rel="import" href="../iron-selector/iron-selector.html">
<link rel="import" href="../paper-input/paper-input-behavior.html">
<link rel="import" href="../paper-input/paper-input-container.html">
<link rel="import" href="../paper-input/paper-input-error.html">
<link rel="import" href="../paper-item/paper-item.html">
<link rel="import" href="../paper-material/paper-material.html">
<link rel="import" href="../paper-styles/default-theme.html">
<link rel="import" href="../paper-styles/typography.html">

<dom-module id="paper-typeahead">
  <template>

    <paper-input-container
        class="selectable"
        no-label-float="[[noLabelFloat]]"
        always-float-label="[[_computeAlwaysFloatLabel(alwaysFloatLabel,placeholder)]]"
        auto-validate$="[[autoValidate]]"
        disabled$="[[disabled]]"
        invalid="[[invalid]]">
      <slot name="prefix" slot="prefix"></slot>
      [[label]]
      <input
          is="iron-input"
          id="input"
          aria-labelledby$="[[_ariaLabelledBy]]"
          aria-describedby$="[[_ariaDescribedBy]]"
          disabled$="[[disabled]]"
          bind-value="{{value}}"
          value="{{typedValue::input}}"
          invalid="{{invalid}}"
          prevent-invalid-input="[[preventInvalidInput]]"
          allowed-pattern="[[allowedPattern]]"
          validator="[[validator]]"
          type$="[[type]]"
          pattern$="[[pattern]]"
          required$="[[required]]"
          autocomplete$="[[autocomplete]]"
          autofocus$="[[autofocus]]"
          inputmode$="[[inputmode]]"
          minlength$="[[minlength]]"
          maxlength$="[[maxlength]]"
          min$="[[min]]"
          max$="[[max]]"
          step$="[[step]]"
          name$="[[name]]"
          placeholder$="[[placeholder]]"
          readonly$="[[readonly]]"
          size$="[[size]]"
          autocapitalize$="[[autocapitalize]]"
          autocorrect$="on"
          on-change="_onChange" slot="input">
      <slot name="suffix" slot="suffix"></slot>
      <paper-input-error tabindex="-1" slot="input">[[errorMessage]]</paper-input-error>
    </paper-input-container>
    <paper-material
      hidden$="[[_hideResults]]"
      elevation="[[elevation]]"
      on-mousedown="_mouseDownItems"
      on-mouseleave="_mouseleaveItems"
      tabindex="-1" slot="input">
      <iron-selector
        id="selector"
        selected="{{selected}}"
        items="[[selectorItems]]">
        <template
          is="dom-repeat"
          id="item-list"
          sort="[[sortFn]]"
          items="[[filteredItems]]"
          on-dom-change="_updateItems">
          <paper-item on-mouseenter="_mouseenterItem" class="result-item selectable" tabindex="-1">
            [[getDataDisplayValue(item, dataKey)]]
          </paper-item>
        </template>
      </iron-selector>
    </paper-material>
  </template>
</dom-module>


text:
require 'redcloth'
require 'haml'

module Dirt
  class StaticController < Dirt::Controller
  	def show(params)
  		if defined? (params[:page].to_s)
  			send(params[:page].to_s, params)
  		elsif
  			notfound(params)
  		end
    end

    def notfound(params)
    	haml "static/not_found"
    end

    def help(params)
      params[:subpage] = "home" if params[:subpage].nil? || params[:subpage].empty?
      if File.exists?("views/static/help/"+params[:subpage].to_s+".textile")
        @page = RedCloth.new(File.read("views/static/help/"+params[:subpage].to_s+".textile")).to_html
        layout = File.read('views/layout.haml')
        template = File.read('views/static/help.haml')
        layout_engine = Haml::Engine.new(layout)
        layout_engine.render(self) do
          template_engine = Haml::Engine.new(template, :format => :html5)
          template_engine.render(self)
        end
      else
        notfound(params)
      end
    end

  end
end


text:
<?php

namespace flat\core\controller\route;
/**
 * provides a RESTful status to route controller that can be provided to route invoker via callback
 *
 * @see \flat\core\controller\route
 * @see \flat\core\controller\route\restful_status\callback_data data provided to callback
 *
 * @package    flat\route
 * @author     D. Bird <retran@gmail.com>
 * @copyright  Copyright (c) 2012-2014 Doug Bird. All Rights Reserved.
 * @version    0.1.0-alpha
 *
 * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html official RFC documenting valid status codes
 * @link http://en.wikipedia.org/wiki/List_of_HTTP_status_codes helpful article on status codes
 *
 * @todo create parent class and children with valid status code
 *    and status string combintions. The methods here could be prone
 *    to breaking an HTTP session if the implementer is not totally
 *    familiar and careful to use HTTP status codes / string combos.
 *
 * @todo change interface to have just get_status()
 * @todo create /flat/core/controller/route/restful_status/controller.php
 *     as convenience for applying this interface.
 */
interface restful_status {
   /**
    * HTTP status code, such as: 200, 404, 500
    * @return int
    */
   public function get_status_code();
   /**
    * HTTP status string, such as: "OK", "Not Found", "Internal Server Error"
    * @return string
    */
   public function get_status_string();
}


text: On Line Software for Collects in Ecuador


text:
using System;
using System.IO;
using System.Collections.Generic;
using Microsoft.Protocols.TestTools.StackSdk;

namespace Microsoft.Protocols.TestTools.StackSdk.RemoteDesktop.Rdpeusb
{
    /// <summary>
    /// The builder is used to build various URB objects.
    /// </summary>
    public class UrbBuilder
    {
        #region Private Members

        private URB_FUNCTIONID function;
        private uint requestId;
        private byte noAck;

        #endregion

        #region Build Methods

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="function">The URB function.</param>
        /// <param name="requestId">An ID that uniquely identifies the TRANSFER_IN_REQUEST or TRANSFER_OUT_REQUEST.</param>
        /// <param name="noAck">f this bit is nonzero the client should not send a URB_COMPLETION message for this
        /// TRANSFER_OUT_REQUEST. This bit can be nonzero only if the NoAckIsochWriteJitterBufferSizeInMs field
        /// in USB_DEVICE_CAPABILITIES is nonzero and URB Function is set to URB_FUNCTION_ISOCH_TRANSFER.
        /// If the RequestId field is set to TRANSFER_IN_REQUEST, this field MUST be set to zero.</param>
        public UrbBuilder(URB_FUNCTIONID function, uint requestId, byte noAck)
        {
            this.function = function;
            this.requestId = requestId;
            this.noAck = noAck;
        }

        /// <summary>
        /// Builds a particular request for a string descriptor from the device.
        /// </summary>
        /// <param name="index">Specifies the device-defined index of the descriptor that is being retrieved or set.</param>
        /// <returns>The string descriptor request.</returns>
        public TS_URB_CONTROL_DESCRIPTOR_REQUEST BuildStringDescriptorRequest(byte index)
        {
            return BuildStringDescriptorRequest(index, 0x0409);
        }

        /// <summary>
        /// Builds a particular request for a string descriptor from the device.
        /// </summary>
        /// <param name="index">Specifies the device-defined index of the descriptor that is being retrieved or set.</param>
        /// <param name="languageId">Locale ID of the language.</param>
        /// <returns>The string descriptor request.</returns>
        public TS_URB_CONTROL_DESCRIPTOR_REQUEST BuildStringDescriptorRequest(byte index, ushort languageId)
        {
            TS_URB_CONTROL_DESCRIPTOR_REQUEST des = new TS_URB_CONTROL_DESCRIPTOR_REQUEST();
            des.Header.Size = 12;
            des.Header.URB_Function = URB_FUNCTIONID.URB_FUNCTION_GET_DESCRIPTOR_FROM_DEVICE;
            des.Header.RequestId = this.requestId;
            des.Header.NoAck = this.noAck;
            des.Index = index;
            des.DescriptorType = (byte)UsbDescriptorTypes.USB_STRING_DESCRIPTOR_TYPE;
            // English (U.S.)
            des.LanguageId = languageId;
            return des;
        }

        /// <summary>
        /// Builds a descriptor request to get the information of the whole device.
        /// </summary>
        /// <returns>The device descriptor request</returns>
        public TS_URB_CONTROL_DESCRIPTOR_REQUEST BuildDeviceDescriptorRequest()
        {
            TS_URB_CONTROL_DESCRIPTOR_REQUEST des = new TS_URB_CONTROL_DESCRIPTOR_REQUEST();
            des.Header.Size = 12;
            des.Header.URB_Function = URB_FUNCTIONID.URB_FUNCTION_GET_DESCRIPTOR_FROM_DEVICE;
            des.Header.RequestId = this.requestId;
            des.Header.NoAck = this.noAck;
            des.Index = 0; // this parameter not used for device descriptors
            des.DescriptorType = (byte)UsbDescriptorTypes.USB_DEVICE_DESCRIPTOR_TYPE;
            des.LanguageId = 0; // this parameter not used for device descriptors
            return des;
        }

        /// <summary>
        /// Builds a descriptor request to get the information of the configurations.
        /// </summary>
        /// <param name="index">number of configuration descriptor</param>
        /// <returns>The configuration descriptor request</returns>
        public TS_URB_CONTROL_DESCRIPTOR_REQUEST BuildConfigurationDescriptorRequest(byte index)
        {
            TS_URB_CONTROL_DESCRIPTOR_REQUEST des = new TS_URB_CONTROL_DESCRIPTOR_REQUEST();
            des.Header.Size = 12;
            des.Header.URB_Function = URB_FUNCTIONID.URB_FUNCTION_GET_DESCRIPTOR_FROM_DEVICE;
            des.Header.RequestId = this.requestId;
            des.Header.NoAck = this.noAck;
            des.Index = index;
            des.DescriptorType = (byte)UsbDescriptorTypes.USB_CONFIGURATION_DESCRIPTOR_TYPE;
            des.LanguageId = 0; // this parameter not used for configuration descriptors
            return des;
        }

        /// <summary>
        /// Builds a configuration-selection request.
        /// </summary>
        /// <param name="interfaces">The interface information field.</param>
        /// <param name="configDescriptor">The configuration descriptor.</param>
        /// <returns>The configuration-selection request.</returns>
        public TS_URB_SELECT_CONFIGURATION BuildSelectConfigRequest(
            TS_USBD_INTERFACE_INFORMATION[] interfaces,
            byte[] configDescriptor
            )
        {
            TS_URB_SELECT_CONFIGURATION req = new TS_URB_SELECT_CONFIGURATION(
                this.requestId,
                this.noAck
                );
            // TS_URB_HEADER (8 bytes) + ConfigurationDescriptorIsValid (1 byte) + Padding (3 bytes)
            // NumInterfaces (4 bytes) + TS_USBD_INTERFACE_INFORMATION + USB_CONFIGURATION_DESCRIPTOR
            int interfaceLength = 0;
            foreach (TS_USBD_INTERFACE_INFORMATION i in interfaces)
            {
                interfaceLength += i.Length;
            }
            req.Header.Size = (ushort)(8 + 1 + 3 + 4 + interfaceLength + configDescriptor.Length);
            req.Header.URB_Function = URB_FUNCTIONID.URB_FUNCTION_SELECT_CONFIGURATION;
            req.Interfaces = interfaces;
            req.NumInterfaces = (uint)interfaces.Length;
            req.UsbConfDesc = configDescriptor;
            req.ConfigurationDescriptorIsValid = (configDescriptor != null ? (byte)1 : (byte)0);
            return req;
        }

        /// <summary>
        /// Builds an interface-selection request.
        /// </summary>
        /// <param name="configuration">The result of configuration-selection.</param>
        /// <param name="index">The index of the interface to be selected.</param>
        /// <returns>The interface-selection request.</returns>
        public TS_URB_SELECT_INTERFACE BuildSelectionInterfaceRequest(TS_URB_SELECT_CONFIGURATION_RESULT configuration, int index)
        {
            if (null == configuration)
            {
                throw new ArgumentNullException("configuration");
            }
            if (index >= configuration.Interface.Length || null == configuration.Interface[index])
            {
                throw new ArgumentException("index specified interface doesn't exist.");
            }

            TS_URB_SELECT_INTERFACE urb = new TS_URB_SELECT_INTERFACE(this.requestId, this.noAck);
            urb.ConfigurationHandle = configuration.ConfigurationHandle;
            urb.Header.Size = 8 + 4; // Header + ConfigurationHandle
            urb.TsUsbdIInfo = new TS_USBD_INTERFACE_INFORMATION();
            TS_USBD_INTERFACE_INFORMATION_RESULT inf = configuration.Interface[index];
            if (inf.NumberOfPipes != inf.Pipes.Length)
            {
                throw new ArgumentException(String.Format(
                    "The selecting interface count doesn't match. NumberOfPipes: {0}, Pipes count: {1}.",
                    inf.NumberOfPipes,
                    inf.Pipes.Length
                    ));
            }

            urb.TsUsbdIInfo.Length = 2 + 2 + 1 + 1 + 2 + 4;
            urb.TsUsbdIInfo.NumberOfPipesExpected = (ushort)inf.NumberOfPipes;
            urb.TsUsbdIInfo.InterfaceNumber = inf.InterfaceNumber;
            urb.TsUsbdIInfo.AlternateSetting = inf.AlternateSetting;
            urb.TsUsbdIInfo.Padding = PaddingGenerator.GeneratePadding();
            urb.TsUsbdIInfo.NumberOfPipes = inf.NumberOfPipes;

            urb.TsUsbdIInfo.Infomations = new TS_USBD_PIPE_INFORMATION[inf.NumberOfPipes];
            for (int i = 0; i < inf.NumberOfPipes; i++)
			{
                urb.TsUsbdIInfo.Length += 2 + 2 + 4 + 4; // count Pipe sizes
                urb.TsUsbdIInfo.Infomations[i] = new TS_USBD_PIPE_INFORMATION();
                urb.TsUsbdIInfo.Infomations[i].MaximumPacketSize = inf.Pipes[i].MaximumPacketSize;
                urb.TsUsbdIInfo.Infomations[i].Padding = PaddingGenerator.GeneratePadding();
                urb.TsUsbdIInfo.Infomations[i].MaximumTransferSize = inf.Pipes[i].MaximumTransferSize;
                urb.TsUsbdIInfo.Infomations[i].PipeFlags = inf.Pipes[i].PipeFlags;
			}

            urb.Header.Size += urb.TsUsbdIInfo.Length; // interface information size.
            return urb;
        }

        /// <summary>
        /// Builds a vendor command request.
        /// </summary>
        /// <param name="request">Specifies the USB or vendor-defined request code for the device, interface, endpoint, or other device-defined target. </param>
        /// <param name="value">Specifies a value, specific to Request, that becomes part of the USB-defined setup packet for the target. This value is defined by the creator of the code used in Request.</param>
        /// <param name="flag">Specifies zero, one, or a combination of the flags of type TransferFlags.</param>
        /// <returns>The vendor command request.</returns>
        public TS_URB_CONTROL_VENDOR_OR_CLASS_REQUEST BuildVendorCommandRequest(byte request, ushort value, TransferFlags flag)
        {
            TS_URB_CONTROL_VENDOR_OR_CLASS_REQUEST req = new TS_URB_CONTROL_VENDOR_OR_CLASS_REQUEST(
                this.requestId,
                this.noAck,
                URB_FUNCTIONID.URB_FUNCTION_VENDOR_DEVICE
                );
            req.Header.Size = 8 + 4 + 1 + 1 + 2 + 2 + 2;
            req.TransferFlags = (uint)flag;
            req.RequestTypeReservedBits = 0;
            req.Request = request;
            req.Value = value;
            req.Index = 0;
            req.Padding = 0;// PaddingGenerator.GeneratePadding();

            return req;
        }

        /// <summary>
        /// Overloaded method to build a partial vendor command request.
        /// </summary>
        /// <returns>The partial vendor command request.</returns>
        public TS_URB_CONTROL_VENDOR_OR_CLASS_REQUEST BuildVendorCommandRequest()
        {
            return BuildVendorCommandRequest(0, 0, TransferFlags.USBD_TRANSFER_DIRECTION_OUT);
        }

        /// <summary>
        /// Builds a request to receive data on a bulk pipe, or receive data on an interrupt pipe.
        /// </summary>
        /// <param name="endpoints">All information of the pipes to be searched.</param>
        /// <param name="endpointNumber">The endpoint number.</param>
        /// <param name="flag">The endpoint flag.</param>
        /// <param name="type">The type of the endpoint.</param>
        /// <returns>The request containing the pipe handle found to receive data on a bulk pipe, or receive data on an interrupt pipe.</returns>
        public TS_URB_BULK_OR_INTERRUPT_TRANSFER BuildInterruptTransferRequest(TS_USBD_PIPE_INFORMATION_RESULT[] endpoints, byte endpointNumber, TransferFlags flag, USBD_PIPE_TYPE type)
        {
            if (((flag & TransferFlags.USBD_TRANSFER_DIRECTION_IN) != TransferFlags.USBD_TRANSFER_DIRECTION_IN)
                && ((flag & TransferFlags.USBD_TRANSFER_DIRECTION_OUT) != TransferFlags.USBD_TRANSFER_DIRECTION_OUT))
            {
                throw new ArgumentException("flag must contain the direction flag.");
            }

            TS_URB_BULK_OR_INTERRUPT_TRANSFER req = new TS_URB_BULK_OR_INTERRUPT_TRANSFER(
                this.requestId,
                this.noAck
                );
            req.Header.URB_Function = this.function;

            req.Header.Size = 8 + 4 + 4;
            req.TransferFlags = (uint)flag;

            bool found = false;
            // Looking for the correct pipe handle.
            foreach (TS_USBD_PIPE_INFORMATION_RESULT e in endpoints)
            {
                byte num = (byte)(e.EndpointAddress & 0x0F);
                if (num == endpointNumber)
                {
                    VerifyEndpointDirection(e.EndpointAddress, flag);

                    VerifyType(e.PipeType, type);

                    req.PipeHandle = e.PipeHandle;
                    found = true;
                    break;
                }
            }

            if (!found)
            {
                throw new ArgumentException(String.Format("Specified endpoint ({0}) cannot be found.", endpointNumber));
            }

            return req;
        }

        /// <summary>
        /// Builds a request to clear a stall condition on an endpoint.
        /// </summary>
        /// <param name="pipeHandle">Specifies an opaque handle to the bulk or interrupt pipe.</param>
        /// <returns></returns>
        public TS_URB_PIPE_REQUEST BuildPipeRequest(uint pipeHandle)
        {
            TS_URB_PIPE_REQUEST req = new TS_URB_PIPE_REQUEST(
                this.requestId,
                this.noAck,
                this.function);
            req.Header.Size = 8 + 4;
            req.PipeHandle = pipeHandle;
            return req;
        }

        /// <summary>
        /// Builds a request to retrieve the current alternate interface setting for an interface in the current configuration.
        /// </summary>
        /// <param name="interfaceIndex">Specifies the device-defined index of the interface descriptor being retrieved.</param>
        /// <returns>The request to retrieve the current alternate interface setting.</returns>
        public TS_URB_CONTROL_GET_INTERFACE_REQUEST BuildGetInterfaceRequest(ushort interfaceIndex)
        {
            TS_URB_CONTROL_GET_INTERFACE_REQUEST req = new TS_URB_CONTROL_GET_INTERFACE_REQUEST(
                this.requestId,
                0);
            req.Interface = interfaceIndex;
            req.Padding = PaddingGenerator.GeneratePadding();
            return req;
        }

        /// <summary>
        /// Builds a request to retrieve Microsoft OS Feature Descriptors from a USB device or an interface on a USB device.
        /// </summary>
        /// <param name="recipient">Specifies whether the recipient is the USB device or an interface on the USB device.</param>
        /// <param name="interfaceNumber">Indicates the interface number that is the recipient of the request, if the Recipient member value is 1. Must be set to 0 if the USB device is the recipient.</param>
        /// <param name="msPageIndex">Must be set to 0. Page index of the 64K page of the MS OS Feature Descriptor to be returned. Current implementation only supports a maximum descriptor size of 4K.</param>
        /// <param name="msFeatureDescriptorIndex">Index for MS OS Feature Descriptor to be requested.</param>
        /// <returns>The request to retrieve Microsoft OS Feature Descriptors from a USB device or an interface on a USB device.</returns>
        public TS_URB_OS_FEATURE_DESCRIPTOR_REQUEST BuildOSFeatureDescriptor(Recipient recipient, byte interfaceNumber, byte msPageIndex, ushort msFeatureDescriptorIndex)
        {
            TS_URB_OS_FEATURE_DESCRIPTOR_REQUEST req = new TS_URB_OS_FEATURE_DESCRIPTOR_REQUEST(
                this.requestId,
                this.noAck
                );
            req.Recipient = (byte)recipient;
            req.InterfaceNumber = recipient == Recipient.Interface ? (byte)interfaceNumber : (byte)0;
            req.MS_PageIndex = msPageIndex;
            req.MS_FeatureDescriptorIndex = msFeatureDescriptorIndex;
            return req;
        }

        #endregion

        #region Private Methods

        private void VerifyEndpointDirection(byte endpointAddress, TransferFlags expectedFlag)
        {
            // Verify direction
            bool isFlagDirIn =
                (expectedFlag & TransferFlags.USBD_TRANSFER_DIRECTION_IN) == TransferFlags.USBD_TRANSFER_DIRECTION_IN;
            bool isEndpointDirIn =
                (endpointAddress >> 7) == 1;
            if (isFlagDirIn != isEndpointDirIn)
            {
                throw new ArgumentException(String.Format(
                    "flag is not consistent to endpoint direction. flag: {0}, Endpoint: {1}.",
                    expectedFlag,
                    isEndpointDirIn ? "In" : "Out"
                    ));
            }
        }

        private void VerifyType(uint pipeType, USBD_PIPE_TYPE expectedType)
        {
            if ((USBD_PIPE_TYPE)pipeType != expectedType)
            {
                throw new ArgumentException(String.Format(
                    "type is not consistent to endpoint type. type: {0}, Endpoint: {1}.",
                    (USBD_PIPE_TYPE)pipeType,
                    expectedType
                ));
            }
        }

        #endregion
    }

    /// <summary>
    /// Used to parse a structure instance from a buffer.
    /// </summary>
    public class UsbStructParser
    {
        /// <summary>
        /// Parses the structure instance from an EusbUrbCompletionPdu object.
        /// </summary>
        /// <typeparam name="T">The type of the structure</typeparam>
        /// <param name="pdu">The an EusbUrbCompletionPdu object containing the buffer to be parsed</param>
        /// <returns>The structure instance.</returns>
        public static T Parse<T>(EusbUrbCompletionPdu pdu) where T : UsbStructure, new()
        {
            if (null == pdu.OutputBuffer ||
                pdu.OutputBufferSize <= 0 ||
                pdu.HResult != (uint)HRESULT_FROM_WIN32.ERROR_SUCCESS)
            {
                return default(T);
            }

            T us = new T();
            if (!PduMarshaler.Unmarshal(pdu.OutputBuffer, us))
            {
                return default(T);
            }
            return us;
        }
    }

    /// <summary>
    /// The parser used to parse the result of USB configuration.
    /// </summary>
    public class UsbConfigurationParser
    {
        #region Private Members

        private List<TS_USBD_INTERFACE_INFORMATION> interfaces = new List<TS_USBD_INTERFACE_INFORMATION>();

        private MemoryStream ms = null;

        // BUGBUG: Check if this is still valid.
        // In Windows XP, Windows Server 2003 and later operating system, the MaximumTransferSize member of
        // the USBD_PIPE_INFORMATION structure is obsolete.
        private const uint USBD_DEFAULT_MAXIMUM_TRANSFER_SIZE = uint.MaxValue;

        #endregion

        #region Public Members

        /// <summary>
        /// The parsed TS_USBD_INTERFACE_INFORMATION result.
        /// </summary>
        public TS_USBD_INTERFACE_INFORMATION[] Interfaces
        {
            get { return interfaces.ToArray(); }
        }

        /// <summary>
        /// The parsed USB_CONFIGURATION_DESCRIPTOR result.
        /// </summary>
        public byte[] configDescriptor { get; private set; }

        /// <summary>
        /// Parses all information of the configuration result.
        /// </summary>
        /// <param name="pdu">The EusbUrbCompletionPdu to be parsed.</param>
        /// <returns>true indicates successful.</returns>
        public bool ParseAll(EusbUrbCompletionPdu pdu)
        {
            if (pdu.OutputBuffer == null)
            {
                return false;
            }
            ms = new MemoryStream(pdu.OutputBuffer);

            USB_CONFIGURATION_DESCRIPTOR cd = UsbStructParser.Parse<USB_CONFIGURATION_DESCRIPTOR>(pdu);
            ms.Seek(USB_CONFIGURATION_DESCRIPTOR.DefaultSize, SeekOrigin.Begin);

            if (ms.Length != cd.wTotalLength)
            {
                return false;
            }

            configDescriptor = pdu.OutputBuffer;

            USB_INTERFACE_DESCRIPTOR interfaceDes = (USB_INTERFACE_DESCRIPTOR)GetNextDescriptor(UsbDescriptorTypes.USB_INTERFACE_DESCRIPTOR_TYPE);
            while (null != interfaceDes)
            {
                TS_USBD_INTERFACE_INFORMATION interfaceInfo = new TS_USBD_INTERFACE_INFORMATION();
                interfaceInfo.NumberOfPipesExpected = interfaceDes.bNumEndpoints;
                interfaceInfo.InterfaceNumber = interfaceDes.bInterfaceNumber;
                interfaceInfo.AlternateSetting = interfaceDes.bAlternateSetting;
                // Padding can be set to any value and MUST be ignored upon receipt.
                interfaceInfo.Padding = PaddingGenerator.GeneratePadding();
                GeneratePipeInformation(interfaceDes, interfaceInfo);
                interfaces.Add(interfaceInfo);

                interfaceDes = (USB_INTERFACE_DESCRIPTOR)GetNextDescriptor(UsbDescriptorTypes.USB_INTERFACE_DESCRIPTOR_TYPE);
            }

            return true;
        }

        #endregion

        #region Private Methods

        private void GeneratePipeInformation(USB_INTERFACE_DESCRIPTOR interfaceDes, TS_USBD_INTERFACE_INFORMATION interfaceInfo)
        {
            uint pipeCount = interfaceDes.bNumEndpoints;
            interfaceInfo.NumberOfPipes = pipeCount;
            interfaceInfo.Infomations = new TS_USBD_PIPE_INFORMATION[pipeCount];

            ushort lenExpectPipeInfo = 2 + 2 + 1 + 1 + 2 + 4;
            interfaceInfo.Length = (ushort)(lenExpectPipeInfo + pipeCount * (2 + 2 + 4 + 4));

            for (int i = 0; i < pipeCount; i++)
            {
                interfaceInfo.Infomations[i] = new TS_USBD_PIPE_INFORMATION();
                // TODO:
                // In Windows XP, Windows Server 2003 and later operating system, Alt settings for an interface or restrict the maximum packet size by setting
                // MaximumPacketSize to some value less than or equal to the value of of wMaxPacketSize defined in device firmware for the current Alt settings.
                interfaceInfo.Infomations[i].MaximumPacketSize = 0;
                interfaceInfo.Infomations[i].Padding = PaddingGenerator.GeneratePadding();
                // In Windows XP, Windows Server 2003 and later operating system, the MaximumTransferSize member of the USBD_PIPE_INFORMATION structure is obsolete.
                interfaceInfo.Infomations[i].MaximumTransferSize = USBD_DEFAULT_MAXIMUM_TRANSFER_SIZE;
                interfaceInfo.Infomations[i].PipeFlags = 0;
            }
        }

        private UsbDescriptorStructure GetNextDescriptor(UsbDescriptorTypes descriptorType)
        {
            byte[] temp = new byte[2];
            UsbDescriptorStructure result = null;

            while (ms.Position < ms.Length - 2)
            {
                if (2 != ms.Read(temp, 0, 2))
                {
                    return null;
                }

                UsbDescriptorStructure des = new UsbDescriptorStructure();
                PduMarshaler.Unmarshal(temp, des);

                if (des.bDescriptorType == descriptorType)
                {
                    ms.Seek(-2, SeekOrigin.Current);

                    switch (des.bDescriptorType)
                    {

                        case UsbDescriptorTypes.USB_INTERFACE_DESCRIPTOR_TYPE:
                            result = new USB_INTERFACE_DESCRIPTOR();
                            if (ParseDescriptor(USB_INTERFACE_DESCRIPTOR.DefaultSize, result))
                            {
                                return result;
                            }
                            break;
                        default:
                            throw new NotImplementedException();
                            //break;
                    }
                }
                else
                {
                    ms.Seek(des.bLength - 1, SeekOrigin.Current);
                }
            }
            return result;
        }

        private bool ParseDescriptor(int length, UsbDescriptorStructure des)
        {
            byte[] temp = new byte[length];
            if(length != ms.Read(temp, 0, length))
            {
                return false;
            }

            return PduMarshaler.Unmarshal(temp, des);
        }

        #endregion
    }

    /// <summary>
    /// Test helper class used to generate a unique unsigned integer ID.
    /// </summary>
    public static class IdGenerator
    {
        private static uint NextId = 0;

        /// <summary>
        /// Generates a new ID.
        /// </summary>
        /// <returns>Next avaliable ID.</returns>
        public static uint NewId()
        {
            if (NextId == uint.MaxValue)
            {
                NextId = 0;
                return uint.MaxValue;
            }
            return NextId++;
        }
    }

    /// <summary>
    /// Test helper class used to generate random paddings.
    /// </summary>
    public static class PaddingGenerator
    {
        /// <summary>
        /// Generates randmon ushort padding.
        /// </summary>
        /// <returns>Padding</returns>
        public static ushort GeneratePadding()
        {
            return (ushort)(new Random().Next());
        }

        /// <summary>
        /// Generates random byte array padding
        /// </summary>
        /// <param name="length">The length of the padding buffer.</param>
        /// <returns>Padding</returns>
        public static byte[] GeneratePadding(int length)
        {
            byte[] p = new byte[length];
            new Random().NextBytes(p);
            return p;
        }
    }
}


text:
function hadoop_classpath_tools_hadoop-rumen
{
  hadoop_add_classpath "${HADOOP_TOOLS_HOME}/${HADOOP_TOOLS_LIB_JARS_DIR}/hadoop-rumen-3.2.4.jar"
}


text:
package mutate

import (
	"archive/tar"
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"path/filepath"
	"strings"
	"time"

	v1 "github.com/google/go-containerregistry/pkg/v1"
	"github.com/google/go-containerregistry/pkg/v1/empty"
	"github.com/google/go-containerregistry/pkg/v1/internal/gzip"
	"github.com/google/go-containerregistry/pkg/v1/match"
	"github.com/google/go-containerregistry/pkg/v1/tarball"
	"github.com/google/go-containerregistry/pkg/v1/types"
)

const whiteoutPrefix = ".wh."

// Addendum contains layers and history to be appended
// to a base image
type Addendum struct {
	Layer       v1.Layer
	History     v1.History
	URLs        []string
	Annotations map[string]string
	MediaType   types.MediaType
}

// AppendLayers applies layers to a base image.
func AppendLayers(base v1.Image, layers ...v1.Layer) (v1.Image, error) {
	additions := make([]Addendum, 0, len(layers))
	for _, layer := range layers {
		additions = append(additions, Addendum{Layer: layer})
	}

	return Append(base, additions...)
}

// Append will apply the list of addendums to the base image
func Append(base v1.Image, adds ...Addendum) (v1.Image, error) {
	if len(adds) == 0 {
		return base, nil
	}
	if err := validate(adds); err != nil {
		return nil, err
	}

	return &image{
		base: base,
		adds: adds,
	}, nil
}

// Appendable is an interface that represents something that can be appended
// to an ImageIndex. We need to be able to construct a v1.Descriptor in order
// to append something, and this is the minimum required information for that.
type Appendable interface {
	MediaType() (types.MediaType, error)
	Digest() (v1.Hash, error)
	Size() (int64, error)
}

// IndexAddendum represents an appendable thing and all the properties that
// we may want to override in the resulting v1.Descriptor.
type IndexAddendum struct {
	Add Appendable
	v1.Descriptor
}

// AppendManifests appends a manifest to the ImageIndex.
func AppendManifests(base v1.ImageIndex, adds ...IndexAddendum) v1.ImageIndex {
	return &index{
		base: base,
		adds: adds,
	}
}

// RemoveManifests removes any descriptors that match the match.Matcher.
func RemoveManifests(base v1.ImageIndex, matcher match.Matcher) v1.ImageIndex {
	return &index{
		base:   base,
		remove: matcher,
	}
}

// Config mutates the provided v1.Image to have the provided v1.Config
func Config(base v1.Image, cfg v1.Config) (v1.Image, error) {
	cf, err := base.ConfigFile()
	if err != nil {
		return nil, err
	}

	cf.Config = cfg

	return ConfigFile(base, cf)
}

// ConfigFile mutates the provided v1.Image to have the provided v1.ConfigFile
func ConfigFile(base v1.Image, cfg *v1.ConfigFile) (v1.Image, error) {
	m, err := base.Manifest()
	if err != nil {
		return nil, err
	}

	image := &image{
		base:       base,
		manifest:   m.DeepCopy(),
		configFile: cfg,
	}

	return image, nil
}

// CreatedAt mutates the provided v1.Image to have the provided v1.Time
func CreatedAt(base v1.Image, created v1.Time) (v1.Image, error) {
	cf, err := base.ConfigFile()
	if err != nil {
		return nil, err
	}

	cfg := cf.DeepCopy()
	cfg.Created = created

	return ConfigFile(base, cfg)
}

// Extract takes an image and returns an io.ReadCloser containing the image's
// flattened filesystem.
//
// Callers can read the filesystem contents by passing the reader to
// tar.NewReader, or io.Copy it directly to some output.
//
// If a caller doesn't read the full contents, they should Close it to free up
// resources used during extraction.
func Extract(img v1.Image) io.ReadCloser {
	pr, pw := io.Pipe()

	go func() {
		// Close the writer with any errors encountered during
		// extraction. These errors will be returned by the reader end
		// on subsequent reads. If err == nil, the reader will return
		// EOF.
		pw.CloseWithError(extract(img, pw))
	}()

	return pr
}

// Adapted from https://github.com/google/containerregistry/blob/da03b395ccdc4e149e34fbb540483efce962dc64/client/v2_2/docker_image_.py#L816
func extract(img v1.Image, w io.Writer) error {
	tarWriter := tar.NewWriter(w)
	defer tarWriter.Close()

	fileMap := map[string]bool{}

	layers, err := img.Layers()
	if err != nil {
		return fmt.Errorf("retrieving image layers: %v", err)
	}
	// we iterate through the layers in reverse order because it makes handling
	// whiteout layers more efficient, since we can just keep track of the removed
	// files as we see .wh. layers and ignore those in previous layers.
	for i := len(layers) - 1; i >= 0; i-- {
		layer := layers[i]
		layerReader, err := layer.Uncompressed()
		if err != nil {
			return fmt.Errorf("reading layer contents: %v", err)
		}
		defer layerReader.Close()
		tarReader := tar.NewReader(layerReader)
		for {
			header, err := tarReader.Next()
			if err == io.EOF {
				break
			}
			if err != nil {
				return fmt.Errorf("reading tar: %v", err)
			}

			basename := filepath.Base(header.Name)
			dirname := filepath.Dir(header.Name)
			tombstone := strings.HasPrefix(basename, whiteoutPrefix)
			if tombstone {
				basename = basename[len(whiteoutPrefix):]
			}

			// check if we have seen value before
			// if we're checking a directory, don't filepath.Join names
			var name string
			if header.Typeflag == tar.TypeDir {
				name = header.Name
			} else {
				name = filepath.Join(dirname, basename)
			}

			if _, ok := fileMap[name]; ok {
				continue
			}

			// check for a whited out parent directory
			if inWhiteoutDir(fileMap, name) {
				continue
			}

			// mark file as handled. non-directory implicitly tombstones
			// any entries with a matching (or child) name
			fileMap[name] = tombstone || !(header.Typeflag == tar.TypeDir)
			if !tombstone {
				tarWriter.WriteHeader(header)
				if header.Size > 0 {
					if _, err := io.Copy(tarWriter, tarReader); err != nil {
						return err
					}
				}
			}
		}
	}
	return nil
}

func inWhiteoutDir(fileMap map[string]bool, file string) bool {
	for {
		if file == "" {
			break
		}
		dirname := filepath.Dir(file)
		if file == dirname {
			break
		}
		if val, ok := fileMap[dirname]; ok && val {
			return true
		}
		file = dirname
	}
	return false
}

// Time sets all timestamps in an image to the given timestamp.
func Time(img v1.Image, t time.Time) (v1.Image, error) {
	newImage := empty.Image

	layers, err := img.Layers()
	if err != nil {
		return nil, fmt.Errorf("getting image layers: %v", err)
	}

	// Strip away all timestamps from layers
	var newLayers []v1.Layer
	for _, layer := range layers {
		newLayer, err := layerTime(layer, t)
		if err != nil {
			return nil, fmt.Errorf("setting layer times: %v", err)
		}
		newLayers = append(newLayers, newLayer)
	}

	newImage, err = AppendLayers(newImage, newLayers...)
	if err != nil {
		return nil, fmt.Errorf("appending layers: %v", err)
	}

	ocf, err := img.ConfigFile()
	if err != nil {
		return nil, fmt.Errorf("getting original config file: %v", err)
	}

	cf, err := newImage.ConfigFile()
	if err != nil {
		return nil, fmt.Errorf("setting config file: %v", err)
	}

	cfg := cf.DeepCopy()

	// Copy basic config over
	cfg.Architecture = ocf.Architecture
	cfg.OS = ocf.OS
	cfg.OSVersion = ocf.OSVersion
	cfg.Config = ocf.Config

	// Strip away timestamps from the config file
	cfg.Created = v1.Time{Time: t}

	for _, h := range cfg.History {
		h.Created = v1.Time{Time: t}
	}

	return ConfigFile(newImage, cfg)
}

func layerTime(layer v1.Layer, t time.Time) (v1.Layer, error) {
	layerReader, err := layer.Uncompressed()
	if err != nil {
		return nil, fmt.Errorf("getting layer: %v", err)
	}
	defer layerReader.Close()
	w := new(bytes.Buffer)
	tarWriter := tar.NewWriter(w)
	defer tarWriter.Close()

	tarReader := tar.NewReader(layerReader)
	for {
		header, err := tarReader.Next()
		if err == io.EOF {
			break
		}
		if err != nil {
			return nil, fmt.Errorf("reading layer: %v", err)
		}

		header.ModTime = t
		if err := tarWriter.WriteHeader(header); err != nil {
			return nil, fmt.Errorf("writing tar header: %v", err)
		}

		if header.Typeflag == tar.TypeReg {
			if _, err = io.Copy(tarWriter, tarReader); err != nil {
				return nil, fmt.Errorf("writing layer file: %v", err)
			}
		}
	}

	if err := tarWriter.Close(); err != nil {
		return nil, err
	}

	b := w.Bytes()
	// gzip the contents, then create the layer
	opener := func() (io.ReadCloser, error) {
		return gzip.ReadCloser(ioutil.NopCloser(bytes.NewReader(b))), nil
	}
	layer, err = tarball.LayerFromOpener(opener)
	if err != nil {
		return nil, fmt.Errorf("creating layer: %v", err)
	}

	return layer, nil
}

// Canonical is a helper function to combine Time and configFile
// to remove any randomness during a docker build.
func Canonical(img v1.Image) (v1.Image, error) {
	// Set all timestamps to 0
	created := time.Time{}
	img, err := Time(img, created)
	if err != nil {
		return nil, err
	}

	cf, err := img.ConfigFile()
	if err != nil {
		return nil, err
	}

	// Get rid of host-dependent random config
	cfg := cf.DeepCopy()

	cfg.Container = ""
	cfg.Config.Hostname = ""
	cfg.DockerVersion = ""

	return ConfigFile(img, cfg)
}

// MediaType modifies the MediaType() of the given image.
func MediaType(img v1.Image, mt types.MediaType) v1.Image {
	return &image{
		base:      img,
		mediaType: &mt,
	}
}

// IndexMediaType modifies the MediaType() of the given index.
func IndexMediaType(idx v1.ImageIndex, mt types.MediaType) v1.ImageIndex {
	return &index{
		base:      idx,
		mediaType: &mt,
	}
}


text:
require 'spec_helper'

describe Jan::Symbol do
  let(:symbol13) { described_class.new('4901085188033') }
  let(:symbol8) { described_class.new('49377415') }

  describe 'initializer' do
    it { expect(symbol13).to be_an_instance_of Jan::Symbol }
    it { expect(symbol8).to be_an_instance_of Jan::Symbol }
  end

  describe '#band_patterns' do
    it { expect(symbol13.band_patterns).to be_an_instance_of Array }
    it { expect(symbol8.band_patterns).to be_an_instance_of Array }
    it { expect(symbol13.band_patterns).to all( be_an Jan::Symbol::BandPattern) }
    it { expect(symbol8.band_patterns).to all( be_an Jan::Symbol::BandPattern) }

    it 'has correct format' do
      patterns = symbol13.band_patterns

      expect(patterns[0]).to be_an_instance_of Jan::Symbol::BandPattern::LeftQuietZone
      expect(patterns[1]).to be_an_instance_of Jan::Symbol::BandPattern::NormalGuardPattern
      expect(patterns[2..7]).to all( be_an Jan::Symbol::BandPattern::SymbolCharacter )
      expect(patterns[8]).to be_an_instance_of Jan::Symbol::BandPattern::CenterGuardPattern
      expect(patterns[9..14]).to all( be_an Jan::Symbol::BandPattern::SymbolCharacter )
      expect(patterns[15]).to be_an_instance_of Jan::Symbol::BandPattern::NormalGuardPattern
      expect(patterns[16]).to be_an_instance_of Jan::Symbol::BandPattern::RightQuietZone

      patterns = symbol8.band_patterns

      expect(patterns[0]).to be_an_instance_of Jan::Symbol::BandPattern::LeftQuietZone
      expect(patterns[1]).to be_an_instance_of Jan::Symbol::BandPattern::NormalGuardPattern
      expect(patterns[2..5]).to all( be_an Jan::Symbol::BandPattern::SymbolCharacter )
      expect(patterns[6]).to be_an_instance_of Jan::Symbol::BandPattern::CenterGuardPattern
      expect(patterns[7..10]).to all( be_an Jan::Symbol::BandPattern::SymbolCharacter )
      expect(patterns[11]).to be_an_instance_of Jan::Symbol::BandPattern::NormalGuardPattern
      expect(patterns[12]).to be_an_instance_of Jan::Symbol::BandPattern::RightQuietZone
    end
  end

  describe '#codepoints' do
    mappings = {
      '0123456789012' => %w[A1 A2 A3 A4 A5 A6 C7 C8 C9 C0 C1 C2],
      '1123456789012' => %w[A1 A2 B3 A4 B5 B6 C7 C8 C9 C0 C1 C2],
      '2123456789012' => %w[A1 A2 B3 B4 A5 B6 C7 C8 C9 C0 C1 C2],
      '3123456789012' => %w[A1 A2 B3 B4 B5 A6 C7 C8 C9 C0 C1 C2],
      '4123456789012' => %w[A1 B2 A3 A4 B5 B6 C7 C8 C9 C0 C1 C2],
      '5123456789012' => %w[A1 B2 B3 A4 A5 B6 C7 C8 C9 C0 C1 C2],
      '6123456789012' => %w[A1 B2 B3 B4 A5 A6 C7 C8 C9 C0 C1 C2],
      '7123456789012' => %w[A1 B2 A3 B4 A5 B6 C7 C8 C9 C0 C1 C2],
      '8123456789012' => %w[A1 B2 A3 B4 B5 A6 C7 C8 C9 C0 C1 C2],
      '9123456789012' => %w[A1 B2 B3 A4 B5 A6 C7 C8 C9 C0 C1 C2],
      '12345678' => %w[A1 A2 A3 A4 C5 C6 C7 C8],
    }

    mappings.each do |code, answer|
      it 'returns codepoints with correct set' do
        symbol = described_class.new(code)
        expect(symbol.codepoints).to eq answer
      end
    end
  end

  describe '#svg' do
    it 'returns SVG string'
  end
end


text:
var d = new Date();

document.getElementById("id_logic_level_version").innerHTML =
	"Business level version: "
	+d.getFullYear() +"." +d.getMonth() + "1"+"." +d.getDate()+".10";

//pentru accesul webcamerei:
var constraints = {audio:false, video: {facingMode:"environment"}};
navigator.mediaDevices.getUserMedia(constraints).then(on_success).catch(on_error);

var video = document.getElementById("id_video");
video.addEventListener("touchstart", snap);
video.addEventListener("mousedown", snap);

var canvas = document.getElementById("id_canvas");
video.addEventListener("touchstart", download);
//---------------------------------------------------
function on_success(stream)
{
	video.srcObject = stream;
}
//---------------------------------------------------
function on_error(error)
{
	alert("Error")
}
//---------------------------------------------------

function snap()
{
	var canvas = document.getElementById("id_canvas")
	var context = canvas.getContext("2d");
	context.drawImage(video, 0, 0, 640, 480);
}
//---------------------------------------------------

function download()
{
	var my_image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
	windows.location.href = my_image;
}


text:
using System;

class ExchangeIfGreater
{
    static void Main(string[] args)
    {
        double firstNumber = double.Parse(Console.ReadLine());
        double secondNumber = double.Parse(Console.ReadLine());
        double holder = 0d;

        if (firstNumber > secondNumber)
        {
            holder = firstNumber;
            firstNumber = secondNumber;
            secondNumber = holder;

            Console.WriteLine("{0} {1}", firstNumber, secondNumber);
        }

        else
        {
            Console.WriteLine("{0} {1}", firstNumber, secondNumber);
        }
    }
}


text:
package com.tiny.demo.firstlinecode.designpattern.chapter06.official;

import com.tiny.demo.firstlinecode.common.utils.LogUtils;

/**
 * Desc:
 * Created by tiny on 2017/10/18.
 * Version:
 */

public class ConcreteDecoratorA extends Decorator {
    private String addedState;//本类独有的功能

    @Override
    public void Operate() {
        super.Operate();//首先执行原Component的Operate的功能,再执行本类的功能。
        addedState = "New State";
        LogUtils.e("具体装饰类A的操作");
    }
}


text:
namespace content {
class WebUIDataSource;
}

namespace keyboard {

class VKMojoHandler;

class VKWebUIController : public content::WebUIController {
 public:
  explicit VKWebUIController(content::WebUI* web_ui);
  ~VKWebUIController() override;

 private:
  void CreateAndStoreUIHandler(
      mojo::InterfaceRequest<KeyboardUIHandlerMojo> request);

  // content::WebUIController:
  void RenderViewCreated(content::RenderViewHost* host) override;

  scoped_ptr<VKMojoHandler> ui_handler_;
  base::WeakPtrFactory<VKWebUIController> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(VKWebUIController);
};

class KEYBOARD_EXPORT VKWebUIControllerFactory
    : public content::WebUIControllerFactory {
 public:
  // WebUIControllerFactory:
  content::WebUI::TypeID GetWebUIType(content::BrowserContext* browser_context,
                                      const GURL& url) const override;
  bool UseWebUIForURL(content::BrowserContext* browser_context,
                      const GURL& url) const override;
  bool UseWebUIBindingsForURL(content::BrowserContext* browser_context,
                              const GURL& url) const override;
  content::WebUIController* CreateWebUIControllerForURL(
      content::WebUI* web_ui,
      const GURL& url) const override;

  static VKWebUIControllerFactory* GetInstance();

 protected:
  VKWebUIControllerFactory();
  ~VKWebUIControllerFactory() override;

 private:
  friend struct DefaultSingletonTraits<VKWebUIControllerFactory>;

  DISALLOW_COPY_AND_ASSIGN(VKWebUIControllerFactory);
};

}  // namespace keyboard

#endif  // UI_KEYBOARD_WEBUI_VK_WEBUI_CONTROLLER_H_


text:
package com.ftfl.icare.util;

public class ICareProfile {
	String mId = "";
	String mName = "";
	String mGender = "";
	String mDateOfBirth = "";
	String mWeight = "";
	String mHeight = "";
	String mBloodGroup = "";
	String mImage = "";

	/*
	 * set id of the profile
	 */
	public void setID(String eID) {
		mId = eID;
	}

	/*
	 * get id of the activity
	 */
	public String getID() {
		return mId;
	}

	/*
	 * Set a name for profile. parameter mName return name
	 */
	public void setName(String eName) {
		mName = eName;
	}

	/*
	 * get name of the profile.
	 */
	public String getName() {
		return mName;
	}

	/*
	 * set age of the person
	 */
	public void setGender(String eGender) {
		mGender = eGender;
	}

	/*
	 * get age of the person
	 */
	public String getGender() {
		return mGender;
	}

	/*
	 * set eye color of the person
	 */
	public void setBloodGroup(String eBloodGroup) {
		mBloodGroup = eBloodGroup;
	}

	/*
	 * get eye color of the person
	 */
	public String getBlooGroup() {
		return mBloodGroup;

	}

	/*
	 * set weight
	 */
	public void setWeight(String eWeight) {
		mWeight = eWeight;
	}

	/*
	 * get weight
	 */
	public String getWeight() {
		return mWeight;
	}

	/*
	 * set height
	 */
	public void setHeight(String eHeight) {
		mHeight = eHeight;
	}

	/*
	 * get height
	 */
	public String getHeight() {
		return mHeight;
	}

	/*
	 * set date of birth
	 */
	public void setDateOfBirth(String eDateOfBirth) {
		mDateOfBirth = eDateOfBirth;
	}

	/*
	 * get date of birth
	 */
	public String getDateOfBirth() {
		return mDateOfBirth;
	}

	/*
	 * set special notes
	 */
	public void setImage(String eImage) {
		mImage = eImage;
	}

	/*
	 * get special notes
	 */
	public String getImage() {
		return mImage;
	}

	/*
	 * set empty constructor of this class
	 */
	public ICareProfile() {

	}

	/*
	 * constructor for set value
	 */
	public ICareProfile(String eId, String eName, String eGender,
			String eDateOfBirth, String eHeight, String eWeight,
			String eBloodGroup, String eImage) {
		mId = eId;
		mName = eName;
		mGender = eGender;
		mBloodGroup = eBloodGroup;
		mWeight = eWeight;
		mHeight = eHeight;
		mDateOfBirth = eDateOfBirth;
		mImage = eImage;
	}
}


text:
module Fog
  module Google
    class SQL
      class Mock
        include Fog::Google::Shared

        def initialize(options)
          shared_initialize(options[:google_project], GOOGLE_SQL_API_VERSION, GOOGLE_SQL_BASE_URL)
        end

        def self.data
          @data ||= Hash.new do |hash, key|
            hash[key] = {
              :backup_runs => {},
              :instances => {},
              :operations => {},
              :ssl_certs => {}
            }
          end
        end

        def self.reset
          @data = nil
        end

        def data
          self.class.data[project]
        end

        def reset_data
          self.class.data.delete(project)
        end

        def random_operation
          "operation-#{Fog::Mock.random_numbers(13)}-#{Fog::Mock.random_hex(13)}-#{Fog::Mock.random_hex(8)}"
        end
      end
    end
  end
end


text:
using UnityEngine;
using System.Collections;

public static class DrawEnviroment
{
	/**
	 * @brief Draw the grass floor.
	 */
	public static void Ground ()
	{
		Material grass_material = Resources.Load ("Materials/Grass", typeof(Material)) as Material;

		GameObject ground = GameObject.CreatePrimitive(PrimitiveType.Plane);
		ground.name = Constants.Name_Ground;
		ground.tag = Constants.Tag_Ground;
		ground.layer = LayerMask.NameToLayer(Constants.Layer_Roads);
		// Ground scale is divided by 10 because measurements of the plane are 10x10 in Unity
		ground.transform.localScale = new Vector3((RoadMap.max_x-RoadMap.min_x)/10, 1, (RoadMap.max_z-RoadMap.min_z)/10);
		ground.GetComponent<Renderer>().material = grass_material;
		ground.GetComponent<Renderer>().material.mainTextureScale = new Vector2(ground.transform.localScale.x, ground.transform.localScale.z);

		Vector3 ground_position = new Vector3((RoadMap.max_x+RoadMap.min_x)/2,Constants.ground_Y_position,(RoadMap.max_z+RoadMap.min_z)/2);
		ground.transform.position = ground_position;
	}
}


text:
Application Manager Docker Hub 2.0
==================================

### Installation on Windows

Install [Docker Machine](https://docs.docker.com/machine/install-machine/).

Create virtual machine:
```
docker-machine create -d virtualbox dev
```

Get IP address:
```
docker-machine ip dev
```

Connect to virtual machine:
```
docker-machine ssh dev
```

### Build on Windows

Go to shared (between host and virtualbox) home directory:
```
cd /c/Users/<WINDOWS USER>
```

Create project directory:
```
mkdir amhub
cd amhub
```

Copy sources to shared (between host and virtualbox) directory:
```
git clone --depth=1 https://github.com/alex-agency/AMHub .
```

Build Docker Image:
```
docker build --force-rm=true -t alexagency/amhub .
```

### Run on Windows

Create and run docker container which connected to src directory where run NodeJS server with watching for source changing:
```
docker run -it --rm -p 8080:8080 -p 2375:2375 -v /var/run/docker.sock:/var/run/docker.sock -v /c/Users/<WINDOWS USER>/amhub/src:/AMHub/src alexagency/amhub yarn watch
```

### Useful Docker Commands

Show list of all containers:

```
docker ps -a
```

Attach to a running container:

```
docker exec -it <CONTAINER ID> bash
```

To remove all stopeed containers:

```
docker rm $(docker ps -a -q)
```

Show list of all images:

```
docker images
```

To remove image by id:

```
docker rmi -f <IMAGE ID>
```

Delete all existing images:

```
docker rmi $(docker images -q -a)
```


text:
import {isBlank, isPresent, BaseException} from 'angular2/src/facade/lang';
import {MapWrapper, ListWrapper, List, Map} from 'angular2/src/facade/collection';
import {PromiseWrapper, Promise} from 'angular2/src/facade/async';
import {DOM} from 'angular2/src/dom/dom_adapter';

import {Parser, Lexer} from 'angular2/change_detection';
import {DirectDomRenderer} from 'angular2/src/render/dom/direct_dom_renderer';
import {Compiler} from 'angular2/src/render/dom/compiler/compiler';
import {ProtoViewRef, ProtoViewDto, ViewDefinition, ViewContainerRef, EventDispatcher, DirectiveMetadata} from 'angular2/src/render/api';
import {DefaultStepFactory} from 'angular2/src/render/dom/compiler/compile_step_factory';
import {TemplateLoader} from 'angular2/src/render/dom/compiler/template_loader';
import {UrlResolver} from 'angular2/src/services/url_resolver';
import {EmulatedUnscopedShadowDomStrategy} from 'angular2/src/render/dom/shadow_dom/emulated_unscoped_shadow_dom_strategy';
import {EventManager, EventManagerPlugin} from 'angular2/src/render/dom/events/event_manager';
import {VmTurnZone} from 'angular2/src/core/zone/vm_turn_zone';
import {StyleUrlResolver} from 'angular2/src/render/dom/shadow_dom/style_url_resolver';
import {ViewFactory} from 'angular2/src/render/dom/view/view_factory';
import {RenderViewHydrator} from 'angular2/src/render/dom/view/view_hydrator';

export class IntegrationTestbed {
  renderer;
  parser;
  eventPlugin;
  _templates:Map<string, ViewDefinition>;

  constructor({urlData, viewCacheCapacity, shadowDomStrategy, templates}) {
    this._templates = MapWrapper.create();
    if (isPresent(templates)) {
      ListWrapper.forEach(templates, (template) => {
        MapWrapper.set(this._templates, template.componentId, template);
      });
    }
    var parser = new Parser(new Lexer());
    var urlResolver = new UrlResolver();
    if (isBlank(shadowDomStrategy)) {
      shadowDomStrategy = new EmulatedUnscopedShadowDomStrategy(new StyleUrlResolver(urlResolver), null);
    }
    var compiler = new Compiler(new DefaultStepFactory(parser, shadowDomStrategy), new FakeTemplateLoader(urlResolver, urlData));

    if (isBlank(viewCacheCapacity)) {
      viewCacheCapacity = 1;
    }
    if (isBlank(urlData)) {
      urlData = MapWrapper.create();
    }
    this.eventPlugin = new FakeEventManagerPlugin();
    var eventManager = new EventManager([this.eventPlugin], new FakeVmTurnZone());
    var viewFactory = new ViewFactory(viewCacheCapacity, eventManager, shadowDomStrategy);
    var viewHydrator = new RenderViewHydrator(eventManager, viewFactory);
    this.renderer = new DirectDomRenderer(compiler, viewFactory, viewHydrator, shadowDomStrategy);
  }

  compileRoot(componentId):Promise<ProtoViewDto> {
    return this.renderer.createHostProtoView(componentId).then( (rootProtoView) => {
      return this._compileNestedProtoViews(rootProtoView, [
        new DirectiveMetadata({
          type: DirectiveMetadata.COMPONENT_TYPE,
          id: componentId
        })
      ]);
    });
  }

  compile(componentId):Promise<ProtoViewDto> {
    var childTemplate = MapWrapper.get(this._templates, componentId);
    if (isBlank(childTemplate)) {
      throw new BaseException(`No template for component ${componentId}`);
    }
    return this.renderer.compile(childTemplate).then( (protoView) => {
      return this._compileNestedProtoViews(protoView, childTemplate.directives);
    });
  }

  _compileNestedProtoViews(protoView, directives):Promise<ProtoViewDto> {
    var childComponentRenderPvRefs = [];
    var nestedPVPromises = [];
    ListWrapper.forEach(protoView.elementBinders, (elementBinder) => {
      var nestedComponentId = null;
      ListWrapper.forEach(elementBinder.directives, (db) => {
        var directiveMeta = directives[db.directiveIndex];
        if (directiveMeta.type === DirectiveMetadata.COMPONENT_TYPE) {
          nestedComponentId = directiveMeta.id;
        }
      });
      var nestedCall;
      if (isPresent(nestedComponentId)) {
        var childTemplate = MapWrapper.get(this._templates, nestedComponentId);
        if (isBlank(childTemplate)) {
          // dynamic component
          ListWrapper.push(childComponentRenderPvRefs, null);
        } else {
          nestedCall = this.compile(nestedComponentId);
        }
      } else if (isPresent(elementBinder.nestedProtoView)) {
        nestedCall = this._compileNestedProtoViews(elementBinder.nestedProtoView, directives);
      }
      if (isPresent(nestedCall)) {
        ListWrapper.push(
          nestedPVPromises,
          nestedCall.then( (nestedPv) => {
            elementBinder.nestedProtoView = nestedPv;
            if (isPresent(nestedComponentId)) {
              ListWrapper.push(childComponentRenderPvRefs, nestedPv.render);
            }
          })
        );
      }
    });
    if (nestedPVPromises.length > 0) {
      return PromiseWrapper.all(nestedPVPromises).then((_) => {
        this.renderer.mergeChildComponentProtoViews(protoView.render, childComponentRenderPvRefs);
        return protoView;
      });
    } else {
      return PromiseWrapper.resolve(protoView);
    }
  }

}

class FakeTemplateLoader extends TemplateLoader {
  _urlData: Map<string, string>;

  constructor(urlResolver, urlData) {
    super(null, urlResolver);
    this._urlData = urlData;
  }

  load(template: ViewDefinition) {
    if (isPresent(template.template)) {
      return PromiseWrapper.resolve(DOM.createTemplate(template.template));
    }

    if (isPresent(template.absUrl)) {
      var content = this._urlData[template.absUrl];
      if (isPresent(content)) {
        return PromiseWrapper.resolve(DOM.createTemplate(content));
      }
    }

    return PromiseWrapper.reject('Load failed');
  }
}

export class FakeVmTurnZone extends VmTurnZone {
  constructor() {
    super({enableLongStackTrace: false});
  }

  run(fn) {
    fn();
  }

  runOutsideAngular(fn) {
    fn();
  }
}

export class FakeEventManagerPlugin extends EventManagerPlugin {
  _eventHandlers: Map;

  constructor() {
    super();
    this._eventHandlers = MapWrapper.create();
  }

  dispatchEvent(eventName, event) {
    MapWrapper.get(this._eventHandlers, eventName)(event);
  }

  supports(eventName: string): boolean {
    return true;
  }

  addEventListener(element, eventName: string, handler: Function, shouldSupportBubble: boolean) {
    MapWrapper.set(this._eventHandlers, eventName, handler);
    return () => {MapWrapper.delete(this._eventHandlers, eventName);}
  }
}

export class LoggingEventDispatcher extends EventDispatcher {
  log:List;
  constructor() {
    super();
    this.log = [];
  }
  dispatchEvent(
    elementIndex:number, eventName:string, locals:Map<string, any>
  ) {
    ListWrapper.push(this.log, [elementIndex, eventName, locals]);
  }
}

export class FakeEvent {
  target;
  constructor(target) {
    this.target = target;
  }
}


text:
layout:     post
title:      "token与activity与window"
subtitle:   ""
date:       2016-05-29
author:     "goIntoAction"
header-img: "img/post-bg.jpg"
tags:
    - android源码分析
---

Token是令牌的意思,我们访问网络的时候就有token的概念,其实Android系统中也有。Android中Token是ActivityRecord的静态内部类

    static class Token extends IApplicationToken.Stub {
            private final WeakReference<ActivityRecord> weakActivity;
            private final ActivityManagerService mService;
            ......
	}

从它现实了Stub,可以看出它其实也是Binder的一种。那么它的作用是什么呢?要说它的作用,需要先从ActivityRecord说起,我们知道在Android中AMS和应用是服务端与客户端的关系,在AMS帮应用维护Activity的生命周期、任务栈,所以在AMS中有一个List<ActivityRecord>来保存启动的Activity的记录,每个Activity就对应一个ActivityRecord。所以在Activity启动过程中,一个对应的ActivityRecord也会被AMS创建。
在ActivityStackSupervisor的startActivityLocked方法中会创建ActivityRecord,startActivityLocked最终调用者是AMS。

    final int startActivityLocked(IApplicationThread caller,
                Intent intent, String resolvedType, ActivityInfo aInfo,
                IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
                IBinder resultTo, String resultWho, int requestCode,
                int callingPid, int callingUid, String callingPackage,
                int realCallingPid, int realCallingUid, int startFlags, Bundle options,
                boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity,
                ActivityContainer container, TaskRecord inTask) {
            ......
        ActivityRecord r = new ActivityRecord(mService, callerApp, callingUid, callingPackage,
                    intent, resolvedType, aInfo, mService.mConfiguration, resultRecord, resultWho,
                    requestCode, componentSpecified, voiceSession != null, this, container, options);
      		......
	}
而在ActivityRecord的构造方法中又会创建Token。

	ActivityRecord(ActivityManagerService _service, ProcessRecord _caller,
            int _launchedFromUid, String _launchedFromPackage, Intent _intent, String _resolvedType,
            ActivityInfo aInfo, Configuration _configuration,
            ActivityRecord _resultTo, String _resultWho, int _reqCode,
            boolean _componentSpecified, boolean _rootVoiceInteraction,
            ActivityStackSupervisor supervisor,
            ActivityContainer container, Bundle options) {
        service = _service;
        appToken = new Token(this, service);
		......
        }

在启动Activity过程中,AMS需要与WMS通信,让WMS去创建窗口,为了能让Activity与Window关联起来,AMS会将Token传递给WMS。这一步骤调用顺序是
ActivityStackSupervisor.startActivityLocked() → ActivityStackSupervisor.startActivityUncheckedLocked() → ActivityStack.startActivityLocked()

	final void startActivityLocked(ActivityRecord r, boolean newTask,
            boolean doResume, boolean keepCurTransition, Bundle options) {
            ......
             mWindowManager.addAppToken(task.mActivities.indexOf(r), r.appToken,
                                r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen,
                                (r.info.flags & ActivityInfo.FLAG_SHOW_FOR_ALL_USERS) != 0,
                                r.userId, r.info.configChanges, task.voiceSession != null,
                                r.mLaunchTaskBehind);
			......
     }

WMS又会使用此Token构造AppWindowToken,并保存起来。

	AppWindowToken atoken = findAppWindowToken(token.asBinder());
            if (atoken != null) {
                Slog.w(TAG, "Attempted to add existing app token: " + token);
                return;
            }
    atoken = new AppWindowToken(this, token, voiceInteraction);

接着Activity启动流程会走到ActivityStackSupervisor.realStartActivityLocked。在此,AMS会通过Binder远程调用应用的ActivityThread.scheduleLaunchActivity,将Token传递到应用进程中。

final boolean realStartActivityLocked(ActivityRecord r,
            ProcessRecord app, boolean andResume, boolean checkConfig)
            throws RemoteException {
            	......
                app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
                    System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),
                    new Configuration(stack.mOverrideConfig), r.compat, r.launchedFromPackage,
                    task.voiceInteractor, app.repProcState, r.icicle, r.persistentState, results,
                    newIntents, !andResume, mService.isNextTransitionForward(), profilerInfo);
                ......
            }

至此AMS、WMS和应用进程中都有可以代表一个Activity的token,所以在三者中就可以做到activity的生命周期回调和窗口切换。例如我们在finish一个Activity的时候,ActivityThread会远程调用AMS的,其中一个参数就是token。

	public final boolean finishActivity(IBinder token, int resultCode, Intent resultData,
            boolean finishTask) {
            	......
            }

待AMS处理完后,才会回调Activity的生命周期方法。


text:
ALTER TABLE cluster ADD COLUMN IF NOT EXISTS additionalfilesystem_id bigint;

-- //@UNDO
-- SQL to undo the change goes here.
ALTER TABLE cluster DROP COLUMN IF EXISTS additionalfilesystem_id;


text:
#if HAVE_CONFIG_H
#include <config.h>
#endif

#ifdef HAVE_W32CE_SYSTEM
#include <windows.h>
#include <time.h>
#include <assert.h>

clock_t
_gcry_clock (void)
{
  assert (CLOCKS_PER_SEC == 1000);
#warning Replace by a correct implementaion.
  /* It seems that GetProcessTimes is available in the kernel but
     without a declaration.  If that fails we would need to walk over
     all threads and tally up the GetThreadTimes.  */

  return GetTickCount ();
}

#else
# error No replacement function for clock known
#endif


text:
package com.example.simple;

import java.util.Scanner;

public class ConsoleInput {
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		System.out.println("请输入一行文字");
		String consoleLine = scan.nextLine();
		System.out.println("控制台输入的是:" + consoleLine);
		scan.close();
	}
}


text:
#pragma once

#include "ParameterOptimizer.h"
#include "ParameterUpdateFunctions.h"
#include "Regularizer.h"

namespace paddle {

// Plain SGD optimization.
class SgdOptimizer : public ParameterOptimizer {
 public:
  explicit SgdOptimizer(const OptimizationConfig& optConfig)
      : ParameterOptimizer(optConfig) {
    addParameterType(PARAMETER_MOMENTUM);
  }

  virtual void startBatch(int64_t numSamplesProcessed) {
    learningRate_ = calcLearningRate(numSamplesProcessed, pass_);
  }
  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& paraConfig,
                      size_t sparseId) const {
    (void)sparseId;
    real torch_learningRate = optConfig_.learning_method() == "torch_momentum"
                                  ? 1.0 - paraConfig.momentum()
                                  : 1.0;
#ifdef PADDLE_WITH_MKLDNN
    sgdUpdate(learningRate_ * paraConfig.learning_rate() *
                  (firstTime_ ? 1.0 : torch_learningRate),
              paraConfig.momentum(),
              applyDecay_ ? paraConfig.decay_rate() : 0,
              vecs[PARAMETER_VALUE].get(),
              vecs[PARAMETER_GRADIENT].get(),
              vecs[PARAMETER_MOMENTUM].get());
#else
    vecs[PARAMETER_VALUE]->sgdUpdate(
        *vecs[PARAMETER_GRADIENT],
        *vecs[PARAMETER_MOMENTUM],
        learningRate_ * paraConfig.learning_rate() *
            (firstTime_ ? 1.0 : torch_learningRate),
        paraConfig.momentum(),
        applyDecay_ ? paraConfig.decay_rate() : 0);
#endif
  }
  virtual void finishBatch() { firstTime_ = false; }
};

// SGD optimization with sparse support.
class SparseMomentumParameterOptimizer : public ParameterOptimizer {
  /* sparse momentum optimizer

    update scheme:

    \alpha_t = \alpha_{t-1} / k
    \beta_t = \beta_{t-1} / (1 + \lambda\gamma_t)
    u_t = u_{t-1} - \alpha_t \gamma_t g_t
    v_t = v_{t-1} + \tau_{t-1} \alpha_t \gamma_t g_t
    \tau_t = \tau_{t-1} + \beta_t / \alpha_t

    where:
    k: momentum
    lambda: decay rate
    \gamma_t: learning rate at the t'th step
  */

 public:
  explicit SparseMomentumParameterOptimizer(
      const OptimizationConfig& optConfig);
  virtual void init(size_t numRows, const ParameterConfig* config);
  virtual void startBatch(int64_t numSamplesProcessed);
  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& paraConfig,
                      size_t sparseId) const;
  virtual TraverseCallback needSpecialTraversal(
      const ParameterConfig& config) const;
  virtual void finishBatch();

 private:
  real alpha_;
  real beta_;
  real tau_;
  real gamma_;
  real threshold_;
  real momentum_;
  real decayRate_;

 protected:
  int64_t timer_;
  mutable std::vector<int64_t> t0Vec_;
  bool isParameterSparse_;
};

/*
 * AdaGrad optimization.
 * http://www.magicbroom.info/Papers/DuchiHaSi10.pdf
 */
class AdagradParameterOptimizer : public ParameterOptimizer {
 public:
  explicit AdagradParameterOptimizer(const OptimizationConfig& optConfig)
      : ParameterOptimizer(optConfig) {
    addParameterType(PARAMETER_MOMENTUM);
    addParameterType(PARAMETER_GRADIENT_SQURESUM);
    addParameterType(PARAMETER_GRADIENT_SQURESUM1);
    addParameterType(PARAMETER_LEARNING_RATE);
    numUpdates_ = 0;
  }

  virtual void startBatch(int64_t numSamplesProcessed) {
    (void)numSamplesProcessed;
    ++numUpdates_;
  }
  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& config,
                      size_t sparseId) const;
  virtual TraverseCallback needSpecialTraversal(
      const ParameterConfig& config) const;

 protected:
  int64_t numUpdates_;
  static const int64_t kMaxNumAccumulates = 16384;
};

/*
 * AdaDelta Optimization.
 * http://www.matthewzeiler.com/pubs/googleTR2012/googleTR2012.pdf
 */
class AdaDeltaParameterOptimizer : public ParameterOptimizer {
 public:
  explicit AdaDeltaParameterOptimizer(const OptimizationConfig& optConfig)
      : ParameterOptimizer(optConfig) {
    addParameterType(PARAMETER_MOMENTUM);
    addParameterType(PARAMETER_GRADIENT_SQURESUM);
    addParameterType(PARAMETER_GRADIENT_SQURESUM1);
    addParameterType(PARAMETER_LEARNING_RATE);
    rou_ = optConfig.ada_rou();
    epsilon_ = optConfig.ada_epsilon();
  }

  virtual void startBatch(int64_t numSamplesProcessed) {
    learningRate_ = calcLearningRate(numSamplesProcessed, pass_);
  }

  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& config,
                      size_t sparseId) const;

 protected:
  real rou_;
  real epsilon_;
};

// RMSProp Parameter Optimization.
class RMSPropParameterOptimizer : public ParameterOptimizer {
 public:
  explicit RMSPropParameterOptimizer(const OptimizationConfig& optConfig)
      : ParameterOptimizer(optConfig) {
    addParameterType(PARAMETER_MOMENTUM);
    addParameterType(PARAMETER_GRADIENT_SQURESUM1);
    addParameterType(PARAMETER_GRADIENT_SQURESUM);
    addParameterType(PARAMETER_LEARNING_RATE);
    rou_ = optConfig.ada_rou();
    epsilon_ = optConfig.ada_epsilon();
  }

  virtual void init(size_t numRows, const ParameterConfig* config) {
    t0Vec_.resize(numRows);
    t0Vec_.assign(t0Vec_.size(), 0);
    timer_ = 0;
  }

  virtual void startBatch(int64_t numSamplesProcessed) {
    learningRate_ = calcLearningRate(numSamplesProcessed, pass_);
  }
  virtual void finishBatch() { timer_++; }

  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& config,
                      size_t sparseId) const;

 protected:
  real rou_;
  real epsilon_;

  /**
   *  counting batches, donot need catch up with
   *  t(timer_) is current time,
   *  t0(t0Vec_) are last occur time of i rows.
   *  if one block is update by multi threads,
   *  caller should hash sparse ids to avoid write conflict in t0Vec_.
   */
  int64_t timer_;
  mutable std::vector<int64_t> t0Vec_;
};

// Decayed AdaGrad Optimization.
class DecayedAdagradParameterOptimizer : public ParameterOptimizer {
 public:
  explicit DecayedAdagradParameterOptimizer(const OptimizationConfig& optConfig)
      : ParameterOptimizer(optConfig) {
    addParameterType(PARAMETER_MOMENTUM);
    addParameterType(PARAMETER_GRADIENT_SQURESUM);
    addParameterType(PARAMETER_LEARNING_RATE);
    rou_ = optConfig.ada_rou();
    epsilon_ = optConfig.ada_epsilon();
  }

  virtual void init(size_t numRows, const ParameterConfig* config) {
    t0Vec_.resize(numRows);
    t0Vec_.assign(t0Vec_.size(), 0);
    timer_ = 0;
  }

  virtual void startBatch(int64_t numSamplesProcessed) {
    learningRate_ = calcLearningRate(numSamplesProcessed, pass_);
  }
  virtual void finishBatch() { timer_++; }

  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& config,
                      size_t sparseId) const;

 protected:
  real rou_;
  real epsilon_;

  /**
   *  counting batches, donot need catch up with
   *  t(timer_) is current time,
   *  t0(t0Vec_) are last occur time of i rows.
   *  if one block is update by multi threads,
   *  caller should hash sparse ids to avoid write conflict in t0Vec_.
   */
  int64_t timer_;
  mutable std::vector<int64_t> t0Vec_;
};

/**
 * Adam Optimizer.
 * Reference Paper: http://arxiv.org/abs/1412.6980 Algorithm 1
 */
class AdamParameterOptimizer : public ParameterOptimizer {
 public:
  explicit AdamParameterOptimizer(const OptimizationConfig& optConfig)
      : ParameterOptimizer(optConfig),
        beta1_(optConfig.adam_beta1()),
        beta2_(optConfig.adam_beta2()),
        epsilon_(optConfig.adam_epsilon()),
        step_(1),
        learningRate_(optConfig.learning_rate()) {
    addParameterType(PARAMETER_MOMENTUM);
    addParameterType(PARAMETER_SECOND_MOMENTUM);
  }

  virtual void startBatch(int64_t numSamplesProcessed) {
    learningRate_ = calcLearningRate(numSamplesProcessed, pass_);
  }

  virtual void finishBatch() { ++step_; }

  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& config,
                      size_t sparseId) const;

 protected:
  real beta1_;
  real beta2_;
  real epsilon_;
  int64_t step_;
  real learningRate_;
};

/**
 * AdaMax Optimizer.
 * Reference Paper: http://arxiv.org/abs/1412.6980 Algorithm 2
 */
class AdamaxParameterOptimizer : public ParameterOptimizer {
 public:
  explicit AdamaxParameterOptimizer(const OptimizationConfig& optConfig)
      : ParameterOptimizer(optConfig),
        beta1_(optConfig.adam_beta1()),
        beta2_(optConfig.adam_beta2()),
        step_(1),
        learningRate_(optConfig.learning_rate()) {
    addParameterType(PARAMETER_MOMENTUM);
    addParameterType(PARAMETER_WEIGHTED_INFINITY_NORM);
  }

  virtual void finishBatch() { ++step_; }

  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& config,
                      size_t sparseId) const;

 protected:
  real beta1_;
  real beta2_;
  int64_t step_;
  real learningRate_;
};

// Used in pserver,
// when PARAMETER_DELTA stores in PARAMETER_GRADIENT.
class AddOptimizer : public ParameterOptimizer {
 public:
  explicit AddOptimizer(const OptimizationConfig& optConfig)
      : ParameterOptimizer(optConfig) {}

  virtual void startBatch(int64_t numSamplesProcessed) {
    // learningRate required by regularizer
    learningRate_ = calcLearningRate(numSamplesProcessed, pass_);
  }
  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& paraConfig,
                      size_t sparseId) const {
    vecs[PARAMETER_VALUE]->add(*vecs[PARAMETER_GRADIENT],
                               optConfig_.delta_add_rate());
  }
};

// A optimizer which does nothing.
class DummyOptimizer : public ParameterOptimizer {
 public:
  explicit DummyOptimizer(const OptimizationConfig& optConfig)
      : ParameterOptimizer(optConfig) {}

  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& paraConfig,
                      size_t sparseId) const {}
};

// Do gradient clipping before sgd update
class OptimizerWithGradientClipping : public ParameterOptimizer {
 public:
  OptimizerWithGradientClipping(const OptimizationConfig& optConfig,
                                ParameterOptimizer* optimizer)
      : ParameterOptimizer(optConfig), optimizer_(optimizer) {
    parameterTypes_ = optimizer_->getParameterTypes();
  }

  virtual void init(size_t numRows, const ParameterConfig* config) {
    optimizer_->init(numRows, config);
  }

  virtual void startPass() { optimizer_->startPass(); }
  virtual void finishPass() { optimizer_->finishPass(); }

  virtual void startBatch(int64_t numSamplesProcessed) {
    optimizer_->startBatch(numSamplesProcessed);
    learningRate_ = optimizer_->getLearningRate();
  }
  virtual void finishBatch() { optimizer_->finishBatch(); }

  virtual TraverseCallback needSpecialTraversal(
      const ParameterConfig& config) const {
    return optimizer_->needSpecialTraversal(config);
  }
  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& config,
                      size_t sparseId) const;

  virtual void setNoDecay() { optimizer_->setNoDecay(); }

 protected:
  std::unique_ptr<ParameterOptimizer> optimizer_;
};

}  // namespace paddle