text:
a fast data render based on jQuery  which could be convenient for show data in html from json

一个基于jQuery的json数据快速展示系统

# Advantage/优势

1.无需写无关的script块模板代码

2.支持自定义回调用来处理特殊的数据绑定

3.轻量无依赖,如果你不考虑angular,vue 这种大家伙

4.特别适应于小页面开发,比如移动端

# 劣势
暂不支持table,下个版本即将支持

# samples

#### html code
```html
<div class="info">
	<span render-html="weather"></span>
	<ul render-loop="seven_days">
	        <li render-html="seven_days.weather"></li>
	</ul>
</div>
```
#### js code
```javascript
var data = {
    weather:'sunshine',
    seven_days:[
        {
            weather:'windy'
        },
        {
            weather:'rainy'
        },
        {
            weather:'cloud'
        }
    ]
};
$(".info").renderValues(data);
```
#desc
1.所有的数据展示都是在某一个标签内

all kind of data must be show at one html element

sample
```html
<span render-html="username"></span>
```
if the type is loop, the child element should be surrounded with a div

循环类型的子循环,子元素的第一个元素,所以尽量套一个div进去

### right
```html
<div render-loop="seven_days">
    <div>
    	<span render-html="seven_days.temperature"></span>
    	<span render-html="seven_days.weather"></span>
    </div>
</div>
```
#### wrong
```html
<div render-loop="seven_days">
    <span render-html="seven_days.temperature"></span>
    <span render-html="seven_days.weather"></span>
</div>
```

2. type list which can be render
<pre>
render-html,
render-src,
render-value,
render-href,
render-loop,
render-attr(self defined property:render-attr="userid=uid")
render-key(this should provide a render-fun property ,please read exmples)
</pre>

### note
Jrender don't support table now


text:
package com.amazonaws.services.ecs.model;

import com.amazonaws.AmazonServiceException;

/**
 * <p>
 * The specified service is not active. You cannot update a service that
 * is not active. If you have previously deleted a service, you can
 * recreate it with CreateService.
 * </p>
 */
public class ServiceNotActiveException extends AmazonServiceException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new ServiceNotActiveException with the specified error
     * message.
     *
     * @param message Describes the error encountered.
     */
    public ServiceNotActiveException(String message) {
        super(message);
    }

}

redpajama_set_name: RedPajamaGithub


text:
using namespace eeros::control;
using namespace eeros::math;

SpaceNavigatorInput::SpaceNavigatorInput(std::string dev, int priority) : sn(dev, priority), rotOut(this), buttonOut(this) {
	setInitPos({0,0,0});
}

SpaceNavigatorInput::~SpaceNavigatorInput() { }

void SpaceNavigatorInput::run() {
	out.getSignal().setValue(Matrix<SPACENAVIGATOR_AXIS_COUNT>{
		sn.current.axis[SpaceNav::Axis::X],
		sn.current.axis[SpaceNav::Axis::Y],
		sn.current.axis[SpaceNav::Axis::Z],
	});
	uint64_t ts = eeros::System::getTimeNs();
	out.getSignal().setTimestamp(ts);
	rotOut.getSignal().setValue(Matrix<SPACENAVIGATOR_ROT_AXIS_COUNT>{
		sn.current.rotAxis[SpaceNav::RotAxis::RX],
		sn.current.rotAxis[SpaceNav::RotAxis::RY],
		sn.current.rotAxis[SpaceNav::RotAxis::RZ],
	});
	rotOut.getSignal().setTimestamp(ts);
	buttonOut.getSignal().setValue(Matrix<SPACENAVIGATOR_BUTTON_COUNT,1,bool>{
		sn.current.button[SpaceNav::Button::L],
		sn.current.button[SpaceNav::Button::R]
	});
	buttonOut.getSignal().setTimestamp(ts);
}

Output<Matrix<SPACENAVIGATOR_ROT_AXIS_COUNT,1,double>>& SpaceNavigatorInput::getRotOut() {
	return rotOut;
}

Output<Matrix<SPACENAVIGATOR_BUTTON_COUNT,1,bool>>& SpaceNavigatorInput::getButtonOut() {
	return buttonOut;
}

void SpaceNavigatorInput::setInitPos(Matrix<SPACENAVIGATOR_AXIS_COUNT> initPos) {
	out.getSignal().setValue(initPos);
}


text:
import fs from "fs";
import path from "path";
import { gitSpecFromVersion } from "./util.js";
import { resource } from "./deps/lively.resources.js";
import semver from "./deps/semver.min.js";

/*

lively.lang.fun.timeToRun(() => {
  let pm = PackageMap.build(["/Users/robert/Lively/lively-dev2/lively.next-node_modules"])
  pm.lookup("lively.morphic")
}, 100);

let dir = System.resource(System.baseURL).join("lively.next-node_modules/")
let pmap = AsyncPackageMap.build([dir]); await pmap.whenReady()

let dir = "/Users/robert/Lively/lively-dev2/lively.next-node_modules/"
let pmap = PackageMap.build([dir]);

let json = pmap.allPackages().reduce((map, spec) => {
  let {name,version} = spec;
  map[name + "@" + version] = spec;
  return map
}, {});

lively.lang.num.humanReadableByteSize(JSON.stringify(json).length)

await fs_dirList(pmap.lookup("react").location)
fs_dirList(pmap.lookup("react").location)

*/

function isAbsolute(path) {
  return path.startsWith("/") || path.match(/^[a-z\.-_\+]+:/i)
}

function ensureResource(x) {
  return x.isResource ? x : resource(x);
}

function parentDir(p) {
  if (p.isResource) return p.parent();
  return path.basename(p);
}

function equalLocation(a, b) {
  if (a.isResource) return a.equals(b);
  return a == b;
}

function join(a, b) {
  if (a.isResource) return a.join(b);
  return path.join(a, b);
}

function normalizePath(p) {
  if (p.isResource) return p.withRelativePartsResolved()
  return path.normalize(p);
}

function fs_isDirectory(location) {
  if (location.isResource) return location.isDirectory();
  return fs.statSync(location).isDirectory();
}

function fs_exists(location) {
  if (location.isResource) return location.exists();
  return fs.existsSync(location);
}

function fs_read(location) {
  if (location.isResource) return location.read();
  return fs.readFileSync(location);
}

function fs_write(location, content) {
  if (location.isResource) return location.write(content);
  return fs.writeFileSync(location, content);
}

function fs_readJson(location) {
  if (location.isResource) return location.exists().then(exists => exists ? location.readJson() : null);
  return fs.existsSync(location) ? JSON.parse(String(fs_read(location))) : null;
}

function fs_writeJson(location, jso) {
  if (location.isResource) return location.writeJson(jso);
  return fs_write(location, JSON.stringify(jso));
}

function fs_dirList(location) {
  if (location.isResource) return location.dirList(1);
  return fs.readdirSync(location).map(ea => join(location, ea));
}

// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

class PackageMap {

  static empty() { return new this(); }

  static get cache() { return this._cache || (this._cache = {}); }

  static keyFor(packageCollectionDirs, individualPackageDirs, devPackageDirs) {
    return `all: ${packageCollectionDirs} ea: ${individualPackageDirs} dev: ${devPackageDirs}`
  }

  static ensure(packageCollectionDirs, individualPackageDirs, devPackageDirs) {
    let key = this.keyFor(packageCollectionDirs, individualPackageDirs, devPackageDirs);
    return this.cache[key] || (this.cache[key] = this.build(
      packageCollectionDirs, individualPackageDirs, devPackageDirs));
  }

  static build(packageCollectionDirs, individualPackageDirs, devPackageDirs) {
    let map = new this();
    map.buildDependencyMap(
      packageCollectionDirs,
      individualPackageDirs,
      devPackageDirs);
    return map;
  }

  constructor() {
    this.dependencyMap = {};
    this.byPackageNames = {};
    this.key = "";
    this.devPackageDirs = [];
    this.individualPackageDirs = [];
    this.packageCollectionDirs = [];
    this._readyPromise = null;
  }

  whenReady() { return this._readyPromise || Promise.resolve(); }

  isReady() { return !this._readyPromise; }

  withPackagesDo(doFn) {
    let result = [];
    for (let key in this.dependencyMap)
      result.push(doFn(key, this.dependencyMap[key]))
    return result;
  }

  findPackage(matchFn) {
    for (let key in this.dependencyMap) {
      let pkg = this.dependencyMap[key]
      if (matchFn(key, pkg)) return pkg
    }
    return null;
  }

  allPackages() {
    let pkgs = [];
    for (let key in this.dependencyMap)
      pkgs.push(this.dependencyMap[key]);
    return pkgs;
  }

  coversDirectory(dir) {
    let { packageCollectionDirs, devPackageDirs, individualPackageDirs } = this;

    if (individualPackageDirs.some(ea => equalLocation(ea, dir))) return "individualPackageDirs";
    if (devPackageDirs.some(ea => equalLocation(ea, dir))) return "devPackageDirs";
    let parent = parentDir(dir);
    if (packageCollectionDirs.some(ea => equalLocation(ea, parent))) {
      return this.allPackages().find(pkg => equalLocation(pkg.location, parent)) ?
        "packageCollectionDirs" : "maybe packageCollectionDirs";
    }
    return null;
  }

  addPackage(packageSpec, isDev = false) {
    // returns false if package already installed, true otherwise

    let self = this;
    if (typeof packageSpec === "string")
      packageSpec = PackageSpec.fromDir(packageSpec);

    return packageSpec instanceof Promise ?
      packageSpec.then(resolvedPackageSpec => {
        packageSpec = resolvedPackageSpec;
        return isPackageSpecIncluded();
      }) : isPackageSpecIncluded();

    function isPackageSpecIncluded() {
      let { location, name, version } = packageSpec,
        { packageCollectionDirs, devPackageDirs, individualPackageDirs } = self,
        isCovered = self.coversDirectory(location);

      if (["devPackageDirs", "individualPackageDirs", "packageCollectionDirs"].includes(isCovered))
        return false;
      if (isDev) devPackageDirs = devPackageDirs.concat(location);
      else individualPackageDirs = individualPackageDirs.concat(location);

      // FIXME key changes....
      let build = self.buildDependencyMap(
        packageCollectionDirs,
        individualPackageDirs,
        devPackageDirs);
      return build instanceof Promise ? build.then(() => true) : true;
    }
  }

  buildDependencyMap(packageCollectionDirs, individualPackageDirs = [], devPackageDirs = []) {
    // looks up all the packages in can find in packageDirs and creates
    // packageSpecs for them.  If a package specifies more flatn_package_dirs in its
    // config then repeat the process until no more new package dirs are found.
    // Finally, combine all the packages found into a single map, like
    // {package-name@version: packageSpec, ...}.
    //
    // Merging of the results of the different package dirs happens so that dirs
    // specified first take precedence. I.e. if a dependency foo@1 is found via
    // packageDirs and then another package specifies a dir that leads to the
    // discovery of another foo@1, the first one ends up in tha packageDir

    let key = this.constructor.keyFor(
      packageCollectionDirs,
      individualPackageDirs,
      devPackageDirs
    );

    let pkgMap = {},
      byPackageNames = {},
      seen = { packageDirs: {}, collectionDirs: {} };

    // 1. find all the packages in collection dirs and separate package dirs;
    for (let p of this._discoverPackagesInCollectionDirs(packageCollectionDirs, seen)) {
      let { name, version } = p;
      pkgMap[`${name}@${version}`] = p;
      (byPackageNames[name] || (byPackageNames[name] = [])).push(`${name}@${version}`);
    }

    for (let dir of individualPackageDirs)
      for (let p of this._discoverPackagesInPackageDir(dir, seen)) {
        let { name, version } = p;
        pkgMap[`${name}@${version}`] = p;
        (byPackageNames[name] || (byPackageNames[name] = [])).push(`${name}@${version}`);
      }

    // 2. read dev packages, those shadow all normal dependencies with the same package name;

    for (let dir of devPackageDirs)
      for (let p of this._discoverPackagesInPackageDir(dir, seen)) {
        let { name, version } = p;
        pkgMap[`${name}`] = p;
        p.isDevPackage = true;
        let versionsOfPackage = byPackageNames[name] || (byPackageNames[name] = []);
        if (versionsOfPackage) for (let key of versionsOfPackage) delete pkgMap[key];
        versionsOfPackage.push(name);
      }

    this.dependencyMap = pkgMap;
    this.byPackageNames = byPackageNames;
    this.packageCollectionDirs = packageCollectionDirs;
    this.individualPackageDirs = individualPackageDirs;
    this.devPackageDirs = devPackageDirs;
    this.key = key;

    return this;
  }

  lookup(name, versionRange) {
    // Query the package map if it has a package name@version
    // Compatibility is either a semver match or if package comes from a git
    // repo then if the git commit matches.  Additionally dev packages are
    // supported.  If a dev package with `name` is found it always matches

    let gitSpec = gitSpecFromVersion(versionRange || "");
    if (!gitSpec && versionRange) {
      try {
        // parse stuff like "3001.0001.0000-dev-harmony-fb" into "3001.1.0-dev-harmony-fb"
        versionRange = new semver.Range(versionRange, true).toString();
      } catch (err) { }
    }
    return this.findPackage((key, pkg) => pkg.matches(name, versionRange, gitSpec));
  }

  _discoverPackagesInCollectionDirs(
    packageCollectionDirs,
    seen = { packageDirs: {}, collectionDirs: {} }
  ) {
    // package collection dir structure is like
    // packages
    // |-package-1
    // | |-0.1.0
    // | | \-package.json
    // | \-0.1.1
    // |   \-package.json
    // |-package-2
    // ...

    let found = [];
    for (let dir of packageCollectionDirs) {
      if (!fs_exists(dir)) continue;
      for (let packageDir of fs_dirList(dir)) {
        if (!fs_isDirectory(packageDir)) continue;
        for (let versionDir of fs_dirList(packageDir))
          found.push(...this._discoverPackagesInPackageDir(versionDir, seen));
      }
    }
    return found;
  }

  _discoverPackagesInPackageDir(
    packageDir,
    seen = { packageDirs: {}, collectionDirs: {} }
  ) {
    let spec = fs_exists(packageDir) && PackageSpec.fromDir(packageDir);
    if (!spec) return [];

    let found = [spec],
      { location, flatn_package_dirs } = spec;

    if (flatn_package_dirs) {
      for (let dir of flatn_package_dirs) {
        if (!isAbsolute(dir)) dir = normalizePath(join(location, dir));
        if (seen.collectionDirs[dir]) continue;
        console.log(`[flatn] project ${location} specifies package dir ${dir}`);
        seen.collectionDirs[dir] = true;
        found.push(...this._discoverPackagesInCollectionDirs([dir], seen));
      }
    }

    return found;
  }

}

class AsyncPackageMap extends PackageMap {

  whenReady() { return this._readyPromise || Promise.resolve(); }

  isReady() { return !this._readyPromise; }

  async buildDependencyMap(
    packageCollectionDirs,
    individualPackageDirs = [],
    devPackageDirs = []
  ) {
    // looks up all the packages in can find in packageDirs and creates
    // packageSpecs for them.  If a package specifies more flatn_package_dirs in its
    // config then repeat the process until no more new package dirs are found.
    // Finally, combine all the packages found into a single map, like
    // {package-name@version: packageSpec, ...}.
    //
    // Merging of the results of the different package dirs happens so that dirs
    // specified first take precedence. I.e. if a dependency foo@1 is found via
    // packageDirs and then another package specifies a dir that leads to the
    // discovery of another foo@1, the first one ends up in tha packageDir

    if (!this.isReady()) {
      return this.whenReady().then(() =>
        this.buildDependencyMap(
          packageCollectionDirs,
          individualPackageDirs,
          devPackageDirs));
    }

    let resolve, reject;
    this._readyPromise = new Promise((_resolve, _reject) => {
      resolve = _resolve; reject = _reject;
    });

    try {

      let key = this.constructor.keyFor(
        packageCollectionDirs,
        individualPackageDirs,
        devPackageDirs
      );

      let pkgMap = {},
        byPackageNames = {},
        seen = { packageDirs: {}, collectionDirs: {} };

      // 1. find all the packages in collection dirs and separate package dirs;
      for (let p of await this._discoverPackagesInCollectionDirs(packageCollectionDirs, seen)) {
        let { name, version } = p;
        pkgMap[`${name}@${version}`] = p;
        (byPackageNames[name] || (byPackageNames[name] = [])).push(`${name}@${version}`);
      }

      for (let dir of individualPackageDirs)
        for (let p of await this._discoverPackagesInPackageDir(dir, seen)) {
          let { name, version } = p;
          pkgMap[`${name}@${version}`] = p;
          (byPackageNames[name] || (byPackageNames[name] = [])).push(`${name}@${version}`);
        }

      // 2. read dev packages, those shadow all normal dependencies with the same package name;

      for (let dir of devPackageDirs)
        for (let p of await this._discoverPackagesInPackageDir(dir, seen)) {
          let { name, version } = p;
          pkgMap[`${name}`] = p;
          p.isDevPackage = true;
          let versionsOfPackage = byPackageNames[name] || (byPackageNames[name] = []);
          if (versionsOfPackage) for (let key of versionsOfPackage) delete pkgMap[key];
          versionsOfPackage.push(name);
        }

      this.dependencyMap = pkgMap;
      this.byPackageNames = byPackageNames;
      this.packageCollectionDirs = packageCollectionDirs;
      this.individualPackageDirs = individualPackageDirs;
      this.devPackageDirs = devPackageDirs;
      this.key = key;

      resolve();
    }
    catch (err) { reject(err); }
    finally { this._readyPromise = null; }

    return this;
  }

  async _discoverPackagesInCollectionDirs(
    packageCollectionDirs,
    seen = { packageDirs: {}, collectionDirs: {} }
  ) {
    let found = [];
    for (let dir of packageCollectionDirs) {
      if (!await dir.exists()) continue;
      for (let packageDir of await dir.dirList()) {
        if (!packageDir.isDirectory()) continue;
        for (let versionDir of await packageDir.dirList())
          found.push(...await this._discoverPackagesInPackageDir(versionDir, seen));
      }
    }
    return found;
  }

  async _discoverPackagesInPackageDir(
    packageDir,
    seen = { packageDirs: {}, collectionDirs: {} }
  ) {
    let spec = await packageDir.exists() && await PackageSpec.fromDir(packageDir);
    if (!spec) return [];
    let found = [spec],
      { location, flatn_package_dirs } = spec;

    location = ensureResource(location);

    if (flatn_package_dirs) {
      for (let dir of flatn_package_dirs) {
        if (isAbsolute(dir)) dir = ensureResource(dir);
        else dir = join(location, dir).withRelativePartsResolved();
        if (seen.collectionDirs[dir.url]) continue;
        console.log(`[flatn] project ${location.url} specifies package dir ${dir.url}`);
        seen.collectionDirs[dir.url] = true;
        found.push(...await this._discoverPackagesInCollectionDirs([dir], seen));
      }
    }

    return found;
  }

}

// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
// PackageSpec => package representation for dependency resolution and build

const lvInfoFileName = ".lv-npm-helper-info.json";

class PackageSpec {

  static fromDir(packageDir) {
    let spec = new this(packageDir),
      read = spec.read();
    return read instanceof Promise
      ? read.then(read => (read ? spec : null))
      : read ? spec : null;
  }

  constructor(location) {
    this.location = location;
    this.isDevPackage = false;

    // from config
    this.scripts = null;
    this.bin = null;
    this.flatn_package_dirs = null;
    this.name = "";
    this.version = "";
    this.dependencies = {};
    this.devDependencies = {};

    // from git spec
    this.branch = null;
    this.gitURL = null;
    this.versionInFileName = null; // @https___github.com_foo_bar#zork
  }

  matches(pName, versionRange, gitSpec) {
    // does this package spec match the package pName@versionRange?
    let { name, version, isDevPackage } = this;

    if (name !== pName) return false;

    if (!versionRange || isDevPackage) return true;

    if (gitSpec && (gitSpec.versionInFileName === version
      || this.versionInFileName === gitSpec.versionInFileName)) {
      return true
    }

    if (semver.parse(version || "", true) && semver.satisfies(version, versionRange, true))
      return true;

    return false;
  }

  read() {
    let self = this,
      packageDir = this.location,
      configFile = join(packageDir, "package.json");

    if (!fs_isDirectory(packageDir)) return false;

    let hasConfig = fs_exists(configFile);

    return hasConfig instanceof Promise ? hasConfig.then(step2) : step2(hasConfig);

    function step2(hasConfig) {
      if (!hasConfig) return false;
      let config = fs_readJson(configFile);
      return config instanceof Promise ? config.then(step3) : step3(config);
    }

    function step3(config) {
      let {
        name, version, bin, scripts,
        dependencies, devDependencies,
        flatn_package_dirs
      } = config;

      if (bin) {
        // npm allows bin to just be a string, it is then mapped to the package name
        bin = typeof bin === "string" ? { [name]: bin } : Object.assign({}, bin);
      }

      Object.assign(self, {
        location: packageDir,
        name, version, bin, scripts,
        dependencies, devDependencies,
        flatn_package_dirs
      });

      let info = self.readLvInfo();
      return info instanceof Promise ? info.then(step4) : step4(info);
    }

    function step4(info) {
      if (info) {
        let { branch, gitURL, versionInFileName } = info;
        Object.assign(self, { branch, gitURL, versionInFileName });
      }
      return true;
    }
  }

  readConfig() {
    const config = fs_readJson(join(this.location, "package.json"));
    return config instanceof Promise ?
      config.then(ensureConfig) : ensureConfig(config);
    function ensureConfig(config) {
      if (config) return config;
      const { name, version } = this;
      return { name, version };
    }
  }

  readLvInfo() {
    let infoF = join(this.location, lvInfoFileName);
    try {
      let read = fs_readJson(infoF);
      return read instanceof Promise ?
        read.catch(err => null) : read;
    } catch (err) { }
    return null;
  }

  writeLvInfo(spec) {
    return fs_writeJson(join(this.location, lvInfoFileName), spec);
  }

  changeLvInfo(changeFn) {
    let read = this.readLvInfo();
    return read instanceof Promise ?
      read.then(read => this.writeLvInfo(changeFn(read))) :
      this.writeLvInfo(changeFn(read));
  }

}

export {
  PackageMap,
  AsyncPackageMap,
  PackageSpec
}


text:
.text-core {
    position: relative;
}

.text-core .text-wrap {
    background: #fff;
    position: absolute;
}

.text-core .text-wrap textarea, .text-core .text-wrap input {
    box-sizing: border-box;
    border-radius: 0px;
    border: 1px solid #9daccc;
    outline: none;
    resize: none;
    position: absolute;
    z-index: 1;
    background: none;
    overflow: hidden;
    margin: 0;
    padding: 3px 5px 4px 5px;
    white-space: nowrap;
    font: 11px "lucida grande", tahoma, verdana, arial, sans-serif;
    line-height: 13px;
    height: auto;
}


text:
There are many micro-frameworks that rely on magic methods. We don't. In this
document we're gonna explore the Respect\Validation API without fluent interfaces
or magic methods. We'll use a traditional dependency injection approach.

```php
use Respect\Validation\Validator as v;

$usernameValidator = v::alnum()->noWhitespace()->length(1,15);
$usernameValidator->validate('alganet'); //true
```

If you `var_dump($usernameValidator)`, you'll see a composite of objects with
`Respect\Validation\Rules\Alnum`, `Respect\Validation\Rules\NoWhitespace` and
`Respect\Validation\Rules\Length`. There is a specific object for each rule, and
the chain only builds the structure. You can build it by yourself:

```php
use Respect\Validation\Rules;

$usernameValidator = new Rules\AllOf(
    new Rules\Alnum(),
    new Rules\NoWhitespace(),
    new Rules\Length(1, 15)
);
$usernameValidator->validate('alganet'); //true
```

This is still a very lean API. You can use it in any dependency injection
container or test it in the way you want. Nesting is still possible:

```php
use Respect\Validation\Rules;

$usernameValidator = new Rules\AllOf(
    new Rules\Alnum(),
    new Rules\NoWhitespace(),
    new Rules\Length(1, 15)
);
$userValidator = new Rules\Key('name', $usernameValidator);
$userValidator->validate(['name' => 'alganet']); //true
```

## How It Works?

The Respect\Validation chain is an
[internal DSL](http://martinfowler.com/bliki/InternalDslStyle.html).
It acts in the creational realm of objects (where Abstract Factories and Builders
live), and it's only job is to make rule construction terse and fluent.

## FAQ

> Is `v` in `v::something` a class name?

No! The class is `Respect\Validation\Validator`, we suggest `v` as a very short alias.

> Is `v::something()` a static call?

Yes. Just like the default `DateTime::createFromFormat()` or
`Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration()`. It builds
something complex and returns for you.

> I really don't like static calls, can I avoid it?

Yes. Just use `$validator = new Validator();` each time you want a new validator,
and continue from there.

> Do you have a static method for each rule?

No. We use `__callStatic()`.

> Magic methods are slow! Why do you use them?

They're optional. If you use the `new` interface, they won't be called.

(still, do some benchmarks, you'd be surprised with our implementation).


text:
'''
Receives OBMP data from Arduino and prints to the screen.
Sends the current time to the Arduino to sync timestamps for OBMP.

Instructions:

1) First run the Arduino code: e.g., OBMPduino_demo1_v2

2) Then run this script via

python send_time_to_arduino.py

3) Follow the instructions printed to the terminal

4) Once you've set up the serial connection, the terminal should start printing OBMP with the correct start-time and relative time values
'''

import os
import serial
from serial.tools import list_ports
import time
import calendar
import json

TIME_HEADER = "T" # Header sent to Arduino with time-sync signal
TIME_REQUEST = 7  # ASCII bell character

def main():

    '''Determine the serial port to communicate with'''
    print "Which of these serial ports is the Arduino attached to?"
    ports = list_serial_ports()
    for i in range(len(ports)): # display the list of ports to the command line for the user
        print str(i) + " : " + ports[i]
    var = raw_input("Enter the number as 0 to N-1 where N is the number of serial ports: ")
    port = ports[int(var)]
    print port
    ser = serial.Serial(port, 19200) # establish a serial connection at 19200 baud rate

    '''Receive output from Arduino. If a time sync request, send the current time.
    Otherwise, process successive lines of output as JSON object, pretty-printing them to the command line.'''
    line = ""
    while(True):
        c = ser.read() # read a single character from the serial port
        if ord(c) == TIME_REQUEST: # do a time sync
            # Greenwich mean time
            gmtime_in_seconds = calendar.timegm(time.gmtime()) # Greenwich mean time in seconds
            time_str = TIME_HEADER + str(gmtime_in_seconds) + "\n" # time-sync response string to send to arduino
            ser.write(time_str) # print time_str
        else: # echo the serial port if it's not doing a time sync
            if c == "\n": # check for the end of a line
                if line[0] == "{": # this is a crude sanity-check test for correct JSON
                    j = json.loads(line) # convert string to JSON objsect
                    s = json.dumps(j, sort_keys=False, indent=4, separators=(',', ': ')) # pretty print JSON object as string
                    print s
                    print "\n"
                else: # ignore input that fails crude sanity-check test for correct JSON
                    # print line
                    # print "\n"
                    pass
                line = "" # start building up a new line of text from the serial input
            else:
                line += c # add the most-recently received character from the serial port to the line of text

'''Find all available serial ports on the computer. The Arduino will show up as a serial port.'''
def list_serial_ports():
    # Windows
    if os.name == 'nt':
        # Scan for available ports.
        available = []
        for i in range(256):
            try:
                s = serial.Serial(i)
                available.append('COM'+str(i + 1))
                s.close()
            except serial.SerialException:
                pass
        return available
    else:
        # Mac / Linux
        return [port[0] for port in list_ports.comports()]

if __name__ == '__main__':
    main()


text:
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Build.Execution;
using Microsoft.Build.Framework;
using Microsoft.Build.Logging;

namespace ContosoUniversity.FunctionalTests.Config
{
    public class MsBuildDeployer
    {
        private readonly IProjectLocation _projectLocation;

        public MsBuildDeployer(IProjectLocation projectLocation)
        {
            _projectLocation = projectLocation;
        }

        public void Deploy(string configTransformName, string deployPath)
        {
            var loggers = new ILogger[] { new ConsoleLogger(LoggerVerbosity.Normal) };
            var parameters = new BuildParameters { Loggers = loggers };

            var globalProperties = new Dictionary<string, string>
	        {
	            { "Configuration", configTransformName },
                { "_PackageTempDir", deployPath }
	        };

            var requestData = new BuildRequestData(_projectLocation.ProjectName, globalProperties, null,
                new[] { "Clean", "Package" }, null);

            var result = BuildManager.DefaultBuildManager.Build(parameters, requestData);

            if (result.OverallResult != BuildResultCode.Success || !Directory.Exists(deployPath))
            {
                throw new Exception("Build failed.");
            }
        }
    }
}


text:
package com.njwd.rpc.monitor.config.dubbo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ProtocolConfig;
import com.alibaba.dubbo.config.ReferenceConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.registry.RegistryService;

@Configuration
@EnableConfigurationProperties(DubboProperties.class)
public class DubboConfig {

	@Autowired
	private DubboProperties properties;

	@Bean
	@ConditionalOnMissingBean
	public ApplicationConfig applicationConfig() {
		ApplicationConfig applicationConfig = new ApplicationConfig();
		applicationConfig.setName(properties.getApplicationName());
		applicationConfig.setLogger("slf4j");
		return applicationConfig;
	}

	@Bean
	@ConditionalOnMissingBean(RegistryConfig.class)
	public RegistryConfig registryConfig() {
		RegistryConfig registryConfig = new RegistryConfig();
		registryConfig.setAddress(properties.getRegistryAddress());
		registryConfig.setCheck(properties.isRegistryCheck());
		registryConfig.setTimeout(properties.getRegistryTimeout());
		return registryConfig;
	}

	@Bean
	@ConditionalOnMissingBean(ProtocolConfig.class)
	public ProtocolConfig protocolConig() {
		ProtocolConfig protocol = new ProtocolConfig();
		protocol.setName(properties.getProtocolName());
		protocol.setPort(properties.getProtocolPort());
		return protocol;
	}

	@Bean
	@ConditionalOnMissingBean(RegistryService.class)
	public RegistryService registerServices(ApplicationConfig appConfig,
			RegistryConfig config) {

		ReferenceConfig<RegistryService> reference = new ReferenceConfig<RegistryService>();
		reference.setApplication(appConfig);
		reference.setRegistry(config);
		reference.setInterface(RegistryService.class);
		return reference.get();
	}

}


text:
package com.facebook.buck.cxx;

import com.facebook.buck.rules.RuleKeyAppendable;
import com.facebook.buck.rules.RuleKeyObjectSink;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Ordering;

/**
 * Helper class for generating compiler invocations for a cxx compilation rule.
 */
class CompilerDelegate implements RuleKeyAppendable {
  // Fields that are added to rule key as is.
  private final Compiler compiler;

  // Fields that added to the rule key with some processing.
  private final CxxToolFlags compilerFlags;

  // Fields that are not added to the rule key.
  private final SourcePathResolver resolver;
  private final DebugPathSanitizer sanitizer;

  public CompilerDelegate(
      SourcePathResolver resolver,
      DebugPathSanitizer sanitizer,
      Compiler compiler,
      CxxToolFlags flags) {
    this.resolver = resolver;
    this.sanitizer = sanitizer;
    this.compiler = compiler;
    this.compilerFlags = flags;
  }

  @Override
  public void appendToRuleKey(RuleKeyObjectSink sink) {
    sink.setReflectively("compiler", compiler);
    sink.setReflectively(
        "platformCompilerFlags",
        sanitizer.sanitizeFlags(compilerFlags.getPlatformFlags()));
    sink.setReflectively(
        "ruleCompilerFlags",
        sanitizer.sanitizeFlags(compilerFlags.getRuleFlags()));
  }

  /**
   * Returns the argument list for executing the compiler.
   */
  public ImmutableList<String> getCommand(CxxToolFlags prependedFlags) {
    return ImmutableList.<String>builder()
        .addAll(getCommandPrefix())
        .addAll(getArguments(prependedFlags))
        .build();
  }

  public ImmutableList<String> getCommandPrefix() {
    return compiler.getCommandPrefix(resolver);
  }

  public ImmutableList<String> getArguments(CxxToolFlags prependedFlags) {
    return ImmutableList.<String>builder()
        .addAll(CxxToolFlags.concat(prependedFlags, compilerFlags).getAllFlags())
        .addAll(
            compiler.debugCompilationDirFlags(sanitizer.getCompilationDirectory())
                .or(ImmutableList.<String>of()))
        .build();
  }

  public CxxToolFlags getCompilerFlags() {
    return compilerFlags;
  }

  public ImmutableMap<String, String> getEnvironment() {
    return compiler.getEnvironment(resolver);
  }

  public ImmutableList<SourcePath> getInputsAfterBuildingLocally() {
    return Ordering.natural().immutableSortedCopy(compiler.getInputs());
  }

  public Optional<ImmutableList<String>> getFlagsForColorDiagnostics() {
    return compiler.getFlagsForColorDiagnostics();
  }

}


text:
print '==> processing options'

cmd = torch.CmdLine()
cmd:text()
cmd:text('SVHN Loss Function')
cmd:text()
cmd:text('Options:')
-- global:
cmd:option('-seed', 1, 'fixed input seed for repeatable experiments')
cmd:option('-threads', 2, 'number of threads')
-- data:
cmd:option('-size', 'full', 'how many samples do we load: small | full | extra')
-- model:
cmd:option('-model', 'convnet', 'type of model to construct: linear | mlp | convnet')
-- loss:
cmd:option('-loss', 'nll', 'type of loss function to minimize: nll | mse | margin')
-- training:
cmd:option('-save', 'results', 'subdirectory to save/log experiments in')
cmd:option('-plot', false, 'live plot')
cmd:option('-optimization', 'SGD', 'optimization method: SGD | ASGD | CG | LBFGS')
cmd:option('-learningRate', 1e-3, 'learning rate at t=0')
cmd:option('-batchSize', 1, 'mini-batch size (1 = pure stochastic)')
cmd:option('-weightDecay', 0, 'weight decay (SGD only)')
cmd:option('-momentum', 0, 'momentum (SGD only)')
cmd:option('-t0', 1, 'start averaging at t0 (ASGD only), in nb of epochs')
cmd:option('-maxIter', 2, 'maximum nb of iterations for CG and LBFGS')
cmd:option('-type', 'double', 'type: double | float | cuda')
cmd:text()
opt = cmd:parse(arg or {})

-- nb of threads and fixed seed (for repeatable experiments)
if opt.type == 'float' then
   print('==> switching to floats')
   torch.setdefaulttensortype('torch.FloatTensor')
elseif opt.type == 'cuda' then
   print('==> switching to CUDA')
   require 'cunn'
   torch.setdefaulttensortype('torch.FloatTensor')
end
torch.setnumthreads(opt.threads)
torch.manualSeed(opt.seed)

----------------------------------------------------------------------
print '==> executing all'

dofile '1_data.lua'
dofile '2_model.lua'
dofile '3_loss.lua'
dofile '4_train.lua'
dofile '5_test.lua'

----------------------------------------------------------------------
print '==> training!'

while true do
   train()
   test()
end


text:
require "active_record"

module HackerNewsCLI
  module DBHelper
    def establish_db_connection
      if HN_ENV == 'production'
        config = { "adapter" => "sqlite3", "database" => HN_DB_PATH, "pool" => 5, "timeout" => 5000 }
      else
        config = YAML.load(File.read(File.join('config','database.yml')))[HN_ENV]
      end
      ActiveRecord::Base.establish_connection config
    end

    def create_tables
      establish_db_connection
      ActiveRecord::Migrator.migrate(File.expand_path("../../../../db/migrate/", __FILE__))
    end

    def ensure_db_exists
      establish_db_connection
      Entry.count
    rescue
      create_tables
    end
  end
end


text:
Diffusion
=========

pyro solves the constant-conductivity diffusion equation:

.. math::

   \frac{\partial \phi}{\partial t} = k \nabla^2 \phi

This is done implicitly using multigrid, using the solver :py:mod:`diffusion`.

The diffusion equation is discretized using Crank-Nicolson
differencing (this makes the diffusion operator time-centered) and the
implicit discretization forms a Helmholtz equation solved by the pyro
multigrid class. The main parameters that affect this solver are:

.. include:: diffusion_defaults.inc

Examples
--------

gaussian
^^^^^^^^

The gaussian problem initializes a strongly peaked Gaussian centered
in the domain. The analytic solution for this shows that the profile
remains a Gaussian, with a changing width and peak. This allows us to
compare our solver to the analytic solution. This is run as:

.. prompt:: bash

   ./pyro_sim.py diffusion gaussian inputs.gaussian

.. image:: gauss_diffusion.png
   :align: center

The above figure shows the scalar field after diffusing significantly
from its initial strongly peaked state. We can compare to the analytic
solution by making radial profiles of the scalar. The plot below shows
the numerical solution (red points) overplotted on the analytic
solution (solid curves) for several different times. The y-axis is
restricted in range to bring out the detail at later times.

.. image:: gauss_diffusion_compare.png
   :align: center

Exercises
---------

The best way to learn these methods is to play with them yourself. The
exercises below are suggestions for explorations and features to add
to the advection solver.

Explorations
^^^^^^^^^^^^

* Test the convergence of the solver by varying the resolution and
  comparing to the analytic solution.

* How does the solution error change as the CFL number is increased
  well above 1?

* Setup some other profiles and experiment with different boundary conditions.

Extensions
^^^^^^^^^^

* Switch from Crank-Nicolson (2nd order in time) to backward's Euler
  (1st order in time) and compare the solution and convergence. This
  should only require changing the source term and coefficents used in
  setting up the multigrid solve. It does not require changes to the
  multigrid solver itself.

* Implement a non-constant coefficient diffusion solver—note: this
  will require improving the multigrid solver.


text:
<?php namespace Modules\Workshop\Manager;

use Illuminate\Contracts\Filesystem\Filesystem;

class PackageInformation
{
    /**
     * @var Filesystem
     */
    private $finder;

    public function __construct(Filesystem $finder)
    {
        $this->finder = $finder;
    }

    /**
     * Get the exact installed version for the specified package
     * @param string $packageName
     * @return string mixed
     */
    public function getPackageInfo($packageName)
    {
        $composerLock = json_decode($this->finder->get('composer.lock'));
        foreach ($composerLock->packages as $package) {
            if ($package->name == $packageName) {
                return $package;
            }
        }
    }
}


text:
header #logo-group .logo{
	width: 230px;
	font-size: 14px;
	font-weight: bold;
}

header .user-info{
	padding:7px 0;
}

.smart-form .col-md-offset-1 {
	margin-left: 8.333333333333332%;
}

.show-grid {
	margin-bottom: 15px;
}

.navbar-form{
	padding:0;
}

.smart-form.navbar-form .table>thead>tr>th, .smart-form.navbar-form .table>thead>tr>td, .smart-form.navbar-form .table>tbody>tr>td{
	color: rgb(51, 51, 51);
}

.smart-form.navbar-form *, .smart-form.navbar-form :after, .smart-form.navbar-form :before{
	box-sizing: border-box;
}

.smart-form.navbar-form .table>tbody>tr>td .label{
	padding: .2em .6em .3em;
	font-size: 10px;
	font-weight: bold;
	height: auto;
	width: auto;
	color: rgb(255, 255, 255);
	display:inline;
}

.smart-form.navbar-form .table>tbody>tr>td a.btn{
	padding: 6px 12px;
}

.table.has-tickbox>thead>tr>th:first, .table.has-tickbox>tbody>tr>td:first{
	padding-left:5px;
	padding-right:5px;
}

.smart-form.navbar-form .table.has-tickbox label.checkbox{
	width:18px;
}

.smart-form.navbar-form .table.has-tickbox label.checkbox i{
	width: 19px;
	height:19px;
}

div.row.action-div{
	margin: 9px 0;
}

div.row.action-div label.select{
	width: 174px;
}

div.row.action-div .btn-default{
	padding: 6px 12px;
}

div.information-content > .row{
	margin: 10px 10px 0 10px;
}

div.information-content > .row span{
	display: inline-block;
	font-size: 20px;
	font-weight: bold;
	margin-right: 10px;
	text-align: right;
	width: 70px;
	font-style: italic;
}

div.information-content > .row a {
	color: #666;
	display: block;
	line-height: 32px;
	text-decoration: none;
	border-bottom: 1px solid #ebebeb;
}

/* Added by Kirill table order child style */
table.smart-form tr.child td:first-child{
    padding-left:30px;
}

table.smart-form tr td:first-child i{
    cursor:pointer;
}

.widget-body-ajax-loading::before{
	content:url(../images/ajax-loader.gif);
}


text:
import * as i2cBus from "i2c-bus";
import printf from "printf";
import { take } from "rxjs/operators";

import { Lsm303Driver, Vector } from "../index";

const lsm303 = new Lsm303Driver({
    // looking at the source code, the synchronous and
    // asynchronous open functions are identical
    i2c: i2cBus.openSync(1)
    // uncomment for debugging information
    // debug: true
});

console.log("Reading 50 accelerometer values...");
lsm303.streamAccelerometer()
    .pipe(
        take(50)
    )
    .subscribe(
        function (next: Vector): void {
            console.log(printf("x: % 6.2f, y: % 6.2f, z: % 6.2f", next.x, next.y, next.z));
        },
        function (err: any): void {
            console.log("Error: " + err);
        },
        function (): void {
            console.log("Completed");
        }
    );


text:
#ifndef GDCMCOMPOSITENETWORKFUNCTIONS_H
#define GDCMCOMPOSITENETWORKFUNCTIONS_H

#include "gdcmDirectory.h"
#include "gdcmBaseRootQuery.h" // EQueryLevel / EQueryType

#include <vector>
#include <string>

namespace gdcm
{
/**
 * \brief Composite Network Functions
 * These functions provide a generic API to the DICOM functions implemented in
 * GDCM.
 * Advanced users can use this code as a template for building their own
 * versions of these functions (for instance, to provide progress bars or some
 * other way of handling returned query information), but for most users, these
 * functions should be sufficient to interface with a PACS to a local machine.
 * Note that these functions are not contained within a static class or some
 * other class-style interface, because multiple connections can be
 * instantiated in the same program.  The DICOM standard is much more function
 * oriented rather than class oriented in this instance, so the design of this
 * API reflects that functional approach.
 * These functions implements the following SCU operations:
 * \li C-ECHO SCU
 * \li C-FIND SCU
 * \li C-STORE SCU
 * \li C-MOVE SCU (+internal C-STORE SCP)
 */
class GDCM_EXPORT CompositeNetworkFunctions
{
public:
  /// The most basic network function.  Use this function to ensure that the
  /// remote server is responding on the given IP and port number as expected.
  /// \param aetitle when not set will default to 'GDCMSCU'
  /// \param call when not set will default to 'ANY-SCP'
  /// \warning This is an error to set remote to NULL or portno to 0
  /// \return true if it worked.
  static bool CEcho( const char *remote, uint16_t portno, const char *aetitle = NULL,
    const char *call = NULL );

  typedef std::pair<Tag, std::string> KeyValuePairType;
  typedef std::vector< KeyValuePairType  > KeyValuePairArrayType;

  /// This function will take a list of strings and tags and fill in a query that
  /// can be used for either CFind or CMove (depending on the input boolean
  /// \param inMove).
  /// Note that the caller is responsible for deleting the constructed query.
  /// This function is used to build both a move and a find query
  /// (true for inMove if it's move, false if it's find)
  static BaseRootQuery* ConstructQuery(ERootType inRootType, EQueryLevel inQueryLevel,
    const DataSet& queryds, bool inMove = false );

  /// \deprecated
  static BaseRootQuery* ConstructQuery(ERootType inRootType, EQueryLevel inQueryLevel,
    const KeyValuePairArrayType& keys, bool inMove = false );

  /// This function will use the provided query to get files from a remote server.
  /// NOTE that this functionality is essentially equivalent to C-GET in the
  /// DICOM standard; however, C-GET has been deprecated, so this function
  /// allows for the user to ask a remote server for files matching a query and
  /// return them to the local machine.
  /// Files will be written to the given output directory.
  /// If the operation succeeds, the function returns true.
  /// This function is a prime candidate for being overwritten by expert users;
  /// if the datasets should remain in memory, for instance, that behavior can
  /// be changed by creating a user-level version of this function.
  /// \param aetitle when not set will default to 'GDCMSCU'
  /// \param call when not set will default to 'ANY-SCP'
  /// This is an error to set remote to NULL or portno to 0
  /// when \param outputdir is not set default to current dir ('.')
  /// \return true if it worked.
  static bool CMove( const char *remote, uint16_t portno, const BaseRootQuery* query,
    uint16_t portscp, const char *aetitle = NULL,
    const char *call = NULL, const char *outputdir = NULL);

  /// This function will use the provided query to determine what files a remote
  /// server contains that match the query strings.  The return is a vector of
  /// datasets that contain tags as reported by the server.  If the dataset is
  /// empty, then it is possible that an error condition was encountered; in
  /// which case, the user should monitor the error and warning streams.
  /// \param aetitle when not set will default to 'GDCMSCU'
  /// \param call when not set will default to 'ANY-SCP'
  /// \warning This is an error to set remote to NULL or portno to 0
  /// \return true if it worked.
  static bool CFind( const char *remote, uint16_t portno,
    const BaseRootQuery* query,
    std::vector<DataSet> &retDataSets,
    const char *aetitle = NULL,
    const char *call = NULL );

  /// This function will place the provided files into the remote server.
  /// The function returns true if it worked for all files.
  /// \warning the server side can refuse an association on a given file
  /// \param aetitle when not set will default to 'GDCMSCU'
  /// \param call when not set will default to 'ANY-SCP'
  /// \warning This is an error to set remote to NULL or portno to 0
  /// \return true if it worked for all files
  static bool CStore( const char *remote, uint16_t portno,
    const Directory::FilenamesType & filenames,
    const char *aetitle = NULL, const char *call = NULL);
};

} // end namespace gdcm

#endif // GDCMCOMPOSITENETWORKFUNCTIONS_H


text:
//////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014-2015, Egret Technology Inc.
//  All rights reserved.
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Egret nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
//  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
//  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
//  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////
var egret;
(function (egret) {
    var gui;
    (function (gui) {
        /**
         * @class egret.gui.PopUpPosition
         * @classdesc
         * 定义弹出位置的常量值。
         * 该常量决定目标对象相对于父级组件的弹出位置。
         */
        var PopUpPosition = (function () {
            function PopUpPosition() {
            }
            var __egretProto__ = PopUpPosition.prototype;
            /**
             * 在组件上方弹出
             * @constant egret.gui.PopUpPosition.ABOVE
             */
            PopUpPosition.ABOVE = "above";
            /**
             * 在组件下方弹出
             * @constant egret.gui.PopUpPosition.BELOW
             */
            PopUpPosition.BELOW = "below";
            /**
             * 在组件中心弹出
             * @constant egret.gui.PopUpPosition.CENTER
             */
            PopUpPosition.CENTER = "center";
            /**
             * 在组件左上角弹出
             * @constant egret.gui.PopUpPosition.TOP_LEFT
             */
            PopUpPosition.TOP_LEFT = "topLeft";
            /**
             * 在组件左边弹出
             * @constant egret.gui.PopUpPosition.LEFT
             */
            PopUpPosition.LEFT = "left";
            /**
             * 在组件右边弹出
             * @constant egret.gui.PopUpPosition.RIGHT
             */
            PopUpPosition.RIGHT = "right";
            /**
             * 在屏幕中心弹出
             * @constant egret.gui.PopUpPosition.SCREEN_CENTER
             */
            PopUpPosition.SCREEN_CENTER = "screenCenter";
            return PopUpPosition;
        })();
        gui.PopUpPosition = PopUpPosition;
        PopUpPosition.prototype.__class__ = "egret.gui.PopUpPosition";
    })(gui = egret.gui || (egret.gui = {}));
})(egret || (egret = {}));


text:
layout: post
title: Masterclass 17
---

### Keywords

The speed recognition doesn't allow you to get in there. Which is very good.
The feeling of a C home base is going to start to leave you.
If the feeling is there we alowe it to be there.

### Exercise

*Solo keyboars*

White major chords

 - **17-01** A C major chord and than two harmonic black tone. OVR.
 - **17-02** Three white tones and one black tone. 3VR of 10.
 - **17-03-01** Black fours. Unlock and sing them. OVR.
 - **17-03-02** Black fours. Identify them. OVR.

*Solo guitar*

...

*Meditation*

 - **16-04** C major with As,Fis but doubles.

*Team players*

 - **16-05-01** Single tone: H-D-F-As,Fis in first octave.
 - **16-05-02** Double melodic tones: H-D-F-As,Fis in first octave.
 - **16-05-03** Triple melodic tones: H-D-F-As,Fis in first octave.
 - **16-05-04** Harmonic doubles tones: H-D-F-As,Fis in first octave.
 - **16-05-05** Harmonic triples tones: H-D-F-As,Fis in first octave.


text:
alter table project__template add `type` varchar(10) not null default '';
alter table `task` add `message` varchar(250) not null default '';
alter table project__template add start_version varchar(20);
alter table project__template add build_template_id int references project__template(id);
alter table `task` add `version` varchar(20);
alter table `task` add commit_hash varchar(40);
alter table `task` add commit_message varchar(100) not null default '';


text:
===================
Fudge Documentation
===================

Fudge is a Python module for using fake objects (mocks and stubs) to test real ones.

In readable Python code, you declare what methods are available on your fake and how they should be called.  Then you inject that into your application and start testing.  This declarative approach means you don't have to record and playback actions and you don't have to inspect your fakes after running code.  If the fake object was used incorrectly then you'll see an informative exception message with a traceback that points to the culprit.

Fudge was inspired by `Mocha <http://mocha.rubyforge.org/>`_ which is a simpler version of `jMock <http://www.jmock.org/>`_.  But unlike Mocha, Fudge does not automatically hijack real objects; you explicitly :ref:`patch <using-fudge>` them in your test.  And unlike jMock, Fudge is only as strict about expectations as you want it to be.  If the type of arguments sent to the fake method aren't important then you don't have to declare an expectation for them.

Download / Install
==================

Just type::

    $ pip install fudge

You can get the `pip command here`_.  Fudge requires Python 2.5 or higher.

.. _pip command here: http://pip.openplans.org/

.. _install-for-python-3:

Installing for Python 3
=======================

As of version 0.9.5, Fudge supports Python 3.  Just install `distribute`_ and type::

    $ python3.x setup.py install

This step will convert the Fudge source code using the 2to3 tool.

.. _distribute: http://packages.python.org/distribute/

.. _fudge-source:

Source
======

The Fudge source can be downloaded as a tar.gz file from http://pypi.python.org/pypi/fudge

Using `Git <https://git-scm.com/>`_ you can clone the source from https://github.com/fudge-py/fudge/

Fudge is free and open for usage under the `MIT license`_.

.. _MIT license: http://en.wikipedia.org/wiki/MIT_License

Contents
========

.. toctree::
   :maxdepth: 2

   using-fudge
   javascript
   why-fudge
   migrating-0.9-to-1.0

.. _fudge-api:

API Reference
=============

.. toctree::
    :glob:

    api/*

Contributing
============

Please submit `bugs and patches <https://github.com/fudge-py/fudge/issues>`_, preferably with tests.  All contributors will be acknowledged.  Thanks!

Credits
=======

Fudge was created by `Kumar McMillan <http://farmdev.com/>`_ and contains contributions by Cristian Esquivias, Michael Williamson, Luis Fagundes and Jeremy Satterfield.

.. _fudge-changelog:

Changelog
=========

- 1.1.1

  - Fixes error when providing tuple or list to arg.isinstance

- 1.1.0

  - **Changed** `moved to github <https://github.com/fudge-py/fudge/>`_ and added maintainers
  - **Changed** remove support for python 3.1 and 3.2 in tests in lieu of 3.4
  - added :func:`fudge.Fake.has_property`
  - added :class:`IsInstance`
  - added :func:`without_args`
  - Deprecation warnings are now real warnings.

- 1.0.3

  - Added :func:`fudge.Fake.is_a_stub` :ref:`documented here <creating-a-stub>`
  - :func:`arg.any_value() <fudge.inspector.ValueInspector.any_value>`
    is **DEPRECATED** in favor of
    :func:`arg.any() <fudge.inspector.ValueInspector.any>`
  - Attributes declared by :func:`fudge.Fake.has_attr` are now settable.
    Thanks to Mike Kent for the bug report.
  - Fixes ImportError when patching certain class methods like
    smtplib.SMTP.sendmail
  - Fixes representation of chained fakes for class instances.

- 1.0.2

  - Object patching is a lot safer in many cases and now supports getter objects
    and static methods. Thanks to Michael Foord and mock._patch for ideas and code.

- 1.0.1

  - Fixed ImportError when a patched path traverses object attributes within a module.

- 1.0.0

  - After extensive usage and community input, the fudge interface has
    been greatly simplified!
  - There is now a :ref:`way better pattern <using-fudge>` for setting up fakes. The old way is
    still supported but you'll want to write all new code in this pattern once
    you see how much easier it is.
  - Added :func:`fudge.patch` and :func:`fudge.test`
  - Added :func:`fudge.Fake.expects_call` and :func:`fudge.Fake.is_callable`
  - **Changed**: The tests are no longer maintained in Python 2.4 although
    Fudge probably still supports 2.4

- 0.9.6

  - Added support to patch builtin modules.  Thanks to Luis Fagundes for the
    patch.

- 0.9.5

  - **Changed**: multiple calls to :func:`fudge.Fake.expects` behave just like
    :func:`fudge.Fake.next_call`.  The same goes for :func:`fudge.Fake.provides`.
    You probably won't need to update any old code for this change, it's just
    a convenience.
  - Added :func:`fudge.Fake.with_matching_args` so that expected
    arguments can be declared more loosely
  - Added :ref:`support for Python 3 <install-for-python-3>`
  - Improved support for Jython

- 0.9.4

  - Fixed bug where __init__ would always return the Fake instance of itself.
    Now you can return a custom object if you want.

- 0.9.3

  - Added ``with_args()`` to :ref:`JavaScript Fudge <javascript-fudge>`.
  - Fixed bug where argument values that overloaded __eq__ might cause declared expectations to fail (patch from Michael Williamson, Issue 9)
  - Fixed bug where :func:`fudge.Fake.raises` obscured :func:`fudge.Fake.with_args` (Issue 6)
  - Fixed ``returns_fake()`` in JavaScript Fudge.

- 0.9.2

  - **Changed**: values in failed comparisons are no longer shortened when too long.
  - **Changed**: :func:`fudge.Fake.calls` no longer trumps expectations
    (i.e. :func:`fudge.Fake.with_args`)
  - **Changed**: :func:`fudge.Fake.with_args` is more strict.  You will now see an error
    when arguments are not expected yet keyword arguments were expected and vice versa.
    This was technically a bug but is listed under
    changes in case you need to update your code.  Note that you can work
    with arguments more expressively using the new :mod:`fudge.inspector` functions.
  - Added :mod:`fudge.inspector` for :ref:`working-with-arguments`.
  - Added :func:`fudge.Fake.remember_order` so that order of expected calls can be verified.
  - Added :func:`fudge.Fake.raises` for simulating exceptions
  - Added keyword :func:`fudge.Fake.next_call(for_method="other_call") <fudge.Fake.next_call>`
    so that arbitrary methods can be modified (not just the last one).
  - Fixed: error is raised if you declare multiple :func:`fudge.Fake.provides` for the same Fake.
    This also applies to :func:`fudge.Fake.expects`
  - Fixed bug where :func:`fudge.Fake.returns` did not work if you had replaced a call with :func:`fudge.Fake.calls`
  - Fixed bug in :func:`fudge.Fake.next_call` so that this now works: ``Fake(callable=True).next_call().returns(...)``
  - Fixed: Improved Python 2.4 compatibility.
  - Fixed bug where ``from fudge import *`` did not import proper objects.

- 0.9.1

  - **DEPRECATED** fudge.start() in favor of :func:`fudge.clear_calls`
  - **DEPRECATED** fudge.stop() in favor of :func:`fudge.verify`
  - Added context manager :func:`fudge.patcher.patched_context` so the with statement can be used for
    patching (contributed by Cristian Esquivias)
  - Added :func:`fudge.Fake.times_called` to expect a certain call count (contributed by Cristian Esquivias)
  - Added :class:`Fake(expect_call=True) <fudge.Fake>` to indicate an expected callable.  Unlike
    :class:`Fake(callable=True) <fudge.Fake>` the former will raise an error if not called.

- 0.9.0

  - first release