text:
var MoneyFiltersModule;
(function (MoneyFiltersModule) {
    var Module = (function () {
        function Module(name, modules, config) {
            this.module = angular.module(name, modules, config);
        }
        Module.prototype.config = function (appConfig) {
            this.module.config(appConfig);
            return this;
        };
        Module.prototype.run = function (appRun) {
            this.module.run(appRun);
            return this;
        };
        Module.prototype.controller = function (name, controller) {
            this.module.controller(name, controller);
            return this;
        };
        Module.prototype.directive = function (name, directive) {
            this.module.directive(name, DirectiveFactory.create(directive));
            return this;
        };
        Module.prototype.filter = function (name, filter) {
            this.module.filter(name, FilterFactory.create(filter));
            return this;
        };
        Module.prototype.service = function (name, service) {
            this.module.service(name, service);
            return this;
        };
        Module.prototype.provider = function (name, provider) {
            this.module.provider(name, provider);
            return this;
        };
        Module.prototype.factory = function (name, factory) {
            this.module.factory(name, factory);
            return this;
        };
        Module.prototype.constant = function (name, value) {
            this.module.constant(name, value);
            return this;
        };
        return Module;
    })();
    MoneyFiltersModule.Module = Module;
    var FilterFactory = (function () {
        function FilterFactory() {
        }
        FilterFactory.create = function (type) {
            var filter = function () {
                var inject = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    inject[_i - 0] = arguments[_i];
                }
                var instance = Activator.create(type, inject);
                return function () {
                    var options = [];
                    for (var _i = 0; _i < arguments.length; _i++) {
                        options[_i - 0] = arguments[_i];
                    }
                    return instance.filter.apply(instance, options);
                };
            };
            filter["$inject"] = type["$inject"];
            return filter;
        };
        return FilterFactory;
    })();
    var DirectiveFactory = (function () {
        function DirectiveFactory() {
        }
        DirectiveFactory.create = function (type) {
            var directive = function () {
                var inject = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    inject[_i - 0] = arguments[_i];
                }
                return Activator.create(type, inject);
            };
            directive["$inject"] = type["$inject"];
            return directive;
        };
        return DirectiveFactory;
    })();
    var Activator = (function () {
        function Activator() {
        }
        Activator.create = function (type, params) {
            var instance = Object.create(type.prototype);
            instance.constructor.apply(instance, params);
            return instance;
        };
        return Activator;
    })();
})(MoneyFiltersModule || (MoneyFiltersModule = {}));
var app = new MoneyFiltersModule.Module("moneyFilters", []);
var MoneyFiltersModule;
(function (MoneyFiltersModule) {
    var MoneyFilter = (function () {
        function MoneyFilter() {
        }
        MoneyFilter.prototype.filter = function (value, code, options) {
            if (value == null || angular.isString(value) && value.trim().length === 0)
                return "";
            if (angular.isObject(code)) {
                options = code;
                code = null;
            }
            if (value.amount) {
                code = value.currency || code;
                value = value.amount;
            }
            if (!options)
                options = {};
            if (options.abbrev) {
                var v = accounting.unformat(value);
                if (v >= 1000) {
                    value = v / 1000;
                    options.precision = 1;
                    options.format = "%s%vK";
                }
                if (v >= 1000000) {
                    value = v / 1000000;
                    options.precision = 1;
                    options.format = "%s%vM";
                }
            }
            options.symbol = currency.symbolize(code);
            return accounting.formatMoney(value, options);
        };
        return MoneyFilter;
    })();
    app.filter('money', MoneyFilter);
})(MoneyFiltersModule || (MoneyFiltersModule = {}));


text:
title: "Quandary"
description: "The Quandary taint analysis detects flows of values between sources and sinks, except if the value went through a \"sanitizer\". In addition to some defaults, users can specify their own sources, sinks, and sanitizers functions."
---

The Quandary taint analysis detects flows of values between sources and sinks, except if the value went through a "sanitizer". In addition to some defaults, users can specify their own sources, sinks, and sanitizers functions.

Activate with `--quandary`.

Supported languages:
- C/C++/ObjC: Yes
- Java: Yes
- C#/.Net: Yes

Quandary is a static taint analyzer that identifies a variety of unsafe
information flows. It has a small list of built-in
[sources](https://github.com/facebook/infer/blob/main/infer/src/quandary/JavaTrace.ml#L36)
and
[sinks](https://github.com/facebook/infer/blob/main/infer/src/quandary/JavaTrace.ml#L178),
and you can define custom sources and sinks in your `.inferconfig` file (see
example
[here](https://github.com/facebook/infer/blob/main/infer/tests/codetoanalyze/java/quandary/.inferconfig)).

## List of Issue Types

The following issue types are reported by this checker:
- [CREATE_INTENT_FROM_URI](/docs/all-issue-types#create_intent_from_uri)
- [CROSS_SITE_SCRIPTING](/docs/all-issue-types#cross_site_scripting)
- [EXPOSED_INSECURE_INTENT_HANDLING](/docs/all-issue-types#exposed_insecure_intent_handling)
- [INSECURE_INTENT_HANDLING](/docs/all-issue-types#insecure_intent_handling)
- [JAVASCRIPT_INJECTION](/docs/all-issue-types#javascript_injection)
- [LOGGING_PRIVATE_DATA](/docs/all-issue-types#logging_private_data)
- [QUANDARY_TAINT_ERROR](/docs/all-issue-types#quandary_taint_error)
- [SHELL_INJECTION](/docs/all-issue-types#shell_injection)
- [SHELL_INJECTION_RISK](/docs/all-issue-types#shell_injection_risk)
- [SQL_INJECTION](/docs/all-issue-types#sql_injection)
- [SQL_INJECTION_RISK](/docs/all-issue-types#sql_injection_risk)
- [UNTRUSTED_BUFFER_ACCESS](/docs/all-issue-types#untrusted_buffer_access)
- [UNTRUSTED_DESERIALIZATION](/docs/all-issue-types#untrusted_deserialization)
- [UNTRUSTED_DESERIALIZATION_RISK](/docs/all-issue-types#untrusted_deserialization_risk)
- [UNTRUSTED_ENVIRONMENT_CHANGE_RISK](/docs/all-issue-types#untrusted_environment_change_risk)
- [UNTRUSTED_FILE](/docs/all-issue-types#untrusted_file)
- [UNTRUSTED_FILE_RISK](/docs/all-issue-types#untrusted_file_risk)
- [UNTRUSTED_HEAP_ALLOCATION](/docs/all-issue-types#untrusted_heap_allocation)
- [UNTRUSTED_INTENT_CREATION](/docs/all-issue-types#untrusted_intent_creation)
- [UNTRUSTED_URL_RISK](/docs/all-issue-types#untrusted_url_risk)
- [UNTRUSTED_VARIABLE_LENGTH_ARRAY](/docs/all-issue-types#untrusted_variable_length_array)
- [USER_CONTROLLED_SQL_RISK](/docs/all-issue-types#user_controlled_sql_risk)

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace CalendR\Test\Period;

use CalendR\Period\Day;
use CalendR\Period\Month;
use CalendR\Period\PeriodInterface;
use CalendR\Period\Year;

class DayTest extends \PHPUnit_Framework_TestCase
{
    public static function providerConstructInvalid()
    {
        return array(
            array(new \DateTime('2014-12-10 17:30')),
            array(new \DateTime('2014-12-10 00:00:01')),
        );
    }

    public static function providerConstructValid()
    {
        return array(
            array(new \DateTime('2012-01-03')),
            array(new \DateTime('2011-12-10')),
            array(new \DateTime('2013-07-13 00:00:00')),
        );
    }

    /**
     * @dataProvider providerConstructInvalid
     * @expectedException \CalendR\Period\Exception\NotADay
     */
    public function testConstructInvalidStrict($start)
    {
        $calendar = new \CalendR\Calendar;
        $calendar->setStrictDates(true);
        new Day($start, $calendar->getFactory());
    }

    /**
     * @dataProvider providerConstructInvalid
     */
    public function testConstructInvalidLazy($start)
    {
        $calendar = new \CalendR\Calendar;
        $calendar->setStrictDates(false);
        new Day($start, $calendar->getFactory());
    }

    /**
     * @dataProvider providerConstructValid
     */
    public function testConstructValid($start)
    {
        new Day($start);
    }

    public static function providerContains()
    {
        return array(
            array(new \DateTime('2012-01-02'), new \DateTime('2012-01-02 00:01'), new \DateTime('2012-01-03')),
            array(new \DateTime('2012-05-30'), new \DateTime('2012-05-30 12:25'), new \DateTime('2012-05-29')),
            array(new \DateTime('2012-09-09'), new \DateTime('2012-09-09 23:59'), new \DateTime('2011-09-09')),
            array(new \DateTime('2013-02-02'), new \DateTime('2013-02-02'), new \DateTime('2013-02-03')),
        );
    }

    /**
     * @dataProvider providerContains
     */
    public function testContains($start, $contain, $notContain)
    {
        $day = new Day($start);

        $this->assertTrue($day->contains($contain));
        $this->assertFalse($day->contains($notContain));
    }

    public function testGetNext()
    {
        $day = new Day(new \DateTime('2012-01-01'));
        $this->assertEquals('2012-01-02', $day->getNext()->getBegin()->format('Y-m-d'));

        $day = new Day(new \DateTime('2012-01-31'));
        $this->assertEquals('2012-02-01', $day->getNext()->getBegin()->format('Y-m-d'));
    }

    public function testGetPrevious()
    {
        $day = new Day(new \DateTime('2012-01-01'));
        $this->assertEquals('2011-12-31', $day->getPrevious()->getBegin()->format('Y-m-d'));

        $day = new Day(new \DateTime('2012-01-31'));
        $this->assertEquals('2012-01-30', $day->getPrevious()->getBegin()->format('Y-m-d'));
    }

    public function testGetDatePeriod()
    {
        $day = new Day(new \DateTime('2012-01-31'));
        foreach ($day->getDatePeriod() as $dateTime) {
            $this->assertEquals('2012-01-31', $dateTime->format('Y-m-d'));
        }
    }

    public function testCurrentDay()
    {
        $currentDate = new \DateTime();
        $otherDate = clone $currentDate;
        $otherDate->add(new \DateInterval('P5D'));

        $currentDay = new Day(new \DateTime(date('Y-m-d')));
        $otherDay = $currentDay->getNext();

        $this->assertTrue($currentDay->contains($currentDate));
        $this->assertFalse($currentDay->contains($otherDate));
        $this->assertFalse($otherDay->contains($currentDate));
    }

    public function testToString()
    {
        $day = new Day(new \DateTime(date('Y-m-d')));
        $this->assertSame($day->getBegin()->format('l'), (string)$day);
    }

    public function testIsValid()
    {
        $this->assertSame(true, Day::isValid(new \DateTime('2013-05-01')));
        $this->assertSame(true, Day::isValid(new \DateTime('2013-05-01 00:00')));
        $this->assertSame(true, Day::isValid(new \DateTime(date('Y-m-d 00:00'))));
        $this->assertSame(false, Day::isValid(new \DateTime));
        $this->assertSame(false, Day::isValid(new \DateTime('2013-05-01 12:43')));
        $this->assertSame(false, Day::isValid(new \DateTime('2013-05-01 00:00:01')));
    }

    /**
     * @dataProvider includesDataProvider
     */
    public function testIncludes(\DateTime $begin, PeriodInterface $period, $strict, $result)
    {
        $day = new Day($begin);
        $this->assertSame($result, $day->includes($period, $strict));
    }

    public function testFormat()
    {
        $day = new Day(new \DateTime);

        $this->assertSame(date('Y-m-d'), $day->format('Y-m-d'));
    }

    public function testIsCurrent()
    {
        $currentDay = new Day(new \DateTime);
        $otherDay   = new Day(new \DateTime('1988-11-12'));

        $this->assertTrue($currentDay->isCurrent());
        $this->assertFalse($otherDay->isCurrent());
    }

    public function includesDataProvider()
    {
        return array(
            array(new \DateTime('2013-09-01'), new Year(new \DateTime('2013-01-01')), true, false),
            array(new \DateTime('2013-09-01'), new Year(new \DateTime('2013-01-01')), false, true),
            array(new \DateTime('2013-09-01'), new Day(new \DateTime('2013-09-01')), true, true),
        );
    }

    public function testIteration()
    {
        $start = new \DateTime('2012-01-15');
        $day = new Day($start);

        $i = 0;

        foreach ($day as $hourKey => $hour) {
            $this->assertTrue(is_int($hourKey) && $hourKey >= 0 && $hourKey < 24);
            $this->assertInstanceOf('CalendR\\Period\\Hour', $hour);
            $this->assertSame($start->format('Y-m-d H'), $hour->getBegin()->format('Y-m-d H'));
            $this->assertSame('00:00', $hour->getBegin()->format('i:s'));
            $start->add(new \DateInterval('PT1H'));
            $i++;
        }

        $this->assertEquals($i, 24);
    }
}


text:
---
layout: post
title: "Digest of <i>Seamless R and C++ Integration with Rcpp</i> (待修改)"
description: ""
category: R
tags: [Rcpp, Book]
---
{% include JB/setup %}

Rcpp 初体验。请结合 [Rcpp Hierarchy](/r/2015/07/17/rcpp-hierarchy) 做进一步的理解。本文待修改。

-----

## Chapter 1. A Gentle Introduction to Rcpp

第一章简单介绍了两种 Rcpp 写法,这里不追求原理,只展示下例子。

### 1.1 inline 写法

#### inline 原理之一:C++ function wrapper

假设我们有一个 C++ function:

```c
int fibonacci(const int x) {
	if (x == 0) return(0);
	if (x == 1) return(1);
	return (fibonacci(x - 1)) + fibonacci(x - 2);
}
```

R 的底层是 C,我们要把这个 C++ function 给 R 调用的话,需要写一个 wrapper。具体的原理这里不展示,你只要知道要有这个 wrapper 就好了:

```c
// SEXP means "pointer to S expression"

extern "C" SEXP fibWrapper(SEXP xs) {
	int x = Rcpp::as<int>(xs);
	int fib = fibonacci(x);
	return (Rcpp::wrap(fib));
}
```

- `Rcpp::as<int>(xs)` converts the incoming argument `xs` from `SEXP` to integer.
- `Rcpp::wrap(fib)` converts the integer result `fib` to the `SEXP` type.

#### inline 实例

注意这里 inline 不是指 C++ 的 inline,而是一个 R package。前面的 `SEXP` 是 R 的底层,是 C 代码;而 `inline::cxxfunction()` 是在 R 的环境里内嵌 C++ 代码,本质上还是 R 代码。

With `inline` package providing a complete wrapper around the compilation, linking, and loading steps, the programmer can concentrate on the actual code (in either one of the supported languages C, C++, or Fortran) and forget about the operating-system specific details of compilation, linking, and loading. A single entry point, the function `cxxfunction()` can be used to turn code supplied as a text variable into an executable function.

- 类似地还有一个 `cfunction()` 接口

```r
library(inline)

incltxt <- '
	int fibonacci(const int x) {
		if (x == 0) return(0);
		if (x == 1) return(1);
		return fibonacci(x - 1) + fibonacci(x - 2);
	}
'

fibRcpp <- cxxfunction(signature(xs="int"),
	plugin="Rcpp",
	incl=incltxt,
	body='
		int x = Rcpp::as<int>(xs);
		return Rcpp::wrap(fibonacci(x));
	'
)
```

这里 `incl` 就是 inline 的 C++ code,`body` 就是 C++ function wrapper。复杂一点的情况,`incl` 里可以定一个 class,然后 `body` 里 new 一个对象,然后调用对象的方法再 return 回去。

若想看后台生成的文件以及调用的过程,可以给 `cxxfunction()` 加一个参数 `verbose=TRUE`。这个设置在调试时也很有用。

### 1.2 Rcpp Attributes 写法

看起来比 inline 要来得简单。这里 Rcpp Attribute 可以理解为 java annotation,但是形式上它是一个注释:

```cpp
/***** fibonacci.cpp *****/

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
int fibonacci(const int x) {
	if (x < 2)
		return x;
	else
		return (fibonacci(x - 1)) + fibonacci(x - 2);
}
```

这里 `[[Rcpp::export]]` 就是一个 Rcpp Attribute。

R 调用起来也很方便:

```r
library(Rcpp)

sourceCpp("fibonacci.cpp")
fibonacci(20)
[1] 6765
```

## Chapter 2. Tools and Setup

### Only gcc compilers are supported on Windows platform

在 windows 系统上只能使用 gcc 编译器,因为 For example, how function names, and member function names inside classes, are represented is not standardized between compiler makers, and this generally prevents mixing of object code between different compilers.

As Rcpp is of course a C++ application, this last restriction applies and we need to stick with the compilers used to build R on the different platforms. 而 R 的 windows 版本是用 gcc 编译器编译的,所以我们自己写的 C++ 文件也要配套使用 gcc 编译器。

### inline 原理之二:.Call() 接口

我们把 C++ 编译好之后(书上的编译过程这里就不研究了),就可以通过 `.Call()` 接口配合 wrapper 来调用:

```r
dyn.load("fibonacci.so")
.Call("fibWrapper", 10)
[1] 55
```

- `dyn.load()` loads the shared library. It uses the full filename, including
	- the explicit platform-dependent extension which is .so on Unix,
	- .dll onWindows,
	- and .dylib on OS X

### Plugins of inline

We have seen the use of the options `plugin="Rcpp"` in the previous examples. Plugins provide a general mechanism for packages using Rcpp to supply additional information which may be needed to compile and link the particular package. 这里说的 additional information,may include additional header files and directories, as well as additional library names to link against as well as their locations.

像 RcppArmadillo, RcppEigen, RcppGSL 这些都是 plugins。

也可以自己手动写一个 plugin,具体参书上 P30。

### cppFunction() and evalCpp()

Rcpp 除了 `sourceCpp()` 外,还有

- `cppFunction()`: creates a function from a argument of text.
	- 步骤包括:
		1. It creates a temporary file.
		1. It creates a wrapper.
		1. It returns an R function which calls the wrapper.
	- 注意 `cxxfunction()` 是 `inline` 包的。
- `evalCpp()`: evaluates a C++ expression directly

```r
cpptxt <- '
	int fibonacci(const int x) {
		if (x < 2) return(x);
		return (fibonacci(x - 1)) + fibonacci(x - 2);
	}
'

fibCpp <- cppFunction(cpptxt) # compiles, load, links, ...
```

这种用法也可以使用 `inline` 的 plugin,比如:

```r
code <- 'C++ code goes here'

gslVolumes <- cppFunction(code, depends="RcppGSL")
```

## Chapter 3. Data Structures: Part One

### 3.1 The RObject Class

In Rcpp class hierarchy, although RObject is not directly user-facing, it provides the foundation upon which many important and frequently-used classes are built. 感觉就像 java 的 Object class。

- An instance of the RObject class encapsulates an R object.
	- Every R object itself is internally represented by a `SEXP`.
		- `SEXP` is a pointer to `SEXPREC`.
			- `SEXPREC` is S expression object.
			- One key aspect is that S expression objects are union types.
	- In fact, the `SEXP` is indeed the only data member of an RObject.
	- 另外还有一种类型 `VECSXP` is a vector of `SEXP`.
- The RObject effectively treats its underlying `SEXP` as a resource.
	- The constructor of the RObject class takes the necessary measures to guarantee that the underlying `SEXP` is protected from the R garbage collector,
	- and the destructor assumes the responsibility to withdraw that protection.

### 3.2 Rcpp::IntegerVector

`Rcpp::IntegerVector` 可以理解为 `vector<int>`,我们可以把 `c(1,2,3)` 或者 `1:10` 传给它,或者 return 一个 `IntegerVector` 回来给 R 用。

### 3.3 Rcpp::NumericVector

类似地,`Rcpp::NumericVector` 可以理解为 `vector<double>`。

#### shallow copy 和 deep copy 的问题

```r
src <- '
	Rcpp::NumericVector invec(vx);
	Rcpp::NumericVector outvec(vx);
	for (int i=0; i<invec.size(); i++) {
		outvec[i] = log(invec[i]);
	}
	return outvec;
'

fun <- cxxfunction(signature(vx="numeric"), src, plugin="Rcpp")
x <- seq(1.0, 3.0, by=1)

cbind(x, fun(x))
x
[1,] 0.0000000 0.0000000
[2,] 0.6931472 0.6931472
[3,] 1.0986123 1.0986123
```

上面这一段最大的问题是:你修改 `outvec` 的同时也改动了 `invec`。反映到 R 上就是你调用 `fun(x)` 的同时也修改了 `x`。这是因为 `NumericVector` 本质是 RObject,而 RObject 的本质是 `SEXP`,而 `SEXP` 又是 pointer to R expression,所以这里 `invec` 和 `outvec` 是两个不同的 pointer 指向了同一个 R vector。

正确的写法是:

```r
// method 1
Rcpp::NumericVector invec(vx);
Rcpp::NumericVector outvec = Rcpp::clone(vx);
...

// method 2
Rcpp::NumericVector invec(vx);
Rcpp::NumericVector outvec = log(invec); // This is Rcpp sugar
```

### 3.4 Other Vector Classes

- `LogicalVector`: `vector<bool>`,但是要注意可以有 NA
- `CharacterVector`: `vector<const char*>`,并不是 `vector<string>`

## Chapter 4. Data Structures: Part Two

### 4.1 Rcpp::Named

```r
someVec <- c(mean=1.23, dim=42.0, cnt=12)
someVec
mean dim cnt
1.23 42.00 12.00
```

等同于:

```r
src <- '
	Rcpp::NumericVector x =
	Rcpp::NumericVector::create(
		Rcpp::Named("mean") = 1.23,
		Rcpp::Named("dim") = 42,
		Rcpp::Named("cnt") = 12
	);
	return x;
'

fun <- cxxfunction(signature(), src, plugin="Rcpp")
fun()
mean dim cnt
1.23 42.00 12.00
```

而 `Rcpp::Named("mean")` 部分又可以简写为:

```r
	Rcpp::NumericVector x = NumericVector::create(
		_["mean"] = 1.23,
		_["dim"] = 42,
		_["cnt"] = 12
	);
```

### 4.2 Rcpp::GenericVector

对应 R 的 list。用法类似 4.1。

### 4.3 Rcpp::DataFrame

对应 R 的 `data.frame`。Internally, data frames are represented as lists.

### 4.4 Rcpp::Function

#### 4.4.1 Rcpp::Function 包装一个 R function

A `Function` object is needed whenever an R function—either supplied by the user or by accessing an R function—is employed.

```r
src <- '
	Function sort(x);
	return sort(y, Named("decreasing", true));
'

fun <- cxxfunction(signature(x="function", y="ANY"), src, plugin="Rcpp")
fun(sort, sample(1:5, 10, TRUE))
[1] 5 5 5 3 3 3 2 2 2 1
```

这里是把 R 的 `sort` 作为 `x` 传给了 `Function sort(x)`。然后注意调用 `Function sort` 的传参方法是 `Named("paraName", paraVal)`

Another useful point to note is that because the second argument `y` is never instantiated (即我们没有把 `y` 转成 Rcpp 的对象), we can pass different types of a suitable nature.

#### 4.4.2 Rcpp::Function 调用一个 R function

The `Function` class can also be used to access R functions directly. In the example below, we draw five random numbers from a t-distribution with three degrees of freedom. As we are accessing the random number generators, we need to ensure that it is in a proper state. The `RNGScope` class ensures this by initializing the random number generator by calling the `GetRNGState()` function from the class constructor, and by restoring the initial state via `PutRNGState()` via its destructor.

```r
src <- '
	RNGScope scp;
	Rcpp::Function rt("rt");
	return rt(5, 3);
'
fun <- cxxfunction(signature(), src, plugin="Rcpp")

set.seed(42)
fun()
[1] 2.339681 0.130995 -0.074028 -0.057701 -0.046482
```

注意这里我们是把 R function 的 name "rt" 传给了 `Rcpp::Function rt("rt");`。

### 4.5 Rcpp::Environment

Environment 主要负责 variable lookup、namespace 这类的职责。

#### 使用 Rcpp::Environment 定位到 R package 中的某个 functions

```r
Rcpp::Environment stats("package:stats");	// 用 environment 定位到 package
Rcpp::Function rnorm = stats["rnorm"];		// 定位到 function

return rnorm(10, Rcpp::Named("sd", 100.0));
```

#### 使用 Rcpp::Environment 访问 R global environment 的 variable、创建新的 variable

```r
Rcpp::Environment global = Rcpp::Environment::global_env();

std::vector<double> vx = global["x"];	// 访问 x

std::map<std::string,std::string> map;
map["foo"] = "oof";
map["bar"] = "rab";
global["y"] = map;						// 创建 y
```

### 4.6 The S4 Class

略

### 4.7 ReferenceClasses

略

### 4.8 The R Mathematics Library Functions

略

## Chapter 5. Using Rcpp in Your Package

This chapter provides an overview of how to use Rcpp when writing an R package. It shows how using the function `Rcpp.package.skeleton()` can create a complete and self-sufficient example of a package using Rcpp. All components of the directory tree created by `Rcpp.package.skeleton()` are discussed in detail.

This chapter complements the _Writing R Extensions_ manual which is the authoritative source on how to extend R in general.

略

## Chapter 6. Extending Rcpp

第五章的末尾有讲:`RcppArmadillo`, `RcppEigen`, `RcppBDT` and `RcppGSL` are packages using `Rcpp`. 同时它们也是 plugins。要进一步研究,可以从这几个包入手,它们都是很好的例子。

This chapter provides an overviewof the steps programmers should follow to extend Rcpp for use with their own classes and class libraries. The packages `RcppArmadillo`, `RcppEigen`, and `RcppGSL` provide working examples of how to extend `Rcpp` to work with, respectively, the `Armadillo` and `Eigen` C++ class libraries as well as the GNU Scientific Library.

The chapter ends with an illustration of how the `RcppBDT` package connects the date types of R with those of the Boost `Date_Time` library by extending Rcpp.

上面 abstract 说得很多,不过本章的实际内容其实是:假设我们有一个自定义的 C++ class `Foo`,我们如何实现 `Foo Rcpp::as(SEXP sexp);` 和 `SEXP Rcpp::wrap(const Foo& object);` 来实现 `Foo` 和 R data structure 的互相转换。

## Chapter 7. Modules

_7.1.1 Exposing Functions Using Rcpp_ 讲的是用 `Rcpp::as()`、`Rcpp::wrap()` 搞来搞去的很烦(不过其实是可以隐式调用的)。

_7.1.2 Exposing Classes Using Rcpp_ 这个更麻烦(不过遇到的时候可以拿书上的内容参考一下)。

于是我们就要推出 Modules,它的作用是消除这些麻烦。

Rcpp modules provide a convenient and easy-to-use way to expose C++ functions and classes to R, grouped together in a single entity.

An Rcpp module is created in a cpp file using the `RCPP_MODULE` macro, which then provides declarative code of what the module exposes to R.

简单说,我们可以在 C++ 中定义 module,然后把 functions 或者 classes 挂到这个 module 下面,然后把这个 module export 到 R,相当于创造了一个 R 对象,可以通过 `module$foo()`、`module$bar()` 这样调用 functions,或者通过 `module$baz` 来指向一个 C++ class,然后在 R 中调用它的构造器创建一个对象并调用 member function。

类比一下,module 就是 R's counterpart of C++ namespace。

## Chapter 8. Sugar

Rcpp sugar is based on expression templates and lazy evaluation techniques.

Put succinctly, the motivation of Rcpp sugar is to bring a subset of the high-level R syntax to C++. 比如我们可以直接在 C++ 里像 R 一样直接写 vector 级别的运算,或者在 C++ 里用 apply,而不用写个 for 来搞。

## Chapter 9. RInside

The `RInside` package permits direct use of R inside of a C++application. 比 Rcpp Sugar 更进一步,但并不是在 C++ 中全面支持 R 语法,而是在 C++ 中构建了一个 embedded R instance(由 `RInside` class 表示)(所以情形就变成了 "在 C++ 的 R instance 中跑 R 代码")。

## Chapter 10. RcppArmadillo

The `RcppArmadillo` package implements an easy-to-use interface to the C++ `Armadillo` library.

`Armadillo` is a C++ linear algebra library aiming towards a good balance between speed and ease of use. The syntax is deliberately similar to Matlab. Integer, floating point and complex numbers are supported, as well as a subset of trigonometric and statistics functions.

## Chapter 11. RcppGSL

The `RcppGSL` package provides an easy-to-use interface between data structures from the GNU Scientific Library, or GSL for short, and R by building on facilities provided in the Rcpp package.

## Chapter 12. RcppEigen

The `RcppEigen` package provides an interface to the `Eigen` library.

`Eigen` is a modern C++ library for linear algebra, similar in scope as `Armadillo`, but with an even more fine-grained application programming interface (API).


text:
package org.apache.qpid.proton.codec.messaging;

import java.util.List;
import org.apache.qpid.proton.amqp.Symbol;
import org.apache.qpid.proton.amqp.UnsignedLong;
import org.apache.qpid.proton.amqp.messaging.AmqpSequence;
import org.apache.qpid.proton.codec.AbstractDescribedType;
import org.apache.qpid.proton.codec.Decoder;
import org.apache.qpid.proton.codec.DescribedTypeConstructor;
import org.apache.qpid.proton.codec.EncoderImpl;

public class AmqpSequenceType extends AbstractDescribedType<AmqpSequence,List> implements DescribedTypeConstructor<AmqpSequence>
{
    private static final Object[] DESCRIPTORS =
    {
        UnsignedLong.valueOf(0x0000000000000076L), Symbol.valueOf("amqp:amqp-sequence:list"),
    };

    private static final UnsignedLong DESCRIPTOR = UnsignedLong.valueOf(0x0000000000000076L);

    AmqpSequenceType(EncoderImpl encoder)
    {
        super(encoder);
    }

    public UnsignedLong getDescriptor()
    {
        return DESCRIPTOR;
    }

    @Override
    protected List wrap(AmqpSequence val)
    {
        return val.getValue();
    }

    public AmqpSequence newInstance(Object described)
    {
        return new AmqpSequence( (List) described );
    }

    public Class<AmqpSequence> getTypeClass()
    {
        return AmqpSequence.class;
    }

    public static void register(Decoder decoder, EncoderImpl encoder)
    {
        AmqpSequenceType type = new AmqpSequenceType(encoder);
        for(Object descriptor : DESCRIPTORS)
        {
            decoder.register(descriptor, type);
        }
        encoder.register(type);
    }
}


text:
package radlab.rain.agent;

import java.util.Random;

import org.apache.log4j.Logger;

import radlab.rain.UnexpectedDeathHandler;
import radlab.rain.load.LoadDefinition;
import radlab.rain.operation.Generator;
import radlab.rain.operation.IOperation;
import radlab.rain.operation.OperationExecution;
import radlab.rain.scoreboard.IScoreboard;

/**
 * Provides the main loop of the agent thread.
 */
public class AgentPOL extends Agent {
	private static Logger logger = Logger.getLogger(AgentPOL.class);

	// Scoreboard reference
	protected IScoreboard scoreboard;

	// The generator used to create operations for this thread
	private Generator generator;

	// The probability of using open loop vs. closed loop
	// by default all operations are synchronous
	private double openLoopProbability = -1;

	// The random number generator used to decide which loop to use
	private Random random = new Random();

	// Interrupted flag
	private boolean interrupted = false;

	// Ended flag
	private boolean ended = false;

	public AgentPOL(long targetId, long id) {
		super(targetId, id);
		Thread.setDefaultUncaughtExceptionHandler(new UnexpectedDeathHandler());
	}

	/**
	 * Decides whether this thread is active or not. The number of threads is equal to the maximum number of generators.
	 * The actual number of threads varies over time. This is achieved by blocking some threads. If a thread is blocked
	 * is decided by this function.
	 */
	private boolean isActive() {
		LoadDefinition loadProfile = loadManager.getCurrentLoadProfile();
		return (id < loadProfile.getNumberOfUsers());
	}

	public void setInterrupt() {
		interrupted = true;
	}

	@Override
	public void dispose() {
		if (ended) {
			setInterrupt();
			this.generator.dispose();
		} else {
			logger.error("Cannot dispose agent that is running target" + targetId);
		}
	}

	public boolean joinAgent(long wait) throws InterruptedException {
		join(wait);
		return ended;
	}

	private void triggerNextOperation(int lastOperationIndex) throws InterruptedException {
		threadState = ThreadStates.Active;

		// Generate next operation using the attached generator
		IOperation nextOperation = generator.nextRequest(lastOperationIndex);

		// Execute operation
		if (nextOperation != null) {
			// Set operation references
			nextOperation.setLoadDefinition(loadManager.getCurrentLoadProfile());

			// Prepare the operation
			nextOperation.prepare();

			// Update last operation index.
			lastOperationIndex = nextOperation.getOperationIndex();

			// EXECUTE OPERATION
			// Decide whether to do things open or closed (throw a coin)
			double randomDouble = random.nextDouble();
			if (randomDouble <= openLoopProbability)
				doAsyncOperation(nextOperation);
			else
				doSyncOperation(nextOperation);
		}
	}

	/**
	 * Load generator loop. Runs the generator for each cycle and executes the returned operation.
	 */
	public void run() {
		try {
			logger.debug("New agent thread " + super.id);

			try {
				// Sleep until its time to start
				sleepUntil(timing.start);

				// Last executed operation (required to run markov chains)
				int lastOperationIndex = -1;

				// Check if benchmark is still running
				while (System.currentTimeMillis() <= timing.endSteadyState && !interrupted) {
					// If generator is not active
					if (!isActive()) {
						threadState = ThreadStates.Inactive;
						// Sleep for 1 second and check active state again
						Thread.sleep(1000);
					} else { // Generator is active

						// IMPORTANT: Next operation is triggered here
						try {
							triggerNextOperation(lastOperationIndex);
						} catch (Exception e) {
							logger.warn("Exception while triggering next operation", e);
							continue;
						}
					}
				}

				logger.debug("Agent ended - interrupted: " + interrupted);

			} catch (InterruptedException ie) {
				logger.error("Load generation thread interrupted exiting!");
			} catch (Exception e) {
				logger.error("Load generation thread died by exception! Reason: " + e.toString());
				e.printStackTrace();
			}
		} finally {
			ended = true;
		}
	}

	/**
	 * Runs the provided operation asynchronously and sleeps this thread on the cycle time.
	 */
	private void doAsyncOperation(IOperation operation) throws InterruptedException {
		// Calculate timings
		long cycleTime = generator.getCycleTime();
		long now = System.currentTimeMillis();

		// Wait after operation execution
		cycleTime = waitUntil(now, cycleTime);

		// Set async flag
		operation.setAsync(true);

		// Trigger operation
		doOperation(operation);

		// Save the cycle time - if we're in the steady state
		scoreboard.dropOffWaitTime(now, operation.getOperationName(), cycleTime);
	}

	private final class DropoffHandler implements Runnable {

		private final IOperation wrapped;

		DropoffHandler(IOperation wrapped) {
			this.wrapped = wrapped;
		}

		@Override
		public void run() {
			OperationExecution result = wrapped.run();
			scoreboard.dropOffOperation(result);
		}
	}

	@Override
	protected void submitAsyncOperation(IOperation operation) {
		DropoffHandler handler = new DropoffHandler(operation);
		executorService.submit(handler);
	}

	@Override
	protected void runSyncOperation(IOperation operation) {
		OperationExecution result = operation.run();
		scoreboard.dropOffOperation(result);
	}

	/**
	 * Runs the provided operation synchronously and sleeps this thread on the think time.
	 */
	private void doSyncOperation(IOperation operation) throws InterruptedException {
		// Configure operation
		operation.setAsync(false);

		// Trigger operation
		doOperation(operation);

		// Calculate timings
		long thinkTime = generator.getThinkTime();
		long now = System.currentTimeMillis();

		// Wait after operation execution
		thinkTime = waitUntil(now, thinkTime);

		// Save the think time
		scoreboard.dropOffWaitTime(now, operation.getOperationName(), thinkTime);
	}

	private long waitUntil(long now, long deltaTime) throws InterruptedException {
		long wakeUpTime = now + deltaTime;
		if (wakeUpTime > timing.endRun) {
			if (now < timing.start) {
				deltaTime = timing.startSteadyState - now;
				sleepUntil(timing.startSteadyState);
			} else {
				deltaTime = timing.endRun - now;
				sleepUntil(timing.endRun);
			}
		} else {
			sleepUntil(wakeUpTime);
		}

		return deltaTime;
	}

	private void sleepUntil(long time) throws InterruptedException {
		long preRunSleep = time - System.currentTimeMillis();
		if (preRunSleep > 0)
			Thread.sleep(preRunSleep);
	}

	public void setOpenLoopProbability(double openLoopProbability) {
		this.openLoopProbability = openLoopProbability;
	}

	@Override
	public void setScoreboard(IScoreboard scoreboard) {
		this.scoreboard = scoreboard;
	}

	@Override
	public void setGenerator(Generator generator) {
		this.generator = generator;
	}
}


text:
require 'rails_helper'

describe MongoidCart::CartItem do

  describe 'relations' do

    before(:each) do
      @cart_item = MongoidCart::CartItem.new
    end

    it 'belongs_to :product' do
      is_expected.to belong_to(:product).of_type(Product).as_inverse_of(:cart_item)
    end

    it 'belongs_to :another_product' do
      is_expected.to belong_to(:another_product).of_type(AnotherProduct).as_inverse_of(:cart_item)
    end

    it 'belongs_to cart' do
      is_expected.to belong_to(:cart).of_type(MongoidCart::Cart).as_inverse_of(:cart_items)
    end

  end

  describe 'methods' do

    context 'sum' do

      specify 'amount by net_price with integer' do
        cart_item = create :cart_item, :with_product,{ net_price: 10.0, amount: 42}

        expect(cart_item.net_sum).to eql 420.0
      end
    end

    context 'related_product with product' do

      before(:each) do
        @cart_item = create :cart_item, :with_product
        @product = create :product
        @another_product = create :another_product
      end

      it 'responds with product' do
        cart = @cart_item.cart
        cart.add @product

        expect(@cart_item.product).to be_an_instance_of Product
      end

      it 'related_product responds with Product' do
        @cart_item.cart.add @product

        expect(@cart_item.related_product).to be_an_instance_of Product
      end
    end

    context 'related_product with another_product' do

      before :each do
        @cart_item = create :cart_item, :with_another_product
        @another_product = create :another_product
      end

      it 'related_product responds with AnotherProduct' do
        @cart_item.cart.add @another_product

        expect(@cart_item.related_product).to be_an_instance_of AnotherProduct
      end

      it 'responds with another_product' do
        cart = @cart_item.cart
        cart.add @another_product

        expect(@cart_item.another_product).to be_an_instance_of AnotherProduct
      end
    end
  end

  describe 'init' do

    specify 'with given Product' do
      product = FactoryGirl.create :product
      cart_item = MongoidCart::CartItem.new(product.to_cart_item_params)
      cart_item.amount = 1

      expect(cart_item.save!).to be_truthy
    end

    specify 'with given AnotherProduct' do
      product = FactoryGirl.create :another_product
      cart_item = MongoidCart::CartItem.new(product.to_cart_item_params)
      cart_item.amount = 1
      expect(cart_item.save).to be_truthy
    end
  end
end


text:
FROM python:3.8

ENV APP_ROOT /dojopuzzles

RUN mkdir ${APP_ROOT}
WORKDIR ${APP_ROOT}

EXPOSE 8100

COPY start_app.sh requirements ${APP_ROOT}/
RUN pip install -r ${APP_ROOT}/requirements

ADD dojopuzzles/ ${APP_ROOT}

CMD ["gunicorn", "--bind", "0.0.0.0:8100", "dojopuzzles.wsgi"]


text:
package org.geometerplus.android.fbreader.preferences;

import android.content.Context;

import org.geometerplus.zlibrary.core.options.ZLBooleanOption;
import org.geometerplus.zlibrary.core.resources.ZLResource;

class ZLBooleanPreference extends ZLCheckBoxPreference {
	private final ZLBooleanOption myOption;

	ZLBooleanPreference(Context context, ZLBooleanOption option, ZLResource rootResource, String resourceKey) {
		super(context, rootResource, resourceKey);
		myOption = option;
		setChecked(option.getValue());
	}

	@Override
	protected void onClick() {
		super.onClick();
		myOption.setValue(isChecked());
	}
}


text:
package net.sourceforge.plantuml.svek.image;

import net.sourceforge.plantuml.awt.geom.XPoint2D;

public class YTransformer {

	private final double alpha;

	public YTransformer(double alpha) {
		this.alpha = alpha;
	}

	public XPoint2D getPoint2D(XPoint2D pt) {
		return new XPoint2D(pt.getX(), pt.getY() * alpha);
	}

	public XPoint2D getReversePoint2D(XPoint2D pt) {
		return new XPoint2D(pt.getX(), pt.getY() / alpha);
	}

	public double getAlpha() {
		return alpha;
	}

}


text:
{% extends "base.html" %}
{% block description %}文章存档{%endblock%}
{% block title %}文章存档{% endblock %}
{% block main_content %}

    {% for blog in blogs %}

        {{blog.publish_time|date:'Y-m-d' }}
        {{blog.title}}

    {% endfor %}

{% endblock %}

{% block panel %} {%include "widget/panel.html"%}{%endblock%}


text:
namespace SSDK {
	struct model_t;

	class IClientEntity { // 0x00 -> IClientUnknown, 0x04 IClientRenderable, 0x08 IClientNetworkable, ..
	public:
		const CBaseHandle& GetRefEHandle() {
			typedef const CBaseHandle&(__thiscall *OrigFn)(void*);
			return CallVFunction<OrigFn>(this, 2)(this);
		}

		ICollideable* GetCollideable() {
			typedef ICollideable*(__thiscall *OrigFn)(void*);
			return CallVFunction<OrigFn>(this, 3)(this);
		}

		const model_t* GetModel() {
			void *pRenderable = (void*)(this + 0x4);
			typedef const model_t*(__thiscall *OrigFn)(void*);
			return CallVFunction<OrigFn>(pRenderable, 8)(pRenderable);
		}

		bool SetupBones(matrix3x4_t *pBoneToWorldOut, int nMaxBones, int boneMask, float currentTime) {
			void *pRenderable = (void*)(this + 0x4);
			typedef bool(__thiscall *OrigFn)(void*, matrix3x4_t*, int, int, float);
			return CallVFunction<OrigFn>(pRenderable, 13)(pRenderable, pBoneToWorldOut, nMaxBones, boneMask, currentTime);
		}

		ClientClass* GetClientClass() {
			void *pNetworked = (void*)(this + 0x8);
			typedef ClientClass*(__thiscall *OrigFn)(void*);
			return CallVFunction<OrigFn>(pNetworked, 2)(pNetworked);
		}

		bool IsDormant() {
			void *pNetworked = (void*)(this + 0x8);
			typedef bool(__thiscall *OrigFn)(void*);
			return CallVFunction<OrigFn>(pNetworked, 9)(pNetworked);
		}

		int EntIndex() {
			void *pNetworked = (void*)(this + 0x8);
			typedef int(__thiscall *OrigFn)(void*);
			return CallVFunction<OrigFn>(pNetworked, 10)(pNetworked);
		}
	};
}


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

<TITLE>
ActivityImpl
</TITLE>

<META NAME="date" CONTENT="2011-06-10">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.google.code.linkedinapi.schema.xpp

Class ActivityImpl

java.lang.Object
  com.google.code.linkedinapi.schema.xpp.BaseSchemaEntity
      com.google.code.linkedinapi.schema.xpp.ActivityImpl

All Implemented Interfaces:
Activity, SchemaEntity, java.io.Serializable

public class ActivityImpl
extends BaseSchemaEntity
implements Activity

See Also:
Serialized Form

Constructor Summary

ActivityImpl()

Method Summary

 java.lang.String
getAppId()

          Gets the value of the appId property.

 java.lang.String
getBody()

          Gets the value of the body property.

 NetworkUpdateContentType
getContentType()

          Gets the value of the contentType property.

 java.lang.String
getLocale()

          Gets the value of the locale property.

 java.lang.Long
getTimestamp()

          Gets the value of the timestamp property.

 void
init(org.xmlpull.v1.XmlPullParser parser)

          Inits the.

 void
setAppId(java.lang.String value)

          Sets the value of the appId property.

 void
setBody(java.lang.String value)

          Sets the value of the body property.

 void
setContentType(NetworkUpdateContentType value)

          Sets the value of the contentType property.

 void
setLocale(java.lang.String value)

          Sets the value of the locale property.

 void
setTimestamp(java.lang.Long value)

          Sets the value of the timestamp property.

 void
toXml(org.xmlpull.v1.XmlSerializer serializer)

          To xml.

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

ActivityImpl

public ActivityImpl()

Method Detail

getTimestamp

public java.lang.Long getTimestamp()

Description copied from interface: Activity

Gets the value of the timestamp property.

Specified by:
getTimestamp in interface Activity

Returns:
possible object is
     String

setTimestamp

public void setTimestamp(java.lang.Long value)

Description copied from interface: Activity

Sets the value of the timestamp property.

Specified by:
setTimestamp in interface Activity

Parameters:
value - allowed object is
     String

getContentType

public NetworkUpdateContentType getContentType()

Description copied from interface: Activity

Gets the value of the contentType property.

Specified by:
getContentType in interface Activity

Returns:
possible object is
     NetworkUpdateContentType

setContentType

public void setContentType(NetworkUpdateContentType value)

Description copied from interface: Activity

Sets the value of the contentType property.

Specified by:
setContentType in interface Activity

Parameters:
value - allowed object is
     NetworkUpdateContentType

getBody

public java.lang.String getBody()

Description copied from interface: Activity

Gets the value of the body property.

Specified by:
getBody in interface Activity

Returns:
possible object is
     String

setBody

public void setBody(java.lang.String value)

Description copied from interface: Activity

Sets the value of the body property.

Specified by:
setBody in interface Activity

Parameters:
value - allowed object is
     String

getLocale

public java.lang.String getLocale()

Description copied from interface: Activity

Gets the value of the locale property.

Specified by:
getLocale in interface Activity

Returns:
possible object is
     String

setLocale

public void setLocale(java.lang.String value)

Description copied from interface: Activity

Sets the value of the locale property.

Specified by:
setLocale in interface Activity

Parameters:
value - allowed object is
     String

getAppId

public java.lang.String getAppId()

Description copied from interface: Activity

Gets the value of the appId property.

Specified by:
getAppId in interface Activity

Returns:
possible object is
     String

setAppId

public void setAppId(java.lang.String value)

Description copied from interface: Activity

Sets the value of the appId property.

Specified by:
setAppId in interface Activity

Parameters:
value - allowed object is
     String

init

public void init(org.xmlpull.v1.XmlPullParser parser)
          throws java.io.IOException,
                 org.xmlpull.v1.XmlPullParserException

Description copied from class: BaseSchemaEntity

Inits the.

Specified by:
init in class BaseSchemaEntity

Parameters:
parser - the element

Throws:

java.io.IOException - TODO

org.xmlpull.v1.XmlPullParserException - TODO

toXml

public void toXml(org.xmlpull.v1.XmlSerializer serializer)
           throws java.io.IOException

Description copied from class: BaseSchemaEntity

To xml.

Specified by:
toXml in class BaseSchemaEntity

Parameters:
serializer - the document

Throws:

java.io.IOException - TODO

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
import { DataEntity } from '@terascope/utils';
import { PostProcessConfig } from '../../../interfaces';
import TransformOpBase from './base';

export default class HexDecode extends TransformOpBase {
    constructor(config: PostProcessConfig) {
        super(config);
    }

    decode(data: string) {
        return Buffer.from(data, 'hex').toString('utf8');
    }

    run(record: DataEntity): DataEntity | null {
        return this.execute(record, this.decode);
    }
}


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

import { NgKeysPipeModule } from './keys.pipe';
import { NgToArrayPipeModule } from './to-array.pipe';
import { NgDefaultsPipeModule } from './defaults.pipe';

@NgModule({
  imports: [NgKeysPipeModule, NgToArrayPipeModule, NgDefaultsPipeModule],
})
export class NgObjectPipesModule {}


text:
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
from builtins import range

import os
import numpy as np
np.random.seed(123)
from sklearn.ensemble import RandomForestRegressor
from sklearn import svm

import tensorflow as tf
tf.set_random_seed(123)
import deepchem as dc

BATCH_SIZE = 128
MAX_EPOCH = 40
LR = 1e-3
LMBDA = 1e-4

def retrieve_datasets():
  os.system(
      'wget -c %s' %
      'https://s3-us-west-1.amazonaws.com/deep-crystal-california/az_logd.csv')
  os.system(
      'wget -c %s' %
      'https://s3-us-west-1.amazonaws.com/deep-crystal-california/az_hppb.csv')
  os.system(
      'wget -c %s' %
      'https://s3-us-west-1.amazonaws.com/deep-crystal-california/az_clearance.csv'
  )

def load_dataset(dataset_file, featurizer='ECFP', split='index'):
  tasks = ['exp']

  if featurizer == 'ECFP':
    featurizer = dc.feat.CircularFingerprint(size=4096)
  elif featurizer == 'GraphConv':
    featurizer = dc.feat.ConvMolFeaturizer()

  loader = dc.data.CSVLoader(
      tasks=tasks, smiles_field="smiles", featurizer=featurizer)
  dataset = loader.featurize(dataset_file, shard_size=8192)

  transformers = [
      dc.trans.NormalizationTransformer(transform_y=True, dataset=dataset)
  ]
  for transformer in transformers:
    dataset = transformer.transform(dataset)

  splitters = {
      'index': dc.splits.IndexSplitter(),
      'random': dc.splits.RandomSplitter(),
      'scaffold': dc.splits.ScaffoldSplitter()
  }
  splitter = splitters[split]
  train, valid, test = splitter.train_valid_test_split(dataset)
  return tasks, (train, valid, test), transformers

def experiment(dataset_file, method='GraphConv', split='scaffold'):
  featurizer = 'ECFP'
  if method == 'GraphConv':
    featurizer = 'GraphConv'
  tasks, datasets, transformers = load_dataset(
      dataset_file, featurizer=featurizer, split=split)
  train, val, test = datasets

  model = None
  if method == 'GraphConv':
    n_feat = 75
    graph_model = dc.nn.SequentialGraph(n_feat)
    graph_model.add(dc.nn.GraphConv(128, n_feat, activation='relu'))
    graph_model.add(dc.nn.BatchNormalization(epsilon=1e-5, mode=1))
    graph_model.add(dc.nn.GraphPool())

    graph_model.add(dc.nn.GraphConv(128, 128, activation='relu'))
    graph_model.add(dc.nn.BatchNormalization(epsilon=1e-5, mode=1))
    graph_model.add(dc.nn.GraphPool())

    graph_model.add(dc.nn.Dense(256, 128, activation='relu'))
    graph_model.add(dc.nn.BatchNormalization(epsilon=1e-5, mode=1))
    graph_model.add(dc.nn.GraphGather(BATCH_SIZE, activation="tanh"))

    model = dc.models.MultitaskGraphRegressor(
        graph_model,
        len(tasks),
        n_feat,
        batch_size=BATCH_SIZE,
        learning_rate=LR,
        learning_rate_decay_time=1000,
        optimizer_type="adam",
        beta1=.9,
        beta2=.999)
  elif method == 'PDNN':
    model = dc.models.TensorflowMultiTaskRegressor(
        len(tasks),
        train.get_data_shape()[0],
        layer_sizes=[384, 196],
        dropouts=[.25, .25],
        weight_init_stddevs=[.02, .02],
        bias_init_consts=[.1, .1],
        learning_rate=LR,
        penalty=LMBDA,
        penalty_type="l2",
        optimizer="adam",
        batch_size=BATCH_SIZE,
        seed=123,
        verbosity="high")
  elif method == 'RF':

    def model_builder_rf(model_dir):
      sklearn_model = RandomForestRegressor(n_estimators=100)
      return dc.models.SklearnModel(sklearn_model, model_dir)

    model = dc.models.SingletaskToMultitask(tasks, model_builder_rf)
  elif method == 'SVR':

    def model_builder_svr(model_dir):
      sklearn_model = svm.SVR(kernel='linear')
      return dc.models.SklearnModel(sklearn_model, model_dir)

    model = dc.models.SingletaskToMultitask(tasks, model_builder_svr)

  return model, train, val, test, transformers

#======================================================================
# Run Benchmarks {GC-DNN, P-DNN, SVR, RF}

retrieve_datasets()

MODEL = 'GraphConv'
SPLIT = 'scaffold'
DATASET = 'az_hppb.csv'

metric = dc.metrics.Metric(dc.metrics.pearson_r2_score, np.mean)
model, train, val, test, transformers = experiment(
    DATASET, method=MODEL, split=SPLIT)
if MODEL == 'GraphConv':
  best_val_score = 0.0
  train_score = 0.0
  for l in range(0, MAX_EPOCH):
    model.fit(train, nb_epoch=1)
    latest_train_score = model.evaluate(train, [metric],
                                        transformers)['mean-pearson_r2_score']
    latest_val_score = model.evaluate(val, [metric],
                                      transformers)['mean-pearson_r2_score']
    if latest_val_score > best_val_score:
      best_val_score = latest_val_score
      train_score = latest_train_score
  print((MODEL, SPLIT, DATASET, train_score, best_val_score))
elif MODEL == 'PDNN':
  model.fit(train, nb_epoch=25)
  train_score = model.evaluate(train, [metric],
                               transformers)['mean-pearson_r2_score']
  val_score = model.evaluate(val, [metric],
                             transformers)['mean-pearson_r2_score']
  print((MODEL, SPLIT, DATASET, train_score, val_score))
  # we cant re-open the closed session...
else:
  model.fit(train)
  train_score = model.evaluate(train, [metric],
                               transformers)['mean-pearson_r2_score']
  val_score = model.evaluate(val, [metric],
                             transformers)['mean-pearson_r2_score']
  print((MODEL, SPLIT, DATASET, train_score, val_score))


text:
using System.Web.Mvc;

namespace TwitterCards.App.Home
{
    public class HomeController : Controller
    {
		[AllowAnonymous]
        public ActionResult Index()
        {
            return View();
        }

		public ActionResult Demo()
		{
			return View();
		}
    }
}


text:
\hypertarget{log__format__common_8h}{\section{log\-\_\-format\-\_\-common.\-h File Reference}
\label{log__format__common_8h}\index{log\-\_\-format\-\_\-common.\-h@{log\-\_\-format\-\_\-common.\-h}}
}

common definitions of log\-::format.

{\ttfamily \#include $<$hryky/intrusive\-\_\-ptr.\-h$>$}\\*
This graph shows which files directly or indirectly include this file\-:\nopagebreak
\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[width=350pt]{log__format__common_8h__dep__incl}
\end{center}
\end{figure}
\subsection*{Namespaces}
\begin{DoxyCompactItemize}
\item
namespace \hyperlink{namespacehryky}{hryky}
\begin{DoxyCompactList}\small\item\em the root of all namespaces in hryky-\/codebase. \end{DoxyCompactList}\item
namespace \hyperlink{namespacehryky_1_1log}{hryky\-::log}
\begin{DoxyCompactList}\small\item\em modules for logging progress. \end{DoxyCompactList}\item
namespace \hyperlink{namespacehryky_1_1log_1_1format}{hryky\-::log\-::format}
\begin{DoxyCompactList}\small\item\em modules to format the output string. \end{DoxyCompactList}\end{DoxyCompactItemize}
\subsection*{Typedefs}
\begin{DoxyCompactItemize}
\item
\hypertarget{namespacehryky_1_1log_ad50448c3f934f1eacd5c1bcffe8111e1}{typedef Intrusive\-Ptr\\*
$<$ format\-::\-Base $>$ \hyperlink{namespacehryky_1_1log_ad50448c3f934f1eacd5c1bcffe8111e1}{hryky\-::log\-::format\-\_\-type}}\label{namespacehryky_1_1log_ad50448c3f934f1eacd5c1bcffe8111e1}

\begin{DoxyCompactList}\small\item\em type of the interface to format each parameter \end{DoxyCompactList}\item
\hypertarget{namespacehryky_1_1log_1_1format_ab7408d1e2ed2d648dbf9bba69eb74288}{typedef string\-\_\-type \hyperlink{namespacehryky_1_1log_1_1format_ab7408d1e2ed2d648dbf9bba69eb74288}{hryky\-::log\-::format\-::name\-\_\-type}}\label{namespacehryky_1_1log_1_1format_ab7408d1e2ed2d648dbf9bba69eb74288}

\begin{DoxyCompactList}\small\item\em name of each format element \end{DoxyCompactList}\item
\hypertarget{namespacehryky_1_1log_1_1format_afb3132c335cc06bc8d0004fab99eb5e4}{typedef std\-::string \hyperlink{namespacehryky_1_1log_1_1format_afb3132c335cc06bc8d0004fab99eb5e4}{hryky\-::log\-::format\-::string\-\_\-type}}\label{namespacehryky_1_1log_1_1format_afb3132c335cc06bc8d0004fab99eb5e4}

\begin{DoxyCompactList}\small\item\em type of string \end{DoxyCompactList}\end{DoxyCompactItemize}
\subsection*{Functions}
\begin{DoxyCompactItemize}
\item
{\footnotesize template$<$typename Value\-T $>$ }\\format\-\_\-type \hyperlink{namespacehryky_1_1log_1_1format_ae8ca636c4b89fe300287aca4f870f2ef}{hryky\-::log\-::format\-::make\-\_\-format} (format\-::name\-\_\-type const \&name, Value\-T const \&value)
\begin{DoxyCompactList}\small\item\em creates the derived instance of \hyperlink{classhryky_1_1log_1_1format_1_1_base}{log\-::format\-::\-Base} corresponding to parameter. \end{DoxyCompactList}\end{DoxyCompactItemize}

\subsection{Detailed Description}
common definitions of log\-::format. \begin{DoxySince}{Since}
2011-\/12-\/29\-T21\-:05\-:02+0900
\end{DoxySince}
\begin{DoxyAuthor}{Author}
H\-R\-Y\-K\-Y
\end{DoxyAuthor}
\begin{DoxyVersion}{Version}

\end{DoxyVersion}
\begin{DoxyParagraph}{Id\-:}
\hyperlink{log__format__common_8h}{log\-\_\-format\-\_\-common.\-h} 87 2012-\/08-\/28 15\-:25\-:35\-Z \href{mailto:hryky.private@gmail.com}{\tt hryky.\-private@gmail.\-com}
\end{DoxyParagraph}


text:
import {assertFirstCreatePass} from '../assert';
import {attachPatchData} from '../context_discovery';
import {registerPostOrderHooks} from '../hooks';
import {ComponentTemplate} from '../interfaces/definition';
import {LocalRefExtractor, TAttributes, TContainerNode, TNodeType, TViewNode} from '../interfaces/node';
import {isDirectiveHost} from '../interfaces/type_checks';
import {HEADER_OFFSET, LView, RENDERER, T_HOST, TView, TViewType} from '../interfaces/view';
import {appendChild} from '../node_manipulation';
import {getLView, getTView, setPreviousOrParentTNode} from '../state';
import {getConstant} from '../util/view_utils';

import {addToViewTree, createDirectivesInstances, createLContainer, createTNode, createTView, getOrCreateTNode, resolveDirectives, saveResolvedLocalsInData} from './shared';

function templateFirstCreatePass(
    index: number, tView: TView, lView: LView, templateFn: ComponentTemplate<any>|null,
    decls: number, vars: number, tagName?: string|null, attrsIndex?: number|null,
    localRefsIndex?: number|null): TContainerNode {
  ngDevMode && assertFirstCreatePass(tView);
  ngDevMode && ngDevMode.firstCreatePass++;
  const tViewConsts = tView.consts;
  // TODO(pk): refactor getOrCreateTNode to have the "create" only version
  const tNode = getOrCreateTNode(
      tView, lView[T_HOST], index, TNodeType.Container, tagName || null,
      getConstant<TAttributes>(tViewConsts, attrsIndex));

  resolveDirectives(tView, lView, tNode, getConstant<string[]>(tViewConsts, localRefsIndex));
  registerPostOrderHooks(tView, tNode);

  const embeddedTView = tNode.tViews = createTView(
      TViewType.Embedded, -1, templateFn, decls, vars, tView.directiveRegistry, tView.pipeRegistry,
      null, tView.schemas, tViewConsts);
  const embeddedTViewNode = createTNode(tView, null, TNodeType.View, -1, null, null) as TViewNode;
  embeddedTViewNode.injectorIndex = tNode.injectorIndex;
  embeddedTView.node = embeddedTViewNode;

  if (tView.queries !== null) {
    tView.queries.template(tView, tNode);
    embeddedTView.queries = tView.queries.embeddedTView(tNode);
  }

  return tNode;
}

/**
 * Creates an LContainer for an ng-template (dynamically-inserted view), e.g.
 *
 * <ng-template #foo>
 *

 * </ng-template>
 *
 * @param index The index of the container in the data array
 * @param templateFn Inline template
 * @param decls The number of nodes, local refs, and pipes for this template
 * @param vars The number of bindings for this template
 * @param tagName The name of the container element, if applicable
 * @param attrsIndex Index of template attributes in the `consts` array.
 * @param localRefs Index of the local references in the `consts` array.
 * @param localRefExtractor A function which extracts local-refs values from the template.
 *        Defaults to the current element associated with the local-ref.
 *
 * @codeGenApi
 */
export function ɵɵtemplate(
    index: number, templateFn: ComponentTemplate<any>|null, decls: number, vars: number,
    tagName?: string|null, attrsIndex?: number|null, localRefsIndex?: number|null,
    localRefExtractor?: LocalRefExtractor) {
  const lView = getLView();
  const tView = getTView();
  const adjustedIndex = index + HEADER_OFFSET;

  const tNode = tView.firstCreatePass ?
      templateFirstCreatePass(
          index, tView, lView, templateFn, decls, vars, tagName, attrsIndex, localRefsIndex) :
      tView.data[adjustedIndex] as TContainerNode;
  setPreviousOrParentTNode(tNode, false);

  const comment = lView[RENDERER].createComment(ngDevMode ? 'container' : '');
  appendChild(tView, lView, comment, tNode);
  attachPatchData(comment, lView);

  addToViewTree(lView, lView[adjustedIndex] = createLContainer(comment, lView, comment, tNode));

  if (isDirectiveHost(tNode)) {
    createDirectivesInstances(tView, lView, tNode);
  }

  if (localRefsIndex != null) {
    saveResolvedLocalsInData(lView, tNode, localRefExtractor);
  }
}


text:
require "spec_helper"

describe Souse::GherkinCollection do
  let(:test_path) { double("path") }
  let(:parser) { Souse::GherkinCollection.new test_path }

  describe "#parse_path" do
    context "with a file path" do
      before { expect(test_path).to receive(:end_with?).with(".feature").and_return(true) }

      it "returns an array" do
        expect(parser.parse_path).to be_an(Array)
      end

      it "returns only the file path" do
        collection = parser.parse_path
        expect(collection.size).to eq 1
        expect(collection.first).to eq test_path
      end
    end

    context "with a directory path" do
      before { expect(test_path).to receive(:end_with?).with(".feature").and_return(false) }

      it "returns an array" do
        expect(parser.parse_path).to be_an(Array)
      end

      it "globs for a recursive list of feature files" do
        expect(Dir).to receive(:glob).with("#{test_path}/**/*.feature")
        parser.parse_path
      end
    end
  end

  describe "#to_json" do
    let(:feature) { double("array") }

    before do
      expect(parser).to receive(:parse_path).and_return(feature)
      expect(feature).to receive(:each).once
      expect(MultiJson).to receive(:load).with(parser.io.string)
    end

    it "iterates over the list of feature files" do
      parser.to_json
    end

    it "closes the formattter" do
      expect(parser.format).to receive(:done)
      parser.to_json
    end
  end
end


text:
Welcome to Redash's GitHub repo! 👋🎉

Do you need help or have a question? Checkout the Support category in our discussion forum: https://discuss.redash.io/c/support.

Got an idea for a new feature? Check if it isn't on the roadmap already: http://bit.ly/redash-roadmap and start a new discussion in the features category: https://discuss.redash.io/c/feature-requests 🌟.

Found a bug? Please fill out the sections below... thank you 👍

### Issue Summary

A summary of the issue and the browser/OS environment in which it occurs.

### Steps to Reproduce

1. This is the first step
2. This is the second step, etc.

Any other info e.g. Why do you consider this to be a bug? What did you expect to happen instead?

### Technical details:

* Redash Version:
* Browser/OS:
* How did you install Redash:


text:
<!DOCTYPE html>

        <title>Community</title>

        <meta charset="UTF-8">

        <link href="style.css" rel="stylesheet">
        <link href='http://fonts.googleapis.com/css?family=Lato:700' rel='stylesheet' type='text/css'>
        <link rel="icon" href="favicon.ico" sizes="16x16 32x32 64x64" type="image/vnd.microsoft.icon">

Socials

We're on Discord! Join our server to talk with the devs.

We're also on Facebook: Arke Industries. Don't forget to smash that link button.

And Starfall has a subreddit of its own: /r/StarfallGame.

Finally, we don't have a company Twitter yet but our community manager, Wizard, has one: AI Wizard on Twitter.


text:
<Record>
<Term>Polyethylene glycol 3350</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<SemanticType>Organic Chemical</SemanticType>
<PrimarySemanticType>Pharmacologic Substance</PrimarySemanticType>
<Synonym>Polyethylene glycol 3350</Synonym>
<Synonym>Miralax</Synonym>
<Synonym>Glycolax</Synonym>
<Source>FDA Registry</Source>
</Record>


text:
package com.mambu.ant.styleGuide.model;

import java.util.Date;

/**
 * Pojo with basic info that is returned by phrase app when a list of style guides is requested
 *
 * @author aifrim.
 */
public class ResponseStyleGuideLightModel {

    private String id;
    private String title;
    private Date created_at;
    private Date updated_at;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Date getCreated_at() {
        return created_at;
    }

    public void setCreated_at(Date created_at) {
        this.created_at = created_at;
    }

    public Date getUpdated_at() {
        return updated_at;
    }

    public void setUpdated_at(Date updated_at) {
        this.updated_at = updated_at;
    }
}


text:
package Paws::CloudFormation::UpdateTerminationProtection;
  use Moose;
  has EnableTerminationProtection => (is => 'ro', isa => 'Bool', required => 1);
  has StackName => (is => 'ro', isa => 'Str', required => 1);

  use MooseX::ClassAttribute;

  class_has _api_call => (isa => 'Str', is => 'ro', default => 'UpdateTerminationProtection');
  class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::CloudFormation::UpdateTerminationProtectionOutput');
  class_has _result_key => (isa => 'Str', is => 'ro', default => 'UpdateTerminationProtectionResult');
1;

### main pod documentation begin ###

=head1 NAME

Paws::CloudFormation::UpdateTerminationProtection - Arguments for method UpdateTerminationProtection on Paws::CloudFormation

=head1 DESCRIPTION

This class represents the parameters used for calling the method UpdateTerminationProtection on the
AWS CloudFormation service. Use the attributes of this class
as arguments to method UpdateTerminationProtection.

You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to UpdateTerminationProtection.

As an example:

  $service_obj->UpdateTerminationProtection(Att1 => $value1, Att2 => $value2, ...);

Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object.

=head1 ATTRIBUTES

=head2 B<REQUIRED> EnableTerminationProtection => Bool

Whether to enable termination protection on the specified stack.

=head2 B<REQUIRED> StackName => Str

The name or unique ID of the stack for which you want to set
termination protection.

=head1 SEE ALSO

This class forms part of L<Paws>, documenting arguments for method UpdateTerminationProtection in L<Paws::CloudFormation>

=head1 BUGS and CONTRIBUTIONS

The source code is located here: https://github.com/pplu/aws-sdk-perl

Please report bugs to: https://github.com/pplu/aws-sdk-perl/issues

=cut


text:
import re, os
from . import VCSRoute, ROUTE_REGEX
from pip.vcs.mercurial import Mercurial

class MercurialRoute(VCSRoute):

    '''

    #### pip-style patterns
    hg+http://hg.myproject.org/MyProject
    hg+ssh://hg@myproject.org/MyProject

    #### all support
    @branch
    @commit (hexidecimal)
    @tag

    '''

    vcs = Mercurial

    def __unicode__(self):
        return "mercurial"

    def _uid(self, identifier):
        pattern_re = re.compile('%(fqdn)s\/%(owner)s\/%(repo)s' % ROUTE_REGEX)
        pattern_match = pattern_re.search(identifier)
        pattern_info = pattern_match.groupdict()
        return "%s.%s" % (pattern_info['owner'],pattern_info['repo'])


text:
package leetcode.dp.hard;

import java.util.*;
/**
 * Created by wangxiaoyi on 16/4/10.
 */
public class WordBreakII {

    public List<String> wordBreak(String s, Set<String> wordDict) {
        List<String> ans = new LinkedList<>();
        if(s == null || s.length() == 0) return ans;

        List<String> currAns = new LinkedList<>();
        Set<Integer> lens = new TreeSet<>();
        for(String word : wordDict){
            lens.add(word.length());
        }
        dfs(s, 0, wordDict, ans, currAns, lens);
        return ans;
    }

    /**
     * 直接暴力dfs 超时
     */
    public void dfs(String s, int sindex, Set<String> wordDict,List<String> ans,
                    List<String> currAns, Set<Integer> lens){
        if(sindex == s.length()){
            StringBuilder sb = new StringBuilder();
            for(String cs : currAns){
                sb.append(cs).append(" ");
            }
            ans.add(sb.toString().trim());
            return;
        }else {
            for(Integer len : lens){
                if(sindex + len > s.length()){
                    return;
                }else {
                    String cs = s.substring(sindex, sindex + len);
                    int nextIndex = sindex + len;
                    if(wordDict.contains(cs)){
                        currAns.add(cs);
                        dfs(s, nextIndex, wordDict, ans, currAns, lens);
                        currAns.remove(currAns.size() - 1);
                    }else
                        continue;
                }
            }

        }
    }

    /**
     * 回溯算法
     * 保存 每个区间String所对应的 break信息
     */

    Map<String, List<String>> map = new HashMap<>();

    public List<String> wordBreak2(String s, Set<String> wordDict) {
        if(map.containsKey(s))
            return map.get(s);
        int len = s.length();
        List<String> ret = new ArrayList<>();
        if(wordDict.contains(s))
            ret.add(s);
        for(int i = 1; i < len; i ++){
            String curr = s.substring(i);
            if(wordDict.contains(curr)){
                List<String> preAns = wordBreak(s.substring(0,i), wordDict);// 计算当前位置的前缀序列
                if(! preAns.isEmpty()){
                    for(String pre : preAns){
                        ret.add(pre + " " + curr);
                    }
                }
            }
        }
        map.put(s, ret);
        return ret;
    }

    //动态规划解法
    public static void main(String []args){

        String s =  "catsanddog";

        Set<String> dict = new HashSet<>();
        dict.add("cat");
        dict.add("cats");
        dict.add("and");
        dict.add("sand");
        dict.add("dog");
        List<String> ans = new WordBreakII().wordBreak(s, dict);
        System.out.print(ans);
    }
}


text:
@org.spongepowered.api.util.annotation.NonnullByDefault
package blue.lapis.common.economy.event.impl;


text:
from __future__ import unicode_literals
from __future__ import print_function
import sys

import traildb

for cookie, trail in traildb.TrailDB(*(sys.argv[1:] or ['a.tdb'])).crumbs():
    print(cookie, trail)


text:
class UpdateChronoModelMetaData < ActiveRecord::Migration[5.1]
  def change
    drop_view :statistic_stations, revert_to_version: 1
    drop_view :statistic_media, revert_to_version: 1
    drop_view :statistic_medium_translations, revert_to_version: 1
    remove_index :statistic_broadcasts, :id
    drop_view :statistic_broadcasts, materialized: true

    ActiveRecord::Base.connection.chrono_setup!

    create_view :statistic_broadcasts, materialized: true
    update_view :statistic_broadcasts, revert_to_version: 5, version: 5, materialized: true
    add_index :statistic_broadcasts, :id, unique: true
    create_view :statistic_stations
    create_view :statistic_media
    create_view :statistic_medium_translations
  end
end


text:
layout: default
isFront: true
image: SacSkyline.jpg
attribution: "City of Sacramento"
published: true
---

Welcome to the Housing Data Hub! This is your go-to resource for learning about locally administered government policies and programs that affect housing affordability in the Sacramento area. We provide an overview of each major program - what it is, its purpose, and related data.

Who is this for? This is for policy makers, decision makers and individuals interested in what Sacramento is doing about affordable housing.

Getting started? Start with some context on housing in Sacramento.

				Housing Overview

Learn about this site and what led to its creation.

			About

Fill out the Rental Survey form!

			Rental Survey Form


text:
<?php

namespace TeleinfoRecorder\Handler;

use Guzzle\Http\Client;

class ThingSpeakFeedHandler extends AbstractHandler
{

    protected $feedId = null;
    protected $apiKey = null;
    protected $fields = array();

    public function __construct($apiKey, $feedId, $fields)
    {
        $this->apiKey   = $apiKey;
        $this->feedId   = $feedId;
        $this->fields   = $fields;
    }

    protected function getDefaultFormatter()
    {
        return null;
    }

    /**
     * Write
     *
     * TODO: check the response
     */
    public function write(array $record)
    {
        if (!is_array($this->fields) or empty($this->fields) or count($this->fields) > 8) {
            return null;
        }

        $postData = array();
        $postData['Channel'] = $this->feedId;
        foreach ($this->fields as $index => $field) {
            $postData['field' . ($index+1)] = $record[$field];
        }

        $client = new Client('https://api.thingspeak.com');
        $request = $client->post('/update/', null, $postData);
        $request->addHeader('X-THINGSPEAKAPIKEY', $this->apiKey);
        $response = $request->send();
    }
}