text:
package org.hisp.dhis.dxf2.metadata.objectbundle.hooks;

import java.util.Collections;
import java.util.List;

import org.hisp.dhis.DhisConvenienceTest;
import org.hisp.dhis.dataelement.DataElement;
import org.hisp.dhis.dxf2.metadata.objectbundle.ObjectBundle;
import org.hisp.dhis.dxf2.metadata.objectbundle.ObjectBundleParams;
import org.hisp.dhis.feedback.ErrorCode;
import org.hisp.dhis.feedback.ErrorReport;
import org.hisp.dhis.option.OptionSet;
import org.hisp.dhis.preheat.Preheat;
import org.hisp.dhis.preheat.PreheatIdentifier;
import org.hisp.dhis.program.Program;
import org.hisp.dhis.program.ProgramStage;
import org.hisp.dhis.program.ProgramStageSectionService;
import org.hisp.dhis.security.acl.AclService;
import org.hisp.dhis.user.User;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith( MockitoExtension.class )
class ProgramStageObjectBundleHookTest
{
    private ProgramStageObjectBundleHook subject;

    @Mock
    private AclService aclService;

    @Mock
    private ProgramStageSectionService programStageSectionService;

    private ProgramStage programStage;

    private Program program;

    private DataElement dataElement;

    private User user;

    private Preheat preheat = new Preheat();

    @BeforeEach
    public void init()
    {
        this.subject = new ProgramStageObjectBundleHook( aclService, programStageSectionService );

        program = DhisConvenienceTest.createProgram( 'A' );
        program.setUid( "jGRqKgwvvb6" );

        programStage = DhisConvenienceTest.createProgramStage( 'A', program );
        programStage.setUid( "giQh4EFWKOk" );

        dataElement = DhisConvenienceTest.createDataElement( 'A' );
        dataElement.setUid( "qtplcYVR1oO" );
        programStage.addDataElement( dataElement, 0 );
        user = DhisConvenienceTest.makeUser( "A" );
        user.setUid( "WAoGUm593U7" );

        preheat.put( PreheatIdentifier.UID, program );
        preheat.put( PreheatIdentifier.UID, programStage );
        preheat.put( PreheatIdentifier.UID, dataElement );
    }

    @Test
    void testValidateDataElementAcl()
    {
        ObjectBundleParams objectBundleParams = new ObjectBundleParams();
        objectBundleParams.setPreheatIdentifier( PreheatIdentifier.UID );
        objectBundleParams.setUser( user );
        ObjectBundle bundle = new ObjectBundle( objectBundleParams, preheat, Collections
            .singletonMap( OptionSet.class, Collections.singletonList( programStage ) ) );

        List<ErrorReport> errors = subject.validate( programStage, bundle );
        Assertions.assertEquals( 1, errors.size() );
        Assertions.assertEquals( ErrorCode.E3012, errors.get( 0 ).getErrorCode() );
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.klose.payment.server.prepare;

import org.klose.payment.bo.BillingData;

public interface PaymentIntegrationService {
	/**
	 * 准备订单数据
	 * @param businessNumber 货物标识符
	 * @return
     */
	BillingData prepareBillingData(String businessNumber);

	void saveTransactionId(String businessNumber, Long transactionId);
}


text:
using Newtonsoft.Json.Linq;

namespace DotJEM.Json.Visitor
{
    /// <summary>
    /// Basic interface for implementing a JToken visitor, the visitor specifies a context implementation.
    /// One implementation of the context could be used to track the location in the current full Json structure.
    /// <br/>
    /// A visitor context must as minumum implement the <see cref="IJsonVisitorContext{TContext}"/> which provides basic traversal methods.
    /// </summary>
    /// <typeparam name="TContext"></typeparam>
    public interface IJsonVisitor<in TContext> where TContext: IJsonVisitorContext<TContext>
    {
        void DoAccept(JToken json, TContext context);
    }

}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const XrcParam_1 = require("./XrcParam");
class LinkService {
    constructor() {
        this.internalRules = new Map();
    }
    clear() {
        this.internalRules.clear();
        return this;
    }
    add(rules) {
        for (const item of rules) {
            const targetType = item.targetType.toLowerCase();
            let targetTypeRules = this.internalRules.get(targetType);
            if (!targetTypeRules) {
                targetTypeRules = new Array();
                this.internalRules.set(targetType, targetTypeRules);
            }
            targetTypeRules.push(new LinkRuleMatch(item.url, targetType, item.conditions));
        }
        return this;
    }
    resolve(obj) {
        if (!obj || !obj.constructor) {
            return undefined;
        }
        let objectType = obj.constructor.name;
        if (!objectType) {
            return undefined;
        }
        objectType = objectType.toLowerCase();
        const targetTypeRules = this.internalRules.get(objectType)
            || this.internalRules.get("any");
        if (!targetTypeRules) {
            return undefined;
        }
        const matched = targetTypeRules
            .filter((t) => t.match(obj))
            .sort((a, b) => a.conditions.length - b.conditions.length);
        if (matched.length === 0) {
            return undefined;
        }
        // evaluate url (replace route parameters)
        const url = matched[matched.length - 1].url;
        return XrcParam_1.XrcParam.replaceParams(url, obj);
    }
}
exports.LinkService = LinkService;
class LinkRulesConditions {
    static equal(propertyName, val) {
        return {
            name: propertyName,
            condition: new OperatorEqual(val)
        };
    }
    static notEqual(propertyName, val) {
        return {
            name: propertyName,
            condition: new OperatorNotEqual(val)
        };
    }
    static isNull(propertyName) {
        return {
            name: propertyName,
            condition: new OperatorIsNull()
        };
    }
    static isNotNull(propertyName) {
        return {
            name: propertyName,
            condition: new OperatorIsNotNull()
        };
    }
    static isDefined(propertyName) {
        return {
            name: propertyName,
            condition: new OperatorIsDefined()
        };
    }
    static isNotDefined(propertyName) {
        return {
            name: propertyName,
            condition: new OperatorIsNotDefined()
        };
    }
}
exports.LinkRulesConditions = LinkRulesConditions;
class OperatorIsNull {
    match(obj, propertyName) {
        if (!obj) {
            return true;
        }
        const val = obj[propertyName];
        return !val;
    }
}
class OperatorIsNotNull {
    match(obj, propertyName) {
        if (!obj) {
            return false;
        }
        const val = obj[propertyName];
        return !!val;
    }
}
class OperatorIsDefined {
    match(obj, propertyName) {
        if (!obj) {
            return false;
        }
        return obj.hasOwnProperty(propertyName);
    }
}
class OperatorIsNotDefined {
    match(obj, propertyName) {
        if (!obj) {
            return true;
        }
        return !obj.hasOwnProperty(propertyName);
    }
}
class OperatorEqual {
    constructor(valueToCompare) {
        this.valueToCompare = valueToCompare;
    }
    match(obj, propertyName) {
        if (!obj) {
            return false;
        }
        const val = obj[propertyName];
        return val === this.valueToCompare;
    }
}
class OperatorNotEqual {
    constructor(valueToCompare) {
        this.valueToCompare = valueToCompare;
    }
    match(obj, propertyName) {
        if (!obj) {
            return true;
        }
        const val = obj[propertyName];
        return val !== this.valueToCompare;
    }
}
class LinkRuleMatch {
    constructor(url, targetType, conditions) {
        this.url = url;
        this.targetType = targetType;
        if (!conditions) {
            conditions = new Array();
        }
        this.conditions = conditions;
    }
    match(obj) {
        return this.conditions.every((c) => c.condition.match(obj, c.name));
    }
}
//# sourceMappingURL=linkRules.js.map


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateLinksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('links', function (Blueprint $table) {
            $table->increments('id');
            $table->string('team_id');
            $table->string('url');
            $table->string('title')->nullable();
            $table->string('user_id');
            $table->string('channel_id');
            $table->nullableTimestamps();

            $table->index('user_id');
            $table->index('channel_id');
            $table->index('title');

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('links');
    }
}


text:
namespace ExampleApp
{
    namespace Net
    {
        namespace SdkModel
        {
            class ConnectivityChangedObserver
            {
            public:

                ConnectivityChangedObserver(Eegeo::Web::WebConnectivityValidator& connectivityValidator,
                                            ExampleAppMessaging::TMessageBus& messageBus);
                ~ConnectivityChangedObserver();

            private:

                Eegeo::Helpers::TCallback0<ConnectivityChangedObserver> m_connectivityChangeCallback;

                void HandleConnectivityChanged();

                ExampleAppMessaging::TMessageBus& m_messageBus;
                Eegeo::Web::WebConnectivityValidator& m_connectivityValidator;
            };
        }
    }
}


text:
package com.josonprog.common.expression.operator;

import com.josonprog.common.expression.Operand;

public abstract class CompareOperator extends AbstractOperator<Boolean> {

	public CompareOperator() {
		super(2, new Class<?>[]{Operand.VAL_TYPE_NULL, Comparable.class});
	}

}


text:
using Starcounter;

namespace KitchenSink
{
    partial class ChartPage : Json
    {
        protected override void OnData()
        {
            base.OnData();

            this.AddChartData("January", 4);
            this.AddChartData("February", 7);
            this.AddChartData("March", 9);
            this.AddChartData("April", 12);
            this.AddChartData("May", 15);
            this.AddChartData("June", 19);
        }

        public void AddChartData(string label, int value)
        {
            Json labelItem = Labels.Add();
            labelItem.StringValue = label;

            Json temperatureItem = Temperatures.Add();
            temperatureItem.IntegerValue = value;
        }
    }
}


text:
var MIME_TYPES: { [key: string]: string[]; } = {
	'BMP': ['image/bmp', 'image/x-windows-bmp'],
	'GIF': ['image/gif'],
	'JPEG': ['image/jpeg', 'image/pjpeg'],
	'ICO': ['image/x-icon'],
	'PGM': ['image/x-portable-graymap'],
	'PNG': ['image/png'],
	'SVG': ['image/svg+xml', 'image/svg-xml'],
	'TIFF': ['image/tiff', 'image/x-tiff'],
	'WebP': ['image/webp'],
	'XBM': ['image/x-xbitmap'],
}

onmessage = function (event) {
	var message = <IAnalyzeMessage>event.data;

	var xhr = new XMLHttpRequest();
	xhr.responseType = 'blob';
	xhr.addEventListener('load', (e) => {
		// Parse the image and pass back any new info we get
		parseImage(xhr.response, (err, info) => {
			if (err) {
				throw new Error(err);
			} else if (info === null) {
				endAnalysis();
			} else {
				sendInfo(info);
			}
		});
	});

	xhr.addEventListener('error', (e) => {
		throw new Error(xhr.status + ' ' + xhr.statusText);
	});

	xhr.addEventListener('loadend', (e) => {
		// Clean up the blob URL
		URL.revokeObjectURL(message.url);
	});
	xhr.open('get', message.url, true);
	xhr.send();
}

function getGenericImageData(type: string, data: ArrayBuffer): ImageInfo {
	return {
		mimeType: type,
		type: getImageType(type),
		fileSize: data.byteLength
	}
}

function getImageType(mimeType: string) {
	for (var key in MIME_TYPES) {
		if (MIME_TYPES.hasOwnProperty(key)) {
			if (MIME_TYPES[key].indexOf(mimeType.toLowerCase()) >= 0) {
				return key;
			}
		}
	}
	return null;
}

function parseImage(blob: Blob, callback: InfoCallback) {
	var fr = new FileReader();
	fr.addEventListener('load', (e) => {
		var info = getGenericImageData(blob.type, fr.result);

		// Send the info we've collected up to now
		callback(null, info);

		try {
			// Pick the right parser based on the image type
			switch (info.type) {
				case 'GIF':
					GifParser.parse(fr.result, info, callback);
					break;

				case 'JPEG':
					JpegParser.parse(fr.result, info, callback);
					break;

				case 'PNG':
					PngParser.parse(fr.result, info, callback);
					break;

				default:
					// No further analysis to do. Send back a 'null' to indicate we're done.
					callback(null, null);
					break;
			}
		} catch (e) {
			callback(e.toString(), null);
		}
	});

	fr.addEventListener('error', (e) => {
		callback(fr.error.toString(), null);
	});

	fr.readAsArrayBuffer(blob);
}

function endAnalysis() {
	(<any>postMessage)({
		action: 'done'
	});
	close();
}

function sendInfo(info: ImageInfo) {
	(<any>postMessage)({
		action: 'info',
		data: info
	});
}

module GifParser {
	/** Implementation of libgif's stream class for ArrayBuffer data*/
	class BlobStream implements GifStream {
		private data: Uint8Array;
		private pos: number;

		constructor(buffer: ArrayBuffer) {
			this.data = new Uint8Array(buffer);
			this.pos = 0;
		}

		public read(length: number): string {
			var s = '';
			for (var i = 0; i < length; i++) {
				s += String.fromCharCode(this.readByte());
			}
			return s;
		}

		public readByte(): number {
			if (this.pos >= this.data.length) {
				throw new Error('Attempted to read past end of stream.');
			}
			return this.data[this.pos++] & 0xFF;
		}

		public readBytes(length: number): number[] {
			var bytes = [];
			for (var i = 0; i < length; i++) {
				bytes.push(this.readByte());
			}
			return bytes;
		}

		public readUnsigned(): number {
			var a = this.readBytes(2);
			return (a[1] << 8) + a[0];
		}

		public skip(length: number): void {
			this.pos += length;
		}
	}

	class Handler implements GifParseHandler {
		callback: Function;
		info: ImageInfo;
		animated: boolean;

		constructor(info: ImageInfo, callback: (err, info) => void) {
			this.callback = callback;
			this.animated = false;
			this.info = info;

			this.info.frames = 0;
			this.info.framerate = 0;
			this.info.duration = 0;
		}

		gce(block: GifGceBlock) {
			this.info.frames += 1;
			this.info.duration += block.delayTime / 100;
		}

		eof(block) {
			if (this.info.duration > 0) {
				this.info.framerate = this.info.frames / this.info.duration;
			} else {
				delete this.info.framerate;
				delete this.info.duration;
			}

			this.callback(null, this.info);
			this.callback(null, null);
		}
	}

	export function parse(buffer: ArrayBuffer, info: ImageInfo, callback: (err, info) => void) {
		importScripts('lib/libgif.js');
		var stream = new BlobStream(buffer);
		var handler = new Handler(info, callback);
		parseGIF(stream, handler);
	}
}

module JpegParser {
	export function parse(buffer: ArrayBuffer, info: ImageInfo, callback: (err, info) => void) {
		importScripts('lib/ExifReader.js');
		try {
			var exif = new ExifReader();
			exif.load(buffer);

			var metadata = exif.getAllTags();

			// Check that the metadata actually contains data
			for (var key in metadata) {
				if (metadata.hasOwnProperty(key)) {
					info.metadata = metadata;
					break;
				}
			}

			callback(null, info);
			callback(null, null);
		} catch (e) {
			if (e instanceof Error && (<Error>e).message === 'No Exif data') {
				// Image doesn't have exif data. Ignore.
				callback(null, null);
			} else {
				throw e;
			}
		}
	}
}

module PngParser {
	export function parse(buffer: ArrayBuffer, info: ImageInfo, callback: (err, info) => void) {
		importScripts('lib/zlib.js');
		importScripts('lib/png.js');

		var info: ImageInfo = {};
		var data = new Uint8Array(buffer);
		var png = new PNG(data);

		info.bitDepth = png.pixelBitlength;

		if (png.animation) {
			info.frames = png.animation.numFrames;

			var duration = 0;
			png.animation.frames.forEach((frame) => {
				duration += frame.delay;
			});

			info.duration = duration / 1000;
			info.framerate = info.frames / info.duration;
		}

		for (var key in png.text) {
			if (png.text.hasOwnProperty(key)) {
				info.metadata = info.metadata || {};
				info.metadata[key] = {
					description: png.text[key],
					value: null
				};
			}
		}

		callback(null, info);
		callback(null, null);
	}
}


text:
/*globals define, Raphael, WebGMEGlobal, $, requirejs*/
/*jshint browser: true*/

/**
 * @author rkereskenyi / https://github.com/rkereskenyi
 * @author nabana / https://github.com/nabana
 */

define(['js/logger',
    'js/util',
    'js/Loader/LoaderCircles',
    'js/Utils/ComponentSettings',
    './ProjectRepositoryWidgetControl',
    'common/regexp',
    'moment',
    'blockies',
    'raphaeljs',
    'css!./styles/ProjectRepositoryWidget.css'
], function (Logger,
             util,
             LoaderCircles,
             ComponentSettings,
             ProjectRepositoryWidgetControl,
             REGEXP,
             moment,
             blockies) {
    'use strict';

    var ProjectRepositoryWidget,
        MASTER_BRANCH_NAME = 'master',
        REPOSITORY_LOG_VIEW_CLASS = 'project-repository-widget',
        SHOW_MORE_BUTTON_TEXT = 'Show more...',
        COMMIT_PACKAGE_COUNT = 100,
        COMMIT_DATA = 'commitData',
        COMMIT_CLASS = 'commit',
        ACTUAL_COMMIT_CLASS = 'actual',
        X_DELTA = 15,
        Y_DELTA = 25,   //Widgets/ProjectRepository/ProjectRepositoryWidget.scss - $table-row-height
        CONTENT_WIDTH = 1,
        CONTENT_HEIGHT = 1,
        ITEM_WIDTH = 8,     //Widgets/ProjectRepository/ProjectRepositoryWidget.scss - $commit-size
        ITEM_HEIGHT = 8,    //Widgets/ProjectRepository/ProjectRepositoryWidget.scss - $commit-size
        LINE_CORNER_SIZE = 5,
        LINE_FILL_COLOR = '#000000',
        NON_EXISTING_PARENT_LINE_GRADIENT_NAME = 'grad1',
        CREATE_BRANCH_EDIT_CONTROL_CLASS = 'create-branch-from-commit',
        BRANCH_LABEL_CLASS = 'branch-label',
        TAG_LABEL_CLASS = 'tag-label',
        COMMON_LABEL_CLASS = 'common-label',
        BTN_LOAD_COMMIT_CLASS = 'btnLoadCommit',
        COMMIT_ID = 'commitId',
        MESSAGE_DIV_CLASS = 'commit-message',
        USER_TO_AVATAR_PATH = {};

    ProjectRepositoryWidget = function (container, client, params) {
        var commitCount = 'commit_count';
        this._el = container;
        this._historyType = 'commits';
        this._start = null;
        this._dialog = params.dialog;
        this._projectAccess = client.getProjectAccess();
        this._client = client;
        this._config = ProjectRepositoryWidget.getDefaultConfig();
        ComponentSettings.resolveWithWebGMEGlobal(this._config, ProjectRepositoryWidget.getComponentId());

        this._commitBadges = Object.keys(this._config.commitBadges);
        this.clear();
        this._initializeUI();

        if (params) {
            COMMIT_PACKAGE_COUNT = params[commitCount] || COMMIT_PACKAGE_COUNT;
            this._start = params.start;
        }

        //attach its controller
        new ProjectRepositoryWidgetControl(client, this);

        this._logger = Logger.create('gme:Widgets:ProjectRepository:ProjectRepositoryWidget',
            WebGMEGlobal.gmeConfig.client.log);
        this._logger.debug('Created');
    };

    ProjectRepositoryWidget.prototype.clear = function () {
        var cCommit,
            i;

        this._commits = this._commits || [];

        for (i = 0; i < this._commits.length; i += 1) {
            cCommit = this._commits[i];
            if (cCommit.ui) {
                cCommit.ui.graphEl.remove();
                cCommit.ui.commitBadges.forEach(function (commitBadge) {
                    if (typeof commitBadge.destroy === 'function') {
                        commitBadge.destroy();
                    }
                });

                cCommit.ui.tableEl.find('*').off();
                cCommit.ui.tableEl.remove();
            }
        }

        this._commits = [];
        this._orderedCommitIds = [];
        this._actualCommitId = undefined;
        this._branches = [];
        this._branchNames = [];
        this._branchListUpdated = false;
        this._tags = [];
        this._tagNames = [];
        this._tagListUpdated = false;

        this._y = 0;
        this._trackEnds = [];
        this._renderIndex = -1;

        this._width = CONTENT_WIDTH;
        this._height = CONTENT_HEIGHT;

        this._nonExistingParentPaths = [];

        //clear UI content
        this._el.empty();

        //detach event handlers
        this._el.off('click');
        this._el.off('keyup');

        this._el.parent().css({
            width: '',
            'margin-left': '',
            'margin-top': '',
            top: ''
        });
    };

    ProjectRepositoryWidget.prototype.destroy = function () {
        this.clear();
        this._el.removeClass(REPOSITORY_LOG_VIEW_CLASS);
    };

    ProjectRepositoryWidget.prototype.addBranch = function (obj) {
        this._addBranch(obj);
    };

    ProjectRepositoryWidget.prototype.clearBranches = function () {
        this._clearBranches();
    };

    ProjectRepositoryWidget.prototype.addTag = function (obj) {
        this._addTag(obj);
    };

    ProjectRepositoryWidget.prototype.clearTags = function () {
        this._clearTags();
    };

    ProjectRepositoryWidget.prototype.addCommit = function (obj) {
        var idx = this._orderedCommitIds.push(obj.id) - 1;

        this._commits.push({
            x: -1,
            y: -1,
            id: obj.id,
            commitData: obj,
            ui: undefined
        });

        this._calculatePositionForCommit(idx);
    };

    ProjectRepositoryWidget.prototype.showProgressbar = function () {
        this._btnShowMore.hide();
        this._loader.start();
    };

    ProjectRepositoryWidget.prototype.hideProgressbar = function () {
        this._loader.stop();
        this._btnShowMore.show();
    };

    ProjectRepositoryWidget.prototype.render = function () {
        this._render();
    };

    ProjectRepositoryWidget.prototype.noMoreCommitsToDisplay = function () {
        this._noMoreCommitsToDisplay();
    };

    ProjectRepositoryWidget.prototype.loadMoreCommits = function (start) {
        if (start) {
            this.onLoadMoreCommits(this._commits.length + COMMIT_PACKAGE_COUNT, start);
        } else {
            this.onLoadMoreCommits(COMMIT_PACKAGE_COUNT, start);
        }
    };

    ProjectRepositoryWidget.prototype.branchesAndTagsUpdated = function () {
        if (this._commits.length === 0) {
            this._table.addClass('no-commits-in-table');
        } else {
            this._table.removeClass('no-commits-in-table');
        }
    };

    /******************* PUBLIC API TO BE OVERRIDDEN IN THE CONTROLLER **********************/

    ProjectRepositoryWidget.prototype.onLoadMoreCommits = function (num, start) {
        this._logger.warn('onLoadMoreCommits not overridden in Controller num: "' + num + '", start: "' + start + '"');
    };

    ProjectRepositoryWidget.prototype.onLoadCommit = function (params) {
        this._logger.warn('onLoadCommit is not overridden in Controller...params: \'' + JSON.stringify(params) + '\'');
    };

    ProjectRepositoryWidget.prototype.onDeleteBranchClick = function (branchName, branchHash) {
        this._logger.warn('onDeleteBranchClick is not overridden in Controller...branch, branchHash:',
            branchName, branchHash);
    };

    ProjectRepositoryWidget.prototype.onDeleteTagClick = function (branchName, branchHash) {
        this._logger.warn('onDeleteTagClick is not overridden in Controller...branch, branchHash:',
            branchName, branchHash);
    };

    ProjectRepositoryWidget.prototype.onCreateBranchFromCommit = function (params) {
        this._logger.warn('onCreateBranchFromCommit is not overridden in Controller...params: \'' +
            JSON.stringify(params) + '\'');
    };

    ProjectRepositoryWidget.prototype.onCreateTagFromCommit = function (params) {
        this._logger.warn('onCreateTagFromCommit is not overridden in Controller...params: \'' +
            JSON.stringify(params) + '\'');
    };

    ProjectRepositoryWidget.prototype.onSquashFromCommit = function (params) {
        this._logger.warn('onSquashFromCommit is not overridden in Controller...params: \'' +
            JSON.stringify(params) + '\'');
    };

    ProjectRepositoryWidget.prototype.onSelectBranch = function (params) {
        this._logger.warn('onSelectBranch is not overridden in Controller...params: \'' +
            JSON.stringify(params) + '\'');
    };

    /******************* PRIVATE API *****************************/

    ProjectRepositoryWidget.cMessageStyleStr = 'div.' + MESSAGE_DIV_CLASS + ' { max-width: __MW__px; }';

    ProjectRepositoryWidget.prototype._initializeUI = function () {
        var self = this;

        this._el.empty();

        this._el.addClass(REPOSITORY_LOG_VIEW_CLASS);

        //initialize all containers
        this._cMessageStyle = $('


text:
require "delegate"
require "github_changelog_generator/helper"

module GitHubChangelogGenerator
  # This class wraps Options, and knows a list of known options. Others options
  # will raise exceptions.
  class Options < SimpleDelegator
    # Raised on initializing with unknown keys in the values hash,
    # and when trying to store a value on an unknown key.
    UnsupportedOptionError = Class.new(ArgumentError)

    # List of valid option names
    KNOWN_OPTIONS = %i[
      add_issues_wo_labels
      add_pr_wo_labels
      add_sections
      author
      base
      between_tags
      breaking_labels
      breaking_prefix
      bug_labels
      bug_prefix
      cache_file
      cache_log
      compare_link
      configure_sections
      date_format
      deprecated_labels
      deprecated_prefix
      due_tag
      enhancement_labels
      enhancement_prefix
      exclude_labels
      exclude_tags
      exclude_tags_regex
      filter_issues_by_milestone
      frontmatter
      future_release
      github_endpoint
      github_site
      header
      http_cache
      include_labels
      issue_prefix
      issue_line_labels
      issue_line_body
      issues
      max_issues
      merge_prefix
      output
      project
      pulls
      release_branch
      release_url
      removed_labels
      removed_prefix
      require
      security_labels
      security_prefix
      simple_list
      since_tag
      ssl_ca_file
      summary_labels
      summary_prefix
      token
      unreleased
      unreleased_label
      unreleased_only
      user
      usernames_as_github_logins
      verbose
    ]

    # @param values [Hash]
    #
    # @raise [UnsupportedOptionError] if given values contain unknown options
    def initialize(values)
      super(values)
      unsupported_options.any? && raise(UnsupportedOptionError, unsupported_options.inspect)
    end

    # Set option key to val.
    #
    # @param key [Symbol]
    # @param val [Object]
    #
    # @raise [UnsupportedOptionError] when trying to set an unknown option
    def []=(key, val)
      supported_option?(key) || raise(UnsupportedOptionError, key.inspect)
      values[key] = val
    end

    # @return [Hash]
    def to_hash
      values
    end

    # Loads the configured Ruby files from the --require option.
    def load_custom_ruby_files
      self[:require].each { |f| require f }
    end

    # Pretty-prints a censored options hash, if :verbose.
    def print_options
      return unless self[:verbose]

      Helper.log.info "Using these options:"
      # For ruby 2.5.0+
      censored_values.each do |key, value|
        print(key.inspect, "=>", value.inspect)
        puts ""
      end
      puts ""
    end

    # Boolean method for whether the user is using configure_sections
    def configure_sections?
      !self[:configure_sections].nil? && !self[:configure_sections].empty?
    end

    # Boolean method for whether the user is using add_sections
    def add_sections?
      !self[:add_sections].nil? && !self[:add_sections].empty?
    end

    # @return [Boolean] whether write to `:output`
    def write_to_file?
      self[:output].present?
    end

    private

    def values
      __getobj__
    end

    # Returns a censored options hash.
    #
    # @return [Hash] The GitHub `:token` key is censored in the output.
    def censored_values
      values.clone.tap { |opts| opts[:token] = opts[:token].nil? ? "No token used" : "hidden value" }
    end

    def unsupported_options
      values.keys - KNOWN_OPTIONS
    end

    def supported_option?(key)
      KNOWN_OPTIONS.include?(key)
    end
  end
end


text:
package sun.io;

import sun.io.*;

public class ByteToCharCp942C extends ByteToCharDBCS_ASCII {
   protected static final String singleByteToChar;
   protected static final boolean leadByte[];
   protected static final short   index1[];
   protected static final String  index2;
   protected static final int     mask1;
   protected static final int     mask2;
   protected static final int     shift;

   static {
      ByteToCharDBCS_ASCII y = new ByteToCharCp942();
      mask1 = y.mask1;
      mask2 = y.mask2;
      shift = y.shift;
      leadByte = y.leadByte;
      index1 = y.index1;
      index2 = y.index2;

      /* Fix converter to pass through 0x00 to 0x7f unchanged to U+0000 to U+007F */
      String indexs = "";
      for (char c = '\0'; c < '\u0080'; ++c) indexs += c;
      singleByteToChar = indexs + y.singleByteToChar.substring(indexs.length());
   }

   public String getCharacterEncoding() {
      return "Cp942C";
   }

   ByteToCharCp942C() {
      super();
      super.mask1 = mask1;
      super.mask2 = mask2;
      super.shift = shift;
      super.leadByte = leadByte;
      super.singleByteToChar = singleByteToChar;
      super.index1 = index1;
      super.index2 = index2;
   }
}


text:
import {Form} from 'widget/form/form'
import {LegendBuilder, defaultColor} from 'app/home/map/legendBuilder'
import {Panel} from 'widget/panel/panel'
import {RecipeFormPanel, recipeFormPanel} from 'app/home/body/process/recipeFormPanel'
import {activator} from 'widget/activation/activator'
import {compose} from 'compose'
import {downloadCsv} from 'widget/download'
import {msg} from 'translate'
import {selectFrom} from 'stateUtils'
import ButtonSelect from 'widget/buttonSelect'
import PropTypes from 'prop-types'
import React from 'react'
import _ from 'lodash'
import guid from 'guid'
import styles from './legend.module.css'

const fields = {
    invalidEntries: new Form.Field()
        .predicate(invalid => !invalid, 'invalid'),
    entries: new Form.Field()
        .predicate((entries, {invalidEntries}) => !invalidEntries && entries.length, 'invalid')
}

const mapRecipeToProps = recipe => {
    const dataSets = selectFrom(recipe, 'model.trainingData').dataSets || []
    return ({
        hasTrainingData: !!dataSets.find(dataSet => dataSet.type !== 'COLLECTED' || !_.isEmpty(dataSet.referenceData)),
        importedLegendEntries: selectFrom(recipe, 'ui.importedLegendEntries'),
        legendEntries: selectFrom(recipe, 'model.legend.entries') || [],
        title: recipe.title || recipe.placeholder
    })
}

class _Legend extends React.Component {
    render() {
        const {dataCollectionManager} = this.props
        return (
            <RecipeFormPanel
                placement='bottom-right'
                className={styles.panel}
                onApply={() => setTimeout(() => setTimeout(() => dataCollectionManager.updateAll()))}>
                <Panel.Header
                    icon='list'
                    title={msg('process.classification.panel.legend.title')}
                />
                <Panel.Content scrollable={false}>
                    {this.renderContent()}
                </Panel.Content>
                <Form.PanelButtons>
                    {this.renderAddButton()}
                </Form.PanelButtons>
            </RecipeFormPanel>
        )
    }

    renderAddButton() {
        const {inputs: {entries}} = this.props
        const options = [
            {
                value: 'import',
                label: msg('map.legendBuilder.load.options.importFromCsv.label'),
                onSelect: () => this.importLegend()
            },
            {
                value: 'export',
                label: msg('map.legendBuilder.load.options.exportToCsv.label'),
                disabled: !entries.value || !entries.value.length,
                onSelect: () => this.exportLegend()
            }
        ]
        return (
            <ButtonSelect
                look={'add'}
                icon={'plus'}
                label={msg('button.add')}
                placement='above'
                tooltipPlacement='bottom'
                options={options}
                onClick={() => this.addEntry()}
            />
        )
    }

    renderContent() {
        const {hasTrainingData, inputs: {entries}} = this.props
        return (
            <LegendBuilder
                entries={entries.value}
                locked={hasTrainingData}
                onChange={(updatedEntries, invalid) => this.updateLegendEntries(updatedEntries, invalid)}
            />
        )
    }

    componentDidMount() {
        const {legendEntries, inputs} = this.props
        inputs.entries.set(legendEntries)
    }

    componentDidUpdate(prevProps) {
        const {inputs, importedLegendEntries, recipeActionBuilder} = this.props
        if (importedLegendEntries && !_.isEqual(importedLegendEntries, prevProps.importedLegendEntries)) {
            recipeActionBuilder('CLEAR_IMPORTED_LEGEND_ENTRIES', {importedLegendEntries})
                .del('ui.importedLegendEntries')
                .dispatch()
            inputs.entries.set(importedLegendEntries)
        }
    }

    addEntry() {
        const {inputs: {entries}} = this.props
        const id = guid()
        const max = _.maxBy(entries.value, 'value')
        const value = max ? max.value + 1 : 1
        const color = defaultColor(entries.value.length)
        const label = ''
        entries.set([...entries.value, {id, value, color, label}])
    }

    updateLegendEntries(legendEntries, invalidLegendEntries) {
        const {inputs} = this.props
        inputs.entries.set(legendEntries)
        inputs.invalidEntries.set(invalidLegendEntries)
    }

    exportLegend() {
        const {title, inputs: {entries}} = this.props
        const csv = [
            ['color,value,label'],
            entries.value.map(({color, value, label}) => `${color},${value},"${label.replaceAll('"', '\\"')}"`)
        ].flat().join('\n')
        const filename = `${title}_legend.csv`
        downloadCsv(csv, filename)
    }

    importLegend() {
        const {activator: {activatables: {legendImport}}} = this.props
        legendImport.activate()
    }
}

const valuesToModel = ({entries}) => ({
    entries: _.sortBy(entries, 'value')
})

const additionalPolicy = () => ({
    _: 'disallow',
    legendImport: 'allow'
})

export const Legend = compose(
    _Legend,
    recipeFormPanel({id: 'legend', fields, mapRecipeToProps, additionalPolicy, valuesToModel}),
    activator('legendImport')
)

Legend.propTypes = {
    dataCollectionManager: PropTypes.object.isRequired,
    recipeId: PropTypes.string,
}


text:
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { CommonModule } from '@angular/common';
import { CheckboxComponent } from './checkbox/checkbox.component';
import { IconModule } from '../icon-module/icon.module';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IconModule
  ],
  declarations: [CheckboxComponent],
  exports: [CheckboxComponent]
})
export class CheckboxModule { }


text:
using UnityEngine;
using System.Collections;
using ParticlePlayground;

[ExecuteInEditMode()]
public class EmitOnTranslation : MonoBehaviour {

	public PlaygroundParticlesC particles;				// Assign the particle system in Inspector
	public Transform movingTransform;					// Assign the moving Transform in Inspector
	public float minSpace = .1f;						// The minimum space required for emission

	bool isReady;
	Vector3 previousPosition;

	void Start () {
		if (particles==null)
			particles = GetComponent<PlaygroundParticlesC>();
		if (movingTransform==null)
			movingTransform = transform;
		if (particles!=null&&movingTransform!=null)
			isReady = true;
		previousPosition = movingTransform.position;
	}

	void Update () {
		if (isReady)
			EmissionMoveCheck();
	}

	/// <summary>
	/// Emit when particle system is moving.
	/// </summary>
	void EmissionMoveCheck () {
		if (movingTransform.position!=previousPosition) {
			float emissionStepper = 0;
			float deltaDistance = Vector3.Distance (previousPosition, movingTransform.position);
			if (deltaDistance<minSpace) return;
			Vector3 delta = previousPosition;
			Vector3 velocity = Vector3.zero;
			Color color = Color.white;
			while (emissionStepper<deltaDistance) {
				delta = Vector3.Lerp (previousPosition, movingTransform.position, emissionStepper/deltaDistance);
				particles.Emit(delta, velocity, color);
				emissionStepper += minSpace;
			}
		}
		previousPosition = movingTransform.position;
	}
}


text:
package org.apache.hadoop.fs.cosn;

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

/**
 * The input stream class is used for buffered files.
 * The purpose of providing this class is to optimize buffer write performance.
 */
public class ByteBufferOutputStream extends OutputStream {
  private ByteBuffer byteBuffer;
  private boolean isFlush;
  private boolean isClosed;

  public ByteBufferOutputStream(ByteBuffer byteBuffer) throws IOException {
    if (null == byteBuffer) {
      throw new IOException("byte buffer is null");
    }
    this.byteBuffer = byteBuffer;
    this.byteBuffer.clear();
    this.isFlush = false;
    this.isClosed = false;
  }

  @Override
  public void write(int b) {
    byte[] singleBytes = new byte[1];
    singleBytes[0] = (byte) b;
    this.byteBuffer.put(singleBytes, 0, 1);
    this.isFlush = false;
  }

  @Override
  public void flush() {
    if (this.isFlush) {
      return;
    }
    this.isFlush = true;
  }

  @Override
  public void close() throws IOException {
    if (this.isClosed) {
      return;
    }
    if (null == this.byteBuffer) {
      throw new IOException("Can not close a null object");
    }

    this.flush();
    this.byteBuffer.flip();
    this.byteBuffer = null;
    this.isFlush = false;
    this.isClosed = true;
  }
}


text:
import * as Promise from 'any-promise';
export declare type ReadFileOp = (path: string, encoding: string) => Promise<string>;
/**
 * Parse a string as JSON.
 */
export declare function parseJson(contents: string, path: string, allowEmpty: boolean): any;
/**
 * Read JSON from a path.
 */
export declare function readJson(path: string, allowEmpty?: boolean): Promise<any>;
export declare const readFile: ReadFileOp;


text:
//
//  XLZoomingScrollView.m
//  XLPhotoBrowserDemo
//
//  Created by Liushannoon on 16/7/15.
//  Copyright © 2016年 LiuShannoon. All rights reserved.
//

#import "XLZoomingScrollView.h"
#import "XLProgressView.h"

#import "SDImageCache.h"
#import "UIImage+GIF.h"

@interface XLZoomingScrollView () <UIScrollViewDelegate>
{
   UIScrollView *_scrollview;
}

@property (nonatomic , strong) UIImageView  *photoImageView;
@property (nonatomic , strong) XLProgressView *progressView;
@property (nonatomic , strong) UILabel *stateLabel;
@property (nonatomic, assign) BOOL hasLoadedImage;
@property (nonatomic , strong) NSURL  *imageURL;

@end

@implementation XLZoomingScrollView

#pragma mark    -   set / get

- (void)setProgress:(CGFloat)progress
{
    _progress = progress;
    self.progressView.progress = progress;
    if ([self.zoomingScrollViewdelegate respondsToSelector:@selector(zoomingScrollView:imageLoadProgress:)]) {
        [self.zoomingScrollViewdelegate zoomingScrollView:self imageLoadProgress:progress];
    }
}

- (UIImageView *)imageView
{
    return self.photoImageView;
}

- (UIImage *)currentImage
{
    return self.photoImageView.image;
}

- (UIImageView *)photoImageView
{
    if (_photoImageView == nil) {
        _photoImageView = [[UIImageView alloc] init];
        _photoImageView.backgroundColor = [UIColor clearColor];
    }

    return _photoImageView;
}

- (UIScrollView *)scrollview
{
    if (!_scrollview) {
        _scrollview = [[UIScrollView alloc] init];
        [_scrollview addSubview:self.photoImageView];
        _scrollview.delegate = self;
        _scrollview.clipsToBounds = YES;
        _scrollview.showsVerticalScrollIndicator = NO;
        _scrollview.showsHorizontalScrollIndicator = NO;
    }
    return _scrollview;
}

- (UILabel *)stateLabel
{
    if (_stateLabel == nil) {
        _stateLabel = [[UILabel alloc] init];
        _stateLabel.text = XLPhotoBrowserLoadNetworkImageFail;
        _stateLabel.font = [UIFont systemFontOfSize:16];
        _stateLabel.textColor = [UIColor whiteColor];
        _stateLabel.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.8];
        _stateLabel.layer.cornerRadius = 5;
        _stateLabel.clipsToBounds = YES;
        _stateLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _stateLabel;
}

- (XLProgressView *)progressView
{
    if (_progressView == nil) {
        _progressView = [[XLProgressView alloc] init];
    }
    return _progressView;
}

#pragma mark    -   initial UI

- (void)awakeFromNib
{
    [super awakeFromNib];
    [self initial];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self initial];
    }
    return self;
}

/**
 *  初始化
 */
- (void)initial
{
    [self addSubview:self.scrollview];

    UITapGestureRecognizer *singleTapBackgroundView = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapBackgroundView:)];
    UITapGestureRecognizer *doubleTapBackgroundView = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTapBackgroundView:)];
    doubleTapBackgroundView.numberOfTapsRequired = 2;
    [singleTapBackgroundView requireGestureRecognizerToFail:doubleTapBackgroundView];
    [self addGestureRecognizer:singleTapBackgroundView];
    [self addGestureRecognizer:doubleTapBackgroundView];
}

- (void)layoutSubviews
{
    [super layoutSubviews];

    self.stateLabel.bounds = CGRectMake(0, 0, 160, 30);
    self.stateLabel.center = CGPointMake(self.bounds.size.width * 0.5, self.bounds.size.height * 0.5);
    self.progressView.bounds = CGRectMake(0, 0, 100, 100);
    self.progressView.xl_centerX = self.xl_width * 0.5;
    self.progressView.xl_centerY = self.xl_height * 0.5;
    self.scrollview.frame = self.bounds;

    [self setMaxAndMinZoomScales];
}

#pragma mark    -   UIScrollViewDelegate

- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    self.photoImageView.center = [self centerOfScrollViewContent:scrollView];
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return self.photoImageView;
}

- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view
{
    self.scrollview.scrollEnabled = YES;
}

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale
{
    self.scrollview.userInteractionEnabled = YES;
}

#pragma mark    -   private method - 手势处理,缩放图片

- (CGPoint)centerOfScrollViewContent:(UIScrollView *)scrollView
{
    CGFloat offsetX = (scrollView.bounds.size.width > scrollView.contentSize.width)?
    (scrollView.bounds.size.width - scrollView.contentSize.width) * 0.5 : 0.0;
    CGFloat offsetY = (scrollView.bounds.size.height > scrollView.contentSize.height)?
    (scrollView.bounds.size.height - scrollView.contentSize.height) * 0.5 : 0.0;
    CGPoint actualCenter = CGPointMake(scrollView.contentSize.width * 0.5 + offsetX,
                                       scrollView.contentSize.height * 0.5 + offsetY);
    return actualCenter;
}

- (CGRect)zoomRectForScale:(CGFloat)scale withCenter:(CGPoint)center
{
    CGFloat height = self.frame.size.height / scale;
    CGFloat width  = self.frame.size.width / scale;
    CGFloat x = center.x - width * 0.5;
    CGFloat y = center.y - height * 0.5;
    return CGRectMake(x, y, width, height);
}

- (void)singleTapBackgroundView:(UITapGestureRecognizer *)singleTap
{
    if (self.zoomingScrollViewdelegate && [self.zoomingScrollViewdelegate respondsToSelector:@selector(zoomingScrollView:singleTapDetected:)]) {
        [self.zoomingScrollViewdelegate zoomingScrollView:self singleTapDetected:singleTap];
    }
}

- (void)doubleTapBackgroundView:(UITapGestureRecognizer *)doubleTap
{
    if (!self.hasLoadedImage) {
        return;
    }
    self.scrollview.userInteractionEnabled = NO;

    if (self.scrollview.zoomScale > self.scrollview.minimumZoomScale) {
        [self.scrollview setZoomScale:self.scrollview.minimumZoomScale animated:YES];
    } else {
        CGPoint point = [doubleTap locationInView:doubleTap.view];
        CGFloat touchX = point.x;
        CGFloat touchY = point.y;
        touchX *= 1/self.scrollview.zoomScale;
        touchY *= 1/self.scrollview.zoomScale;
        touchX += self.scrollview.contentOffset.x;
        touchY += self.scrollview.contentOffset.y;
        CGRect zoomRect = [self zoomRectForScale:self.scrollview.maximumZoomScale withCenter:CGPointMake(touchX, touchY)];
        [self.scrollview zoomToRect:zoomRect animated:YES];
    }
}

- (void)resetZoomScale
{
    self.scrollview.maximumZoomScale = 1.0;
    self.scrollview.minimumZoomScale = 1.0;
}

#pragma mark    -   public method

/**
 *  显示图片
 *
 *  @param image 图片
 */
- (void)setShowImage:(UIImage *)image
{
    self.photoImageView.image = image;
    if ([image isGIF]) {
        NSLog(@"ssssss");
    }

    [self setMaxAndMinZoomScales];
    [self setNeedsLayout];
    self.progress = 1.0;
    self.hasLoadedImage = YES;
}

/**
 *  显示图片
 *
 *  @param url         图片的高清大图链接
 *  @param placeholder 占位的缩略图 / 或者是高清大图都可以
 */
- (void)setShowHighQualityImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder
{
    if (!url) {
        [self setShowImage:placeholder];
        return;
    }

    UIImage *cacheImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:[url absoluteString]];
    if (cacheImage) {
        [self setShowImage:cacheImage];
        return;
    }

    self.photoImageView.image = placeholder;
    [self setMaxAndMinZoomScales];

    __weak typeof(self) weakSelf = self;

    [self addSubview:self.progressView];;
    self.progressView.mode = XLProgressViewProgressMode;
    self.imageURL = url;

    // TODO 失败点击重新下载功能
    [weakSelf.photoImageView sd_setImageWithURL:url placeholderImage:placeholder options:SDWebImageRetryFailed| SDWebImageLowPriority| SDWebImageHandleCookies progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
        dispatch_async(dispatch_get_main_queue(), ^{
            __strong __typeof(weakSelf)strongSelf = weakSelf;
            if ([strongSelf.imageURL isEqual:targetURL] && expectedSize > 0) {
                strongSelf.progress = (CGFloat)receivedSize / expectedSize ;
//                NSLog(@"targetURL %@ , strongSelf %@ , strongSelf.imageURL = %@ , progress = %f",targetURL , strongSelf , strongSelf.imageURL,strongSelf.progress);
            }
        });
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf.progressView removeFromSuperview];
        if (error) {
            [strongSelf setMaxAndMinZoomScales];
            [strongSelf addSubview:strongSelf.stateLabel];
            XLPBLog(@"加载图片失败 , 图片链接imageURL = %@ , 错误信息: %@ ,检查是否开启允许HTTP请求",imageURL,error);
        } else {
            [strongSelf.stateLabel removeFromSuperview];
            [UIView animateWithDuration:0.25 animations:^{
                [strongSelf setShowImage:image];
                [strongSelf.photoImageView setNeedsDisplay];
                [strongSelf setMaxAndMinZoomScales];
            }];
        }
    }];
}

/**
 *  根据图片和屏幕比例关系,调整最大和最小伸缩比例
 */
- (void)setMaxAndMinZoomScales
{
    // self.photoImageView的初始位置
    UIImage *image = self.photoImageView.image;
    if (image == nil || image.size.height==0) {
        return;
    }
    CGFloat imageWidthHeightRatio = image.size.width / image.size.height;
    self.photoImageView.xl_width = self.xl_width;
    self.photoImageView.xl_height = self.xl_width / imageWidthHeightRatio;
    self.photoImageView.xl_x = 0;
    if (self.photoImageView.xl_height > XLScreenH) {
        self.photoImageView.xl_y = 0;
        self.scrollview.scrollEnabled = YES;
    } else {
        self.photoImageView.xl_y = (XLScreenH - self.photoImageView.xl_height ) * 0.5;
        self.scrollview.scrollEnabled = NO;
    }
    self.scrollview.maximumZoomScale = MAX(XLScreenH / self.photoImageView.xl_height, 3.0);
    self.scrollview.minimumZoomScale = 1.0;
    self.scrollview.zoomScale = 1.0;
    self.scrollview.contentSize = CGSizeMake(self.photoImageView.xl_width, MAX(self.photoImageView.xl_height, XLScreenH));
}

/**
 *  重用,清理资源
 */
- (void)prepareForReuse
{
//    NSLog(@"prepareForReuse: strongSelf %@ , strongSelf.imageURL = %@ , progress = %f" , self , self.imageURL,self.progress);
    [self setMaxAndMinZoomScales];
    self.progress = 0;
    self.photoImageView.image = nil;
    self.hasLoadedImage = NO;
    [self.stateLabel removeFromSuperview];
    [self.progressView removeFromSuperview];
}

@end


text:
<?php

namespace Zeus;

/**
 * This class is meant to be extended by others classes that needs to be
 * persisted into database. It implements methods for storing and recovering
 * objects. Specialized classes should be a Doctrine Entity.
 */
class Entity
{

    /**
     * Finds a object using its identificator
     * @param mixed $id The identificator value
     * @return Entity The object being searched
     */
    public static function find($id)
    {
        $em = Database::getEntityManager();
        return $em->find(get_called_class(), $id);
    }

    /**
     * Saves the object into database (inserting or updating)
     */
    public function save()
    {
        $em = Database::getEntityManager();
        $em->beginTransaction();
        $em->persist($this);
        $em->commit();
        $em->flush();
    }

    /**
     * Deletes the object from database
     */
    public function delete()
    {
        $em = Database::getEntityManager();
        $em->beginTransaction();
        $em->remove($this);
        $em->commit();
        $em->flush();
    }

    /**
     * Returns a Doctrine QueryBuilder initially with all rows
     * @param string $alias Class alias used within the QueryBuilder
     * @param mixed $fields List of attributes from the called class
     * @return \Doctrine\ORM\QueryBuilder
     * @see http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/query-builder.html
     */
    public static function select(string $alias, $fields = null)
    {
        $em = Database::getEntityManager();
        return $em->createQueryBuilder()->select(is_null($fields) ? $alias : $fields)->from(get_called_class(), $alias);
    }

    /**
     * Returns a Doctrine Expression builder, for complex expressions
     * @return \Doctrine\ORM\Query\Expr
     */
    public static function expr()
    {
        $em = Database::getEntityManager();
        return $em->createQueryBuilder()->expr();
    }

}


text:
tropaj = {
  variables = {};
  get get(){
    var vars = {};
    if(window.location.search.length!==0)
      window.location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value){
      key=decodeURIComponent(key);
      if(typeof vars[key]==="undefined") {vars[key]= decodeURIComponent(value);}
      else {vars[key]= [].concat(vars[key], decodeURIComponent(value));}
      });
    return vars;
    }
    function css(elem,st) {
      e = document.getElementByID(elem);
      e.style = st;
    };
    function addTextToElement(elem,text) {
      e = document.getElementById(elem)
      e.appendChild(document.createTextNode(text))
    };
    function getAllParameters() {
      return variables;
    };
    function addParameter(name,val) {
      variables[name] = val;
    }
};


text:
describe('`string.includes()` determines if a string can be found inside another one', function() {
  describe('finding a single character', function() {
    it('can be done (a character is also a string, in JS)', function() {
      //// const searchString = 'a';
      const searchString = 'x';
      assert.equal('xyz'.includes(searchString), true);
    });
    it('reports false if character was not found', function() {
      //// const actual = '???';
      const actual = false;
      assert.equal(actual, 'xyz'.includes('abc'));
    });
  });
  describe('find a string', function() {
    it('that matches exactly', function() {
      //// const findSome = findMe => 'xyz'.includes;
      const findSome = findMe => 'xyz'.includes(findMe);
      assert.equal(findSome('xyz'), true);
    });
  });
  describe('search for an empty string, is always true', function() {
    it('in an empty string', function() {
      //// const emptyString = ' ';
      const emptyString = '';
      assert.equal(''.includes(emptyString), true);
    });
    it('in `abc`', function() {
      //// const actual = _.includes('');
      const actual = ''.includes('');
      assert.equal(actual, true);
    });
  });
  describe('special/corner cases', function() {
    it('search for `undefined` in a string fails', function() {
      //// const findInAbc = (what) => 'abc'.includes;
      const findInAbc = (what) => 'abc'.includes(what);
      assert.equal(findInAbc(undefined), false);
    });
    it('searches are case-sensitive', function() {
      //// const findInAbc = (what) => 'abc'.inkludez(what);
      const findInAbc = (what) => 'abc'.includes(what);
      assert.equal(findInAbc('A'), false);
    });
    it('must NOT be a regular expression', function() {
      //// const regExp = '';
      const regExp = /.*/;
      assert.throws(() => {''.includes(regExp)});
    });
    describe('coerces the searched "thing" into a string', function() {
      it('e.g. from a number', function() {
        //// const actual = '123'.includes(4);
        const actual = '1234'.includes(4);
        assert.equal(actual, true);
      });
      it('e.g. from an array', function() {
        //// const actual = '123'.includes([1,2,3]);
        const actual = '1,2,3'.includes([1,2,3]);
        assert.equal(actual, true);
      });
      it('e.g. from an object, with a `toString()` method', function() {
        //// const objWithToString = {toString: 1};
        const objWithToString = {toString: () => '123'};
        assert.equal('123'.includes(objWithToString), true);
      });
    });
  });
  describe('takes a position from where to start searching', function() {
    it('does not find `a` after position 1 in `abc`', function() {
      //// const position = 0;
      const position = 1;
      assert.equal('abc'.includes('a', position), false);
    });
    it('even the position gets coerced', function() {
      //// const findAtPosition = position => 'xyz'.includes('x', pos);
      const findAtPosition = pos => 'xyz'.includes('x', pos);
      assert.equal(findAtPosition('2'), false);
    });
    describe('invalid positions get converted to 0', function() {
      it('e.g. `undefined`', function() {
        //// const findAtPosition = (pos=2) => 'xyz'.includes('x', pos);
        const findAtPosition = (pos) => 'xyz'.includes('x', pos);
        assert.equal(findAtPosition(undefined), true);
      });
      it('negative numbers', function() {
        //// const findAtPosition = (pos) => 'xyz'.includes('x', -pos);
        const findAtPosition = (pos) => 'xyz'.includes('x', pos);
        assert.equal(findAtPosition(-2), true);
      });
      it('NaN', function() {
        //// const findAtPosition = (pos) => 'xyz'.includes('x', 1);
        const findAtPosition = (pos) => 'xyz'.includes('x', pos);
        assert.equal(findAtPosition(NaN), true);
      });
    });
  });
});


text:
@interface GHUITableViewCell : UITableViewCell

+ (Class)contentViewClass;

- (id)viewForContent;

+ (GHUITableViewCell *)tableViewCellForContentView:(UIView *)contentView;

@end


text:
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web;
using Microsoft.Owin;

namespace FunctionalTests.Facts.IntegratedPipeline
{
    public class IntegratedPipelineMiddleware : OwinMiddleware
    {
        private const string Error_Incorrect_Middleware_Unwinding = "[Failed]: Correct OWIN middlewareId not called in reverse order while unwinding. Expected middlewareId '{0}' to be called now, but middlewareId '{1}' called instead";
        private const string Error_UnexpectedMiddleware = "[Failed]: OWIN middlewareId '{2}' expected to be called at '{0}' where as it is called at '{1}'";

        private RequestNotification expectedStageName;
        private int middlewareId;

        public IntegratedPipelineMiddleware(OwinMiddleware next, RequestNotification expectedStageName, int middlewareId)
            : base(next)
        {
            this.expectedStageName = expectedStageName;
            this.middlewareId = middlewareId;
        }

        public override Task Invoke(IOwinContext context)
        {
            validateStage(context, expectedStageName, middlewareId);
            context.Get<Stack<int>>("stack").Push(middlewareId);

            return this.Next.Invoke(context).ContinueWith((result) =>
            {
                validateStage(context, RequestNotification.EndRequest, middlewareId);

                var expectedMiddlewareId = context.Get<Stack<int>>("stack").Pop();
                if (expectedMiddlewareId != middlewareId)
                {
                    throw new Exception(string.Format(Error_Incorrect_Middleware_Unwinding, expectedMiddlewareId, middlewareId));
                }
            });
        }

        private void validateStage(IOwinContext context, RequestNotification expectedStageName, int middlewareId)
        {
            var calledAtStage = context.Get<System.Web.HttpContextWrapper>("System.Web.HttpContextBase").CurrentNotification;
            if (calledAtStage != expectedStageName)
            {
                throw new Exception(string.Format(Error_UnexpectedMiddleware, expectedStageName, calledAtStage, middlewareId));
            }
        }
    }
}


text:
NS_ASSUME_NONNULL_BEGIN

// Fake NSURLSessionDataTask class which can be used for testing. |cancel| and
// |resume| methods only change the |state| of this task without actually
// starting or stopping the download.
@interface CRWFakeNSURLSessionTask : NSURLSessionDataTask

// Redefined NSURLSessionTask properties as readwrite.
@property(nonatomic) int64_t countOfBytesReceived;
@property(nonatomic) int64_t countOfBytesExpectedToReceive;
@property(nonatomic) NSURLSessionTaskState state;
@property(nonatomic, nullable, copy) NSURLResponse* response;

- (nullable instancetype)initWithURL:(NSURL*)URL NS_DESIGNATED_INITIALIZER;
- (nonnull instancetype)init NS_UNAVAILABLE;

@end

NS_ASSUME_NONNULL_END

#endif  // IOS_WEB_TEST_FAKES_CRW_FAKE_NSURL_SESSION_TASK_H_


text:
/**
 * 包含 n 个reducer 函数的模块(根据老的 state和 action返回一个新的 state)
 */
import {ADD_COMMENT, DELETE_COMMENT, RECEIVE_COMMENTS} from './action-types'
import {combineReducers} from 'redux'
// const initComments = [
//   { username: "Tom", content: "React 挺好的!" },
//   { username: "Jack", content: "React太难了!还是学不会" },
// ];

const initComments = [];

// state 的原状态不能改变,要产生一个新的状态
function comments(state = initComments, action) {
  switch (action.type) {
    case ADD_COMMENT:
      return [action.data, ...state];
    case DELETE_COMMENT:
      return state.filter((comment, index) => index !==action.data);
    case RECEIVE_COMMENTS:
      return action.data;
    default:
      return state;
  }
}

export default combineReducers({
  comments, // 指定 reducer 对应的属性
})

// redux 向外暴露的是state个什么结构
// {comments:[], ...}


text:
* 2016-04-11 Added support for rate limiting new connections. See [Connection Limits](http://developer.oanda.com/rest-live/best-practices/#connection_limits) for details on limits. Rate limiting is NOT enabled by default. To enable rate limiting:

   ```ruby
		OandaAPI.configure do |config|
		  config.use_request_throttling = true
		  config.max_new_connections_per_second = 1
		end
	```

  `config.use_request_throttling = true` can prevent exceeding Oanda's limit on the rate of creating new connections (you'll receive an HTTP 429 response, and a message stating: "Rate limit violation of newly established connections" if you exceed the limit). Note that this is a completely separate rate limit from the maximum number of requests allowed per second on an established connection (use `config.max_requests_per_second` to configure that).

## 0.9.5
* 2016-03-18 Fixed `OandaAPI::Resource::Order#initialize` to correctly initialize `#order_opened`, `#trade_opened`, `#trade_reduced`, and `#trades_closed` from the response data.

* 2016-03-16 Added support for the Oanda [Forex Labs Spread History](http://developer.oanda.com/rest-live/forex-labs/#spreads) API:

   ```ruby
     require 'oanda_api'
     # If you want to use sugar like: 1.day, 1.hour, 1.week, etc.
     require 'active_support/core_ext/numeric/time'

     client = OandaAPI::Client::TokenClient.new(:practice, ENV.fetch("OANDA_PRACTICE_TOKEN"))
     spreads = client.spreads(instrument: "EUR_USD", period: 1.day).get

     spreads.class                    # OandaAPI::Resource::Labs::SpreadHistory
     spreads.averages.size            # => 94
     spreads.maximums.size            # => 76
     spreads.averages.size            # => 50

     spreads.averages.first.spread    # => 1.81711
     spreads.averages.first.timestamp # => 1458081900
     spreads.averages.first.time      # => 2016-03-15 23:00:00 UTC

     spreads.maximums.first.spread    # => 2.1
     spreads.maximums.first.timestamp # => 1458082800
     spreads.maximums.first.time      # => 2016-03-15 23:00:00 UTC

     spreads.minimums.first.spread    # => 1.6
     spreads.minimums.first.timestamp # => 1458081900
     spreads.minimums.first.time      # => 2016-03-15 23:00:00 UTC
   ```

* 2016-03-16 Fixed `OandaAPI::Streaming::Client#emit_heartbeats=true`. Now heartbeats actually will be emitted if true. Previously this setting was ignored and heartbeats were never emitted. Thanks [dogwood008](https://github.com/dogwood008)!

* 2016-03-15  Now TLS verify_mode is explicitly set to OpenSSL::SSL::VERIFY_PEER instead of relying on underlying library defaults.

* 2016-03-14  Added support for the Oanda [Forex Labs Economic Calendar](http://developer.oanda.com/rest-live/forex-labs/#calendar) API:

  Thanks [unageanu](https://github.com/unageanu)!

   ```ruby
     require 'oanda_api'
     # If you want to use sugar like: 1.day, 1.hour, 1.week, etc.
     require 'active_support/core_ext/numeric/time'

     client = OandaAPI::Client::TokenClient.new(:practice, ENV.fetch("OANDA_PRACTICE_TOKEN"))

     client.calendar_events(period: 1.day).get.each do |event|
       event.class     # => OandaAPI::Resource::CalendarEvent
       event.title     # => "Industrial Production"
       event.currency  # => "EUR"
       event.region    # => "europe"
       event.forecast  # => "-0.3"
       event.previous  # => "-0.3"
       event.actual    # => "3.3"
       event.impact    # => "2"
       event.unit      # => "% m/m"
       event.timestamp # => 1457420400
       event.time      # => 2016-03-08 07:00:00 UTC
     end
   ```

* 2016-03-14 Deprecated `OandaAPI::Client::UsernameClient`. The `http://api-sandbox.oanda.com/` endpoint that this client used is no longer supported by Oanda. Instead, you can use `OandaAPI::Client::TokenClient` with a practice account.

## 0.9.4

* Added multi-threaded support for request throttling. Now if you've configured the API to use request throttling:

  ```ruby
  OandaAPI.configure do |config|
      config.use_request_throttling = true
      config.max_requests_per_second = 15
  end
  ```
and if you access a single instance of the API from multiple threads, then the request rate will be throttled correctly.

* Added a new configuration to customize the number of connections the API holds in the connection pool. Useful if your application requires multiple connections to the API, for example multiple threads issuing requests through the API. The default connection pool size is 2.

   ```ruby
   OandaAPI.configure do |config|
      config.connection_pool_size = 5
  end
   ```
Thanks [LifeBCE](https://github.com/lifeBCE)!

## 0.9.3

* Fixed support for retrieving [full account history](http://developer.oanda.com/rest-live/transaction-history/#getFullAccountHistory). Thanks [bewon](https://github.com/bewon)!
* Fixed issue [#6](https://github.com/nukeproof/oanda_api/issues/6) to make streaming JSON parsers available correctly under *nix. Thanks [LifeBCE](https://github.com/lifeBCE)!

## 0.9.2

 * Specify version of HTTParty as 0.13.3 until HTTParty issue [#398](https://github.com/jnunemaker/httparty/issues/398) is resolved.
 * Now support any whitespace as delimiting multiple JSON objects in streaming API with `OandaAPI::Streaming::Adapters::Generic`.

## 0.9.1

 * Fixed JSON serialization for nested ResourceBase instances.
 * Fixed some edge cases that could generate ParseError when parsing streaming JSON.
 * Added support for streaming JSON parsers [yajl-ruby](https://github.com/brianmario/yajl-ruby) and [gson](https://github.com/avsej/gson.rb).
 * Serialized JSON is now deserialized using symbolized names to avoid garbage collection overhead that occurs when strings are used.

###What's New?
As with version 0.9.0, `OandaAPI::Streaming::Client` will use the JSON gem parser if it is the only JSON parser installed. However, the JSON gem does not support parsing streams of objects very robustly (i.e. it expects complete documents, or the stream to delimit multiple objects consistently). If you are using the streaming API, and install either the [yajl-ruby](https://github.com/brianmario/yajl-ruby) gem (for MRI and Rubinius ruby) or the [gson](https://github.com/avsej/gson.rb) gem (for jruby), then `OandaAPI::Streaming::Client` will use either of those streaming JSON gems for a gain in reliability.

## 0.9.0

 * Add support for live [Streaming](http://developer.oanda.com/rest-live/streaming/).
 * Add #to_json serialization to resource classes.
 * Fixed Yardoc formatting.

###What's New?
OandaAPI now supports Oanda's streaming API for consuming realtime ticks and account transactions. See the example in the README and have a look at the specs for `OandaAPI::Streaming::Client`.


text:
guid: 22727592-92bd-4050-a5e6-f21c7bccbc8a
type: Live
reformat: True
shortenReferences: True
categories: mnemonics
scopes: InCSharpTypeMember(minimumLanguageVersion=2.0); InCSharpTypeAndNamespace(minimumLanguageVersion=2.0)
parameterOrder: fieldname
fieldname-expression: constant("fieldname")
---

# nd

A field of type $typename$ initialized to the default value.

```
private double $fieldname$ = 0.0;
```


text: Rails.application.config.session_store :cookie_store, key: '_webmock_session', expire_after: 7.days


text:
<?php

/**
 * Wrapper for PHP notices.
 * You can disable notice-to-exception conversion by setting
 *
 * <code>
 * PHPUnit_Framework_Error_Notice::$enabled = FALSE;
 * </code>
 *
 * @package    PHPUnit
 * @subpackage Framework_Error
 * @author     Sebastian Bergmann <sebastian@phpunit.de>
 * @copyright  2002-2011 Sebastian Bergmann <sebastian@phpunit.de>
 * @license    http://www.opensource.org/licenses/bsd-license.php  BSD License
 * @version    Release: @package_version@
 * @link       http://www.phpunit.de/
 * @since      Class available since Release 3.3.0
 */
class PHPUnit_Framework_Error_Notice extends PHPUnit_Framework_Error
{
    public static $enabled = TRUE;
}


text:
package org.apache.camel.component.azure.storage.blob.operations;

import java.util.Collections;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

import com.azure.storage.blob.models.BlobStorageException;
import com.azure.storage.blob.models.PublicAccessType;
import org.apache.camel.Exchange;
import org.apache.camel.component.azure.storage.blob.BlobConfiguration;
import org.apache.camel.component.azure.storage.blob.BlobConstants;
import org.apache.camel.component.azure.storage.blob.BlobTestUtils;
import org.apache.camel.component.azure.storage.blob.client.BlobClientFactory;
import org.apache.camel.component.azure.storage.blob.client.BlobContainerClientWrapper;
import org.apache.camel.component.azure.storage.blob.client.BlobServiceClientWrapper;
import org.apache.camel.support.DefaultExchange;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.awaitility.Awaitility;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;

import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class BlobContainerOperationsIT extends CamelTestSupport {

    private BlobConfiguration configuration;
    private BlobServiceClientWrapper blobServiceClientWrapper;

    @BeforeAll
    public void setup() throws Exception {
        final Properties properties = BlobTestUtils.loadAzureAccessFromJvmEnv();

        configuration = new BlobConfiguration();
        configuration.setAccountName(properties.getProperty("account_name"));
        configuration.setAccessKey(properties.getProperty("access_key"));

        blobServiceClientWrapper = new BlobServiceClientWrapper(BlobClientFactory.createBlobServiceClient(configuration));
    }

    @Test
    public void testCreateAndDeleteContainer() {
        final BlobContainerClientWrapper containerClientWrapper = blobServiceClientWrapper.getBlobContainerClientWrapper("testcontainer1");
        final BlobContainerOperations blobContainerOperations = new BlobContainerOperations(containerClientWrapper);

        final BlobOperationResponse response = blobContainerOperations.createContainer(null);

        assertNotNull(response);
        assertNotNull(response.getHeaders().get(BlobConstants.RAW_HTTP_HEADERS));
        assertTrue((boolean) response.getBody());

        // delete everything
        blobContainerOperations.deleteContainer(null);

        // test with options being set
        final Exchange exchange = new DefaultExchange(context);
        exchange.getIn().setHeader(BlobConstants.METADATA, Collections.singletonMap("testKeyMetadata", "testValueMetadata"));
        exchange.getIn().setHeader(BlobConstants.PUBLIC_ACCESS_TYPE, PublicAccessType.CONTAINER);

        // try to create the container again, we try until we can
        Awaitility.given()
                .ignoreException(BlobStorageException.class)
                .with()
                .pollInterval(100, TimeUnit.MILLISECONDS)
                .await()
                .atMost(60, TimeUnit.SECONDS)
                .until(() -> {
                    final BlobOperationResponse response1 = blobContainerOperations.createContainer(exchange);
                    assertNotNull(response1);
                    assertNotNull(response1.getHeaders().get(BlobConstants.RAW_HTTP_HEADERS));

                    return (boolean) response1.getBody();
                });
    }

    @AfterAll
    public void cleanUp() {
        blobServiceClientWrapper.getBlobContainerClientWrapper("testcontainer1").deleteContainer(null, null);
    }
}


text:
require 'rails'

module Jspdf
  module Rails
    class Engine < ::Rails::Engine
    end
  end
end


text:
package xworker.dataObject.annotation;

import org.apache.commons.collections.MapUtils;
import org.xmeta.ActionContext;
import org.xmeta.ActionException;
import org.xmeta.Thing;
import org.xmeta.util.UtilString;
import xworker.dataObject.DataObject;
import xworker.dataObject.PageInfo;
import xworker.util.UtilData;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class BeanDataObjectHelper {
    private final static String KEY = "__BeanDataObjectHelper__";
    private static Map<Class<?>, BeanDataObjectHelper> helpers = new HashMap<>();

    private Map<String, FieldHelper> fieldHelpes = new HashMap<String, FieldHelper>();

    /**
     * 创建bean的方法。
     */
    Method beanCreator;

    Method createMethod;
    Method updateMethod;
    Method deleteMethod;
    Method queryMethod;
    Method loadMethod;

    Thing dataObjectThing;

    Class<?> cls;

    public static BeanDataObjectHelper parse(Thing dataObjectThing, Class<?> cls) {
        synchronized(helpers){
            BeanDataObjectHelper helper = helpers.get(cls);

            if(helper == null){
                BeanDataObject[] dataObjects = cls.getAnnotationsByType(BeanDataObject.class);
                if(dataObjects.length > 0){
                    helper = new BeanDataObjectHelper();
                    helper.cls = cls;
                    helper.loadMethod = getMethod(cls, "doLoad", cls);
                    helper.createMethod = getMethod(cls, "doCreate", cls);
                    helper.updateMethod = getMethod(cls, "doUpdate", cls);
                    helper.deleteMethod = getMethod(cls, "doDelete", cls);
                    helper.queryMethod = getMethod(cls, "doQuery", Map.class, PageInfo.class);

                    helper.dataObjectThing = createDataObjectThing(cls, dataObjects[0]);
                    helper.dataObjectThing.setData(KEY, helper);

                    for(Field field : cls.getDeclaredFields()){
                        BeanDataObjectField[] fields = field.getAnnotationsByType(BeanDataObjectField.class);
                        if(fields.length > 0){

                        }
                    }

                }else{
                    throw new ActionException("Class " + cls.getName() + " is not a BeanDataObject, please add annotation @BeanDataObject.");
                }
            }

            return helper;
        }
    }

    public static Method getMethod(Class<?> cls, String methodName, Class<?> ... params){
        try {
            return cls.getMethod(methodName, params);
        }catch(Exception e){
            return null;
        }
    }
    public static BeanDataObjectHelper getHelper(Thing dataObjectThing){
        BeanDataObjectHelper helper = (BeanDataObjectHelper) dataObjectThing.getData(KEY);
        if(helper == null){
            Class<?> cls = dataObjectThing.doAction("getClass", new ActionContext());
            if(cls != null){
                helper = BeanDataObjectHelper.parse(dataObjectThing, cls);
                dataObjectThing.setData(KEY, helper);
            }
        }

        return null;
    }

    private static Thing createFieldThing(Field field, BeanDataObjectField dataObjectField){
        return null;
    }

    private static Thing createDataObjectThing(Class<?> cls, BeanDataObject dataObject){
        Thing thing = new Thing("xworker.dataObject.AbstractDataObject");
        thing.set("name", cls.getSimpleName());
        thing.set("paging", dataObject.paging());
        thing.set("pageSize", dataObject.pageSize());
        thing.set("gridEditable", dataObject.gridEditable());
        thing.set("autoLoad", dataObject.autoLoad());
        thing.set("autoSave", dataObject.autoSave());
        thing.set("valueName", dataObject.valueName());
        thing.set("displayName", dataObject.displayName());

        String attributes = dataObject.attributes();
        if(!attributes.isEmpty()){
            thing.getAttributes().putAll(UtilString.getParams(attributes));
        }

        Thing actions = new Thing("xworker.dataObject.AbstractDataObject/@actions");
        thing.addChild(actions);

        return thing;
    }

    public Thing getDataObjectThing(){
        return null;
    }

    public DataObject toDataObject(DataObject data, Object obj){
        if(obj == null){
            return null;
        }

        data.setWrappedObject(obj);
        for(String key : fieldHelpes.keySet()){
            FieldHelper fieldHelper = fieldHelpes.get(key);
            data.put(key, fieldHelper.getValue(obj));
        }
        return data;
    }

    public Object toBean(DataObject dataObject){
        if(dataObject.getWrappedObject() != null){
            return dataObject.getWrappedObject();
        }

        return null;
    }

    public DataObject create(DataObject dataObject){
        if(createMethod == null){
            throw new ActionException("Can not create, please add public static " + cls.getSimpleName()
                    + " doCreate(" + cls.getSimpleName() + "bean)");
        }
        Object bean = toBean(dataObject);
        try {
            Object newBean = createMethod.invoke(null, bean);
            return toDataObject(dataObject, newBean);
        }catch(Exception e){
            throw new ActionException(e);
        }
    }

    static class FieldHelper{
        Field field;
        Method getMethod;
        Method setMethod;

        public Object getValue(Object obj) {
            try {
                if (getMethod != null) {
                    return getMethod.invoke(obj);
                } else if (field != null) {
                    return field.get(obj);
                } else {
                    throw new ActionException("Can not get value, not field or getMethod");
                }
            }catch (Exception e){
                throw new ActionException(e);
            }
        }

        public void setValue(Object obj, Object value) {
            try {
                if (setMethod != null) {
                    setMethod.invoke(obj, value);
                } else if (field != null) {
                    field.set(obj, value);
                } else {
                    throw new ActionException("Ca not set value, no field or setMethod");
                }
            }catch(Exception e){
                throw new ActionException(e);
            }
        }
    }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Composition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;

namespace Microsoft.CodeAnalysis.Navigation
{
    [ExportWorkspaceServiceFactory(typeof(ISymbolNavigationService), ServiceLayer.Default), Shared]
    internal class DefaultSymbolNavigationServiceFactory : IWorkspaceServiceFactory
    {
        private ISymbolNavigationService _singleton;

        [ImportingConstructor]
        [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
        public DefaultSymbolNavigationServiceFactory()
        {
        }

        public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
        {
            if (_singleton == null)
            {
                _singleton = new DefaultSymbolNavigationService();
            }

            return _singleton;
        }
    }
}


text:
(function(){
//分类表中的一行
    var Data=Backbone.Model.extend({});
    var collection=Backbone.Collection.extend({
        model:Data,
        initialize:function(){
            var mode='',data;
            var self=this;
            var curmodel=new this.model();
            /*
             _.each(data,function(value){
             mode=curmodel.clone();
             mode.set(value)
             self.push(mode);
             })
             */
        }
    });
    //创建管理员管理设置数据
    window.ADMIN.M.wechatSet=collection;

})();


text:
SYNONYM

#### According to
GRIN Taxonomy for Plants

#### Published in
Bull. Soc. Hist. Nat. Afrique N. 19:33. 1928

#### Original name
null

### Remarks
null


text:
@interface TEOctagon : TERegularPolygon

@end


text:
var proc = this, args = proc.getArguments();

Webos.require([
	'/usr/lib/webos/font-detector.js',

	//Bootstrap
	/*'/usr/lib/bootstrap/bootstrap.min.js',
	'/usr/share/css/bootstrap/bootstrap.min.css'*/

	//JSPDF
	{
		path: '/usr/lib/jspdf/jspdf.js',
		exportApis: 'jsPDF'
	},
	'/usr/lib/jspdf/jspdf.standard_fonts_metrics.js',
	'/usr/lib/jspdf/jspdf.split_text_to_size.js',
	'/usr/lib/jspdf/jspdf.from_html.js',
	//WebODF
	{
		path: '/usr/lib/webodf/webodf.min.js',
		exportApis: ['odf', 'webodf_css']
	}
], function () {
	var Writer = function () {
		Webos.Observable.call(this);

		this.initialize();
	};
	Writer.prototype = {
		_$win: $(),
		_$docInner: $(),
		_file: null,
		_saved: false,
		initialize: function () {
			var that = this;

			W.xtag.loadUI('/usr/share/templates/writer/main.html', function(windows) {
				that._$win = $(windows).filter(':eq(0)');

				var $win = that._$win;
				that._$docInner = $win.find('.writer-inner');

				$win.window('open');

				that._initUi();

				if (!that.supports()) {
					W.Error.trigger('Your browser is not supported, falling back to "read only" mode.', 'The support of the "contenteditable" HTML5 property is required to edit the documents.');
				}

				that.trigger('ready');
			});
		},
		_initUi: function () {
			var that = this;
			var $win = this._$win;

			var btnsHandlers = {
				'btn-document-new': function () {
					W.Cmd.execute('writer');
				},
				'btn-document-open': function () {
					that.openFile();
				},
				'btn-edit-undo': function () {
					that.command('undo');
				},
				'btn-edit-redo': function () {
					that.command('redo');
				},

				'btn-document-save': function () {
					that.saveFile();
				},
				'btn-document-export': function () {
					that.exportToPdf();
				},
				'btn-settings': function () {},

				'btn-format-text-bold': function () {
					that.command('bold');
				},
				'btn-format-text-italic': function () {
					that.command('italic');
				},
				'btn-format-text-underline': function () {
					that.command('underline');
				},
				'btn-format-align-left': function () {
					that.command('justifyleft');
				},
				'btn-format-align-center': function () {
					that.command('justifycenter');
				},
				'btn-format-align-right': function () {
					that.command('justifyright');
				},
				'btn-format-align-justify': function () {
					that.command('justifyfull');
				},
				'btn-format-list-unordered': function () {
					that.command('insertUnorderedList');
				},
				'btn-format-list-ordered': function () {
					that.command('insertOrderedList');
				}
			};

			var sel = null;
			var saveSel = function () {
				var newSel = that._saveSelection();
				if (newSel) {
					sel = newSel;
				}
			};
			var restoreSel = function () {
				that._restoreSelection(sel);
			};

			var refreshUi = function () {
				if (!that._$docInner.is(':focus')) {
					return;
				}

				$win.find('.format-font-size:not(:focus)').val(that.commandValue('fontSize') || 2);

				var fontFamilies = that.commandValue('fontName').split(','), fontFamily = '';
				for (var i = 0; i < fontFamilies.length; i++) {
					var font = fontFamilies[i].replace(/(^[ '"]+|[ '"]+$)/g, '');
					if (that._detectFont(font)) {
						fontFamily = font;
						break;
					}
				}
				$win.find('.font-family').html(fontFamily);
				$win.find('.font-family-input:not(:focus)').val(fontFamily.toLowerCase());

				var fontColor = that.commandValue('foreColor') || 'black';
				$win.find('.font-color').css('background-color', fontColor);
				$win.find('.font-color-input:not(:focus)').val(fontColor);

				var align = {
					left: that.commandValue('justifyleft'),
					center: that.commandValue('justifycenter'),
					right: that.commandValue('justifyright'),
					justify: that.commandValue('justifyfull')
				};
				for (var alignType in align) {
					var alignVal = align[alignType];

					if (alignVal === 'true' || alignVal === alignType) {
						alignVal = true;
					} else {
						alignVal = false;
					}

					$win.find('.btn-format-align-'+alignType).button('option', 'activated', alignVal);
				}

				var isBold = that.commandValue('bold');
				$win.find('.btn-format-text-bold').button('option', 'activated', (isBold && isBold != 'false'));
				var isItalic = that.commandValue('italic');
				$win.find('.btn-format-text-italic').button('option', 'activated', (isItalic && isItalic != 'false'));
				var isUnderline = that.commandValue('underline');
				$win.find('.btn-format-text-underline').button('option', 'activated', (isUnderline && isUnderline != 'false'));

				var isUnorderedList = that.commandValue('insertUnorderedList');
				$win.find('.btn-format-list-unordered').button('option', 'activated', (isUnorderedList && isUnorderedList != 'false'));
				var isOrderedList = that.commandValue('inserOrderedList');
				$win.find('.btn-format-list-ordered').button('option', 'activated', (isOrderedList && isOrderedList != 'false'));
			};

			for (var btnName in btnsHandlers) {
				(function (btnName, btnHandler) {
					$win.find('.'+btnName).click(function () {
						restoreSel();
						btnHandler();
						refreshUi();
					});
				})(btnName, btnsHandlers[btnName]);
			}

			$win.find('.writer-inner').on('mouseup keyup', function () {
				if (typeof document.onselectstart == 'undefined') {
					$(this).trigger('selectstart', { emulated: true }); //Not all browsers support the "select" event
				}
			}).on('selectstart', function (evt, data) {
				if (data && data.emulated) {
					refreshUi();
				} else { //This is an original event, we have to wait the selection to be changed
					setTimeout(function () {
						refreshUi();
					}, 0);
				}
			});

			$win.find('.writer-toolbar').mousedown(function () {
				saveSel();
			});

			$win.find('.format-font-size').on('keyup mouseup input', function (evt) {
				restoreSel();

				that.command('fontSize', $(this).val());
				$(this).focus();
			});
			$win.find('.font-color-input').on('keyup input', function (evt) {
				restoreSel();

				that.command('foreColor', $(this).val());
				$(this).focus();
			});
			$win.find('.font-family-input').children('option').each(function () {
				var font = $(this).text();

				if (!that._detectFont(font)) {
					$(this).remove();
				} else {
					$(this).attr('value', font.toLowerCase());
				}
			});
			$win.find('.font-family-input').on('change', function (evt) {
				restoreSel();

				that.command('fontName', $(this).val());
				refreshUi();
			});

			$win.find('.writer-page').click(function (evt) {
				if (!$(evt.target).is('.writer-page')) {
					return;
				}

				that._$docInner.focus();
			});

			that.command('styleWithCSS');
			that.command('enableInlineTableEditing');
			that.command('enableObjectResizing');
			this._$docInner.focus();
		},
		//From http://jsfiddle.net/timdown/gEhjZ/4/
		_saveSelection: function () {
			var containerEl = this._$docInner[0];

			if (window.getSelection && document.createRange) {
				var doc = containerEl.ownerDocument, win = doc.defaultView;

				if (!win.getSelection().rangeCount) {
					return null;
				}

				var range = win.getSelection().getRangeAt(0);

				if (!range.intersectsNode(containerEl)) {
					return null;
				}

				var preSelectionRange = range.cloneRange();
				preSelectionRange.selectNodeContents(containerEl);
				preSelectionRange.setEnd(range.startContainer, range.startOffset);
				var start = preSelectionRange.toString().length;

				return {
					start: start,
					end: start + range.toString().length
				};
			} else {
				var doc = containerEl.ownerDocument, win = doc.defaultView || doc.parentWindow;
				var selectedTextRange = doc.selection.createRange();
				var preSelectionTextRange = doc.body.createTextRange();
				preSelectionTextRange.moveToElementText(containerEl);
				preSelectionTextRange.setEndPoint("EndToStart", selectedTextRange);
				var start = preSelectionTextRange.text.length;

				return {
					start: start,
					end: start + selectedTextRange.text.length
				};
			}
		},
		_restoreSelection: function (savedSel) {
			var containerEl = this._$docInner[0];

			if (!this._$docInner.is(':focus')) {
				this._$docInner.focus();
			}

			if (!savedSel) {
				return;
			}

			if (window.getSelection && document.createRange) {
				var doc = containerEl.ownerDocument, win = doc.defaultView;
				var charIndex = 0, range = doc.createRange();
				range.setStart(containerEl, 0);
				range.collapse(true);
				var nodeStack = [containerEl], node, foundStart = false, stop = false;

				while (!stop && (node = nodeStack.pop())) {
					if (node.nodeType == 3) {
						var nextCharIndex = charIndex + node.length;
						if (!foundStart && savedSel.start >= charIndex && savedSel.start <= nextCharIndex) {
							range.setStart(node, savedSel.start - charIndex);
							foundStart = true;
						}
						if (foundStart && savedSel.end >= charIndex && savedSel.end <= nextCharIndex) {
							range.setEnd(node, savedSel.end - charIndex);
							stop = true;
						}
						charIndex = nextCharIndex;
					} else {
						var i = node.childNodes.length;
						while (i--) {
							nodeStack.push(node.childNodes[i]);
						}
					}
				}

				var sel = win.getSelection();
				sel.removeAllRanges();
				sel.addRange(range);
			} else {
				var doc = containerEl.ownerDocument, win = doc.defaultView || doc.parentWindow;
				var textRange = doc.body.createTextRange();
				textRange.moveToElementText(containerEl);
				textRange.collapse(true);
				textRange.moveEnd("character", savedSel.end);
				textRange.moveStart("character", savedSel.start);
				textRange.select();
			}
		},
		_detectFont: function(fontName) {
			var detector = new FontDetector();
			return detector.detect(fontName);
		},
		command: function (cmd, arg) {
			if (!document.execCommand) {
				return false;
			}

			if (!this._$docInner.is(':focus')) {
				this._$docInner.focus();
			}
			var isSuccess = document.execCommand(cmd, false, arg || null);

			if (!isSuccess) {
				if (document.queryCommandSupported && document.queryCommandSupported(cmd)) {
					return;
				}

				return false;
			}
		},
		commandValue: function (cmd) {
			if (!document.queryCommandValue) {
				return;
			}

			return document.queryCommandValue(cmd);
		},
		supports: function () {
			return (typeof $('body')[0].contentEditable != 'undefined');
		},
		_openFile: function (file) {
			var that = this;

			if (!file) {
				W.Error.trigger('Cannot open file: no file specified');
				return;
			}
			file = W.File.get(file);

			var openers = {
				'text/html': function (contents) {
					var pageContents = '';
					try {
						var xmlDoc = $.parseXML(contents), $xml = $(xmlDoc), $body = $xml.find('body');

						if ($body.length == 1) {
							pageContents = $body.html();
						} else {
							pageContents = $xml;
						}
					} catch (e1) {
						try {
							$xml = $(contents);
							pageContents = $xml;
						} catch (e2) {
							Webos.Error.trigger('Cannot open "'+file.get('basename')+'": corrupted file', e2.getMessage());
							return false;
						}
					} finally {
						$pageContents = $(pageContents);
						$pageContents.find('script').remove();
						$pageContents.find('style').prop('scoped', true);
						$pageContents.find('link').each(function () {
							$(this).replaceWith($('').prop('scoped', true).html('@import "'+$(this).attr('href')+'";'));
						});

						that._$docInner.html($pageContents);
					}
				},
				'application/vnd.oasis.opendocument.*': {
					readAs: false,
					handler: function () {
						var odfCanvas = new odf.OdfCanvas(that._$docInner[0]);

						odfCanvas.load(file.get('realpath'));
console.log(odfCanvas);window.odfCanvas = odfCanvas;
						that._odfCanvas = odfCanvas;

						that._$win.find('.writer-ctn').addClass('writer-size-auto');

						//TODO: doesn't work
						that.command('styleWithCSS');
						that.command('enableInlineTableEditing');
						that.command('enableObjectResizing');
					}
				}
			};

			var openerName = '';
			for (var mimeType in openers) {
				if (file.matchesMimeType(mimeType)) {
					openerName = mimeType;
					break;
				}
			}

			if (!openerName) {
				W.Error.trigger('Cannot open "'+file.get('basename')+'": unsupported file type', 'File type "'+fileType+'" isn\'t supported yet');
				return;
			}

			var opener = openers[openerName];

			this._$win.window('loading', true, {
				message: 'Opening "'+file.get('basename')+'"...'
			});

			var callOpener = function (contents) {
				that._$win.window('loading', false);
				that._$win.find('.writer-ctn').removeClass('writer-size-auto');

				that._file = file;
				that._saved = true;

				var openerCallback;
				if (typeof opener == 'function') {
					openerCallback = opener;
				} else {
					openerCallback = opener.handler;
				}
				openerCallback(contents);
			};

			if (opener.readAs === false) {
				callOpener();
			} else {
				file[(opener.readAs == 'blob') ? 'readAsBlob' : 'readAsText']([function(contents) {
					callOpener(contents);
				}, function(resp) {
					that._$win.window('loading', false);
					resp.triggerError('Cannot open "'+file.get('basename')+'": error while reading file');
				}]);
			}
		},
		_saveFile: function (file) {
			var that = this;

			if (!file) {
				W.Error.trigger('Cannot save file: no file specified');
				return;
			}
			file = W.File.get(file)
;
			var savers = {
				'text/html': function () {
					var contents = '<!doctype html><meta charset="UTF-8">';

					if (that._file.get('mime_type') == 'application/vnd.oasis.opendocument.text' && webodf_css) {
						contents += '';
					}

					contents += '';
					contents += that._$docInner.html();
					contents += '';

					return contents;
				},
				'application/vnd.oasis.opendocument.text': function () {
					var op = Webos.Operation.create();

					var odfCanvas = that._odfCanvas,
						odfCtn = odfCanvas.odfContainer();

					odfCtn.createByteArray(function (data) {
						var blob = new Blob([data.buffer], { type: 'application/vnd.oasis.opendocument.text' });

						file.writeAsBlob(blob, [function () {
							op.setCompleted();
						}, function (err) {
							op.setCompleted(err);
						}]);
					}, function (err) {
						op.setCompleted(Webos.Callback.Result.error(err));
					});

					return op;
				},
				'text/plain': function () {
					return that._$docInner.text();
				}
			};

			var saverName = '';
			for (var mimeType in savers) {
				if (file.matchesMimeType(mimeType)) {
					saverName = mimeType;
					break;
				}
			}

			if (!saverName) {
				switch (file.get('extension')) {
					case 'html':
					case 'htm':
						saverName = 'text/html';
						break;
					case 'odt':
						saverName = 'application/vnd.oasis.opendocument.text';
						break;
					case 'txt':
						saverName = 'text/plain';
						break;
				}
			}

			if (!saverName) {
				W.Error.trigger('Cannot save "'+file.get('basename')+'": unsupported file type', 'File type "'+fileType+'" isn\'t supported yet');
				return;
			}

			var saver = savers[saverName];

			this._$win.window('loading', true, {
				message: 'Saving "'+file.get('basename')+'"...',
				lock: false
			});

			var result = saver();

			var op;
			if (Webos.isInstanceOf(result, Webos.Operation)) {
				op = result;
			} else {
				op = Webos.Operation.create();

				file.writeAsText(result, [function () {
					op.setCompleted();
				}, function (err) {
					op.setCompleted(err);
				}]);
			}

			op.on({
				complete: function () {
					that._$win.window('loading', false);
				},
				success: function () {
					if (file.can('read')) {
						that._file = file;
						that._saved = true;
					}
				},
				error: function (data) {
					data.result.triggerError('Cannot save "'+file.get('basename')+'": error while writing file');
				}
			});
		},
		openFile: function (file) {
			var that = this;

			if (file) {
				that._openFile(file);
				return;
			}

			new NautilusFileSelectorWindow({
				parentWindow: this._$win,
				mime_type: 'text/html' //TODO: ['text/html', ...]
			}, function(files) {
				if (files.length) {
					that._openFile(files[0]);
				}
			});
		},
		saveFile: function (file) {
			var that = this;

			if (file) {
				this._saveFile(file);
				return;
			}

			if (file !== false && this._file && this._file.can('write')) {
				this._saveFile(this._file);
				return;
			}

			var mimeType = 'text/html';
			if (this._file && this._file.get('mime_type')) {
				mimeType = this._file.get('mime_type');
			}

			new NautilusFileSelectorWindow({
				parentWindow: this._$win,
				exists: false,
				mime_type: mimeType
			}, function(paths) {
				if (paths.length) {
					var path = paths[0];

					if (typeof path == 'string') {
						if (!/\.(html|htm|odt)$/.test(path)) {
							path += '.html';
						}
						file = W.File.get(path);
					} else {
						file = path;
					}

					that._saveFile(file);
				} else {
					//Operation aborded
				}
			});
		},
		_exportToPdf: function () {
			var pdf = new jsPDF('p','in','letter');
			pdf.fromHTML(this._$docInner[0], 0.5, 0.5, {
				width: 7.5,
				elementHandlers: {}
			});
			return pdf.output('datauristring');
		},
		exportToPdf: function () {
			var that = this;

			new NautilusFileSelectorWindow({
				parentWindow: this._$win,
				title: 'Export to PDF',
				exists: false,
				mime_type: 'application/pdf'
			}, function(paths) {
				if (paths.length) {
					var path = paths[0], file;

					if (typeof path == 'string') {
						if (!/\.pdf$/.test(path)) {
							path += '.pdf';
						}
						file = W.File.get(path);
					} else {
						file = path;
					}

					that._$win.window('loading', true, {
						message: 'Converting to PDF...'
					});

					var pdfContents = that._exportToPdf();

					that._$win.window('loading', true, {
						message: 'Saving file...'
					});

					file.writeAsDataUrl(pdfContents, [function() {
						that._$win.window('loading', false);
					}, function(response) {
						that._$win.window('loading', false);
						response.triggerError('Can\'t export file to "'+file.get('path')+'"');
					}]);
				} else {
					//Operation aborded
				}
			});
		}
	};
	Webos.inherit(Writer, Webos.Observable);

	Writer.open = function (options) {
		var writer = new Writer();

		options = $.extend({
			file: ''
		}, options);

		if (options.file) {
			writer.one('ready', function () {
				writer.openFile(options.file);
			});
		}

		return writer;
	};

	var options = {};
	if (args.isParam(0)) {
		options.file = args.getParam(0);
	}
	Writer.open(options);
});