text:
package tokenize

import (
	"bufio"
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"strings"

	"github.com/ikawaha/kagome.ipadic/tokenizer"
)

// subcommand property
const (
	CommandName  = "tokenize"
	Description  = `command line tokenize`
	usageMessage = "%s [-file input_file] [-dic dic_file] [-udic userdic_file] [-sysdic (normal|simple)] [-mode (normal|search|extended)]\n"
)

// ErrorWriter writes to stderr
var (
	ErrorWriter = os.Stderr
)

// options
type option struct {
	file    string
	dic     string
	udic    string
	sysdic  string
	mode    string
	flagSet *flag.FlagSet
}

// ContinueOnError ErrorHandling // Return a descriptive error.
// ExitOnError                   // Call os.Exit(2).
// PanicOnError                  // Call panic with a descriptive error.flag.ContinueOnError
func newOption(w io.Writer, eh flag.ErrorHandling) (o *option) {
	o = &option{
		flagSet: flag.NewFlagSet(CommandName, eh),
	}
	// option settings
	o.flagSet.SetOutput(w)
	o.flagSet.StringVar(&o.file, "file", "", "input file")
	o.flagSet.StringVar(&o.dic, "dic", "", "dic")
	o.flagSet.StringVar(&o.udic, "udic", "", "user dic")
	o.flagSet.StringVar(&o.sysdic, "sysdic", "normal", "system dic type (normal|simple)")
	o.flagSet.StringVar(&o.mode, "mode", "normal", "tokenize mode (normal|search|extended)")

	return
}

func (o *option) parse(args []string) (err error) {
	if err = o.flagSet.Parse(args); err != nil {
		return
	}
	// validations
	if nonFlag := o.flagSet.Args(); len(nonFlag) != 0 {
		return fmt.Errorf("invalid argument: %v", nonFlag)
	}
	if o.mode != "" && o.mode != "normal" && o.mode != "search" && o.mode != "extended" {
		return fmt.Errorf("invalid argument: -mode %v", o.mode)
	}
	if o.sysdic != "" && o.sysdic != "normal" && o.sysdic != "simple" {
		return fmt.Errorf("invalid argument: -sysdic %v", o.sysdic)
	}
	return
}

//OptionCheck receives a slice of args and returns an error if it was not successfully parsed
func OptionCheck(args []string) (err error) {
	opt := newOption(ioutil.Discard, flag.ContinueOnError)
	if e := opt.parse(args); e != nil {
		return fmt.Errorf("%v, %v", CommandName, e)
	}
	return nil
}

// command main
func command(opt *option) error {
	var dic tokenizer.Dic
	if opt.dic == "" {
		if opt.sysdic == "simple" {
			dic = tokenizer.SysDicIPASimple()
		} else {
			dic = tokenizer.SysDic()
		}
	} else {
		var err error
		dic, err = tokenizer.NewDic(opt.dic)
		if err != nil {
			return err
		}
	}
	var udic tokenizer.UserDic
	if opt.udic != "" {
		var err error
		udic, err = tokenizer.NewUserDic(opt.udic)
		if err != nil {
			return err
		}
	}
	var fp = os.Stdin
	if opt.file != "" {
		var err error
		fp, err = os.Open(opt.file)
		if err != nil {
			return err
		}
		defer fp.Close()
	}

	t := tokenizer.NewWithDic(dic)
	t.SetUserDic(udic)

	mode := tokenizer.Normal
	switch opt.mode {
	case "normal":
		mode = tokenizer.Normal
	case "search":
		mode = tokenizer.Search
	case "extended":
		mode = tokenizer.Extended
	}

	scanner := bufio.NewScanner(fp)
	for scanner.Scan() {
		line := scanner.Text()
		tokens := t.Analyze(line, mode)
		for i, size := 1, len(tokens); i < size; i++ {
			tok := tokens[i]
			c := tok.Features()
			if tok.Class == tokenizer.DUMMY {
				fmt.Printf("%s\n", tok.Surface)
			} else {
				fmt.Printf("%s\t%v\n", tok.Surface, strings.Join(c, ","))
			}
		}
	}
	return scanner.Err()
}

// Run receives the slice of args and executes the tokenize tool
func Run(args []string) error {
	opt := newOption(ErrorWriter, flag.ExitOnError)
	if e := opt.parse(args); e != nil {
		Usage()
		PrintDefaults(flag.ExitOnError)
		return fmt.Errorf("%v, %v", CommandName, e)
	}
	return command(opt)
}

// Usage provides information on the use of the tokenize tool
func Usage() {
	fmt.Fprintf(ErrorWriter, usageMessage, CommandName)
}

// PrintDefaults prints out the default flags
func PrintDefaults(eh flag.ErrorHandling) {
	o := newOption(ErrorWriter, eh)
	o.flagSet.PrintDefaults()
}


text:
require 'active_support/concern'

module Grape
  module DSL
    # Defines DSL methods, meant to be applied to a ParamsScope, which define
    # and describe the parameters accepted by an endpoint, or all endpoints
    # within a namespace.
    module Parameters
      extend ActiveSupport::Concern

      # Include reusable params rules among current.
      # You can define reusable params with helpers method.
      #
      # @example
      #
      #     class API < Grape::API
      #       helpers do
      #         params :pagination do
      #           optional :page, type: Integer
      #           optional :per_page, type: Integer
      #         end
      #       end
      #
      #       desc "Get collection"
      #       params do
      #         use :pagination
      #       end
      #       get do
      #         Collection.page(params[:page]).per(params[:per_page])
      #       end
      #     end
      def use(*names)
        named_params = @api.namespace_stackable_with_hash(:named_params) || {}
        options = names.extract_options!
        names.each do |name|
          params_block = named_params.fetch(name) do
            raise "Params :#{name} not found!"
          end
          instance_exec(options, &params_block)
        end
      end
      alias use_scope use
      alias includes use

      # Require one or more parameters for the current endpoint.
      #
      # @param attrs list of parameter names, or, if :using is
      #   passed as an option, which keys to include (:all or :none) from
      #   the :using hash. The last key can be a hash, which specifies
      #   options for the parameters
      # @option attrs :type [Class] the type to coerce this parameter to before
      #   passing it to the endpoint. See {Grape::Validations::Types} for a list of
      #   types that are supported automatically. Custom classes may be used
      #   where they define a class-level `::parse` method, or in conjunction
      #   with the `:coerce_with` parameter. `JSON` may be supplied to denote
      #   `JSON`-formatted objects or arrays of objects. `Array[JSON]` accepts
      #   the same values as `JSON` but will wrap single objects in an `Array`.
      # @option attrs :types [Array<Class>] may be supplied in place of +:type+
      #   to declare an attribute that has multiple allowed types. See
      #   {Validations::Types::MultipleTypeCoercer} for more details on coercion
      #   and validation rules for variant-type parameters.
      # @option attrs :desc [String] description to document this parameter
      # @option attrs :default [Object] default value, if parameter is optional
      # @option attrs :values [Array] permissable values for this field. If any
      #   other value is given, it will be handled as a validation error
      # @option attrs :using [Hash[Symbol => Hash]] a hash defining keys and
      #   options, like that returned by {Grape::Entity#documentation}. The value
      #   of each key is an options hash accepting the same parameters
      # @option attrs :except [Array[Symbol]] a list of keys to exclude from
      #   the :using Hash. The meaning of this depends on if :all or :none was
      #   passed; :all + :except will make the :except fields optional, whereas
      #   :none + :except will make the :except fields required
      # @option attrs :coerce_with [#parse, #call] method to be used when coercing
      #   the parameter to the type named by `attrs[:type]`. Any class or object
      #   that defines `::parse` or `::call` may be used.
      #
      # @example
      #
      #     params do
      #       # Basic usage: require a parameter of a certain type
      #       requires :user_id, type: Integer
      #
      #       # You don't need to specify type; String is default
      #       requires :foo
      #
      #       # Multiple params can be specified at once if they share
      #       # the same options.
      #       requires :x, :y, :z, type: Date
      #
      #       # Nested parameters can be handled as hashes. You must
      #       # pass in a block, within which you can use any of the
      #       # parameters DSL methods.
      #       requires :user, type: Hash do
      #         requires :name, type: String
      #       end
      #     end
      def requires(*attrs, &block)
        orig_attrs = attrs.clone

        opts = attrs.extract_options!.clone
        opts[:presence] = { value: true, message: opts[:message] }
        opts = @group.merge(opts) if @group

        if opts[:using]
          require_required_and_optional_fields(attrs.first, opts)
        else
          validate_attributes(attrs, opts, &block)

          block_given? ? new_scope(orig_attrs, &block) : push_declared_params(attrs)
        end
      end

      # Allow, but don't require, one or more parameters for the current
      #   endpoint.
      # @param (see #requires)
      # @option (see #requires)
      def optional(*attrs, &block)
        orig_attrs = attrs.clone

        opts = attrs.extract_options!.clone
        type = opts[:type]
        opts = @group.merge(opts) if @group

        # check type for optional parameter group
        if attrs && block_given?
          raise Grape::Exceptions::MissingGroupTypeError.new if type.nil?
          raise Grape::Exceptions::UnsupportedGroupTypeError.new unless Grape::Validations::Types.group?(type)
        end

        if opts[:using]
          require_optional_fields(attrs.first, opts)
        else
          validate_attributes(attrs, opts, &block)

          block_given? ? new_scope(orig_attrs, true, &block) : push_declared_params(attrs)
        end
      end

      # Define common settings for one or more parameters
      # @param (see #requires)
      # @option (see #requires)
      def with(*attrs, &block)
        new_group_scope(attrs.clone, &block)
      end

      # Disallow the given parameters to be present in the same request.
      # @param attrs [*Symbol] parameters to validate
      def mutually_exclusive(*attrs)
        validates(attrs, mutual_exclusion: { value: true, message: extract_message_option(attrs) })
      end

      # Require exactly one of the given parameters to be present.
      # @param (see #mutually_exclusive)
      def exactly_one_of(*attrs)
        validates(attrs, exactly_one_of: { value: true, message: extract_message_option(attrs) })
      end

      # Require at least one of the given parameters to be present.
      # @param (see #mutually_exclusive)
      def at_least_one_of(*attrs)
        validates(attrs, at_least_one_of: { value: true, message: extract_message_option(attrs) })
      end

      # Require that either all given params are present, or none are.
      # @param (see #mutually_exclusive)
      def all_or_none_of(*attrs)
        validates(attrs, all_or_none_of: { value: true, message: extract_message_option(attrs) })
      end

      # Define a block of validations which should be applied if and only if
      # the given parameter is present. The parameters are not nested.
      # @param attr [Symbol] the parameter which, if present, triggers the
      #   validations
      # @raise Grape::Exceptions::UnknownParameter if `attr` has not been
      #   defined in this scope yet
      # @yield a parameter definition DSL
      def given(*attrs, &block)
        attrs.each do |attr|
          proxy_attr = attr.is_a?(Hash) ? attr.keys[0] : attr
          raise Grape::Exceptions::UnknownParameter.new(proxy_attr) unless declared_param?(proxy_attr)
        end
        new_lateral_scope(dependent_on: attrs, &block)
      end

      # Test for whether a certain parameter has been defined in this params
      # block yet.
      # @return [Boolean] whether the parameter has been defined
      def declared_param?(param)
        # @declared_params also includes hashes of options and such, but those
        # won't be flattened out.
        @declared_params.flatten.include?(param)
      end

      alias group requires

      def map_params(params, element)
        if params.is_a?(Array)
          params.map do |el|
            map_params(el, element)
          end
        elsif params.is_a?(Hash)
          params[element] || {}
        else
          {}
        end
      end

      # @param params [Hash] initial hash of parameters
      # @return hash of parameters relevant for the current scope
      # @api private
      def params(params)
        params = @parent.params(params) if @parent
        params = map_params(params, @element) if @element
        params
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
title: Python unbuffered
categories:
- blog
---

Python по-умолчанию буферизирует вывод, что иногда приводит к проблеме: строки
выводятся не в том порядке. Это случается, например, при запуске python-скрипта
в jenkins. Есть несколько способов отключить буферизацию.

* Использовать опцию -u к интерпретатору.

  ```bash
  python -u script.py
  ```

  При этом следующуая конструкция в начале скрипта работать не будет:

  ```bash
  #!/usr/bin/env python -u
  ```

* Установить переменную окружения PYTHONUNBUFFERED

  ```bash
  PYTHONUNBUFFERED=true python script.py
  ```

* В начале скрипта переоткрыть sys.stdout с размером буфера = 0

  ```bash
  sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
  ```


text:
/*
 * Created on 24 Oct 2015 ( Time 23:23:56 )
 * Generated by Telosys Tools Generator ( version 2.1.1 )
 */
package com.kumasi.journal.domain;

import java.io.Serializable;

import javax.validation.constraints.*;

public class BookPublisher implements Serializable {

    private static final long serialVersionUID = 1L;

    //----------------------------------------------------------------------
    // ENTITY PRIMARY KEY ( BASED ON A SINGLE FIELD )
    //----------------------------------------------------------------------
    @NotNull
    private Integer publisherId;
    @NotNull
    private Integer bookId;

    //----------------------------------------------------------------------
    // ENTITY DATA FIELDS
    //----------------------------------------------------------------------

    //----------------------------------------------------------------------
    // GETTER & SETTER FOR THE KEY FIELD
    //----------------------------------------------------------------------
    public void setPublisherId( Integer publisherId ) {
        this.publisherId = publisherId ;
    }

    public Integer getPublisherId() {
        return this.publisherId;
    }

    public void setBookId( Integer bookId ) {
        this.bookId = bookId ;
    }

    public Integer getBookId() {
        return this.bookId;
    }

    //----------------------------------------------------------------------
    // GETTERS & SETTERS FOR FIELDS
    //----------------------------------------------------------------------

    //----------------------------------------------------------------------
    // toString METHOD
    //----------------------------------------------------------------------

        public String toString() {
        StringBuffer sb = new StringBuffer();
        sb.append(publisherId);
        sb.append("|");
        sb.append(bookId);
        return sb.toString();
    }

}


text:
package com.example.annotryeclipse;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import com.example.annotryeclipse.R.layout;
import com.googlecode.androidannotations.api.SdkVersionHelper;

public final class MainActivity_
    extends MainActivity
{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        init_(savedInstanceState);
        super.onCreate(savedInstanceState);
        setContentView(layout.activity_main);
    }

    private void init_(Bundle savedInstanceState) {
    }

    private void afterSetContentView_() {
    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        afterSetContentView_();
    }

    @Override
    public void setContentView(View view, LayoutParams params) {
        super.setContentView(view, params);
        afterSetContentView_();
    }

    @Override
    public void setContentView(View view) {
        super.setContentView(view);
        afterSetContentView_();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (((SdkVersionHelper.getSdkInt()< 5)&&(keyCode == KeyEvent.KEYCODE_BACK))&&(event.getRepeatCount() == 0)) {
            onBackPressed();
        }
        return super.onKeyDown(keyCode, event);
    }

    public static MainActivity_.IntentBuilder_ intent(Context context) {
        return new MainActivity_.IntentBuilder_(context);
    }

    public static class IntentBuilder_ {

        private Context context_;
        private final Intent intent_;

        public IntentBuilder_(Context context) {
            context_ = context;
            intent_ = new Intent(context, MainActivity_.class);
        }

        public Intent get() {
            return intent_;
        }

        public MainActivity_.IntentBuilder_ flags(int flags) {
            intent_.setFlags(flags);
            return this;
        }

        public void start() {
            context_.startActivity(intent_);
        }

        public void startForResult(int requestCode) {
            if (context_ instanceof Activity) {
                ((Activity) context_).startActivityForResult(intent_, requestCode);
            } else {
                context_.startActivity(intent_);
            }
        }

    }

}


text:
协调嵌套的 BetterScroll 滚动行为。

::: warning 警告
v2.1.0 支持**多层嵌套**的 BetterScroll,并且功能更强大,性能更好。在这之前,只支持**双层嵌套**,请尽快升级至 2.1.0 版本。
:::

::: tip 提示
**v2.1.0** 完美解决多层嵌套 BetterScroll 的 click 事件多次派发的问题。
:::

## 安装

```bash
npm install @better-scroll/nested-scroll --save

// or

yarn add @better-scroll/nested-scroll
```

## 使用

你需要首先引入 `nested-scroll` 插件,并通过全局方法 `BScroll.use()` 使用

```js
  import BScroll from '@better-scroll/core'
  import NestedScroll from '@better-scroll/nested-scroll'

  BScroll.use(NestedScroll)
```

上面步骤完成后,BScroll 的 `options` 中配置 `nestedScroll`。

```js
  // < v2.1.0
  // parent bs
  new BScroll('.outerWrapper', {
    nestedScroll: true
  })
  // child bs
  new BScroll('.innerWrapper', {
    nestedScroll: true
  })

  // v2.1.0
  // parent bs
  new BScroll('.outerWrapper', {
    nestedScroll: {
      groupId: 'dummy-divide' // string or number
    }
  })
  // child bs
  new BScroll('.innerWrapper', {
    nestedScroll: {
      groupId: 'dummy-divide'
    }
  })
```

具有相同 `groupId` 的 BetterScroll 实例(bs)**共享同一个** NestedScroll 实例(ns),ns 会协调每个 bs 滚动行为,一旦某个 bs 销毁的时候,ns 都会失去对它的掌控,例如:

```js
// parent bs
const bs1 = new BScroll('.outerWrapper', {
  nestedScroll: {
    groupId: 'shared' // string or number
  }
})
// child bs
const bs2 = new BScroll('.innerWrapper', {
  nestedScroll: {
    groupId: 'shared'
  }
})

console.log(bs1.plugins.nestedScroll === bs2.plugins.nestedScroll) // true

bs2.destroy() // nestedScroll 不再约束 bs2,不再协调 bs1 与 bs2 的滚动行为
```

## 示例

- **竖向双层嵌套 <Badge text='2.1.0' />**

  <demo qrcode-url="nested-scroll/vertical" :render-code="true">
    <template slot="code-template">
      <<< @/examples/vue/components/nested-scroll/vertical.vue?template
    </template>
    <template slot="code-script">
      <<< @/examples/vue/components/nested-scroll/vertical.vue?script
    </template>
    <template slot="code-style">
      <<< @/examples/vue/components/nested-scroll/vertical.vue?style
    </template>
    <nested-scroll-vertical slot="demo"></nested-scroll-vertical>
  </demo>

- **竖向三层嵌套 <Badge text='2.1.0' />**

  <demo qrcode-url="nested-scroll/triple-vertical" :render-code="true">
    <template slot="code-template">
      <<< @/examples/vue/components/nested-scroll/triple-vertical.vue?template
    </template>
    <template slot="code-script">
      <<< @/examples/vue/components/nested-scroll/triple-vertical.vue?script
    </template>
    <template slot="code-style">
      <<< @/examples/vue/components/nested-scroll/triple-vertical.vue?style
    </template>
    <nested-scroll-triple-vertical slot="demo"></nested-scroll-triple-vertical>
  </demo>

- **横向双层嵌套 <Badge text='2.1.0' />**

  <demo qrcode-url="nested-scroll/horizontal">
    <template slot="code-template">
      <<< @/examples/vue/components/nested-scroll/horizontal.vue?template
    </template>
    <template slot="code-script">
      <<< @/examples/vue/components/nested-scroll/horizontal.vue?script
    </template>
    <template slot="code-style">
      <<< @/examples/vue/components/nested-scroll/horizontal.vue?style
    </template>
    <nested-scroll-horizontal slot="demo"></nested-scroll-horizontal>
  </demo>

  - **横向竖向双层嵌套 <Badge text='2.1.0' />**

    <demo qrcode-url="nested-scroll/horizontal-in-vertical">
      <template slot="code-template">
        <<< @/examples/vue/components/nested-scroll/horizontal-in-vertical.vue?template
      </template>
      <template slot="code-script">
        <<< @/examples/vue/components/nested-scroll/horizontal-in-vertical.vue?script
      </template>
      <template slot="code-style">
        <<< @/examples/vue/components/nested-scroll/horizontal-in-vertical.vue?style
      </template>
      <nested-scroll-horizontal-in-vertical slot="demo"></nested-scroll-horizontal-in-vertical>
    </demo>

## 实例方法 <Badge text='2.1.0' />

:::tip 提示
以下方法皆已代理至 BetterScroll 实例,例如:

```js
import BScroll from '@better-scroll/core'
import NestedScroll from '@better-scroll/nested-scroll'

BScroll.use(NestedScroll)

const bs1 = new BScroll('.parent-wrapper', {
  nestedScroll: {
    groupId: 'dummy'
  }
})

const bs2 = new BScroll('.child-wrapper', {
  nestedScroll: {
    groupId: 'dummy'
  }
})

// 销毁 nestedScroll,bs1 与 bs2 共享同一个 nestedScroll 实例,因为他们的 groupId 相同
bs1.purgeNestedScroll() // 与 bs2.purgeNestedScroll() 的效果一样
```
:::

### `purgeNestedScroll()`

  - **介绍**:销毁管控自己的 nestedScroll

::: warning 注意
不同的 `groupId` 会生成不同的 nestedScroll,相同的 `groupId` 会共享同一份 nestedScroll,因此你应该在合适的时机(比如组件销毁的时候)调用 `purgeNestedScroll` 来清理内存。或者你也可以调用 BetterScroll 的 destroy 方法把自身从 nestedScroll 移除,例如:

```js
const bs1 = new BScroll('.parent-wrapper', {
  nestedScroll: {
    groupId: 'dummy'
  }
})

const bs2 = new BScroll('.child-wrapper', {
  nestedScroll: {
    groupId: 'dummy'
  }
})

bs1.destroy() // nestedScroll 不再管控 bs1
bs2.destroy() // nestedScroll 不再管控 bs2
```
:::

## 静态方法 <Badge text='2.1.0' />

### `getAllNestedScrolls()`

  - **介绍**:获取当前所有的 nestedScroll 实例

  - **返回**:nestedScroll 实例组成的数组

  ```typescript
  import NestedScroll from '@better-scroll/nested-scroll'

  const nestedScrolls: NestedScroll[] = NestedScroll.getAllNestedScrolls()
  ```

### `purgeAllNestedScrolls()`

  - **介绍**:销毁当前所有的 nestedScroll 实例

  ```typescript
  import NestedScroll from '@better-scroll/nested-scroll'

  // 不再约束任何 BetterScroll 实例
  NestedScroll.purgeAllNestedScrolls()
  ```


text:
Microsoft.WebPortal.Services.HeaderBarSection = function (webPortal, id, template) {
    /// <summary>
    /// A base class that represents a section in the header bar. Extend this to implement your custom header bar sections.
    /// </summary>
    /// <param name="webPortal">The web portal instance.</param>
    /// <param name="id">The section id.</param>
    /// <param name="template">The section template.</param>

    if (!webPortal) {
        throw new Error("Microsoft.WebPortal.Services.HeaderBarSection: Invalid webPortal instance.");
    }

    this.webPortal = webPortal;

    this.webPortal.Helpers.throwIfNotSet(id, "id", "Microsoft.WebPortal.Services.HeaderBarSection.constructor.");
    this.webPortal.Helpers.throwIfNotSet(template, "template", "Microsoft.WebPortal.Services.HeaderBarSection.constructor.");

    this.id = ko.observable(id);
    this.template = ko.observable(template);
    this.style = ko.observable("");
};

Microsoft.WebPortal.Services.HeaderBarSection.prototype.initialize = function () {
    /// <summary>
    /// This function is called to initialize the header bar section.
    /// </summary>
};

Microsoft.WebPortal.Services.HeaderBarSection.prototype.destroy = function () {
    /// <summary>
    /// This function is called to destroy the header bar section.
    /// </summary>
};

//@ sourceURL=HeaderBarSection.js


text:
package org.baade.eel.core.server;

import org.baade.eel.core.LifecycleAdaptor;
import org.baade.eel.core.Log;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;

/**
 * Server的抽象类
 * @author Baade Eel Project
 *         2017/3/16.
 */
public abstract class AbstractServer extends LifecycleAdaptor implements IServer{

    protected int port;

    public AbstractServer() {
        super();
    }

    @Override
    public long getDeadline() {
        return -1;
    }

    @Override
    public void start() {
        new Thread(this).start();
    }

    @Override
    public void setPort(int port) {
        this.port = port;
    }

    @Override
    public String toString() {
        return this.getClass() + "[端口:" + this.port + ", 创建时间:" + this.getCreateTime() + "]";
    }
}


text:
#include "repoApiTest.h"

#include <QtCore/QPointF>

using namespace qrTest;
using namespace qrRepo;
using namespace qReal;

Id const logicalElement("editor", "diagram", "element", "id");
Id const graphicalElement("editor", "diagram", "element", "graphicalId");

void RepoApiTest::SetUp()
{
	mRepoApi = new RepoApi("test.qrs");

	mRepoApi->addChild(Id::rootId(), logicalElement);
	mRepoApi->addChild(Id::rootId(), graphicalElement, logicalElement);
}

void RepoApiTest::TearDown()
{
	delete mRepoApi;
}

TEST_F(RepoApiTest, graphicalPartPropertyTest)
{
	mRepoApi->createGraphicalPart(graphicalElement, 0);
	mRepoApi->setGraphicalPartProperty(graphicalElement, 0, "position", QPointF(10, 20));
	QPointF const position = mRepoApi->graphicalPartProperty(graphicalElement, 0, "position").toPointF();
	ASSERT_FLOAT_EQ(10.0, position.x());
	ASSERT_FLOAT_EQ(20.0, position.y());
}


text:
import type { IComponentOptions, IController } from 'angular';
import { module } from 'angular';
import { intersection, uniq } from 'lodash';
import type { Subject, Subscription } from 'rxjs';

import type {
  IAccountDetails,
  ISecurityGroup,
  ISecurityGroupRule,
  ISecurityGroupsByAccountSourceData,
  IVpc,
} from '@spinnaker/core';
import { AWSProviderSettings } from '../../aws.settings';

interface IInfiniteScroll {
  currentItems: number;
}

interface IRuleCommand extends ISecurityGroupRule {
  crossAccountEnabled?: boolean;
  accountName?: string;
  vpcId?: string;
  existing: boolean;
  name: string;
}

interface ISecurityGroupCommand extends ISecurityGroup {
  regions: string[];
  credentials: string;
}

class IngressRuleSelectorController implements IController {
  public rule: IRuleCommand;
  public securityGroup: ISecurityGroupCommand;
  public accounts: IAccountDetails[];
  public crossAccountAccounts: IAccountDetails[];
  public vpcs: IVpc[];
  public regionalVpcs: { [region: string]: IVpc[] };
  public allSecurityGroups: ISecurityGroupsByAccountSourceData;
  public coordinatesChanged: Subject<void>;
  public allSecurityGroupsUpdated: Subject<void>;
  public availableSecurityGroups: string[];
  public coordinatesChangedListener: Subscription;
  public securityGroupsUpdatedListener: Subscription;

  public infiniteScroll: IInfiniteScroll = {
    currentItems: 20,
  };

  public addMoreItems(): void {
    this.infiniteScroll.currentItems += 20;
  }

  public resetCurrentItems(): void {
    this.infiniteScroll.currentItems = 20;
  }

  public addRegionalVpc(vpc: IVpc): void {
    const account = vpc.account;
    if (!this.regionalVpcs[account]) {
      this.regionalVpcs[account] = [];
    }
    this.regionalVpcs[account].push({
      name: vpc.name,
      region: vpc.region,
      account,
      id: vpc.id,
      label: vpc.label,
      deprecated: vpc.deprecated,
      cloudProvider: vpc.cloudProvider,
    });
  }

  public enableCrossAccount(): void {
    this.rule.crossAccountEnabled = true;
    this.crossAccountAccounts = this.accounts;
    const exclusions = AWSProviderSettings?.crossAccountIngressExclusions[this.securityGroup.credentials];
    if (exclusions && Array.isArray(exclusions)) {
      this.crossAccountAccounts = this.accounts.filter((account) => !exclusions.includes(account.name));
    }
    this.rule.accountName = this.securityGroup.credentials;
    this.rule.vpcId = this.securityGroup.vpcId;
  }

  public disableCrossAccount(): void {
    this.rule.crossAccountEnabled = false;
    this.rule.accountName = undefined;
    this.rule.vpcId = undefined;
  }

  public $onInit(): void {
    this.setAvailableSecurityGroups();
    this.coordinatesChangedListener = this.coordinatesChanged.subscribe(() => this.setAvailableSecurityGroups());
    this.securityGroupsUpdatedListener = this.allSecurityGroupsUpdated.subscribe(() =>
      this.setAvailableSecurityGroups(),
    );
  }

  public $onDestroy() {
    this.coordinatesChangedListener.unsubscribe();
    this.securityGroupsUpdatedListener.unsubscribe();
  }

  public setAvailableSecurityGroups(): void {
    const account = this.rule.accountName || this.securityGroup.credentials;
    const regions = this.securityGroup.regions;
    const vpcId = this.rule.vpcId || this.securityGroup.vpcId || null;

    let existingSecurityGroupNames: string[] = [];
    let availableSecurityGroups: string[] = [];

    if (regions.length > 1) {
      this.disableCrossAccount();
    }

    regions.forEach((region) => {
      let regionalVpcId: string = null;
      if (vpcId) {
        const baseVpc: IVpc = this.vpcs.find((vpc) => vpc.id === vpcId);
        const regionalVpc: IVpc = this.vpcs.find(
          (vpc) => vpc.account === account && vpc.region === region && vpc.name === baseVpc.name,
        );
        regionalVpcId = regionalVpc ? regionalVpc.id : undefined;
      }

      const regionalGroupNames = (this.allSecurityGroups?.[account]?.aws?.[region] ?? [])
        .filter((sg) => sg.vpcId === regionalVpcId)
        .map((sg) => sg.name);

      existingSecurityGroupNames = uniq(existingSecurityGroupNames.concat(regionalGroupNames));

      if (!availableSecurityGroups.length) {
        availableSecurityGroups = existingSecurityGroupNames;
      } else {
        availableSecurityGroups = intersection(availableSecurityGroups, regionalGroupNames);
      }
    });
    if (regions.length === 1) {
      this.configureAvailableVpcs();
    }
    this.availableSecurityGroups = availableSecurityGroups;
    if (!availableSecurityGroups.includes(this.rule.name) && !this.rule.existing) {
      this.rule.name = null;
    }
  }

  public configureAvailableVpcs(): void {
    const region = this.securityGroup.regions[0];
    const filtered = this.vpcs.filter((vpc) => vpc.region === region);
    this.regionalVpcs = {};
    filtered.forEach((vpc) => this.addRegionalVpc(vpc));
    this.reconcileRuleVpc(filtered);
  }

  private reconcileRuleVpc(filtered: IVpc[]): void {
    if (this.rule.vpcId && !this.rule.existing) {
      if (!this.securityGroup.vpcId) {
        this.rule.vpcId = null;
        this.rule.name = null;
        return;
      }
      const baseVpc = filtered.find((vpc) => vpc.id === this.rule.vpcId);
      const regionalVpc = filtered.find((vpc) => vpc.account === this.rule.accountName && vpc.name === baseVpc.name);
      if (regionalVpc) {
        this.rule.vpcId = regionalVpc.id;
      } else {
        this.rule.vpcId = null;
        this.rule.name = null;
      }
    }
  }
}

const ingressRuleSelector: IComponentOptions = {
  bindings: {
    rule: '=',
    securityGroup: '=',
    accounts: '=',
    vpcs: '=',
    allSecurityGroups: '=',
    coordinatesChanged: '=',
    allSecurityGroupsUpdated: '=',
  },
  templateUrl: require('./ingressRuleGroupSelector.component.html'),
  controller: IngressRuleSelectorController,
};

export const INGRESS_RULE_GROUP_SELECTOR_COMPONENT =
  'spinnaker.amazon.securityGroup.configure.ingressRuleGroupSelector';
module(INGRESS_RULE_GROUP_SELECTOR_COMPONENT, []).component('ingressRuleGroupSelector', ingressRuleSelector);


text:
package com.facebook.buck.util;

import com.facebook.buck.util.environment.Platform;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.CharMatcher;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;

import java.io.File;
import java.nio.file.Path;
import java.util.Iterator;

public final class Escaper {

  private static final char MAKEFILE_ESCAPE_CHAR = '\\';

  /** Utility class: do not instantiate. */
  private Escaper() {}

  /**
   * The quoting style to use when escaping.
   */
  public static enum Quoter {

    SINGLE('\'') {
      @Override
      public String quote(String str) {
        return '\'' + str.replace("\'", "'\\''") + '\'';
      }
    },
    DOUBLE('"') {
      @Override
      public String quote(String str) {
        return '"' + str.replace("\"", "\\\"") + '"';
      }
    },
    DOUBLE_WINDOWS_JAVAC('"') {
      @Override
      public String quote(String str) {
        return '"' + str.replace("\\", "\\\\") + '"';
      }
    }
    ;

    private final char value;

    private Quoter(char value) {
      this.value = value;
    }

    /**
     * @return the string with this quoting style applied.
     */
    public abstract String quote(String str);

    /**
     * @return the raw quote character.
     */
    public char getValue() {
      return value;
    }

  }

  /**
   * Escapes the special characters identified the {@link CharMatcher}, using single quotes.
   * @param matcher identifies characters to be escaped
   * @param str string to quote
   * @return possibly quoted string
   */
  public static String escape(Quoter quoter, CharMatcher matcher, String str) {
    if (matcher.matchesAnyOf(str) || str.isEmpty()) {
      return quoter.quote(str);
    } else {
      return str;
    }
  }

  /**
   * @return a escaper function using the given quote style and escaping characters determined
   *     by the given matcher.
   */
  public static Function<String, String> escaper(
      final Quoter quoter,
      final CharMatcher matcher) {
    return new Function<String, String>() {
      @Override
      public String apply(String input) {
        return escape(quoter, matcher, input);
      }
    };
  }

  public static Function<String, String> javacEscaper() {
    if (Platform.detect() == Platform.WINDOWS) {
      return Escaper.escaper(
          Quoter.DOUBLE_WINDOWS_JAVAC,
          CharMatcher.anyOf("#'").or(CharMatcher.whitespace()));
    } else {
      return Escaper.escaper(
          Escaper.Quoter.DOUBLE,
          CharMatcher.anyOf("#\"'").or(CharMatcher.whitespace()));
    }
  }

  private static final CharMatcher BASH_SPECIAL_CHARS =
      CharMatcher
          .anyOf("<>|!?*[]$\\(){}\"'`&;=")
          .or(CharMatcher.whitespace());

  /**
   * Bash quoting {@link com.google.common.base.Function Function} which can be passed to
   * {@link com.google.common.collect.Iterables#transform Iterables.transform()}.
   */
  public static final Function<String, String> BASH_ESCAPER =
      escaper(Quoter.SINGLE, BASH_SPECIAL_CHARS);

  /**
   * CreateProcess (Windows) quoting {@link com.google.common.base.Function Function} which can be
   * passed to {@link com.google.common.collect.Iterables#transform Iterables.transform()}.
   */
  public static final Function<String, String> CREATE_PROCESS_ESCAPER =
      new Function<String, String>() {
        @Override
        public String apply(String input) {
          return WindowsCreateProcessEscape.quote(input);
        }
      };

  /**
   * Platform-aware shell quoting {@link com.google.common.base.Function Function} which can be
   * passed to {@link com.google.common.collect.Iterables#transform Iterables.transform()}
   * TODO(sdwilsh): get proper cmd.EXE escaping implemented on Windows
   */
  public static final Function<String, String> SHELL_ESCAPER =
      Platform.detect() == Platform.WINDOWS ? CREATE_PROCESS_ESCAPER : BASH_ESCAPER;

  /**
   * Quotes a string to be passed to the shell, if necessary.  This works for the appropriate shell
   * regardless of the platform it is run on.
   * @param str string to escape
   * @return possibly escaped string
   */
  public static String escapeAsShellString(String str) {
    return SHELL_ESCAPER.apply(str);
  }

  /**
   * Quotes a string to be passed to Bash, if necessary. Uses single quotes to prevent variable
   * expansion, `...` evaluation etc.
   * @param str string to quote
   * @return possibly quoted string
   */
  public static String escapeAsBashString(String str) {
    if (Platform.detect() == Platform.WINDOWS) {
      return CREATE_PROCESS_ESCAPER.apply(str);
    } else {
      return escape(Quoter.SINGLE, BASH_SPECIAL_CHARS, str);
    }
  }

  public static String escapeAsBashString(Path path) {
    return escapeAsBashString(path.toString());
  }

  // Adapted from org.apache.commons.lang.StringEscapeUtils

  /**
   * @return a double-quoted string with metacharacters and quotes escaped with
   *         a backslash; non-ASCII characters escaped as \u
   */
  public static String escapeAsPythonString(String str) {
    StringBuilder builder = new StringBuilder();
    builder.append('"');
    for (Character ch : str.toCharArray()) {
      // Handle Unicode.
      if (ch > 0xfff) {
        builder.append("\\u" + hex(ch));
      } else if (ch > 0xff) {
        builder.append("\\u0" + hex(ch));
      } else if (ch > 0x7f) {
        builder.append("\\u00" + hex(ch));
      } else if (ch < 32) {
        switch (ch) {
        case '\b':
          builder.append('\\');
          builder.append('b');
          break;
        case '\n':
          builder.append('\\');
          builder.append('n');
          break;
        case '\t':
          builder.append('\\');
          builder.append('t');
          break;
        case '\f':
          builder.append('\\');
          builder.append('f');
          break;
        case '\r':
          builder.append('\\');
          builder.append('r');
          break;
        default:
          if (ch > 0xf) {
            builder.append("\\u00" + hex(ch));
          } else {
            builder.append("\\u000" + hex(ch));
          }
          break;
        }
      } else {
        switch (ch) {
        case '\'':
          builder.append('\\');
          builder.append('\'');
          break;
        case '"':
          builder.append('\\');
          builder.append('"');
          break;
        case '\\':
          builder.append('\\');
          builder.append('\\');
          break;
        default:
          builder.append(ch);
          break;
        }
      }
    }
    builder.append('"');
    return builder.toString();
  }

  private static boolean shouldEscapeMakefileString(
      String escapees,
      String blob,
      int index) {

    Preconditions.checkArgument(blob.length() > index);

    for (int i = index; i < blob.length(); i++) {
      if (escapees.indexOf(blob.charAt(i)) != -1) {
        return true;
      }
      if (blob.charAt(i) != MAKEFILE_ESCAPE_CHAR) {
        return false;
      }
    }

    return true;
  }

  private static String escapeAsMakefileString(String escapees, String str) {
    StringBuilder builder = new StringBuilder();

    for (int i = 0; i < str.length(); i++) {
      if (shouldEscapeMakefileString(escapees, str, i)) {
        builder.append(MAKEFILE_ESCAPE_CHAR);
      }
      builder.append(str.charAt(i));
    }

    return builder.toString().replace("$", "$$");
  }

  /**
   * @return an escaped string suitable for use in a GNU makefile on the right side of a variable
   *     assignment.
   */
  public static String escapeAsMakefileValueString(String str) {
    return escapeAsMakefileString("#", str);
  }

  /**
   * Escapes forward slashes in a Path as a String that is safe to consume with other tools (such
   * as gcc).  On Unix systems, this is equivalent to {@link java.nio.file.Path Path.toString()}.
   * @param path the Path to escape
   * @return the escaped Path
   */
  public static String escapePathForCIncludeString(Path path) {
    if (File.separatorChar != '\\') {
      return path.toString();
    }
    StringBuilder result = new StringBuilder();
    if (path.startsWith(File.separator)) {
      result.append("\\\\");
    }
    for (Iterator<Path> iterator = path.iterator(); iterator.hasNext();) {
      result.append(iterator.next());
      if (iterator.hasNext()) {
        result.append("\\\\");
      }
    }
    if (path.getNameCount() > 0 && path.endsWith(File.separator)) {
      result.append("\\\\");
    }
    return result.toString();
  }

  @VisibleForTesting
  static String hex(char ch) {
    return Integer.toHexString(ch).toUpperCase();
  }

}


text:
%
% Travail d'Initiative Personnelle Encadré
% https://github.com/LeoColomb/TIPE
% Copyright (c) 2014 Léo Colombaro
% Licensed under MIT License
%
  \begin{center}
  ---------
  \end{center}
\section*{Références}
\begin{itemize}
\item \textbf{Daniel Perrin}, \textit{La suite logistique et le chaos}, IREM, 2008
\item \textbf{Douglas Hofstadter}, \textit{Jeux Mathématiques}, Pour la Science, 1982
\item \textbf{Elmer G. Wiens}, \textit{Nonlinear Dynamics}, www.egwald.ca
\item \textbf{Mitchell Feigenbaum}, \textit{Universal behavior in nonlinear systems}, Los Alamos Science, 1980
\item \textbf{Robert Ferréol}, \textit{Construire des fractals grâce aux AFC}, Tangente, 2004
\item \textbf{Elisabeth Busser}, \textit{Excursion au pays des attracteurs étranges}
\end{itemize}


text:
#include <aws/devicefarm/model/GetProjectRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::DeviceFarm::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

GetProjectRequest::GetProjectRequest() :
    m_arnHasBeenSet(false)
{
}

Aws::String GetProjectRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_arnHasBeenSet)
  {
   payload.WithString("arn", m_arn);

  }

  return payload.WriteReadable();
}

Aws::Http::HeaderValueCollection GetProjectRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "DeviceFarm_20150623.GetProject"));
  return headers;

}


text:
<?php
class profilesController extends BaseController{

	function get(){

	}
	function save(){

	}
    public function update(){
        $data  =	 Input::get('data');
        $dateNow = date("Y-m-d");
        if(!Auth::User()->hasRole('hijo') && !Auth::User()->hasRole('hijo_free') && !Auth::User()->hasRole('demo_hijo')){
            $date_min =strtotime("-18 year",strtotime($dateNow));
        }else{
             $date_min =strtotime("-4 year",strtotime($dateNow));
        }
        $date_min=date("Y-m-d",$date_min);
        $rules= [
            "username_persona"          =>"required|user_check|max:50",
            "password_new"              =>"min:8|max:100",
            "cpassword_new"             =>"same:password_new",
            "nombre_persona"            =>"required|letter|max:50",
            "apellido_paterno_persona"  =>"required|letter|max:30",
            "apellido_materno_persona"  =>"required|letter|max:30",
            "sexo_persona"              =>"required|string|size:1",
            "fecha_nacimiento_persona"  =>"required|date_format:Y-m-d|before:$date_min"
        ];
        $messages = [
               "required"    =>  "Este campo :attribute es requerido",
               "alpha"       =>  "Solo puedes ingresar letras",
               "before"      =>  "La fecha que ingresaste tiene que ser menor al $date_min",
               "date"        =>  "Formato de fecha invalido",
               "numeric"     =>  "Solo se permiten digitos",
               "email"       =>  "Ingresa un formato de correo valido",
               "unique"      =>  "Este usuario ya existe",
               "integer"     =>  "Solo se permiten numeros enteros",
               "exists"      =>  "El campo :attribute no existe en el sistema",
               "unique"      =>  "El campo :attribute no esta disponible intente con otro valor",
               "integer"     =>  "Solo puedes ingresar numeros enteros",
               "same"        =>  "Las contraseñas no coinciden",
               "after"       =>  "La fecha de expiracion es incorrecta, no puedes ingresar fechas inferiores al día de hoy",
        ];
        if(!Hash::check($data["password_persona"],Auth::user()->password)){
            return Response::json("contraseña incorrecta");
        }
        $valid = Validator::make($data,$rules,$messages);
        if($valid->fails()){
            return $valid->messages();
        }else{
            $data["password"]=Hash::make($data["password_new"]);
            $data["username"]=$data["username_persona"];
            $user =User::find(Auth::user()->id);
            $user->update($data);
            $person = $user->persona();
            $data_person = [
               "nombre"            =>  $data["nombre_persona"],
               "apellido_paterno"  =>  $data["apellido_paterno_persona"],
               "apellido_materno"  =>  $data["apellido_materno_persona"],
               "sexo"              =>  $data["sexo_persona"],
               "fecha_nacimiento"  =>  $data["fecha_nacimiento_persona"]
           ];
            $person->update($data_person);
            $rolee = Auth::user()->roles[0]->name;
            if ($rolee == "padre" || $rolee == "padre_free" || $rolee == "demo_padre"){
                $dadId = Auth::user()->persona()->first()->padre()->first()->id;
                $dad = padre::where('id', '=', $dadId)->first();
                $dad->update($data);
            }
            return Response::json(array('status' => 200, 'statusMessage' => 'success'));
        }
    }
    function delete(){

	}

}
?>


text:
from __future__ import unicode_literals

import django.core.validators
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('kisa', '0001_initial'),
    ]

    operations = [
        migrations.AlterField(
            model_name='link',
            name='domain',
            field=models.TextField(validators=[django.core.validators.URLValidator()]),
        ),
    ]


text:
<?php

namespace home_api\core {

    /**
     * Event handling
     */
    class Events {

        /// Events management
        protected static $events;

        /**
         * Register an event listener with the system.
         *
         * An event listener can be set to listen for a specific event, or a collection of events using wildcards.
         *
         * Namespaces are used to define the namespace of the event.
         *
         * The function being registered must have the following prototype:
         *
         * \code
         * 	function Object::foo($namespace, $event, &$parameters)
         * 	{
         * 	    // Your code, return boolean false will stop any further events being processed
         * 	}
         * \endcode
         *
         * @section Example
         *
         * This example registers a couple of hooks for handling a number of different events:
         *
         * \code
         * 	// Listen to the saved event of a blog post (but not any of its subclasses)
         * 	Events::register('obj:blog', 'saved', 'object_save_event_handler');
         *
         * 	// Listen to the update event of all objects and subclasses
         * 	Events::register('obj:*', 'updated', 'object_update_event_handler');
         * \endcode
         *
         * @param string $namespace The event class, you may specify wild cards.
         * @param string $event The event, you may specify wild cards.
         * @param string $handler Handling function
         * @param int $priority Value determining the order of execution.
         */
        public static function register($namespace, $event, $handler, $priority = 500) {

            // Turn highchair/elgg style wildcards into correct ones.
            $namespace = str_replace('*', '.*', $namespace);
            $namespace = str_replace('/', '\/', $namespace);
            $namespace = '/^' . str_replace('all', '.*', $namespace) . '$/';

            $event = str_replace('*', '.*', $event);
            $event = str_replace('/', '\/', $event);
            $event = '/^' . str_replace('all', '.*', $event) . '$/';

            if (!isset(self::$events))
                self::$events = array();

            if (!isset(self::$events[$namespace]))
                self::$events[$namespace] = array();

            if (!isset(self::$events[$namespace][$event]))
                self::$events[$namespace][$event] = array();

            while (isset(self::$events[$namespace][$event][$priority]))
                $priority++;

            self::$events[$namespace][$event][$priority] = $handler;

            ksort(self::$events[$namespace][$event]);

            return true;
        }

        /**
         * Trigger an event.
         *
         * If a triggered event returns false it will prevent subsequent events
         * in the chain from executing.
         *
         * @param string $namespace The event namespace
         * @param string $event The event
         * @param array $parameters Associated array of parameters.
         * @return bool
         */
        public static function trigger($namespace, $event, array $parameters = NULL) {
            $merged = array();
            if (!$parameters)
                $parameters = array(
                    'halt' => false,
                    'return' => null
                );

            if (!self::$events)
                self::$events = array();

            // Get events we're triggering
            foreach (self::$events as $namespace_key => $event_list) {
                // Does the namespace being triggered match a registered namespace?
                if (preg_match($namespace_key, $namespace)) {
                    foreach (self::$events[$namespace_key] as $event_key => $function_list) {
                        // Does the event being triggered match a registered event
                        if (preg_match($event_key, $event)) {
                            // Now add and prioritise events
                            foreach ($function_list as $priority => $function) {
                                // Adjust priority to free slot
                                while (isset($merged[$priority]))
                                    $priority++;
                                $merged[$priority] = $function;
                            }
                        }
                    }
                }
            }

            // Now sort and execute
            ksort($merged);
            foreach ($merged as $function) {
                $result = null;

                $result = call_user_func_array($function, array($namespace, $event, $parameters));

                if (isset($result)) $parameters['return'] = $result;
                if ($parameters['halt'])
                    return $parameters['return'];
            }

            return $parameters['return'];
        }

        /**
         * Return whether a given event has a handler.
         * @param type $namespace
         * @param type $event
         * @return bool
         */
        public static function exists($namespace, $event) {
            if (isset(self::$events[$namespace][$event]))
                return is_array(self::$events[$namespace][$event]);
            return false;
        }

    }

}


text:
'use strict';

describe('AnalyzerElementReference: output/analyzer/analyzerElementReference.js', function () {

    describe('Default construction', function () {

        var analyzerElementReference;
        before(function (done) {
            analyzerElementReference = new MyScript.AnalyzerElementReference();
            done();
        });

        it('Check initial state', function () {
            expect(analyzerElementReference).to.be.an('object');
            expect(analyzerElementReference).to.be.an.instanceOf(MyScript.AnalyzerElementReference);
        });

        it('Unique Id getter', function () {
            expect(analyzerElementReference.getUniqueId()).to.be.undefined;
        });

        it('Type getter', function () {
            expect(analyzerElementReference.getType()).to.be.undefined;
        });

    });

    describe('JSON construction', function () {

        var analyzerElementReference;
        before(function (done) {
            analyzerElementReference = new MyScript.AnalyzerElementReference({
                uniqueID: 'test',
                type: 'test'
            });
            done();
        });

        it('Check initial state', function () {
            expect(analyzerElementReference).to.be.an('object');
            expect(analyzerElementReference).to.be.an.instanceOf(MyScript.AnalyzerElementReference);
        });

        it('Test AnalyzerElementReference object construction', function () {
            expect(analyzerElementReference.getUniqueId()).to.not.be.undefined;
            expect(analyzerElementReference.getType()).to.not.be.undefined;
        });

    });

});


text:
// LogiFrame
// Copyright 2015 Tim Potze
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace LogiFrame
{
    /// <summary>
    ///     Represents rectangle styles.
    /// </summary>
    public enum RectangleStyle
    {
        /// <summary>
        ///     A blank rectangle.
        /// </summary>
        Blank,

        /// <summary>
        ///     A bordered rectangle.
        /// </summary>
        Bordered,

        /// <summary>
        ///     A filled rectangle.
        /// </summary>
        Filled
    }
}


text:
SnapSell-API
============

Node-Express-Mongo API backend for SnapSell, the buying and selling Android application developed for LAHacks 2014.


text:
title: "Tiistain tunnille"
tags: läksyt rub11.2
---

Huomenna sanakoe tekstistä 3. Lue siihen alleviivaukset työvihkosta.

Kuuntelukoe vasta torstain tunnilla.


text:
package net.fusemc.zcore.languageAPI;

import net.fusemc.zcore.ZCore;
import org.apache.commons.lang.text.StrSubstitutor;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import static com.google.common.base.Preconditions.checkArgument;

public final class TranslationHelper {
    public static String translate(Player p, String id, String... substitutions) {
        checkArgument(substitutions.length % 2 == 0, "Substitution count must be dividable by two");

        Language lang = ZCore.getLanguageSettingsManager().getLanguage(p);
        String translation = lang.getDictionary().getTranslation(id);
        if (translation == null) {
            // get english translation
            translation = ZCore.getLanguageManager().getLanguageByName("en_US").getDictionary().getTranslation(id);
        }

        Map<String, String> replacementMap = new HashMap<>();

        // note: this increments by two
        for (int i = 0; i < substitutions.length; i+=2) {
            replacementMap.put(substitutions[i], substitutions[i+1]);
        }

        StrSubstitutor substitutor = new StrSubstitutor(replacementMap);
        return substitutor.replace(translation);
    }

    public static void broadcast(Collection<Player> players, String id, String... substitutions) {
        for (Player p : players) {
            p.sendMessage(translate(p, id, substitutions));
        }
    }

    public static void broadcast(String id, String... substitutions) {
        broadcast(Arrays.asList(Bukkit.getOnlinePlayers()), id, substitutions);
    }
}


text:
import Functions
from operator import itemgetter
f = open("PrideAndPrejudice.txt")
Text = f.read()
LetterFrequency = {}
WordFrequency = {}

#The following code uses CreateList and DictionaryUpdate to create a list then
#updating the associated dictionary. The list of letters is then displayed in
#descending order of their usage.
for a in Text:
    LetterList = Functions.CreateList(a)
    for Letter in LetterList:
        Functions.DictionaryUpdate(Letter,LetterFrequency)

#The dictionary is sorted then reverse to display in descending order.
print "This program displays the letter and words used in Pride and Prejudice, sorted by their amount of usage.\n"
print "The Frequency of Letters is given in the following table:\n"
print "{:<8} {:<15}".format('Letter','Frequency')
for key, value in sorted(LetterFrequency.items(), key=itemgetter(1), reverse=True):
    print "{:<8} {:<15}".format(key,value)

#This portion of the code deals with counting words and displaying them in descending order.
#For limits, displaying has been restricted to words with 500 occurences in the text.
print "\nThe Frequency of Words is given in the following table (Restricted to usage of 500 and above)\n"
print "{:<8} {:<15}".format('Word','Frequency')
Functions.WordCount(Text,WordFrequency)
for key,value in sorted(WordFrequency.items(), key=itemgetter(1), reverse=True):
    if value >= 500:
        print "{:<8} {:<15}".format(key,value)

f.close()
raw_input("\nPress Enter to Exit.")


text:
module Fog
  module Compute
    class Brightbox
      class Real

        def remove_firewall_policy(identifier, options)
          return nil if identifier.nil? || identifier == ""
          request("post", "/1.0/firewall_policies/#{identifier}/remove", [202], options)
        end

      end
    end
  end
end


text:
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

import {
	Radio as FoundationRadio,
	RadioOptions,
	radioTemplate as template,
} from '@microsoft/fast-foundation';
import {radioStyles as styles} from './radio.styles';

/**
 * The Visual Studio Code radio class.
 *
 * @public
 */
export class Radio extends FoundationRadio {
	/**
	 * Component lifecycle method that runs when the component is inserted
	 * into the DOM.
	 *
	 * @internal
	 */
	public connectedCallback() {
		super.connectedCallback();
		if (this.textContent) {
			this.setAttribute('aria-label', this.textContent);
		} else {
			// Fallback to the label if there is no text content
			this.setAttribute('aria-label', 'Radio');
		}
	}
}

/**
 * The Visual Studio Code radio component registration.
 *
 * @remarks
 * HTML Element: `<vscode-radio>`
 *
 * @public
 */
export const vsCodeRadio = Radio.compose<RadioOptions, typeof Radio>({
	baseName: 'radio',
	template,
	styles,
	checkedIndicator: `

	`,
});


text:
<!DOCTYPE html>
<title>CanvasKit (Skia via Web Assembly)</title>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

Drop in replacement for HTML Canvas (e.g. node.js)

<canvas id=api1_c width=300 height=300></canvas>

<canvas id=api2_c width=300 height=300></canvas>

<canvas id=api3_c width=300 height=300></canvas>

<canvas id=api4_c width=300 height=300></canvas>

<canvas id=api5_c width=300 height=300></canvas>

<canvas id=api6_c width=300 height=300></canvas>

<canvas id=api7_c width=300 height=300></canvas>

<canvas id=api8_c width=300 height=300></canvas>

 CanvasKit expands the functionality of a stock HTML canvas

<canvas id=vertex1 width=300 height=300></canvas>
<canvas id=vertex2 width=300 height=300></canvas>
<canvas id=gradient1 width=300 height=300></canvas>
<canvas id=patheffect width=300 height=300></canvas>
<canvas id=paths width=200 height=200></canvas>
<canvas id=ink width=300 height=300></canvas>
<canvas id=surfaces width=300 height=300></canvas>
<canvas id=atlas width=300 height=300></canvas>

 CanvasKit can allow for text shaping (e.g. breaking, kerning)

<canvas id=shape1 width=600 height=600></canvas>
<canvas id=shape2 width=600 height=600></canvas>
<canvas id=textonpath width=300 height=300></canvas>


text:
<?php

namespace Jackalope\Transport;

use Iterator;
use PHPCR\SessionInterface;
use PHPCR\Observation\EventFilterInterface;

/**
 * Defines the methods needed for observation.
 *
 * @see JCR 2.0, chapter 12
 *
 * @license http://www.apache.org/licenses Apache License Version 2.0, January 2004
 * @license http://opensource.org/licenses/MIT MIT License
 */
interface ObservationInterface extends TransportInterface
{
    /**
     * Request a fragment of the observation journal from the server.
     *
     * This method returns a buffer of events matching the filter that might
     * lazy-load events from storage. But it may never load events that happen
     * later than the time the buffer was created, to avoid endless looping on
     * busy repositories.
     *
     * @param int                  $date    milliseconds since the epoch - see
     *                                      EventJournalInterface::skipTo
     * @param EventFilterInterface $filter  event filter the transport must apply
     * @param SessionInterface     $session in case the transport needs this
     *                                      for filtering
     *
     * @return Iterator
     *
     * @throws \PHPCR\RepositoryException if an error occurs
     */
    public function getEvents($date, EventFilterInterface $filter, SessionInterface $session);

    /**
     * Set user data to be included with subsequent requests.
     * Setting userData to null (which it is by default) will result in no user data header being sent.
     *
     * @param mixed $userData null or string
     */
    public function setUserData($userData);
}


text:
#include <QtGui/QOpenGLContext>
#include <QtGui/QOpenGLShaderProgram>
#include <QtGui/QOpenGLFramebufferObject>
#include <QtGui/private/qopengltextureblitter_p.h>
#include <qpa/qplatformbackingstore.h>

#include "qeglcompositor_p.h"
#include "qeglplatformwindow_p.h"
#include "qeglplatformscreen_p.h"

QT_BEGIN_NAMESPACE

static QEGLCompositor *compositor = 0;

QEGLCompositor::QEGLCompositor()
    : m_context(0),
      m_window(0),
      m_blitter(0)
{
    Q_ASSERT(!compositor);
    m_updateTimer.setSingleShot(true);
    m_updateTimer.setInterval(0);
    connect(&m_updateTimer, SIGNAL(timeout()), SLOT(renderAll()));
}

QEGLCompositor::~QEGLCompositor()
{
    Q_ASSERT(compositor == this);
    if (m_blitter) {
        m_blitter->destroy();
        delete m_blitter;
    }
    compositor = 0;
}

void QEGLCompositor::schedule(QOpenGLContext *context, QEGLPlatformWindow *window)
{
    m_context = context;
    m_window = window;
    if (!m_updateTimer.isActive())
        m_updateTimer.start();
}

void QEGLCompositor::renderAll()
{
    Q_ASSERT(m_context && m_window);
    m_context->makeCurrent(m_window->window());

    if (!m_blitter) {
        m_blitter = new QOpenGLTextureBlitter;
        m_blitter->create();
    }
    m_blitter->bind();

    QEGLPlatformScreen *screen = static_cast<QEGLPlatformScreen *>(m_window->screen());
    QList<QEGLPlatformWindow *> windows = screen->windows();
    for (int i = 0; i < windows.size(); ++i)
        render(windows.at(i));

    m_blitter->release();
    m_context->swapBuffers(m_window->window());

    for (int i = 0; i < windows.size(); ++i)
        windows.at(i)->composited();
}

void QEGLCompositor::render(QEGLPlatformWindow *window)
{
    const QPlatformTextureList *textures = window->textures();
    if (!textures)
        return;

    const QRect targetWindowRect(QPoint(0, 0), window->screen()->geometry().size());
    glViewport(0, 0, targetWindowRect.width(), targetWindowRect.height());

    for (int i = 0; i < textures->count(); ++i) {
        uint textureId = textures->textureId(i);
        glBindTexture(GL_TEXTURE_2D, textureId);
        QMatrix4x4 target = QOpenGLTextureBlitter::targetTransform(textures->geometry(i),
                                                                   targetWindowRect);

        if (textures->count() > 1 && i == textures->count() - 1) {
            // Backingstore for a widget with QOpenGLWidget subwidgets
            m_blitter->setSwizzleRB(true);
            glEnable(GL_BLEND);
            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
            m_blitter->blit(textureId, target, QOpenGLTextureBlitter::OriginTopLeft);
            glDisable(GL_BLEND);
        } else if (textures->count() == 1) {
            // A regular QWidget window
            m_blitter->setSwizzleRB(true);
            m_blitter->blit(textureId, target, QOpenGLTextureBlitter::OriginTopLeft);
        } else {
            // Texture from an FBO belonging to a QOpenGLWidget
            m_blitter->setSwizzleRB(false);
            m_blitter->blit(textureId, target, QOpenGLTextureBlitter::OriginBottomLeft);
        }
    }
}

QEGLCompositor *QEGLCompositor::instance()
{
    if (!compositor)
        compositor = new QEGLCompositor;
    return compositor;
}

void QEGLCompositor::destroy()
{
    delete compositor;
    compositor = 0;
}

QT_END_NAMESPACE


text:
const passport = ["passport", {
    login_url: "/user/signin",
    verify_callback (email, password, cb) {
        if (email === "foo@bar.com" && password === "42") {
            return cb(null, { name: "foo" })
        }
        cb(new Error("Invalid username or password."))
    }
}]


text:
package com.example.jiangrui.crimeintent;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.Display;
import android.widget.ImageView;

/**
 * Created by Jiang Rui on 2016/6/5.
 */
public class PictureUtils {
    /*
    Get a BitmapDrawable from a local file that is scaled down
    to fit the current Window size.
     */
    @SuppressWarnings("deprecation")
    public static BitmapDrawable getScaledDrawable(Activity activity, String path) {
        Display display = activity.getWindowManager().getDefaultDisplay();
        float destWidth = display.getWidth();
        float destHeight = display.getHeight();

        //Read in the dimensions of the image on disk
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;                  //只解析out...fields,bitmap不加载到内存
        BitmapFactory.decodeFile(path,options);             //加载bitmap对象但只返回out...fields
        float srcWidth = options.outWidth;
        float srcHeight = options.outHeight;

        int inSampleSize = 1;

        if (srcHeight > destHeight || srcWidth > destWidth) {
            if (srcHeight > destHeight) {
                inSampleSize = Math.round(srcHeight / destHeight);
            } else {
                inSampleSize = Math.round(srcWidth / destWidth);
            }
            while ((srcHeight / inSampleSize > destHeight) || (srcWidth / inSampleSize) > destWidth) {
                inSampleSize *= 2;
            }
        }
        options = new BitmapFactory.Options();           //默认options.inJustDecodeBounds = false
        options.inSampleSize = inSampleSize;

        Bitmap bitmap = BitmapFactory.decodeFile(path, options);   //加载 inSampleSize 比率缩小的bitmap对象
        return new BitmapDrawable(activity.getResources(), bitmap);
    }

    public static void cleanImageView(ImageView imageView) {
        if (!(imageView.getDrawable() instanceof BitmapDrawable))
            return;
        //Clean up the view's image for the sake of memory
        BitmapDrawable b = (BitmapDrawable) imageView.getDrawable();
        b.getBitmap().recycle();
        imageView.setImageDrawable(null);
    }

}


text:
<?php
/**
 * Functions which enhance the theme by hooking into WordPress
 *
 * @package Delicatesther
 */

/**
 * Adds custom classes to the array of body classes.
 *
 * @param array $classes Classes for the body element.
 * @return array
 */
function delicatesther_body_classes( $classes ) {
	// Adds a class of hfeed to non-singular pages.
	if ( ! is_singular() ) {
		$classes[] = 'hfeed';
	}

	return $classes;
}
add_filter( 'body_class', 'delicatesther_body_classes' );

/**
 * Add a pingback url auto-discovery header for singularly identifiable articles.
 */
function delicatesther_pingback_header() {
	if ( is_singular() && pings_open() ) {
		echo '<link rel="pingback" href="', esc_url( get_bloginfo( 'pingback_url' ) ), '">';
	}
}
add_action( 'wp_head', 'delicatesther_pingback_header' );


text:
const EmberController = require('./../controllers/EmberController');
module.exports = function(controller) {
    controller = controller ? controller : new EmberController();
    return function(req, res, next) {
        if (req.headers.ember) {
            return controller.findone(req, res);
        }
        next();
    };
};


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:facebook="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Switch
        android:id="@+id/poweronSwitch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/padding_xlarge"
        android:text="@string/label_bootdevice"
        android:textOff="@string/label_off"
        android:textOn="@string/label_on"
        android:textSize="14sp" />

    <TextView
        android:id="@+id/description"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center" />

</LinearLayout>


text:
namespace policy {

TEST(PolicyMacUtilTest, PropertyToValue) {
  base::DictionaryValue root;

  // base::Value::TYPE_NULL
  root.Set("null", base::Value::CreateNullValue());

  // base::Value::TYPE_BOOLEAN
  root.SetBoolean("false", false);
  root.SetBoolean("true", true);

  // base::Value::TYPE_INTEGER
  root.SetInteger("int", 123);
  root.SetInteger("zero", 0);

  // base::Value::TYPE_DOUBLE
  root.SetDouble("double", 123.456);
  root.SetDouble("zerod", 0.0);

  // base::Value::TYPE_STRING
  root.SetString("string", "the fox jumps over something");
  root.SetString("empty", "");

  // base::Value::TYPE_LIST
  base::ListValue list;
  root.Set("emptyl", list.DeepCopy());
  for (base::DictionaryValue::Iterator it(root); !it.IsAtEnd(); it.Advance())
    list.Append(it.value().DeepCopy());
  EXPECT_EQ(root.size(), list.GetSize());
  list.Append(root.DeepCopy());
  root.Set("list", list.DeepCopy());

  // base::Value::TYPE_DICTIONARY
  base::DictionaryValue dict;
  root.Set("emptyd", dict.DeepCopy());
  // Very meta.
  root.Set("dict", root.DeepCopy());

  base::ScopedCFTypeRef<CFPropertyListRef> property(ValueToProperty(root));
  ASSERT_TRUE(property);
  std::unique_ptr<base::Value> value = PropertyToValue(property);
  ASSERT_TRUE(value);
  EXPECT_TRUE(root.Equals(value.get()));
}

}  // namespace policy


text: Check .properties files against their associated Dust templates


text:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Qlue.Logging;
using Qlue.Transport;

namespace Qlue
{
    public class NotifyChannel : INotifyChannel, IDisposable
    {
        private ILog log;

        private Dictionary<Type, Dispatch> dispatchers;
        private BusReceiver messageReceiver;
        private readonly Pipeline.PipelineDefaultFactory pipelineFactory;
        private readonly IServiceChannel serviceChannel;
        private readonly string version;

        public NotifyChannel(
            ILogFactory logFactory,
            string listenTopic,
            IBusTransportFactory busTransportFactory,
            IBlobClient blobClient,
            IServiceChannel serviceChannel,
            string subscriptionName = null,
            string version = null)
        {
            this.log = logFactory.GetLogger("Qlue");

            this.log.Info("Creating NotifyChannel for '{0}' topic, version {1}", listenTopic, version);

            this.serviceChannel = serviceChannel;
            this.version = version;

            this.dispatchers = new Dictionary<Type, Dispatch>();

            var blobRepository = new BlobRepository(this.log, blobClient);

            var serializer = new MessageSerializer();
            this.pipelineFactory = new Pipeline.PipelineDefaultFactory(this.log, serializer);

            Func<Pipeline.PipelineContext, Task<bool>> incomingObserver = async ctx =>
            {
                AsyncContext.StoreKeyValue("MessageId", ctx.MessageId);
                AsyncContext.StoreKeyValue("CustomSessionId", ctx.CustomSessionId);

                ILog dispatchLog = this.log;
                IDisposable ndc = null;

                try
                {
                    Dispatch dispatch = null;
                    lock (this.dispatchers)
                    {
                        this.dispatchers.TryGetValue(ctx.BodyType, out dispatch);
                    }

                    if (dispatch != null)
                    {
                        if (dispatch.Log != null)
                            dispatchLog = dispatch.Log;

                        var invokeContext = new InvokeContext(ctx.MessageId, ctx.CustomSessionId, Notify, dispatchLog);

                        ndc = dispatchLog.Context(ctx.BodyType.Name);
                        dispatchLog.Trace("Dispatching message id {0} from custom session {1}, topic {2}", ctx.MessageId, ctx.CustomSessionId, ctx.From);

                        await dispatch.ExecuteAction(ctx.Body, invokeContext, r => Task.FromResult(false));
                    }
#if FULL_LOGGING
                    else
                        this.log.Debug("Notify type {0} not found in dispatchers for subscription {1}", ctx.BodyType.Name, subscriptionName);
#endif
                }
                catch (Exception ex)
                {
                    dispatchLog.ErrorException("Exception in IncomingObserver", ex);
                }
                finally
                {
                    if (ndc != null)
                        ndc.Dispose();

                    AsyncContext.StoreKeyValue("MessageId", null);
                    AsyncContext.StoreKeyValue("CustomSessionId", null);
                }

                return true;
            };

            var inboundPipeline = this.pipelineFactory.CreateInboundPipeline(blobRepository);

            this.messageReceiver = BusReceiver.CreateNotifyReceiver(
                this.log,
                listenTopic,
                incomingObserver,
                inboundPipeline,
                busTransportFactory,
                subscriptionName,
                this.version);
        }

        public void StartReceiving()
        {
            this.messageReceiver.StartReceiving();
        }

        public void Dispose()
        {
            Dispose(true);

            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (this.messageReceiver != null)
                {
                    this.messageReceiver.Dispose();
                    this.messageReceiver = null;
                }
            }
        }

        public void RegisterAsyncDispatch<TRequest>(Func<TRequest, InvokeContext, Task> executeAction, ILog logForDispatch)
        {
            lock (this.dispatchers)
            {
                this.dispatchers.Add(typeof(TRequest), new Dispatch<TRequest>(executeAction, logForDispatch));
            }
        }

        public void RegisterDispatch<TRequest>(Action<TRequest, InvokeContext> executeAction, ILog logForDispatch)
        {
            lock (this.dispatchers)
            {
                this.dispatchers.Add(typeof(TRequest), new Dispatch<TRequest>((r, ctx) =>
                {
                    // Execute synchronously
                    executeAction(r, ctx);

                    return Task.FromResult(false);
                }, logForDispatch));
            }
        }

        protected Task<string> Notify(object notifyObject, string topicName, ILog logForDispatch)
        {
            var sendChannel = this.serviceChannel as ServiceChannel;
            if (sendChannel == null)
                throw new InvalidOperationException("ServiceChannel is not configured");

            return sendChannel.Notify(notifyObject, topicName, logForDispatch);
        }
    }
}