text:
var user = require('../model/user');
var logger = require('../util/logger');

export class AuthSetup {
    public static isLocal(): boolean {
        return(process.env.ENVIRONMENT === "local")
    }

    public static logout(req: any) {
        if (AuthSetup.isLocal()) {
            let passportStub = require('passport-stub');
            passportStub.logout();
        } else {
            req.logout();
        }
    }

    public static setAuth(app: any): void {
        // encapsulate the authentication setup and strategy.
        // disable for environment "local"
        let passport = require('passport');

        // Passport session setup.
        //   To support persistent login sessions, Passport needs to be able to
        //   serialize users into and deserialize users out of the session.  Typically,
        //   this will be as simple as storing the user ID when serializing, and finding
        //   the user by ID when deserializing.  However, since this example does not
        //   have a database of user records, the complete Google profile is
        //   serialized and deserialized.
        passport.serializeUser(function (user, done) {
            logger.info('serialize user: ' + JSON.stringify(user));
            done(null, user);
        });

        passport.deserializeUser(function (obj, done) {
            logger.info('deserialize user: ' + JSON.stringify(obj));
            done(null, obj);
        });

        //set auth strategy
        if (AuthSetup.isLocal()) {
            // bypass authentication
            logger.info("authSetup only local, environment = ", process.env.ENVIRONMENT)
            let passportStub = require('passport-stub');
            passportStub.install(app);
        } else {
            logger.info("authSetup not local, environment = ", process.env.ENVIRONMENT)
            var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;

            // Use the GoogleStrategy within Passport.
            //   Strategies in Passport require a `verify` function, which accept
            //   credentials (in this case, an accessToken, refreshToken, and Google
            //   profile), and invoke a callback with a user object.
            passport.use(new GoogleStrategy({
                clientID: process.env.GOOGLE_CLIENT_ID,
                clientSecret: process.env.GOOGLE_CLIENT_SECRET,
                callbackURL: process.env.GOOGLE_RETURN_URL_HOST + '/auth/google/callback'
            },
                function (accessToken, refreshToken, profile, done) {
                    logger.info('callback from google: profile = %s', JSON.stringify(profile));
                    user.findOrCreate({ profile: profile }, function (err, user) {
                        return done(err, user);
                    });
                }
            ));
        }
        // Initialize Passport!  Also use passport.session() middleware, to support
        // persistent login sessions (recommended).
        app.use(passport.initialize());
        app.use(passport.session());
    }
}


text:
<!doctype html>

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

		<canvas id="canvas" width="1280" height="720" oncontextmenu="event.preventDefault()"></canvas>

		{{{ SCRIPT }}}

redpajama_set_name: RedPajamaGithub


text:
"use strict";
var base_1 = require('../../../unitTesting/grid/base');
var sorting_1 = require('./sorting');
var constants_1 = require('../../constants');
describe('Sorting', function () {
    function BucketOwner() { }
    var h;
    var columns;
    var getBucket = function (options) {
        return new sorting_1.SortingBucket(options);
    };
    var getComponent = function (codeBased, domBased) {
        var gridOptions = h.getGridOptions(codeBased, domBased + "<columns><column field=\"FirstName\"></column><column field=\"LastName\"></column><column field=\"Age\"></column></columns>");
        gridOptions.columns = [columns.age, columns.firstName, columns.lastName];
        var subject = new sorting_1.SortingComponent(gridOptions, h.gridInternals, h.dataSource);
        subject.tryEnable();
        return subject;
    };
    var mode = constants_1.sortingMode;
    beforeEach(function () {
        h = new base_1.GridTestHelpers();
        h.beforeEach();
        columns = {
            firstName: h.getColumn({
                field: 'FirstName'
            }),
            lastName: h.getColumn({
                field: 'LastName'
            }),
            age: h.getColumn({
                field: 'Age'
            })
        };
    });
    describe('component', function () {
        var component;
        beforeEach(function () {
            component = undefined;
        });
        describe('should start with', function () {
            it('adding main bucket', function () {
                component = getComponent({ sorting: true }, "");
                expect(component.buckets.length).toBe(1);
                expect(component.buckets[0].owner).toEqual(sorting_1.SortingComponent);
                expect(component.buckets[0].order).toBe(0);
            });
        });
        describe('should be able to save state', function () {
            it("", function () {
                var state = {};
                component = getComponent({ sorting: { mode: mode.multiple } }, "");
                var bucket = component.getBucketByOwner(sorting_1.SortingComponent);
                bucket.sortBy(columns.firstName, 0, 'desc');
                bucket.sortBy(columns.lastName, 1, 'asc');
                component.saveState(state);
                expect(state.columns).toEqual([{
                        id: columns.firstName.getUniqueId(),
                        direction: bucket.getSortingDirection(columns.firstName)
                    }, {
                        id: columns.lastName.getUniqueId(),
                        direction: bucket.getSortingDirection(columns.lastName)
                    }]);
            });
            it("and uses SortingComponent's bucket", function () {
                var state = {};
                component = getComponent({ sorting: true }, "");
                var stub = sinon.stub(component, 'getBucketByOwner').returns({ columns: [] });
                component.saveState(state);
                expect(stub.calledOnce).toBe(true);
                expect(stub.calledWithExactly(sorting_1.SortingComponent)).toBe(true);
            });
        });
        describe('should be able to load state', function () {
            it('', function () {
                component = getComponent({ sorting: { mode: mode.multiple } }, "");
                var bucket = component.getBucketByOwner(sorting_1.SortingComponent);
                component.loadState({
                    columns: [{
                            id: columns.lastName.getUniqueId(),
                            direction: 'desc'
                        }, {
                            id: columns.age.getUniqueId(),
                            direction: 'asc'
                        }]
                });
                expect(bucket.getSortingDirection(columns.lastName)).toBe('desc');
                expect(bucket.getSortingDirection(columns.age)).toBe('asc');
                expect(columns.lastName.state.sortOrder).toBeLessThan(columns.age.state.sortOrder);
                expect(h.gridInternals.refresh.calledOnce).toBe(true);
            });
            it('and work in case if provided state is empty', function () {
                component = getComponent({ sorting: true }, "");
                component.loadState({ columns: [] });
                expect(h.gridInternals.refresh.called).toBe(false);
                component.loadState({});
                expect(h.gridInternals.refresh.called).toBe(false);
                component.loadState(undefined);
                expect(h.gridInternals.refresh.called).toBe(false);
                component.loadState(null);
                expect(h.gridInternals.refresh.called).toBe(false);
            });
        });
        describe('should be able to create options', function () {
            it('from code based settings', function () {
                component = getComponent({ sorting: { mode: mode.multiple } }, "");
                expect(component.options.mode).toBe(mode.multiple);
                component = getComponent({ sorting: { mode: mode.single } }, "");
                expect(component.options.mode).toBe(mode.single);
            });
            it('from code based settings', function () {
                component = getComponent({}, "<sorting mode=\"multiple\"></sorting>");
                expect(component.options.mode).toBe(mode.multiple);
                component = getComponent({}, "<sorting mode=\"single\"></sorting>");
                expect(component.options.mode).toBe(mode.single);
            });
            it('use default options as a fallback plan', function () {
                component = getComponent({ sorting: true }, "");
                expect(component.options.mode).toBe(component.defaultOptions.mode);
            });
            it('when configuration is not available', function () {
                component = getComponent({}, "");
                expect(component.options).toBeFalsy();
            });
        });
        describe('on data read should', function () {
            it('use all buckets to create params', function () {
                var params = {};
                component = getComponent({ sorting: true }, "");
                var componentBucket = component.getBucketByOwner(sorting_1.SortingComponent);
                componentBucket.sortBy(columns.age, 0, 'desc');
                var customBucket = component.addBucket(BucketOwner, -1, {
                    alwaysSorted: true,
                    mode: mode.multiple
                });
                customBucket.sortBy(columns.firstName, 0, 'asc');
                customBucket.sortBy(columns.lastName, 1, 'desc');
                h.dataSource.subscribe.emit('DataRead', params);
                expect(params.sortBy.length).toBe(3);
                expect(params.sortBy[0].column).toBe(columns.firstName);
                expect(params.sortBy[0].direction).toBe('asc');
                expect(params.sortBy[1].column).toBe(columns.lastName);
                expect(params.sortBy[1].direction).toBe('desc');
                expect(params.sortBy[2].column).toBe(columns.age);
                expect(params.sortBy[2].direction).toBe('desc');
            });
            it('work without any sorting applies', function () {
                var params = {};
                component = getComponent({ sorting: true }, "");
                h.dataSource.subscribe.emit('DataRead', params);
                expect(params.sortBy.length).toBe(0);
            });
        });
        describe('onColumnClicked method should', function () {
            it('start sorting with default sorting bucket', function () {
                component = getComponent({ sorting: true }, "");
                columns.firstName.other.sortable = true;
                component.sortOrder = 99;
                component._onColumnClicked(columns.firstName);
                expect(columns.firstName.state.sortOrder).toBe(100);
                expect(columns.firstName.state.sortByDirection).toBe('asc');
                expect(h.gridInternals.refresh.calledOnce).toBe(true);
            });
            it('go to next sorting state if column already sorted with default sorting bucket', function () {
                component = getComponent({ sorting: true }, "");
                columns.firstName.other.sortable = true;
                component.sortOrder = 99;
                component._onColumnClicked(columns.firstName);
                component._onColumnClicked(columns.firstName);
                expect(columns.firstName.state.sortOrder).toBe(100);
                expect(columns.firstName.state.sortByDirection).toBe('desc');
                expect(h.gridInternals.refresh.calledTwice).toBe(true);
            });
            it('do nothing if column is not sortable', function () {
                component = getComponent({ sorting: true }, "");
                var test = function (sortable) {
                    columns.firstName.other.sortable = sortable;
                    component._onColumnClicked(columns.firstName);
                    expect(h.gridInternals.refresh.called).toBe(false);
                };
                test('false');
                test(undefined);
                test(false);
            });
        });
        describe('addBucket method', function () {
            it('should add bucket', function () {
                component = getComponent({ sorting: true }, "");
                var options = {
                    alwaysSorted: true,
                    mode: mode.multiple
                };
                var bucket = component.addBucket(BucketOwner, 0, options);
                expect(component.buckets.length).toBe(2);
                expect(component.buckets[1].bucket).toBe(bucket);
                expect(component.buckets[1].owner).toBe(BucketOwner);
                expect(component.buckets[1].order).toBe(0);
            });
            it('should refresh order', function () {
                component = getComponent({ sorting: true }, "");
                var options = {
                    alwaysSorted: true,
                    mode: mode.multiple
                };
                var bucket1 = component.addBucket(BucketOwner, -1, options);
                var bucket2 = component.addBucket(BucketOwner, 1, options);
                expect(component.buckets.length).toBe(3);
                expect(component.buckets[0].bucket).toBe(bucket1);
                expect(component.buckets[2].bucket).toBe(bucket2);
            });
        });
        describe('getBucketByColumn method', function () {
            it('should get bucket which contains given column', function () {
                component = getComponent({ sorting: true }, "");
                var bucket = component.addBucket(BucketOwner, 1, {
                    alwaysSorted: true,
                    mode: mode.single
                });
                bucket.addColumn(columns.lastName);
                var result = component.getBucketByColumn(columns.lastName);
                expect(result).toBe(bucket);
            });
            it('should return undefined if bucket not found', function () {
                component = getComponent({ sorting: true }, "");
                var result = component.getBucketByColumn(columns.lastName);
                expect(result).toBeUndefined();
            });
        });
        describe('getBucketByOwner method', function () {
            it('should get bucket using given owner', function () {
                component = getComponent({ sorting: true }, "");
                var bucket = component.addBucket(BucketOwner, 1, {
                    alwaysSorted: true,
                    mode: mode.single
                });
                var result = component.getBucketByOwner(BucketOwner);
                expect(result).toBe(bucket);
            });
            it('should return undefined if bucket not found', function () {
                component = getComponent({ sorting: true }, "");
                var result = component.getBucketByOwner(BucketOwner);
                expect(result).toBeUndefined();
            });
        });
        it('should unregister correctly', function () {
            component = getComponent({ sorting: true }, "");
            expect(h.gridInternals.subscribe.subscribers.length).toBeGreaterThan(0);
            expect(h.dataSource.subscribe.subscribers.length).toBeGreaterThan(0);
            component.stop();
            expect(h.gridInternals.subscribe.subscribers.length).toBe(0);
            expect(h.dataSource.subscribe.subscribers.length).toBe(0);
        });
    });
    describe('bucket', function () {
        var bucket;
        var validate = function (column, index, order, direction) {
            expect(bucket.columns[index]).toBe(column);
            expect(column.state.sortOrder).toBe(order);
            expect(bucket.getSortingDirection(column)).toBe(direction);
            expect(column.hasClass('m-grid-sort-' + direction)).toBe(true);
            expect(column.hasClass('m-grid-sort-' + (direction === 'asc' ? 'desc' : 'asc'))).toBe(false);
        };
        describe('sortBy method should', function () {
            it('apply sorting to the column with multiple mode', function () {
                bucket = getBucket({ mode: mode.multiple, alwaysSorted: undefined });
                bucket.sortBy(columns.lastName, 3, 'desc');
                bucket.sortBy(columns.firstName, 0, 'asc');
                bucket.sortBy(columns.age, 1, 'asc');
                expect(bucket.columns.length).toBe(3);
                validate(columns.lastName, 0, 3, 'desc');
                validate(columns.firstName, 1, 0, 'asc');
                validate(columns.age, 2, 1, 'asc');
            });
            it('apply sorting to the column with single mode', function () {
                bucket = getBucket({ mode: mode.single, alwaysSorted: undefined });
                bucket.sortBy(columns.lastName, 3, 'desc');
                bucket.sortBy(columns.firstName, 0, 'asc');
                bucket.sortBy(columns.age, 1, 'asc');
                expect(bucket.columns.length).toBe(1);
                validate(columns.age, 0, 1, 'asc');
            });
            it('use previous sorted direction as default if has been already sorted', function () {
                bucket = getBucket({ mode: mode.single, alwaysSorted: undefined });
                bucket.sortBy(columns.lastName, 1, 'desc');
                bucket.sortBy(columns.lastName, 3, undefined);
                validate(columns.lastName, 0, 3, 'desc');
            });
            it('use "asc" direction if other not specified', function () {
                bucket = getBucket({ mode: mode.single, alwaysSorted: undefined });
                columns.lastName.state.sortOrder = 1;
                bucket.sortBy(columns.lastName, 3, undefined);
                validate(columns.lastName, 0, 3, 'asc');
            });
        });
        describe('nextSortingDirectionOn method should', function () {
            it('switch from "asc" to "desc" direction', function () {
                bucket = getBucket({ mode: mode.single, alwaysSorted: undefined });
                bucket.sortBy(columns.firstName, 1, 'asc');
                bucket.nextSortingDirectionOn(columns.firstName);
                expect(bucket.getSortingDirection(columns.firstName)).toBe('desc');
            });
            it('switch from "desc" to "asc" direction if alwaysSorted option is enabled', function () {
                bucket = getBucket({ mode: mode.single, alwaysSorted: true });
                bucket.sortBy(columns.firstName, 1, 'desc');
                bucket.nextSortingDirectionOn(columns.firstName);
                expect(bucket.getSortingDirection(columns.firstName)).toBe('asc');
            });
            it('switch clear from "desc" direction if alwaysSorted option is disabled', function () {
                bucket = getBucket({ mode: mode.single, alwaysSorted: false });
                bucket.sortBy(columns.firstName, 1, 'desc');
                bucket.nextSortingDirectionOn(columns.firstName);
                expect(!!bucket.getSortingDirection(columns.firstName)).toBe(false);
            });
            it('do nothing if column is not in the bucket', function () {
                bucket = getBucket({ mode: mode.single, alwaysSorted: false });
                bucket.nextSortingDirectionOn(columns.firstName);
                expect(bucket.columns.length).toBe(0);
                expect(columns.firstName.headerClass).toBe('');
            });
        });
        it('hasSortingApplied method should determine if sorting has been applied to the column', function () {
            bucket = getBucket({ mode: mode.single, alwaysSorted: false });
            bucket.sortBy(columns.firstName, 1, 'desc');
            bucket.sortBy(columns.age, 2, 'asc');
            expect(bucket.hasSortingApplied(columns.firstName)).toBe(false);
            expect(bucket.hasSortingApplied(columns.lastName)).toBe(false);
            expect(bucket.hasSortingApplied(columns.age)).toBe(true);
        });
        describe('addColumn method should', function () {
            it('add new column', function () {
                bucket = getBucket({ mode: mode.single, alwaysSorted: undefined });
                bucket.addColumn(columns.age);
                expect(bucket.columns.length).toBe(1);
                expect(bucket.columns).toContain(columns.age);
            });
            it('do nothing if column has been already added', function () {
                bucket = getBucket({ mode: mode.single, alwaysSorted: undefined });
                bucket.addColumn(columns.age);
                bucket.addColumn(columns.age);
                expect(bucket.columns.length).toBe(1);
                expect(bucket.columns).toContain(columns.age);
            });
        });
        describe('removeColumn method should', function () {
            it('remove existing column', function () {
                bucket = getBucket({ mode: mode.single, alwaysSorted: undefined });
                bucket.addColumn(columns.age);
                bucket.removeColumn(columns.age);
                expect(bucket.columns.length).toBe(0);
                expect(bucket.columns).not.toContain(columns.age);
            });
            it('do nothing if column is not in the bucket', function () {
                bucket = getBucket({ mode: mode.single, alwaysSorted: undefined });
                bucket.removeColumn(columns.age);
                expect(bucket.columns.length).toBe(0);
                expect(bucket.columns).not.toContain(columns.age);
            });
        });
        describe('hasColumn method should', function () {
            it('return true if column in the bucket', function () {
                bucket = getBucket({ mode: mode.single, alwaysSorted: undefined });
                bucket.addColumn(columns.age);
                var result = bucket.hasColumn(columns.age);
                expect(result).toBe(true);
            });
            it('return false if column is not in the bucket', function () {
                bucket = getBucket({ mode: mode.single, alwaysSorted: undefined });
                var result = bucket.hasColumn(columns.age);
                expect(result).toBe(false);
            });
        });
    });
});


text:
import { StandardArticle } from "@artsy/reaction/dist/Components/Publishing/Fixtures/Articles"
import { ImageCollection } from "@artsy/reaction/dist/Components/Publishing/Fixtures/Components"
import {
  ArticleImage,
  EditImage,
} from "client/apps/edit/components/content/sections/images/components/edit_image"
import { mount } from "enzyme"
import { extend } from "lodash"
import React from "react"
import { DragSource, DragSourceContainer } from "../drag_source"

describe("DragSource", () => {
  let props
  const image: ArticleImage = extend(ImageCollection[0], { type: "image" })

  const imageProps = {
    article: StandardArticle,
    image,
    index: 0,
    isHero: false,
    editing: false,
    section: ImageCollection,
    width: 200,
    onChangeHeroAction: jest.fn(),
    onChangeSectionAction: jest.fn(),
    progress: 0,
  }

  const getWrapper = (passedProps = props) => {
    return mount(
      <DragSource {...passedProps}>
        <EditImage {...imageProps} />
      </DragSource>
    )
  }

  beforeEach(() => {
    props = {
      isActiveSource: false,
      isDraggable: true,
      index: 2,
      onDragEnd: jest.fn(),
      setDragSource: jest.fn(),
    }
  })

  it("Renders children", () => {
    const component = getWrapper()
    expect(component.find(EditImage)).toHaveLength(1)
  })

  it("Calls #setDragSource onDragStart", () => {
    const component = getWrapper()
    component.find(DragSourceContainer).simulate("dragStart")
    expect(props.setDragSource).toBeCalled()
  })

  it("Calls props.onDragEnd onDragEnd", () => {
    const component = getWrapper()
    component.find(DragSourceContainer).simulate("dragEnd")
    expect(props.onDragEnd).toBeCalled()
  })

  describe("#setDragSource", () => {
    it("Calculates dragStartY and dragSourceHeight", () => {
      const component = getWrapper().instance() as DragSource
      component.setDragSource({ clientY: 250 })
      expect(props.setDragSource).toBeCalledWith(props.index, 0, 450)
    })

    it("Does nothing if isDraggable is false", () => {
      props.isDraggable = false
      const component = getWrapper().instance() as DragSource
      component.setDragSource({ clientY: 250 })
      expect(props.setDragSource).not.toBeCalled()
    })
  })
})


text:
package com.danialgoodwin.globaloverlay;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.WindowManager;

/** All the boilerplate for setting up a nice floating overlay that stays above all apps and
 * Activities. Overlays can be removed by the user dragging it down to the remove view at the
 * bottom, or by stopping the service.
 *
 * Currently, only supports one overlay view. And, when the user removes the view,
 * the service will be destroyed.
 *
 * Note: Currently, the `mOnLongClickListener` is not implemented. It might be in the future
 * though. Feel free to send a pull request. */
public abstract class GlobalOverlayService extends Service {
    private static final String LOGCAT_TAG = "GlobalOverlayService";
    private static void log(String message) {
        Log.d(LOGCAT_TAG, message);
    }

    private WindowManager mWindowManager;
    private View mRemoveView;
    private View mOverlayView;
    @SuppressWarnings("FieldCanBeLocal")
    private View.OnTouchListener mOnTouchListener;
    private View.OnClickListener mOnClickListener;
    private View.OnLongClickListener mOnLongClickListener;
    private OnRemoveOverlayListener mOnRemoveOverlayListener;
    private WindowManager.LayoutParams mOverlayLayoutParams;

    @Override
    public void onCreate() {
        super.onCreate();
        mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        mRemoveView = onGetRemoveView();
        setupRemoveView(mRemoveView);
    }

    @Override
    public void onDestroy() {
        // Views are automatically removed once service is through.
//        removeOverlayView(mOverlayView);
//        if (mRemoveView != null) { mWindowManager.removeView(mRemoveView); }
        super.onDestroy();
    }

    // Override this to bind.
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /** Return the view to use for the "remove view" that appears at the bottom of the screen.
     * Override this to change the image for the remove view. Returning null will throw a
     * NullPointerException in a subsequent method.*/
    @SuppressLint("InflateParams")
    protected View onGetRemoveView() {
        return LayoutInflater.from(this).inflate(R.layout.overlay_remove_view, null);
    }

    /** Sets this view to the bottom of the screen and only visible when user is dragging an
     * overlay view. This modifies the instance passed in. */
    private void setupRemoveView(View removeView) {
        removeView.setVisibility(View.GONE);
        mWindowManager.addView(removeView, newWindowManagerLayoutParamsForRemoveView());
    }

    /** Add a global floating view.
     *
     * @param view the view to overlay across all apps and activities
     * @param onClickListener get notified of a click, set null to ignore
     */
    public final void addOverlayView(View view, View.OnClickListener onClickListener) {
        addOverlayView(view, onClickListener, null, null);
    }

    /** Add a global floating view.
     *
     * @param view the view to overlay across all apps and activities
     * @param onClickListener get notified of a click, set null to ignore
     * @param onLongClickListener not implemented yet, just set as null
     * @param onRemoveOverlayListener get notified when overlay is removed (not from a destroyed service though)
     */
    public final void addOverlayView(View view, View.OnClickListener onClickListener,
            View.OnLongClickListener onLongClickListener, OnRemoveOverlayListener onRemoveOverlayListener) {
        mOverlayView = view;
        mOnClickListener = onClickListener;
        mOnLongClickListener = onLongClickListener;
        mOnRemoveOverlayListener = onRemoveOverlayListener;
        mOverlayLayoutParams = newWindowManagerLayoutParams();

        mOnTouchListener = newSimpleOnTouchListener();
        mOverlayView.setOnTouchListener(mOnTouchListener);

        mWindowManager.addView(mOverlayView, newWindowManagerLayoutParams());
    }

    /** Manually remove an overlay without destroying the service. */
    public final void removeOverlayView(View view) {
        removeOverlayView(view, false);
    }

    /** Remove a overlay without destroying the service. */
    public final void removeOverlayView(View view, boolean isRemovedByUser) {
        if (view != null) {
            if (mOnRemoveOverlayListener != null) {
                mOnRemoveOverlayListener.onRemoveOverlay(view, isRemovedByUser);
            }
            mWindowManager.removeView(view);
        }
    }

    /** Provides the drag ability for the overlay view. This touch listener
     * allows user to drag the view anywhere on screen. */
    private View.OnTouchListener newSimpleOnTouchListener() {
        return new View.OnTouchListener() {
//            private long timeStart; // Maybe use in the future, with ViewConfiguration's getLongClickTime or whatever it is called.
            private int initialX;
            private int initialY;
            private float initialTouchX;
            private float initialTouchY;
            private int[] overlayViewLocation = {0,0};

            private boolean isOverRemoveView;
            private int[] removeViewLocation = {0,0};

            private final int touchSlop = ViewConfiguration.get(getBaseContext()).getScaledTouchSlop();

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
//                        timeStart = System.currentTimeMillis();
                        initialX = mOverlayLayoutParams.x;
                        initialY = mOverlayLayoutParams.y;
                        initialTouchX = event.getRawX();
                        initialTouchY = event.getRawY();

                        mRemoveView.setVisibility(View.VISIBLE);
                        return true;
                    case MotionEvent.ACTION_MOVE:
                        mOverlayLayoutParams.x = initialX + (int) (event.getRawX() - initialTouchX);
                        mOverlayLayoutParams.y = initialY + (int) (event.getRawY() - initialTouchY);
                        mWindowManager.updateViewLayout(mOverlayView, mOverlayLayoutParams);

                        mOverlayView.getLocationOnScreen(overlayViewLocation);
                        mRemoveView.getLocationOnScreen(removeViewLocation);
                        isOverRemoveView = isPointInArea(overlayViewLocation[0], overlayViewLocation[1],
                                removeViewLocation[0], removeViewLocation[1], mRemoveView.getWidth());
                        if (isOverRemoveView) {
                            // TODO: Maybe, make it look like the overlay view is perfectly on the remove view.
                        }

                        return true;
                    case MotionEvent.ACTION_UP:
                        if (isOverRemoveView) {
                            removeOverlayView(v, true);
                            // Not sure if setting to null is the best way to handle this. Though,
                            // currently it's needed to prevent a `IllegalArgumentException ... not attached to window manager`
//                            v = null;
                            stopSelf();
                        } else {
                            if (mOnClickListener != null && Math.abs(initialTouchY - event.getRawY()) <= touchSlop) {
                                mOnClickListener.onClick(v);
                            }
                        }

                        mRemoveView.setVisibility(View.GONE);
                        return true;
                    case MotionEvent.ACTION_CANCEL:
                        mRemoveView.setVisibility(View.GONE);
                        return true;
                }
                return false;
            }
        };
    }

    /** Return true if point (x1,y1) is in the square defined by (x2,y2) with radius, otherwise false.  */
    private boolean isPointInArea(int x1, int y1, int x2, int y2, int radius) {
//        log("isPointInArea(). x1=" + x1 + ",y1=" + y1);
//        log("isPointInArea(). x2=" + x2 + ",y2=" + y2 + ",radius=" + radius);
        return x1 >= x2 - radius && x1 <= x2 + radius && y1 >= y2 - radius && y1 <=  y2 + radius;
    }

    /** Returns the default layout params for the overlay views. */
    private static WindowManager.LayoutParams newWindowManagerLayoutParams() {
        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_PHONE,
//                WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT);
        params.gravity = Gravity.CENTER_HORIZONTAL | Gravity.START;
        return params;
    }

    private static WindowManager.LayoutParams newWindowManagerLayoutParamsForRemoveView() {
        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_PHONE,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
                        WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH |
                        WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
                PixelFormat.TRANSLUCENT);
        params.gravity = Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM;
        params.y = 56;
        return params;
    }

    /** Interface definition for when an overlay view has been removed. */
    public static interface OnRemoveOverlayListener {
        /** This overlay has been removed.
         * @param v the removed view
         * @param isRemovedByUser true if user manually removed view, false if removed another way */
        public void onRemoveOverlay(View v, boolean isRemovedByUser);
    }

}


text:
<?php
namespace PhpLego\Yii2\AsyncMailer;
use React\EventLoop\Factory;
use React\EventLoop\LoopInterface;
use yii\console\Controller;

abstract class DaemonCommand extends Controller
{
    /** @var LoopInterface */
    protected $loop;
    public function init()
    {
        parent::init();
        $this->loop = Factory::create();
    }
    public function actionDaemon()
    {
        $this->prepare();
        $this->loop->run();
    }
    abstract public function prepare();
}


text:
@interface CocoaLabel : NSTextField {
@public
  phoenix::Label* label;
}
-(id) initWith:(phoenix::Label&)label;
@end

namespace phoenix {

struct pLabel : public pWidget {
  Label& label;
  CocoaLabel* cocoaLabel = nullptr;

  Size minimumSize();
  void setGeometry(Geometry geometry);
  void setText(string text);

  pLabel(Label& label) : pWidget(label), label(label) {}
  void constructor();
  void destructor();
};

}


text:
(function() {
	var dependencies = [ "jquery", "underscore", "backbone", "app/controllers/sampleController", "app/sampleModule" ];
	function sample($, _, Backbone, AppController, sampleModule) {

		var appController = new AppController();
		appController.start();

		sampleModule.run();
	}

	define(dependencies, sample);
})();


text:
Minimal Logging removes some of the noise from the Rails Server log so you can focus on the most important events.  It also formats parameters and actions in a more readable way to quickly see what's going on.

So you can go from this
![Image of Normal Rails Log](http://i.imgur.com/UtmFpyt.png)

To this
![Image of Rails Log with Minimal Logging](http://i.imgur.com/o1fYDre.png)

## Installation

Add this to your application's Gemfile:

```ruby
group :development do
  gem 'minimal_logging'
end
```

And then execute:

    $ bundle

Or install it yourself:

    $ gem install minimal_logging

## Usage

You can set minimal_logging's configuration options in application.rb or development.rb in your config.

By default, minimal_logging will change your log_level to :info.  If you want to set the log level yourself, you can turn this behavior off.
 ```ruby
 config.minimal_logging.change_log_level = false
 ```

You can turn logging assets back on.  Much of the logic for quietting assets thanks to the [quiet_assets](https://github.com/evrone/quiet_assets) gem.
```ruby
config.minimal_logging.quiet_assets = false
```

And you can turn off minimal_logging itself.
```ruby
config.minimal_logging.enabled = false
```

## Contributing

1. Fork it ( https://github.com/nelsonscott/minimal_logging/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
This module has grown over time based on a range of contributions from
people using it. If you follow these contributing guidelines your patch
will likely make it into a release a little quicker.

## Contributing

Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms. [Contributor Code of Conduct](https://github.com/puppet-community/code-of-conduct).

1. Fork the repo.

1. Create a separate branch for your change.

1. Run the tests. We only take pull requests with passing tests, and
   documentation.

1. Add a test for your change. Only refactoring and documentation
   changes require no new tests. If you are adding functionality
   or fixing a bug, please add a test.

1. Squash your commits down into logical components. Make sure to rebase
   against the current master.

1. Push the branch to your fork and submit a pull request.

Please be prepared to repeat some of these steps as our contributors review
your code.

## Dependencies

The testing and development tools have a bunch of dependencies,
all managed by [bundler](http://bundler.io/) according to the
[Puppet support matrix](http://docs.puppetlabs.com/guides/platforms.html#ruby-versions).

By default the tests use a baseline version of Puppet.

If you have Ruby 2.x or want a specific version of Puppet,
you must set an environment variable such as:

    export PUPPET_VERSION="~> 4.2.0"

Install the dependencies like so...

    bundle install

## Syntax and style

The test suite will run [Puppet Lint](http://puppet-lint.com/) and
[Puppet Syntax](https://github.com/gds-operations/puppet-syntax) to
check various syntax and style things. You can run these locally with:

    bundle exec rake test

## Running the unit tests

The unit test suite covers most of the code, as mentioned above please
add tests if you're adding new functionality. If you've not used
[rspec-puppet](http://rspec-puppet.com/) before then feel free to ask
about how best to test your new feature. To run your specific spec test
you can pass it to `SPEC`:

    bundle exec rake spec SPEC=spec/foo_spec.rb

## Integration tests

The unit tests just check the code runs, not that it does exactly what
we want on a real machine. For that we're using
[beaker](https://github.com/puppetlabs/beaker).

This fires up a new virtual machine (using vagrant) and runs a series of
simple tests against it after applying the module. You can run this
with:

    bundle exec rake acceptance

This will run the tests on an Ubuntu 12.04 virtual machine. You can also
run the integration tests against Centos 6.5 with.

    RS_SET=centos-64-x64 bundle exec rake acceptances

If you don't want to have to recreate the virtual machine every time you
can use `BEAKER_DESTROY=no` and `BEAKER_PROVISION=no`. On the first run you will
at least need `BEAKER_PROVISION` set to yes (the default). The Vagrantfile
for the created virtual machines will be in `.vagrant/beaker_vagrant_fies`.


text:
package com.opengamma.financial.analytics.model.forex.option.localvol;

import com.opengamma.analytics.financial.model.volatility.local.LocalVolatilityForwardPDECalculator;
import com.opengamma.analytics.financial.model.volatility.local.LocalVolatilityForwardPDESingleResultCalculator;
import com.opengamma.analytics.financial.model.volatility.local.LocalVolatilityForwardPDESpotGreeksGridCalculator;
import com.opengamma.analytics.financial.model.volatility.local.PDELocalVolatilityCalculator;
import com.opengamma.analytics.math.interpolation.Interpolator1D;
import com.opengamma.engine.value.ValueRequirementNames;

/**
 *
 */
public class FXOptionLocalVolatilityForwardPDEForwardDeltaFunction extends FXOptionLocalVolatilityForwardPDEFunction {

  public FXOptionLocalVolatilityForwardPDEForwardDeltaFunction(final String blackSmileInterpolatorName) {
    super(blackSmileInterpolatorName);
  }

  @Override
  protected String getRequirementName() {
    return ValueRequirementNames.FORWARD_DELTA;
  }

  @Override
  protected PDELocalVolatilityCalculator<?> getPDECalculator(final LocalVolatilityForwardPDECalculator pdeCalculator, final Interpolator1D interpolator) {
    return new LocalVolatilityForwardPDESingleResultCalculator(new LocalVolatilityForwardPDESpotGreeksGridCalculator.DeltaCalculator(pdeCalculator, interpolator), interpolator);
  }

}


text:
package com.nattrmon.config;

import java.util.ArrayList;

import com.nattrmon.core.Attribute;
import com.nattrmon.core.Object;
import com.nattrmon.core.Service;
import com.nattrmon.output.Output.OutputType;

public class XMLObject {
	protected String name = null;
	protected String params = null;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	protected ArrayList<XMLAttribute> attributes = new ArrayList<XMLAttribute>();

	public ArrayList<XMLAttribute> getXMLAttributes() {
		return attributes;
	}

	public ArrayList<Attribute> getAttributes(Object parentObject) {
		ArrayList<Attribute> attrs = new ArrayList<Attribute>();

		for(XMLAttribute xattr :getXMLAttributes()) {
			attrs.add(xattr.getAttribute(parentObject));
		}

		return attrs;
	}

	public void setXMLAttributes(ArrayList<XMLAttribute> attributes) {
		this.attributes = attributes;
	}

	public void addXMLAttribute(XMLAttribute xmlAttr) {
		attributes.add(xmlAttr);
	}

	public Object getObject(Service parentService) {
		Object obj = parentService.getNewObject(name, params);
		if (obj != null) {
			obj.setName(name);
			obj.setParams(params);
			obj.setAttributes(getAttributes(obj));
		}

		return obj;
	}

	public String getParams() {
		return params;
	}

	public void setParams(String params) {
		this.params = params;
	}

}


text:
====

> NodeJS + MSSQ = DataBase layer. Easy to use layer for querying Microsoft databases, built on top of mssql npm module.
> Initially created as a part of my [Pine Project](https://github.com/anvk/Pine)

## Prerequisites

Node + NPM installed

Based on the [MSSQL connector for NodeJS](https://github.com/patriksimek/node-mssql)

## Configuration

### Options

**dbconfig** - configuration required to connect to the Database. user + password + database + server
**parseCallback** - callback which would be used by default for data manipulation before returning it back to the user for every api call
**onError** - callback which would be used for error handling for every api call
**verbose** - boolean to indicate if module should log extra data in the console
**debug** - boolean for setting debug mode to true (currently not in use)

### Default options

```javascript
var defaults = {
  dbconfig: {
    user: undefined,
    password: undefined,
    server: undefined,
    database: undefined
  },
  parseCallback: undefined,
  onError: undefined,
  verbose: false,
  debug: false
};
```

### API

#### query(options);

> Function to execute a query in the DB

**query** - query in a string format to be executed in MSSQL database
**parseCallback** - callback which would be used upon data retreival to parse the returning recordset data
**onError** - callback which would be used for error handling
**onSuccess** - callback which would be executed upon data retreival
**verbose** - true for more console logs for the function

#### call(options);

> Function to execute a stored procedure in the DB

**storProcName** - name of the stored procedure to be executed
**args** - object which consist of arguments to be passed into the stored procedure. key is argument's name and value is argument's value
**parseCallback** - callback which would be used upon data retreival to parse the returning recordset data
**onError** - callback which would be used for error handling
**onSuccess** - callback which would be executed upon data retreival
**verbose** - true for more console logs for the function

## Testing

### To run tests

```
npm test
```

### To debug tests in Node Inspector

1. Uncomment `beforeEach()` function inside of **tests/nmdb-tests.js**
2. Start node inspector
3. Run the command `npm test`
4. Open node inspector url in Chrome to start debugging. (the process is set to wait for 10 seconds before hitting the first breakpoint)

### Problem with mocha command

Instead of `mocha` command try to use `node_modules/.bin/mocha`

## License
The MIT License (MIT)

Copyright (c) 2013 Alexey Novak

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
<?php
/**
 * Отображение для postAdmin/index:
 *
 *   @category YupeView
 *   @package  YupeCMS
 *   @author   Yupe Team <team@yupe.ru>
 *   @license  https://github.com/yupe/yupe/blob/master/LICENSE BSD
 *   @link     http://yupe.ru
 **/
$this->breadcrumbs = array(
    Yii::app()->getModule('blog')->getCategory() => array(),
    Yii::t('BlogModule.blog', 'Записи') => array('/blog/PostAdmin/index'),
    Yii::t('BlogModule.blog', 'Управление'),
);

$this->pageTitle = Yii::t('BlogModule.blog', 'Записи - управление');

$this->menu = array(
    array('label' => Yii::t('BlogModule.blog', 'Блоги'), 'items' => array(
        array('icon' => 'list-alt', 'label' => Yii::t('BlogModule.blog', 'Управление блогами'), 'url' => array('/blog/BlogAdmin/index')),
        array('icon' => 'plus-sign', 'label' => Yii::t('BlogModule.blog', 'Добавить блог'), 'url' => array('/blog/BlogAdmin/create')),
    )),
    array('label' => Yii::t('BlogModule.blog', 'Записи'), 'items' => array(
        array('icon' => 'list-alt', 'label' => Yii::t('BlogModule.blog', 'Управление записями'), 'url' => array('/blog/PostAdmin/index')),
        array('icon' => 'plus-sign', 'label' => Yii::t('BlogModule.blog', 'Добавить запись'), 'url' => array('/blog/PostAdmin/create')),
    )),
    array('label' => Yii::t('BlogModule.blog', 'Участники'), 'items' => array(
        array('icon' => 'list-alt', 'label' => Yii::t('BlogModule.blog', 'Управление участниками'), 'url' => array('/blog/UserToBlogAdmin/index')),
        array('icon' => 'plus-sign', 'label' => Yii::t('BlogModule.blog', 'Добавить участника'), 'url' => array('/blog/UserToBlogAdmin/create')),
    )),
);
?>

        <?php echo Yii::t('BlogModule.blog', 'Записи'); ?>
        <?php echo Yii::t('BlogModule.blog', 'управление'); ?>

<button class="btn btn-small dropdown-toggle" data-toggle="collapse" data-target="#search-toggle">

    <?php echo CHtml::link(Yii::t('BlogModule.blog', 'Поиск записей'), '#', array('class' => 'search-button')); ?>

</button>

<?php
Yii::app()->clientScript->registerScript(
    'search', "
    $('.search-form form').submit(function() {
        $.fn.yiiGridView.update('post-grid', {
            data: $(this).serialize()
        });
        return false;
    });"
);
$this->renderPartial('_search', array('model' => $model));
?>

<?php echo Yii::t('BlogModule.blog', 'В данном разделе представлены средства управления записями'); ?>

<?php $this->widget(
    'application.modules.yupe.components.YCustomGridView', array(
        'id'           => 'post-grid',
        'type'         => 'condensed',
        'dataProvider' => $model->search(),
        'filter'       => $model,
        'columns'      => array(
            'id',
            array(
                'name'  => 'title',
                'type'  => 'raw',
                'value' => 'CHtml::link($data->title, array("/blog/postAdmin/update", "id" => $data->id))',
            ),
            'slug',
            array(
                'name'  => 'blog_id',
                'type'  => 'raw',
                'value' => 'CHtml::link($data->blog->name, array("/blog/blogAdmin/view", "id" => $data->blog->id))',
            ),
            array(
                'name'  => 'access_type',
                'type'  => 'raw',
                'value' => '$this->grid->returnBootstrapStatusHtml($data, "access_type", "AccessType", array(1 => "globe", 2 => "home"))',
            ),
            array(
                'name'  => 'create_user_id',
                'type'  => 'raw',
                'value' => 'CHtml::link($data->createUser->getFullName(), array("/user/default/view", "id" => $data->createUser->id))',
            ),
            array(
                'name'  => 'publish_date',
                'value' => 'Yii::app()->getDateFormatter()->formatDateTime($data->publish_date, "short", "short")',
            ),
            array(
                'name'  => 'create_date',
                'value' => 'Yii::app()->getDateFormatter()->formatDateTime($data->create_date, "short", "short")',
            ),
            array(
                'name'  => 'status',
                'type'  => 'raw',
                'value' => '$this->grid->returnBootstrapStatusHtml($data, "status", "Status", array("pencil", "ok-sign", "time"))',
            ),
            array(
                'name'  => 'comment_status',
                'type'  => 'raw',
                'value' => '$this->grid->returnBootstrapStatusHtml($data, "comment_status", "CommentStatus", array(1 => "ok-sign", 2 => "lock"))',
            ),
            //'quote',
            //'content',
            //'keywords',
            //'description',
            array(
                'class' => 'bootstrap.widgets.TbButtonColumn',
            ),
        ),
    )
); ?>


text:
static NSNumberFormatter *sNumberFormatter = nil;

@implementation NSNumber (BAAdditions)

+ (NSNumber *)ba_numberFromUSNumberString:(NSString *)numberString {
    return [[self ba_USNumberFormatter] numberFromString:numberString];
}

- (NSString *)ba_USNumberString {
    return [[[self class] ba_USNumberFormatter] stringFromNumber:self];
}

+ (NSNumberFormatter *)ba_USNumberFormatter {
    if (!sNumberFormatter) {
        sNumberFormatter = [NSNumberFormatter ba_USNumberFormatter];
    }

    return sNumberFormatter;
}

@end


text:
<?php
/**
 * Created by PhpStorm.
 * User: kolya
 * Date: 21.07.14
 * Time: 13:46
 */

namespace Wind\ModelBundle\Repository;

use Doctrine\ORM\EntityRepository;

class PostRepository extends EntityRepository {
    /**
     * Find latest
     * @param $num
     */
    public function findLatests($num)
    {
        $qb = $this->getQueryBuilder()
            ->orderBy('p.createdAt', 'desc')
            ->setMaxResults($num);
        return $qb->getQuery()->getResult();
    }

    /**
     * Find the first post
     */
    public function findFirst()
    {
        $qb = $this->getQueryBuilder()
            ->orderBy('p.id', 'asc')
            ->setMaxResults(1);
        return $qb->getQuery()->getSingleResult();
    }
    private function getQueryBuilder()
    {
        $em = $this->getEntityManager();

        $qb = $em->getRepository('WindModelBundle:Post')
            ->createQueryBuilder('p');
        return $qb;
    }
}


text:
'use strict';

var React = require('react/addons');

// CSS
require('normalize.css');
require('../styles/main.less');

// 获取图片数据
var imageDatas = require('../data/imagesData.json');

// 利用自执行函数。将图片信息转化为图片URL路径信息
imageDatas = (function genImageURL(imageDatasArr){
	for (var i = 0; i < imageDatasArr.length; i++) {
		var singleImageData = imageDatasArr[i];

		singleImageData.imageURL = require('../images/' + singleImageData.fileName);

		imageDatasArr[i] = singleImageData;
	}
	return imageDatasArr;
})(imageDatas);

/*
 *获取区间的随机值
 */
function getRangeRandom(low, high){
	return Math.ceil(Math.random() * (high - low) + low);
}

/*
 *获取角度为0-30;
 */
function get30rotate(){
    return ((Math.random() > 0.5 ? '' : '-') + Math.ceil(Math.random() * 30));
}
var ImgFigure = React.createClass({
	/*
	 *imgFigure的点击处理函数
	 */
	handleClick: function(e){
		if(this.props.arrange.iscenter){
			this.props.inverse();
		}else{
			this.props.center();
		}
		e.stopPropagation();
		e.preventDefault();
	},

	render: function(){

		var styleObj = {};

		// 如果props属性中指定了这张图片等的位置
		if(this.props.arrange.pos){
			styleObj = this.props.arrange.pos;
		}

		// 如果图片旋转角度有值,并不为0,添加旋转角度
		if(this.props.arrange.rotate){
			(['MozTransform', 'msTransform', 'WebkitTransform', 'transform']).forEach(function (value) {
				styleObj[value] = 'rotate(' + this.props.arrange.rotate + 'deg)';
			}.bind(this));
		}

		if(this.props.arrange.iscenter){
			styleObj.zIndex = 11;
		}
		var ImgFigureClassName = 'img-figure';
		ImgFigureClassName += this.props.arrange.isInverse ? ' is-inverse ' : '';

		return (

{this.props.data.title}

{this.props.data.desc}

			);
	}
});

// 控制组装件
var ControllerUnits = React.createClass({
	handleClick: function(e){

		// 如果点击的是当前居中态的图片,则翻转图片,负责居中对应的图片
		if(this.props.arrange.iscenter){
			this.props.inverse();
		}else{
			this.props.center();
		}
		e.preventDefault();
		e.stopPropagation();
	},
	render: function () {
		var controllerUnitsClassName = 'controller-units';

		// 如果对应的是居中的图片,显示控制按钮的居中态
		if(this.props.arrange.iscenter){
			controllerUnitsClassName += ' is-center';

			// 如果同时对应的是反转图片,显示控制按钮的翻转状态
			if(this.props.arrange.isInverse){
				controllerUnitsClassName += ' is-inverse';
			}
		}
		return (

			);
	}
});

var GalleryByReactApp = React.createClass({
	Constant: {
		centerPos: {
			left: 0,
			right: 0
		},
		hPosRange: {
			leftSecX: [0, 0],
			rightSecX: [0, 0],
			y: [0, 0]
		},
		vPosRange: {
			x: [0, 0],
			topY: [0, 0]
		}
	},
	/*
	 *反转图片
	 *@param index  输入当前执行isInverse操作的图片对应图片信息数组的index值
	 *@retuen {Funtion} 这是一个闭包函数,期内return一个真正待执行的函数
	 */
	inverse: function(index){
		return function() {
			var imgsArrangeArr = this.state.imgsArrangeArr;

			imgsArrangeArr[index].isInverse = !imgsArrangeArr[index].isInverse;

			this.setState({
				imgsArrangeArr: imgsArrangeArr
			});

		}.bind(this);
	},

	/*
	 *重新布局所有图片
	 *@param centerIndex指定居中排布那个图片
	 */
	rearrange: function(centerIndex){
		var imgsArrangeArr = this.state.imgsArrangeArr,
			Constant = this.Constant,
			centerPos = Constant.centerPos,
			hPosRange = Constant.hPosRange,
			vPosRange = Constant.vPosRange,
			hPosRangeLeftSecX = hPosRange.leftSecX,
			hPosRangeRightSecX = hPosRange.rightSecX,
			hPosRangeY = hPosRange.y,
			vPosRangeTopY = vPosRange.topY,
			vPosRangeX = vPosRange.x,

			imgsArrangeTopArr = [],
			topImgNum = Math.floor(Math.random() * 2),
			// 取一个或者不取
			topImgSpliceIndex = 0,
			imgsArrangeCenterArr = imgsArrangeArr.splice(centerIndex, 1);

			// 首先居中centerIndex的图片
			imgsArrangeCenterArr[0] = {
				pos: centerPos,
				rotate: 0,
				iscenter: true
			};
			// 取出要布局上侧的图片信息
			topImgSpliceIndex = Math.ceil(Math.random() * (imgsArrangeArr.length - topImgNum));
			imgsArrangeTopArr = imgsArrangeArr.splice(topImgSpliceIndex, topImgNum);
			// 布局位于上侧的图片
			imgsArrangeTopArr.forEach(function(value, index){
				imgsArrangeTopArr[index] = {
					pos: {
						top: getRangeRandom(vPosRangeTopY[0], vPosRangeTopY[1]),
						left: getRangeRandom(vPosRangeX[0], vPosRangeX[1])
					},
					rotate: get30rotate(),
					iscenter: false
				};
			});

			// 布局左右两侧的图片
			for(var i = 0, j = imgsArrangeArr.length, k = j / 2; i < j; i++){
				var hPosRangeLORX = null;

				// 前半部分布局左边,后半部分布局右边
				if(i < k){
					hPosRangeLORX = hPosRangeLeftSecX;
				}else{
					hPosRangeLORX = hPosRangeRightSecX;
				}

				imgsArrangeArr[i] = {
					pos: {
						top: getRangeRandom(hPosRangeY[0], hPosRangeY[1]),
						left: getRangeRandom(hPosRangeLORX[0], hPosRangeLORX[1])
					},
					rotate: get30rotate(),
					iscenter: false
				};
			}

			if(imgsArrangeTopArr && imgsArrangeTopArr[0]){
				imgsArrangeArr.splice(topImgSpliceIndex, 0, imgsArrangeTopArr[0]);
			}

			imgsArrangeArr.splice(centerIndex, 0, imgsArrangeCenterArr[0]);

			this.setState({
				imgsArrangeArr: imgsArrangeArr
			});

	},

	/*
	 *利用rearrange函数,居中对应的index的图片
	 *@param index 需要被居中的图片对应的图片信息数组的index值
	 *@return {Function}
	 */
	center: function(index){
		return function(){
			this.rearrange(index);
		}.bind(this);
	},

	getInitialState: function(){
		return {
			imgsArrangeArr: [
				/*{
					pos:{
						left:'0',
						top:'0'
					},
					rotate: k,
					isInverse: false,
					iscenter: false
				}*/
			]
		};
	},
// 组件加载以后,为每张图片计算其位置
	componentDidMount: function(){

		// 拿到舞台的大小
		var stageDOM = React.findDOMNode(this.refs.stage),
			stageW = stageDOM.scrollWidth,
			stageH = stageDOM.scrollHeight,
			halfStageW = Math.ceil(stageW / 2),
			halfStageH = Math.ceil(stageH / 2);

		// 拿到一个imageFigure的大小
		var ImgFigureDOM = React.findDOMNode(this.refs.ImgFigure0),
			imgW = ImgFigureDOM.scrollWidth,
			imgH = ImgFigureDOM.scrollHeight,
			halfImgW = Math.ceil(imgW / 2),
			halfImgH = Math.ceil(imgH / 2);

		// 计算中心区域的位置点
		this.Constant.centerPos = {
			left: halfStageW - halfImgW,
			top: halfStageH - halfImgH
		};

		// 计算左右侧图片排布取值范围
		this.Constant.hPosRange.leftSecX[0] = -halfImgW;
		this.Constant.hPosRange.leftSecX[1] = halfStageW - halfImgW * 3;

		this.Constant.hPosRange.rightSecX[0] = halfStageW + halfImgW;
		this.Constant.hPosRange.rightSecX[1] = stageW - halfImgW;

		this.Constant.hPosRange.y[0] = -halfImgH;
		this.Constant.hPosRange.y[1] = stageH - halfImgH;

		// 计算上侧区域图片排布的位置取值范围
		this.Constant.vPosRange.topY[0] = -halfImgH;
		this.Constant.vPosRange.topY[1] = halfStageH - halfImgH * 3;
		this.Constant.vPosRange.x[0] = halfStageW - imgW;
		this.Constant.vPosRange.x[1] = halfStageW;
		this.rearrange(0);
	},

  render: function(){

	var controllerUnits = [];
	var ImgFigures = [];

	imageDatas.forEach(function(value, index){

		if(!this.state.imgsArrangeArr[index]){
			this.state.imgsArrangeArr[index] = {
				pos: {
					left: 0,
					top: 0
				},
				rotate: 0,
				isInverse: false,
				iscenter: false
			};
		}
		ImgFigures.push(<ImgFigure key={index} data={value} ref={'ImgFigure' + index} arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)} center={this.center(index)}/>);
		controllerUnits.push(<ControllerUnits key={index} arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)} center={this.center(index)}/>);
	}.bind(this));
    return (

      {ImgFigures}

      {controllerUnits}

    );
  }
});
React.render(<GalleryByReactApp />, document.getElementById('content')); // jshint ignore:line

module.exports = GalleryByReactApp;


text:
angular.module('officeAddin', ['xml']);

// When Office has initalized, manually bootstrap the app
Office.initialize = function(){
    angular.bootstrap(document.getElementById('container'), ['officeAddin']);
};


text:
// type for entry in mldap_errorcodes[] array:
struct mldap_errorcode {
  const char *ident;
  int code;
};

// NULL terminated array of error code strings with error code integers
// derived from ldap.h (see above copyright notice):
static const struct mldap_errorcode mldap_errorcodes[] = {
  {"operations_error", 1},
  {"protocol_error", 2},
  {"timelimit_exceeded", 3},
  {"sizelimit_exceeded", 4},
  {"compare_false", 5},
  {"compare_true", 6},
//  {"auth_method_not_supported", 7},
  {"strong_auth_not_supported", 7},
  {"strong_auth_required", 8},
//  {"stronger_auth_required", 8},
  {"partial_results", 9},
  {"referral", 10},
  {"adminlimit_exceeded", 11},
  {"unavailable_critical_extension", 12},
  {"confidentiality_required", 13},
  {"sasl_bind_in_progress", 14},
  {"no_such_attribute", 16},
  {"undefined_type", 17},
  {"inappropriate_matching", 18},
  {"constraint_violation", 19},
  {"type_or_value_exists", 20},
  {"invalid_syntax", 21},
  {"no_such_object", 32},
  {"alias_problem", 33},
  {"invalid_dn_syntax", 34},
  {"is_leaf", 35},
  {"alias_deref_problem", 36},
  {"x_proxy_authz_failure", 47},
  {"inappropriate_auth", 48},
  {"invalid_credentials", 49},
  {"insufficient_access", 50},
  {"busy", 51},
  {"unavailable", 52},
  {"unwilling_to_perform", 53},
  {"loop_detect", 54},
  {"naming_violation", 64},
  {"object_class_violation", 65},
  {"not_allowed_on_nonleaf", 66},
  {"not_allowed_on_rdn", 67},
  {"already_exists", 68},
  {"no_object_class_mods", 69},
  {"results_too_large", 70},
  {"affects_multiple_dsas", 71},
  {"vlv_error", 76},
  {"other", 80},
  {"cup_resources_exhausted", 113},
  {"cup_security_violation", 114},
  {"cup_invalid_data", 115},
  {"cup_unsupported_scheme", 116},
  {"cup_reload_required", 117},
  {"cancelled", 118},
  {"no_such_operation", 119},
  {"too_late", 120},
  {"cannot_cancel", 121},
  {"assertion_failed", 122},
  {"proxied_authorization_denied", 123},
  {"sync_refresh_required", 4096},
  {"x_sync_refresh_required", 16640},
  {"x_assertion_failed", 16655},
  {"x_no_operation", 16654},
  {"x_no_referrals_found", 16656},
  {"x_cannot_chain", 16657},
  {"x_invalidreference", 16658},
  {"x_txn_specify_okay", 16672},
  {"x_txn_id_invalid", 16673},
  {"server_down", (-1)},
  {"local_error", (-2)},
  {"encoding_error", (-3)},
  {"decoding_error", (-4)},
  {"timeout", (-5)},
  {"auth_unknown", (-6)},
  {"filter_error", (-7)},
  {"user_cancelled", (-8)},
  {"param_error", (-9)},
  {"no_memory", (-10)},
  {"connect_error", (-11)},
  {"not_supported", (-12)},
  {"control_not_found", (-13)},
  {"no_results_returned", (-14)},
  {"more_results_to_return", (-15)},
  {"client_loop", (-16)},
  {"referral_limit_exceeded", (-17)},
  {"x_connecting", (-18)},
  {NULL, 0}
};

void mldap_set_errorcodes(lua_State *L) {
  // stores mldap_errorcodes[] mappings in the Lua table on top of the stack
  // in both directions (string mapped to integer and vice versa)

  const struct mldap_errorcode *errorcode;  // pointer to entry in mldap_errorcodes[] array

  // iterate through entries in mldap_errorcodes[] array:
  for (errorcode=mldap_errorcodes; errorcode->ident; errorcode++) {

    // store a mapping from the string to the integer:
    lua_pushstring(L, errorcode->ident);
    lua_pushinteger(L, errorcode->code);
    lua_settable(L, -3);

    // store a mapping from the integer to the string:
    lua_pushinteger(L, errorcode->code);
    lua_pushstring(L, errorcode->ident);
    lua_settable(L, -3);

  }

}


text:
form-validate
=============

# 使用示例
引入js文件
```html
<script src=".../form-validate/form-validate.js"></script>
```
HTML
```html
<input type="text" id="username" name="username" placeholder="用户名" value=""
       form-pattern=".{6,50}" form-classtarget="#group-username"
       form-correctclass="has-success" form-errorclass="has-error"
       form-msgtarget="#msg-username" form-msg="请输入6~50位的字符">
```
javascript
```javascript
$('form').formValidate({
    success: function () {
        // Do ajax request
        $.post(this.action, $(this).serializeArray()).done(function (data) {

        });
        return false;
        // If you return true, do normal form submit.
    }
});
```


text:
require 'xdr'

# === xdr source ============================================================
#
#   enum TrustLineFlags
#   {
#       // issuer has authorized account to perform transactions with its credit
#       AUTHORIZED_FLAG = 1
#   };
#
# ===========================================================================
module Stellar
  class TrustLineFlags < XDR::Enum
    member :authorized_flag, 1

    seal
  end
end


text:
class CFX_WideTextBuf final : public CFX_BinaryBuf {
 public:
  // CFX_BinaryBuf:
  size_t GetLength() const override;

  pdfium::span<wchar_t> GetWideSpan();
  pdfium::span<const wchar_t> GetWideSpan() const;
  WideStringView AsStringView() const;
  WideString MakeString() const;

  void AppendChar(wchar_t wch);
  void Delete(int start_index, int count);

  CFX_WideTextBuf& operator<<(int i);
  CFX_WideTextBuf& operator<<(double f);
  CFX_WideTextBuf& operator<<(ByteStringView ascii);
  CFX_WideTextBuf& operator<<(const wchar_t* lpsz);
  CFX_WideTextBuf& operator<<(WideStringView str);
  CFX_WideTextBuf& operator<<(const WideString& str);
  CFX_WideTextBuf& operator<<(const CFX_WideTextBuf& buf);

 private:
  // Returned span is the newly-expanded space.
  pdfium::span<wchar_t> ExpandWideBuf(size_t char_count);
};

#endif  // CORE_FXCRT_CFX_WIDETEXTBUF_H_


text:
<?php

/**
 * Order status resource model
 */
class Mage_Sales_Model_Mysql4_Order_Status extends Mage_Sales_Model_Resource_Order_Status
{
}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/securitycenter/v1beta1/securitycenter_service.proto

package com.google.cloud.securitycenter.v1beta1;

public interface GroupFindingsRequestOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.securitycenter.v1beta1.GroupFindingsRequest)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Required. Name of the source to groupBy. Its format is
   * "organizations/[organization_id]/sources/[source_id]". To groupBy across
   * all sources provide a source_id of `-`. For example:
   * organizations/{organization_id}/sources/-
   *

   *
   *
   * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The parent.
   */
  java.lang.String getParent();
  /**
   *
   *
   *

   * Required. Name of the source to groupBy. Its format is
   * "organizations/[organization_id]/sources/[source_id]". To groupBy across
   * all sources provide a source_id of `-`. For example:
   * organizations/{organization_id}/sources/-
   *

   *
   *
   * string parent = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The bytes for parent.
   */
  com.google.protobuf.ByteString getParentBytes();

  /**
   *
   *
   *

   * Expression that defines the filter to apply across findings.
   * The expression is a list of one or more restrictions combined via logical
   * operators `AND` and `OR`.
   * Parentheses are not supported, and `OR` has higher precedence than `AND`.
   * Restrictions have the form `<field> <operator> <value>` and may have a `-`
   * character in front of them to indicate negation. Examples include:
   *  * name
   *  * source_properties.a_property
   *  * security_marks.marks.marka
   * The supported operators are:
   * * `=` for all value types.
   * * `>`, `<`, `>=`, `<=` for integer values.
   * * `:`, meaning substring matching, for strings.
   * The supported value types are:
   * * string literals in quotes.
   * * integer literals without quotes.
   * * boolean literals `true` and `false` without quotes.
   * For example, `source_properties.size = 100` is a valid filter string.
   *

   *
   * string filter = 2;
   *
   * @return The filter.
   */
  java.lang.String getFilter();
  /**
   *
   *
   *

   * Expression that defines the filter to apply across findings.
   * The expression is a list of one or more restrictions combined via logical
   * operators `AND` and `OR`.
   * Parentheses are not supported, and `OR` has higher precedence than `AND`.
   * Restrictions have the form `<field> <operator> <value>` and may have a `-`
   * character in front of them to indicate negation. Examples include:
   *  * name
   *  * source_properties.a_property
   *  * security_marks.marks.marka
   * The supported operators are:
   * * `=` for all value types.
   * * `>`, `<`, `>=`, `<=` for integer values.
   * * `:`, meaning substring matching, for strings.
   * The supported value types are:
   * * string literals in quotes.
   * * integer literals without quotes.
   * * boolean literals `true` and `false` without quotes.
   * For example, `source_properties.size = 100` is a valid filter string.
   *

   *
   * string filter = 2;
   *
   * @return The bytes for filter.
   */
  com.google.protobuf.ByteString getFilterBytes();

  /**
   *
   *
   *

   * Required. Expression that defines what assets fields to use for grouping (including
   * `state`). The string value should follow SQL syntax: comma separated list
   * of fields. For example:
   * "parent,resource_name".
   * The following fields are supported:
   * * resource_name
   * * category
   * * state
   * * parent
   *

   *
   * string group_by = 3 [(.google.api.field_behavior) = REQUIRED];
   *
   * @return The groupBy.
   */
  java.lang.String getGroupBy();
  /**
   *
   *
   *

   * Required. Expression that defines what assets fields to use for grouping (including
   * `state`). The string value should follow SQL syntax: comma separated list
   * of fields. For example:
   * "parent,resource_name".
   * The following fields are supported:
   * * resource_name
   * * category
   * * state
   * * parent
   *

   *
   * string group_by = 3 [(.google.api.field_behavior) = REQUIRED];
   *
   * @return The bytes for groupBy.
   */
  com.google.protobuf.ByteString getGroupByBytes();

  /**
   *
   *
   *

   * Time used as a reference point when filtering findings. The filter is
   * limited to findings existing at the supplied time and their values are
   * those at that specific time. Absence of this field will default to the
   * API's version of NOW.
   *

   *
   * .google.protobuf.Timestamp read_time = 4;
   *
   * @return Whether the readTime field is set.
   */
  boolean hasReadTime();
  /**
   *
   *
   *

   * Time used as a reference point when filtering findings. The filter is
   * limited to findings existing at the supplied time and their values are
   * those at that specific time. Absence of this field will default to the
   * API's version of NOW.
   *

   *
   * .google.protobuf.Timestamp read_time = 4;
   *
   * @return The readTime.
   */
  com.google.protobuf.Timestamp getReadTime();
  /**
   *
   *
   *

   * Time used as a reference point when filtering findings. The filter is
   * limited to findings existing at the supplied time and their values are
   * those at that specific time. Absence of this field will default to the
   * API's version of NOW.
   *

   *
   * .google.protobuf.Timestamp read_time = 4;
   */
  com.google.protobuf.TimestampOrBuilder getReadTimeOrBuilder();

  /**
   *
   *
   *

   * The value returned by the last `GroupFindingsResponse`; indicates
   * that this is a continuation of a prior `GroupFindings` call, and
   * that the system should return the next page of data.
   *

   *
   * string page_token = 5;
   *
   * @return The pageToken.
   */
  java.lang.String getPageToken();
  /**
   *
   *
   *

   * The value returned by the last `GroupFindingsResponse`; indicates
   * that this is a continuation of a prior `GroupFindings` call, and
   * that the system should return the next page of data.
   *

   *
   * string page_token = 5;
   *
   * @return The bytes for pageToken.
   */
  com.google.protobuf.ByteString getPageTokenBytes();

  /**
   *
   *
   *

   * The maximum number of results to return in a single response. Default is
   * 10, minimum is 1, maximum is 1000.
   *

   *
   * int32 page_size = 6;
   *
   * @return The pageSize.
   */
  int getPageSize();
}


text:
<navbar>

</navbar>

Group

Users

Cars

Vendors

Destinations

    <alert ng-repeat="alert in alerts" type="alert.type" close="closeAlert($index)">{{alert.msg}}</alert>

{{group.name}}'s Destinations<button class="btn btn-primary pull-right" ng-click="changeToAddDestination()">Add Destination</button>

            <google-map
                    center="map.center"
                    zoom="map.zoom"
                    draggable="true"
                    dragging="map.dragging"
                    bounds="map.bounds"
                    events="map.events"
                    options="map.options"
                    pan="true"
                    control="map.control"
                    >

                <layer type="TrafficLayer" show="map.showTraffic"></layer>

                <markers  models="map.dynamicMarkers" coords="'self'">
                    <windows show="'showWindow'" ng-cloak>

Name: {{make}}

                            {{ latitude | number:4 }}, {{ longitude | number:4}}

                    </windows>
                </markers>
            </google-map>

            Name
            Address
            Created at

            {{destination.name}}
            {{destination.location.address}}
            {{destination.created_at | date:'yyyy-MM-dd'}}

 Delete


text:
	A physical model of a spring, useful in many applications.

	A spring is an object that will compute based upon Hooke's law. Properties only evaluate
	upon index making this model good for lazy applications.

	```lua
	local RunService = game:GetService("RunService")
	local UserInputService = game:GetService("UserInputService")

	local spring = Spring.new(Vector3.new(0, 0, 0))

	RunService.RenderStepped:Connect(function()
		if UserInputService:IsKeyDown(Enum.KeyCode.W) then
			spring.Target = Vector3.new(0, 0, 1)
		else
			spring.Target = Vector3.new(0, 0, 0)
		end

		print(spring.Position) -- A smoothed out version of the input keycode W
	end)
	```

	A good visualization can be found here, provided by Defaultio:
	https://www.desmos.com/calculator/hn2i9shxbz

	@class Spring
]=]
local Spring = {}

--[=[
	Constructs a new Spring at the position and target specified, of type T.

	```lua
	-- Linear spring
	local linearSpring = Spring.new(0)

	-- Vector2 spring
	local vector2Spring = Spring.new(Vector2.new(0, 0))

	-- Vector3 spring
	local vector3Spring = Spring.new(Vector3.new(0, 0, 0))
	```

	@param initial T -- The initial parameter is a number or Vector3 (anything with * number and addition/subtraction).
	@param clock? () -> number -- The clock function is optional, and is used to update the spring
	@return Spring<T>
]=]
function Spring.new(initial, clock)
	local target = initial or 0
	clock = clock or os.clock
	return setmetatable({
		_clock = clock;
		_time0 = clock();
		_position0 = target;
		_velocity0 = 0*target;
		_target = target;
		_damper = 1;
		_speed = 1;
	}, Spring)
end

--[=[
	Impulses the spring, increasing velocity by the amount given. This is useful to make something shake,
	like a Mac password box failing.

	@param velocity T -- The velocity to impulse with
	@return ()
]=]
function Spring:Impulse(velocity)
	self.Velocity = self.Velocity + velocity
end

--[=[
	Instantly skips the spring forwards by that amount time
	@param delta number -- Time to skip forwards
	@return ()
]=]
function Spring:TimeSkip(delta)
	local now = self._clock()
	local position, velocity = self:_positionVelocity(now+delta)
	self._position0 = position
	self._velocity0 = velocity
	self._time0 = now
end

--[=[
	The current position at the given clock time. Assigning the position will change the spring to have that position.

	```lua
	local spring = Spring.new(0)
	print(spring.Position) --> 0
	```

	@prop Position T
	@within Spring
]=]
--[=[
	Alias for [Spring.Position](/api/Spring#Position)

	@prop p T
	@within Spring
]=]
--[=[
	The current velocity. Assigning the velocity will change the spring to have that velocity.

	```lua
	local spring = Spring.new(0)
	print(spring.Velocity) --> 0
	```

	@prop Velocity T
	@within Spring
]=]
--[=[
	Alias for [Spring.Velocity](/api/Spring#Velocity)

	@prop v T
	@within Spring
]=]
--[=[
	The current target. Assigning the target will change the spring to have that target.

	```lua
	local spring = Spring.new(0)
	print(spring.Target) --> 0
	```

	@prop Target T
	@within Spring
]=]
--[=[
	Alias for [Spring.Target](/api/Spring#Target)
	@prop t T
	@within Spring
]=]
--[=[
	The current damper, defaults to 1. At 1 the spring is critically damped. At less than 1, it
	will be underdamped, and thus, bounce, and at over 1, it will be critically damped.

	@prop Damper number
	@within Spring
]=]
--[=[
	Alias for [Spring.Damper](/api/Spring#Damper)

	@prop d number
	@within Spring
]=]
--[=[
	The speed, defaults to 1, but should be between [0, infinity)

	@prop Speed number
	@within Spring
]=]
--[=[
	Alias for [Spring.Speed](/api/Spring#Speed)

	@prop s number
	@within Spring
]=]
--[=[
	The current clock object to syncronize the spring against.

	@prop Clock () -> number
	@within Spring
]=]
function Spring:__index(index)
	if Spring[index] then
		return Spring[index]
	elseif index == "Value" or index == "Position" or index == "p" then
		local position, _ = self:_positionVelocity(self._clock())
		return position
	elseif index == "Velocity" or index == "v" then
		local _, velocity = self:_positionVelocity(self._clock())
		return velocity
	elseif index == "Target" or index == "t" then
		return self._target
	elseif index == "Damper" or index == "d" then
		return self._damper
	elseif index == "Speed" or index == "s" then
		return self._speed
	elseif index == "Clock" then
		return self._clock
	else
		error(("%q is not a valid member of Spring"):format(tostring(index)), 2)
	end
end

function Spring:__newindex(index, value)
	local now = self._clock()

	if index == "Value" or index == "Position" or index == "p" then
		local _, velocity = self:_positionVelocity(now)
		self._position0 = value
		self._velocity0 = velocity
		self._time0 = now
	elseif index == "Velocity" or index == "v" then
		local position, _ = self:_positionVelocity(now)
		self._position0 = position
		self._velocity0 = value
		self._time0 = now
	elseif index == "Target" or index == "t" then
		local position, velocity = self:_positionVelocity(now)
		self._position0 = position
		self._velocity0 = velocity
		self._target = value
		self._time0 = now
	elseif index == "Damper" or index == "d" then
		local position, velocity = self:_positionVelocity(now)
		self._position0 = position
		self._velocity0 = velocity
		self._damper = value
		self._time0 = now
	elseif index == "Speed" or index == "s" then
		local position, velocity = self:_positionVelocity(now)
		self._position0 = position
		self._velocity0 = velocity
		self._speed = value < 0 and 0 or value
		self._time0 = now
	elseif index == "Clock" then
		local position, velocity = self:_positionVelocity(now)
		self._position0 = position
		self._velocity0 = velocity
		self._clock = value
		self._time0 = value()
	else
		error(("%q is not a valid member of Spring"):format(tostring(index)), 2)
	end
end

function Spring:_positionVelocity(now)
	local p0 = self._position0
	local v0 = self._velocity0
	local p1 = self._target
	local d = self._damper
	local s = self._speed

	local t = s*(now - self._time0)
	local d2 = d*d

	local h, si, co
	if d2 < 1 then
		h = math.sqrt(1 - d2)
		local ep = math.exp(-d*t)/h
		co, si = ep*math.cos(h*t), ep*math.sin(h*t)
	elseif d2 == 1 then
		h = 1
		local ep = math.exp(-d*t)/h
		co, si = ep, ep*t
	else
		h = math.sqrt(d2 - 1)
		local u = math.exp((-d + h)*t)/(2*h)
		local v = math.exp((-d - h)*t)/(2*h)
		co, si = u + v, u - v
	end

	local a0 = h*co + d*si
	local a1 = 1 - (h*co + d*si)
	local a2 = si/s

	local b0 = -s*si
	local b1 = s*si
	local b2 = h*co - d*si

	return
		a0*p0 + a1*p1 + a2*v0,
		b0*p0 + b1*p1 + b2*v0
end

return Spring


text:
<!DOCTYPE html>

    <title>XML TAG UPDATE FOR RIT</title>

Enter a Raw XML

      <form>
        <input onchange="toggleOrderList(this);" id = 'PlainName' type='radio' name="updateType" value="PlainName" checked>Plain Name
        <input onchange="toggleOrderList(this);" id = 'Sequence' type='radio' name="updateType" value="Sequence" >Numbered Sequence
        <select id = 'SequenceOrder' name="TagOrder" disabled="true">Select Order
          <option value="zero">Start with... 0 (default)</option>
          <option value="one">Start with... 1</option>
        </select>

    </form>
    <textarea id="RawXMLTXTA" rows="20" cols="75"></textarea>

    <button type="button" onclick="updateXML();">Process XML</button>
    <button type="button" onclick="clearTxt();">Clear</button>
    <button type="button" onclick="refresh();">Refresh</button>

Updated XML for RIT

    <textarea id="UpdatedXMLTXTA" rows="20" cols="75"></textarea>


text:
/* Purpose: Fix code, bump version, create build, create snapshot */

'use strict'

// Import modules
let env = require('./env')
let alert = require('./alert')
let cmd = require('./cmd')
let found = require('./found')
let jsonScheme = require('./json-scheme')
let fs = require('fs-extra')
let img = require('jimp')
let abs = require('path').resolve
let rec = require('recursive-readdir')
let ver = require('semver')
let webpack = require('webpack')

// Define build mode
let mode
if (env.arg.dev === true) {
  mode = 'dev'
} else if (env.arg.patch === true) {
  mode = 'patch'
} else if (env.arg.minor === true) {
  mode = 'minor'
} else if (env.arg.major === true) {
  mode = 'major'
} else {
  alert('Build script must have one argument of dev, patch, minor or major.', 'error')
}

// Step: Fix code
let fixCode = function (callback) {
  if (env.cfg.fixCodeOnBuild === true) {
    cmd(__dirname, 'node code-check --fix', function () {
      callback()
    })
  } else {
    callback()
  }
}

// Step: Build webpack
let buildWebpack = function (callback) {
  alert('Webpack build process ongoing - please wait ...')
  let webpackConfig = require('./webpack-config').production
  // Empty webpack cache folder
  fs.emptyDir(abs(env.cache, 'build/www'), function (err) {
    if (err) {
      alert('Clean-up of the webpack cache folder failed.', 'issue')
    } else {
      // Build webpack to cache
      webpack(webpackConfig, function (err, stats) {
        if (err) {
          alert('Webpack build process failed.', 'issue')
        } else {
          alert('Webpack build process done.')
          callback()
        }
      })
    }
  })
}

// Step: Update license date
let updateLicense = function (callback) {
  if (env.installed === false) {
    alert('License update ongoing - please wait ...')
    let file = abs(env.proj, 'LICENSE')
    let text = fs.readFileSync(file, 'utf8')
    text = text.replace(/Copyright \(c\) ([0-9]{4}) scriptPilot/, 'Copyright (c) ' + (new Date()).getFullYear() + ' scriptPilot')
    fs.writeFileSync(file, text)
    alert('License update done.')
    callback()
  } else {
    callback()
  }
}

// Step: Update documentation
let updateDocumentation = function (callback) {
  if (env.installed === false) {
    alert('Documentation update ongoing - please wait ...')
    let update = jsonScheme.markdown(abs(__dirname, '../config-scheme.json'), abs(__dirname, '../docs/configuration.md'), 'config-options')
    if (Array.isArray(update)) {
      alert('Failed to update the documentation file.\n' + update.join('\n'), 'issue')
    } else {
      alert('Documentation update done.')
      callback()
    }
  } else {
    callback()
  }
}

// Step: Manage icons
let manageIcons = function (callback) {
  alert('Browserconfig and manifest creation ongoing - please wait ...')
  try {
    // Copy main icon file
    let iconFile = abs(env.app, 'icon.png')
    if (!found(iconFile)) {
      alert('Cannot find "icon.png" file.', 'error')
    }
    fs.copySync(iconFile, abs(env.cache, 'build/icon.png'))
    // Create manifest file (see http://realfavicongenerator.net/faq for details)
    let manifest = {
      name: env.cfg.title,
      icons: [
        {
          'src': 'android-chrome-192x192.png',
          'sizes': '192x192',
          'type': 'image/png'
        },
        {
          'src': 'android-chrome-512x512.png',
          'sizes': '512x512',
          'type': 'image/png'
        }
      ],
      theme_color: env.cfg.iconBackgroundColor,
      background_color: env.cfg.iconBackgroundColor,
      display: 'standalone'
    }
    fs.writeJsonSync(abs(env.cache, 'build/www/manifest.json'), manifest, {spaces: 0})
    // Create browserconfig file
    let xml = '<?xml version="1.0" encoding="utf-8"?>' +
              '<browserconfig>' +
                '<msapplication>' +
                  '<tile>' +
                    '<square150x150logo src="mstile-150x150.png"/>' +
                    '<TileColor>#da532c</TileColor>' +
                  '</tile>' +
                '</msapplication>' +
              '</browserconfig>'
    fs.writeFileSync(abs(env.cache, 'build/www/browserconfig.xml'), xml)
    // Copy icon files (see http://realfavicongenerator.net/faq for details)
    let iconCacheFolder = abs(env.cache, 'icons/dev')
    let iconFiles = fs.readdirSync(iconCacheFolder)
    iconFiles.map(i => {
      if (/^(favicon|android-chrome|mstile|apple-touch-icon)/.test(i) === true) {
        fs.copySync(abs(iconCacheFolder, i), abs(env.cache, 'build/www', i))
      }
    })
    // Rename Apple touch icon
    fs.renameSync(abs(env.cache, 'build/www/apple-touch-icon-180x180.png'), abs(env.cache, 'build/www/apple-touch-icon.png'))
    // Delete Framework7 icon from CSS file >> removed due to 404 error in browser
    // Copy store icons
    iconFiles.map(i => {
      if (/^(.+)-store-(.+)/.test(i) === true) {
        fs.copySync(abs(iconCacheFolder, i), abs(env.cache, 'build', i.replace(/^(.+)-store-icon(.+)\.(png|jpg)/, '$1-store-icon.png')))
      }
    })
    // Callback
    callback()
  } catch (err) {
    alert('Browserconfig and manifest creation failed.', 'issue')
  }
}

// Step: Copy Firebase files
let copyFirebaseFiles = function (callback) {
  alert('Firebase files update ongoing - please wait ...')
  fs.copy(abs(env.app, 'firebase-database.json'), abs(env.cache, 'build/firebase-database.json'), err => {
    if (err) {
      alert('Failed to copy "firebase-database.json" file.', 'issue')
    } else {
      try {
        // Correct storage bucket in database rules (with prod info only)
        let rules = fs.readFileSync(abs(env.app, 'firebase-storage.txt'), 'utf8')
        rules = rules.replace(/match \/b\/(.+?)\/o {/, 'match /b/' + (env.cfg.firebase.storageBucket !== '' ? env.cfg.firebase.storageBucket : '<your-storage-bucket>') + '/o {')
        fs.writeFileSync(abs(env.app, 'firebase-storage.txt'), rules)
        // Copy file
        fs.copySync(abs(env.app, 'firebase-storage.txt'), abs(env.cache, 'build/firebase-storage.txt'))
        // Alert
        alert('Firebase files update done.')
        callback()
      } catch (err) {
        alert('Failed copy "firebase-database.json" file.', 'issue')
      }
    }
  })
}

// Step: Compress images
let compressImages = function (callback, files) {
  if (files === undefined) {
    if (found(env.cache, 'build/www/img')) {
      alert('Images compression ongoing - please wait ...')
      rec(abs(env.cache, 'build/www/img'), function (err, files) {
        if (err) {
          alert('Failed to read image files.' + err, 'issue')
        } else {
          compressImages(callback, files)
        }
      })
    } else {
      callback()
    }
  } else if (Array.isArray(files) && files.length > 0) {
    let file = files.shift()
    if (/\.jpg$/.test(file)) {
      let original = abs(file)
      let compressed = abs(file.replace(/\.jpg$/, '.temp.jpg'))
      img.read(original, function (err, image) {
        if (err) {
          alert('Failed to read image file.', 'issue')
        } else {
          image.quality(60, function (err, image) {
            if (err) {
              alert('Failed to compress JPG file.', 'issue')
            } else {
              image.write(compressed, function (err) {
                if (err) {
                  alert('Failed to write compressed image file.', 'issue')
                } else {
                  try {
                    let originalStat = fs.statSync(original)
                    let compressedStat = fs.statSync(compressed)
                    if (originalStat.size > compressedStat.size) {
                      fs.removeSync(original)
                      fs.renameSync(compressed, original)
                    } else {
                      fs.removeSync(compressed)
                    }
                    compressImages(callback, files)
                  } catch (err) {
                    alert('Failed to compress JPG images.', 'issue')
                  }
                }
              })
            }
          })
        }
      })
    } else {
      compressImages(callback, files)
    }
  } else {
    alert('Image compression done.')
    callback()
  }
}
function updatePreloader (callback) {
  alert('Preloader update ongoing - please wait ...')
  try {
    // Read appcache file
    let appcache = fs.readFileSync(abs(env.cache, 'build/www/manifest.appcache'), 'utf8')
    // Get init file name and cache files
    let initFile = ''
    let cacheFiles = []
    appcache.split('\n').map(function (file) {
      file = file.substr(1)
      // Init file
      if (/^init\.[0-9a-z]+\.js$/.test(file)) {
        initFile = file
      // JavaScript and CSS files (with icon fonts)
      } else if (/\.(js|css)$/.test(file) && !/^init\.[0-9a-z]+\.css$/.test(file)) {
        cacheFiles.push(file)
      // Image files
      } else if (env.cfg.preloadImages === true && /\.(png|jpe?g|gif)$/.test(file)) {
        cacheFiles.push(file)
      }
    })
    // Update preloader files in init.js
    let fileContent = fs.readFileSync(abs(env.cache, 'build/www', initFile), 'utf8')
    fileContent = fileContent.replace('["app.js"]', JSON.stringify(cacheFiles))
    fs.writeFileSync(abs(env.cache, 'build/www', initFile), fileContent)
    // Alert and callback
    alert('Preloader update done.')
    callback()
  } catch (err) {
    alert('Preloader update failed.', 'issue')
  }
}

// Run steps
fixCode(function () {
  cmd(__dirname, 'node checkLanguageFiles', function () {
    cmd(__dirname, 'node update-routes', function () {
      cmd(__dirname, 'node applyConfiguration', function () {
        if (mode !== 'dev') {
          // Update version in package.json
          let pkg = fs.readJsonSync(abs(env.proj, 'package.json'))
          pkg.version = ver.inc(pkg.version, mode)
          fs.writeJsonSync(abs(env.proj, 'package.json'), pkg)
          env.pkg.version = pkg.version
          require.cache = {}
        }
        cmd(__dirname, 'node addLoginPopup', function () {
          updateLicense(function () {
            updateDocumentation(function () {
              fs.emptyDir(abs(env.cache, 'build'), function (err) {
                if (err) {
                  alert('Failed to empty build folder in cache.', 'issue')
                } else {
                  buildWebpack(function () {
                    cmd(__dirname, 'node create-icons', function () {
                      manageIcons(function () {
                        copyFirebaseFiles(function () {
                          updatePreloader(function () {
                            // Dev build
                            if (mode === 'dev') {
                              alert('Development build done.')
                            // Pruduction build
                            } else {
                              alert('Build folder update ongoing - please wait ...')
                              // Empty existing build folder
                              fs.emptyDir(abs(env.proj, 'build'), function (err) {
                                if (err) {
                                  alert('Clean-up the existing build folder failed.', 'issue')
                                } else {
                                  // Copy files
                                  fs.copy(abs(env.cache, 'build'), abs(env.proj, 'build'), function (err) {
                                    if (err) {
                                      alert('Build folder update failed.', 'issue')
                                    } else {
                                      compressImages(function () {
                                        // Create snapshot
                                        cmd(__dirname, 'node create-snapshot --name "build-' + env.pkg.version + '"', function () {
                                          alert('Build process done for version ' + env.pkg.version + '.')
                                        })
                                      })
                                    }
                                  })
                                }
                              })
                            }
                          })
                        })
                      })
                    })
                  })
                }
              })
            })
          })
        })
      })
    })
  })
})