text:
<?php

declare(strict_types=1);

namespace Talesweaver\Application\Controller\Chapter;

use Assert\Assertion;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Ramsey\Uuid\Uuid;
use Talesweaver\Application\Bus\CommandBus;
use Talesweaver\Application\Command\Scene\Create\Command;
use Talesweaver\Application\Form\FormHandlerFactoryInterface;
use Talesweaver\Application\Form\FormHandlerInterface;
use Talesweaver\Application\Form\Type\Chapter\NextScene;
use Talesweaver\Application\Http\ApiResponseFactoryInterface;
use Talesweaver\Application\Http\Entity\ChapterResolver;
use Talesweaver\Application\Http\UrlGenerator;
use Talesweaver\Domain\Chapter;
use Talesweaver\Domain\ValueObject\ShortText;

final class SceneAddController
{
    /**
     * @var ChapterResolver
     */
    private $chapterResolver;

    /**
     * @var ApiResponseFactoryInterface
     */
    private $apiResponseFactory;

    /**
     * @var FormHandlerFactoryInterface
     */
    private $formHandlerFactory;

    /**
     * @var CommandBus
     */
    private $commandBus;

    /**
     * @var UrlGenerator
     */
    private $urlGenerator;

    public function __construct(
        ChapterResolver $chapterResolver,
        ApiResponseFactoryInterface $apiResponseFactory,
        FormHandlerFactoryInterface $formHandlerFactory,
        CommandBus $commandBus,
        UrlGenerator $urlGenerator
    ) {
        $this->chapterResolver = $chapterResolver;
        $this->apiResponseFactory = $apiResponseFactory;
        $this->formHandlerFactory = $formHandlerFactory;
        $this->commandBus = $commandBus;
        $this->urlGenerator = $urlGenerator;
    }

    public function __invoke(ServerRequestInterface $request): ResponseInterface
    {
        $chapter = $this->chapterResolver->fromRequest($request);
        $formHandler = $this->createFormHandler($request, $chapter);
        if (true === $formHandler->isSubmissionValid()) {
            return $this->handeFormSubmissionAndReturnSuccessResponse(
                $chapter,
                $formHandler->getData()['title']
            );
        }

        return $this->apiResponseFactory->form(
            'form/modalContent.html.twig',
            ['form' => $formHandler->createView()],
            $formHandler->displayErrors(),
            'scene.header.new'
        );
    }

    private function createFormHandler(
        ServerRequestInterface $request,
        Chapter $chapter
    ): FormHandlerInterface {
        return $this->formHandlerFactory->createWithRequest(
            $request,
            NextScene::class,
            null,
            [
                'chapter' => $chapter,
                'attr' => [
                    'action' => $this->urlGenerator->generate(
                        'chapter_add_scene',
                        ['id' => $chapter->getId()]
                    ),
                    'class' => 'js-form'
                ]
            ]
        );
    }

    private function handeFormSubmissionAndReturnSuccessResponse(Chapter $chapter, ?string $title): ResponseInterface
    {
        Assertion::notNull($title);
        $this->commandBus->dispatch(new Command(Uuid::uuid4(), new ShortText($title), $chapter));
        return $this->apiResponseFactory->success([]);
    }
}


text:
<!doctype html>

  <meta charset="utf-8">
  <title>Addons io.js v3.3.0 Manual & Documentation</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic">
  <link rel="stylesheet" href="assets/style.css">
  <link rel="stylesheet" href="assets/sh.css">
  <link rel="canonical" href="https://iojs.org/api/addons.html">

          io.js (1)

About these Docs

Synopsis

Assertion Testing

Buffer

C/C++ Addons

Child Processes

Cluster

Console

Crypto

Debugger

DNS

Domain

Errors

Events

File System

Globals

HTTP

HTTPS

Modules

Net

OS

Path

Process

Punycode

Query Strings

Readline

REPL

Stream

String Decoder

Timers

TLS/SSL

TTY

UDP/Datagram

URL

Utilities

V8

VM

ZLIB

io.js v3.3.0 Documentation

            Index |
            View on single page |
            View as JSON

Table of Contents

Addons

Hello world

Addon patterns

Function arguments

Callbacks

Object factory

Function factory

Wrapping C++ objects

Factory of wrapped objects

Passing wrapped objects around

AtExit hooks

void AtExit(callback, args)

Addons#

Addons are dynamically linked shared objects. They can provide glue to C and
C++ libraries. The API (at the moment) is rather complex, involving
knowledge of several libraries:

V8 JavaScript, a C++ library. Used for interfacing with JavaScript:
creating objects, calling functions, etc.  Documented mostly in the
v8.h header file (deps/v8/include/v8.h in the io.js source
tree), which is also available
online.

libuv, C event loop library.
Anytime one needs to wait for a file descriptor to become readable,
wait for a timer, or wait for a signal to be received one will need
to interface with libuv. That is, if you perform any I/O, libuv will
need to be used.

Internal io.js libraries. Most importantly is the node::ObjectWrap
class which you will likely want to derive from.

Others. Look in deps/ for what else is available.

io.js statically compiles all its dependencies into the executable.
When compiling your module, you don't need to worry about linking to
any of these libraries.

All of the following examples are available for
download and may be
used as a starting-point for your own Addon.

Hello world#

To get started let's make a small Addon which is the C++ equivalent of
the following JavaScript code:

module.exports.hello = function() { return 'world'; };

First we create a file hello.cc:

// hello.cc
#include <node.h>

namespace demo {

using v8::FunctionCallbackInfo;
using v8::HandleScope;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;

void Method(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();
  args.GetReturnValue().Set(String::NewFromUtf8(isolate, "world"));
}

void init(Local<Object> exports) {
  NODE_SET_METHOD(exports, "hello", Method);
}

NODE_MODULE(addon, init)

}  // namespace demo

Note that all io.js addons must export an initialization function:

void Initialize(Local<Object> exports);
NODE_MODULE(module_name, Initialize)

There is no semi-colon after NODE_MODULE as it's not a function (see
node.h).

The module_name needs to match the filename of the final binary (minus the
.node suffix).

The source code needs to be built into addon.node, the binary Addon. To
do this we create a file called binding.gyp which describes the configuration
to build your module in a JSON-like format. This file gets compiled by
node-gyp.

{
  "targets": [
    {
      "target_name": "addon",
      "sources": [ "hello.cc" ]
    }
  ]
}

The next step is to generate the appropriate project build files for the
current platform. Use node-gyp configure for that.

Now you will have either a Makefile (on Unix platforms) or a vcxproj file
(on Windows) in the build/ directory. Next invoke the node-gyp build
command.

Now you have your compiled .node bindings file! The compiled bindings end up
in build/Release/.

You can now use the binary addon in an io.js project hello.js by pointing
require to the recently built hello.node module:

// hello.js
var addon = require('./build/Release/addon');

console.log(addon.hello()); // 'world'

Please see patterns below for further information or

https://github.com/arturadib/node-qt for an example in production.

Addon patterns#

Below are some addon patterns to help you get started. Consult the online
v8 reference for help with the various v8
calls, and v8's Embedder's Guide
for an explanation of several concepts used such as handles, scopes,
function templates, etc.

In order to use these examples you need to compile them using node-gyp.
Create the following binding.gyp file:

{
  "targets": [
    {
      "target_name": "addon",
      "sources": [ "addon.cc" ]
    }
  ]
}

In cases where there is more than one .cc file, simply add the file name to
the sources array, e.g.:

"sources": ["addon.cc", "myexample.cc"]

Now that you have your binding.gyp ready, you can configure and build the
addon:

$ node-gyp configure build

Function arguments#

The following pattern illustrates how to read arguments from JavaScript
function calls and return a result. This is the main and only needed source
addon.cc:

// addon.cc
#include <node.h>

namespace demo {

using v8::Exception;
using v8::FunctionCallbackInfo;
using v8::HandleScope;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::String;
using v8::Value;

void Add(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (args.Length() < 2) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong number of arguments")));
    return;
  }

  if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
    isolate->ThrowException(Exception::TypeError(
        String::NewFromUtf8(isolate, "Wrong arguments")));
    return;
  }

  double value = args[0]->NumberValue() + args[1]->NumberValue();
  Local<Number> num = Number::New(isolate, value);

  args.GetReturnValue().Set(num);
}

void Init(Local<Object> exports) {
  NODE_SET_METHOD(exports, "add", Add);
}

NODE_MODULE(addon, Init)

}  // namespace demo

You can test it with the following JavaScript snippet:

// test.js
var addon = require('./build/Release/addon');

console.log( 'This should be eight:', addon.add(3,5) );

Callbacks#

You can pass JavaScript functions to a C++ function and execute them from
there. Here's addon.cc:

// addon.cc
#include <node.h>

namespace demo {

using v8::Function;
using v8::FunctionCallbackInfo;
using v8::HandleScope;
using v8::Isolate;
using v8::Local;
using v8::Null;
using v8::Object;
using v8::String;
using v8::Value;

void RunCallback(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();
  Local<Function> cb = Local<Function>::Cast(args[0]);
  const unsigned argc = 1;
  Local<Value> argv[argc] = { String::NewFromUtf8(isolate, "hello world") };
  cb->Call(Null(isolate), argc, argv);
}

void Init(Local<Object> exports, Local<Object> module) {
  NODE_SET_METHOD(module, "exports", RunCallback);
}

NODE_MODULE(addon, Init)

}  // namespace demo

Note that this example uses a two-argument form of Init() that receives
the full module object as the second argument. This allows the addon
to completely overwrite exports with a single function instead of
adding the function as a property of exports.

To test it run the following JavaScript snippet:

// test.js
var addon = require('./build/Release/addon');

addon(function(msg){
  console.log(msg); // 'hello world'
});

Object factory#

You can create and return new objects from within a C++ function with this
addon.cc pattern, which returns an object with property msg that echoes
the string passed to createObject():

// addon.cc
#include <node.h>

namespace demo {

using v8::FunctionCallbackInfo;
using v8::HandleScope;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;

void CreateObject(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  Local<Object> obj = Object::New(isolate);
  obj->Set(String::NewFromUtf8(isolate, "msg"), args[0]->ToString());

  args.GetReturnValue().Set(obj);
}

void Init(Local<Object> exports, Local<Object> module) {
  NODE_SET_METHOD(module, "exports", CreateObject);
}

NODE_MODULE(addon, Init)

}  // namespace demo

To test it in JavaScript:

// test.js
var addon = require('./build/Release/addon');

var obj1 = addon('hello');
var obj2 = addon('world');
console.log(obj1.msg+' '+obj2.msg); // 'hello world'

Function factory#

This pattern illustrates how to create and return a JavaScript function that
wraps a C++ function:

// addon.cc
#include <node.h>

namespace demo {

using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::HandleScope;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;

void MyFunction(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();
  args.GetReturnValue().Set(String::NewFromUtf8(isolate, "hello world"));
}

void CreateFunction(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction);
  Local<Function> fn = tpl->GetFunction();

  // omit this to make it anonymous
  fn->SetName(String::NewFromUtf8(isolate, "theFunction"));

  args.GetReturnValue().Set(fn);
}

void Init(Local<Object> exports, Local<Object> module) {
  NODE_SET_METHOD(module, "exports", CreateFunction);
}

NODE_MODULE(addon, Init)

}  // namespace demo

To test:

// test.js
var addon = require('./build/Release/addon');

var fn = addon();
console.log(fn()); // 'hello world'

Wrapping C++ objects#

Here we will create a wrapper for a C++ object/class MyObject that can be
instantiated in JavaScript through the new operator. First prepare the main
module addon.cc:

// addon.cc
#include <node.h>
#include "myobject.h"

namespace demo {

using v8::Local;
using v8::Object;

void InitAll(Local<Object> exports) {
  MyObject::Init(exports);
}

NODE_MODULE(addon, InitAll)

}  // namespace demo

Then in myobject.h make your wrapper inherit from node::ObjectWrap:

// myobject.h
#ifndef MYOBJECT_H
#define MYOBJECT_H

#include <node.h>
#include <node_object_wrap.h>

namespace demo {

class MyObject : public node::ObjectWrap {
 public:
  static void Init(v8::Local<v8::Object> exports);

 private:
  explicit MyObject(double value = 0);
  ~MyObject();

  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
  static void PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args);
  static v8::Persistent<v8::Function> constructor;
  double value_;
};

}  // namespace demo

#endif

And in myobject.cc implement the various methods that you want to expose.
Here we expose the method plusOne by adding it to the constructor's
prototype:

// myobject.cc
#include "myobject.h"

namespace demo {

using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::HandleScope;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::Persistent;
using v8::String;
using v8::Value;

Persistent<Function> MyObject::constructor;

MyObject::MyObject(double value) : value_(value) {
}

MyObject::~MyObject() {
}

void MyObject::Init(Local<Object> exports) {
  Isolate* isolate = exports->GetIsolate();

  // Prepare constructor template
  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
  tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject"));
  tpl->InstanceTemplate()->SetInternalFieldCount(1);

  // Prototype
  NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne);

  constructor.Reset(isolate, tpl->GetFunction());
  exports->Set(String::NewFromUtf8(isolate, "MyObject"),
               tpl->GetFunction());
}

void MyObject::New(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (args.IsConstructCall()) {
    // Invoked as constructor: `new MyObject(...)`
    double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
    MyObject* obj = new MyObject(value);
    obj->Wrap(args.This());
    args.GetReturnValue().Set(args.This());
  } else {
    // Invoked as plain function `MyObject(...)`, turn into construct call.
    const int argc = 1;
    Local<Value> argv[argc] = { args[0] };
    Local<Function> cons = Local<Function>::New(isolate, constructor);
    args.GetReturnValue().Set(cons->NewInstance(argc, argv));
  }
}

void MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.Holder());
  obj->value_ += 1;

  args.GetReturnValue().Set(Number::New(isolate, obj->value_));
}

}  // namespace demo

Test it with:

// test.js
var addon = require('./build/Release/addon');

var obj = new addon.MyObject(10);
console.log( obj.plusOne() ); // 11
console.log( obj.plusOne() ); // 12
console.log( obj.plusOne() ); // 13

Factory of wrapped objects#

This is useful when you want to be able to create native objects without
explicitly instantiating them with the new operator in JavaScript, e.g.

var obj = addon.createObject();
// instead of:
// var obj = new addon.Object();

Let's register our createObject method in addon.cc:

// addon.cc
#include <node.h>
#include "myobject.h"

namespace demo {

using v8::FunctionCallbackInfo;
using v8::HandleScope;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;

void CreateObject(const FunctionCallbackInfo<Value>& args) {
  MyObject::NewInstance(args);
}

void InitAll(Local<Object> exports, Local<Object> module) {
  MyObject::Init(exports->GetIsolate());

  NODE_SET_METHOD(module, "exports", CreateObject);
}

NODE_MODULE(addon, InitAll)

}  // namespace demo

In myobject.h we now introduce the static method NewInstance that takes
care of instantiating the object (i.e. it does the job of new in JavaScript):

// myobject.h
#ifndef MYOBJECT_H
#define MYOBJECT_H

#include <node.h>
#include <node_object_wrap.h>

namespace demo {

class MyObject : public node::ObjectWrap {
 public:
  static void Init(v8::Isolate* isolate);
  static void NewInstance(const v8::FunctionCallbackInfo<v8::Value>& args);

 private:
  explicit MyObject(double value = 0);
  ~MyObject();

  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
  static void PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args);
  static v8::Persistent<v8::Function> constructor;
  double value_;
};

}  // namespace demo

#endif

The implementation is similar to the above in myobject.cc:

// myobject.cc
#include <node.h>
#include "myobject.h"

namespace demo {

using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::HandleScope;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::Persistent;
using v8::String;
using v8::Value;

Persistent<Function> MyObject::constructor;

MyObject::MyObject(double value) : value_(value) {
}

MyObject::~MyObject() {
}

void MyObject::Init(Isolate* isolate) {
  // Prepare constructor template
  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
  tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject"));
  tpl->InstanceTemplate()->SetInternalFieldCount(1);

  // Prototype
  NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne);

  constructor.Reset(isolate, tpl->GetFunction());
}

void MyObject::New(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (args.IsConstructCall()) {
    // Invoked as constructor: `new MyObject(...)`
    double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
    MyObject* obj = new MyObject(value);
    obj->Wrap(args.This());
    args.GetReturnValue().Set(args.This());
  } else {
    // Invoked as plain function `MyObject(...)`, turn into construct call.
    const int argc = 1;
    Local<Value> argv[argc] = { args[0] };
    Local<Function> cons = Local<Function>::New(isolate, constructor);
    args.GetReturnValue().Set(cons->NewInstance(argc, argv));
  }
}

void MyObject::NewInstance(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  const unsigned argc = 1;
  Local<Value> argv[argc] = { args[0] };
  Local<Function> cons = Local<Function>::New(isolate, constructor);
  Local<Object> instance = cons->NewInstance(argc, argv);

  args.GetReturnValue().Set(instance);
}

void MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.Holder());
  obj->value_ += 1;

  args.GetReturnValue().Set(Number::New(isolate, obj->value_));
}

}  // namespace demo

Test it with:

// test.js
var createObject = require('./build/Release/addon');

var obj = createObject(10);
console.log( obj.plusOne() ); // 11
console.log( obj.plusOne() ); // 12
console.log( obj.plusOne() ); // 13

var obj2 = createObject(20);
console.log( obj2.plusOne() ); // 21
console.log( obj2.plusOne() ); // 22
console.log( obj2.plusOne() ); // 23

Passing wrapped objects around#

In addition to wrapping and returning C++ objects, you can pass them around
by unwrapping them with io.js's node::ObjectWrap::Unwrap helper function.
In the following addon.cc we introduce a function add() that can take on two
MyObject objects:

// addon.cc
#include <node.h>
#include <node_object_wrap.h>
#include "myobject.h"

namespace demo {

using v8::FunctionCallbackInfo;
using v8::HandleScope;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::String;
using v8::Value;

void CreateObject(const FunctionCallbackInfo<Value>& args) {
  MyObject::NewInstance(args);
}

void Add(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  MyObject* obj1 = node::ObjectWrap::Unwrap<MyObject>(
      args[0]->ToObject());
  MyObject* obj2 = node::ObjectWrap::Unwrap<MyObject>(
      args[1]->ToObject());

  double sum = obj1->value() + obj2->value();
  args.GetReturnValue().Set(Number::New(isolate, sum));
}

void InitAll(Local<Object> exports) {
  MyObject::Init(exports->GetIsolate());

  NODE_SET_METHOD(exports, "createObject", CreateObject);
  NODE_SET_METHOD(exports, "add", Add);
}

NODE_MODULE(addon, InitAll)

}  // namespace demo

To make things interesting we introduce a public method in myobject.h so we
can probe private values after unwrapping the object:

// myobject.h
#ifndef MYOBJECT_H
#define MYOBJECT_H

#include <node.h>
#include <node_object_wrap.h>

namespace demo {

class MyObject : public node::ObjectWrap {
 public:
  static void Init(v8::Isolate* isolate);
  static void NewInstance(const v8::FunctionCallbackInfo<v8::Value>& args);
  inline double value() const { return value_; }

 private:
  explicit MyObject(double value = 0);
  ~MyObject();

  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
  static v8::Persistent<v8::Function> constructor;
  double value_;
};

}  // namespace demo

#endif

The implementation of myobject.cc is similar as before:

// myobject.cc
#include <node.h>
#include "myobject.h"

namespace demo {

using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::HandleScope;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::Persistent;
using v8::String;
using v8::Value;

Persistent<Function> MyObject::constructor;

MyObject::MyObject(double value) : value_(value) {
}

MyObject::~MyObject() {
}

void MyObject::Init(Isolate* isolate) {
  // Prepare constructor template
  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
  tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject"));
  tpl->InstanceTemplate()->SetInternalFieldCount(1);

  constructor.Reset(isolate, tpl->GetFunction());
}

void MyObject::New(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  if (args.IsConstructCall()) {
    // Invoked as constructor: `new MyObject(...)`
    double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
    MyObject* obj = new MyObject(value);
    obj->Wrap(args.This());
    args.GetReturnValue().Set(args.This());
  } else {
    // Invoked as plain function `MyObject(...)`, turn into construct call.
    const int argc = 1;
    Local<Value> argv[argc] = { args[0] };
    Local<Function> cons = Local<Function>::New(isolate, constructor);
    args.GetReturnValue().Set(cons->NewInstance(argc, argv));
  }
}

void MyObject::NewInstance(const FunctionCallbackInfo<Value>& args) {
  Isolate* isolate = args.GetIsolate();

  const unsigned argc = 1;
  Local<Value> argv[argc] = { args[0] };
  Local<Function> cons = Local<Function>::New(isolate, constructor);
  Local<Object> instance = cons->NewInstance(argc, argv);

  args.GetReturnValue().Set(instance);
}

}  // namespace demo

Test it with:

// test.js
var addon = require('./build/Release/addon');

var obj1 = addon.createObject(10);
var obj2 = addon.createObject(20);
var result = addon.add(obj1, obj2);

console.log(result); // 30

AtExit hooks#

void AtExit(callback, args)#

callback: void (*)(void*) - A pointer to the function to call at exit.

args: void* - A pointer to pass to the callback at exit.

Registers exit hooks that run after the event loop has ended, but before the VM
is killed.

Callbacks are run in last-in, first-out order. AtExit takes two parameters:
a pointer to a callback function to run at exit, and a pointer to untyped
context data to be passed to that callback.

The file addon.cc implements AtExit below:

// addon.cc
#undef NDEBUG
#include <assert.h>
#include <stdlib.h>
#include <node.h>

namespace demo {

using node::AtExit;
using v8::HandleScope;
using v8::Isolate;
using v8::Local;
using v8::Object;

static char cookie[] = "yum yum";
static int at_exit_cb1_called = 0;
static int at_exit_cb2_called = 0;

static void at_exit_cb1(void* arg) {
  Isolate* isolate = static_cast<Isolate*>(arg);
  HandleScope scope(isolate);
  Local<Object> obj = Object::New(isolate);
  assert(!obj.IsEmpty()); // assert VM is still alive
  assert(obj->IsObject());
  at_exit_cb1_called++;
}

static void at_exit_cb2(void* arg) {
  assert(arg == static_cast<void*>(cookie));
  at_exit_cb2_called++;
}

static void sanity_check(void*) {
  assert(at_exit_cb1_called == 1);
  assert(at_exit_cb2_called == 2);
}

void init(Local<Object> exports) {
  AtExit(sanity_check);
  AtExit(at_exit_cb2, cookie);
  AtExit(at_exit_cb2, cookie);
  AtExit(at_exit_cb1, exports->GetIsolate());
}

NODE_MODULE(addon, init);

}  // namespace demo

Test in JavaScript by running:

// test.js
var addon = require('./build/Release/addon');

redpajama_set_name: RedPajamaGithub


text:
package org.springframework.cloud.data.admin.repository;

import org.springframework.cloud.data.core.TaskDefinition;
import org.springframework.data.repository.PagingAndSortingRepository;

/**
 * @author Michael Minella
 */
public interface TaskDefinitionRepository extends PagingAndSortingRepository<TaskDefinition, String> {
}


text:
require "rails_helper"
require "tariff_synchronizer"

describe TariffSynchronizer::Response do

  describe "#terminated?" do
    it "Returns true if response_code is 200 or 404" do
      response = build(:response, response_code: 200)
      expect(response).to be_terminated
    end

    it "Returns false if response_code is different from 200 or 404" do
      response = build(:response, response_code: 401)
      expect(response).to_not be_terminated
    end
  end

  describe "#retry_count_exceeded!" do
    it "sets the internal state to exceeded" do
      response = build(:response)
      expect(response.retry_count_exceeded?).to be_falsey
      response.retry_count_exceeded!
      expect(response.retry_count_exceeded?).to be_truthy
    end
  end

  describe "#state" do
    it "Returns the successful symbol" do
      response = build(:response, response_code: 200, content: "xyz")
      expect(response.state).to eq(:successful)
    end

    it "Returns the empty symbol when content is empty" do
      response = build(:response, response_code: 200, content: "")
      expect(response.state).to eq(:empty)
    end

    it "Returns the exceeded symbol when marked as exceeded" do
      response = build(:response, response_code: 401)
      response.retry_count_exceeded!
      expect(response.state).to eq(:exceeded)
    end

    it "Returns the not_found symbol when status is 404" do
      response = build(:response, response_code: 404)
      expect(response.state).to eq(:not_found)
    end
  end

  describe '#successful?' do
    it 'should return true for 200 and content' do
      response = build(:response, response_code: 200, content: "xyz")
      expect(response.send(:successful?)).to be_truthy
    end

    it 'should return false in other cases' do
      response = build(:response, response_code: 404, content: "xyz")
      expect(response.send(:successful?)).to be_falsey
    end
  end
end


text:
MAKEFLAGS += -s

# additional flags for cmake, e.g. install path -DCMAKE_INSTALL_PREFIX=$(HOME)/.local
CMAKEFLAGS +=

all: release
ci: debug release test

help:
		@echo "        debug: Run a debug build"
		@echo "      release: Run a release build"
		@echo "      install: Install release build"
		@echo "    uninstall: Uninstall release build"
		@echo "      package: Package release build"
		@echo "         lint: Lint check all source-code"
		@echo "         test: Build and run tests"
		@echo "        clean: Clean all build output"
		@echo "rebuild_cache: Rebuild all CMake caches"

rebuild_cache: build/Debug build/Release
		@$(MAKE) -C build/Debug rebuild_cache
		@$(MAKE) -C build/Release rebuild_cache

debug: build/Debug
		@echo "[DEBUG]"
		@$(MAKE) -C build/Debug

release: build/Release
		@echo "[RELEASE]"
		@$(MAKE) -C build/Release

install: build/Release
		@echo "[INSTALL] Release"
		@$(MAKE) -C build/Release install

uninstall: build/Release
		@echo "[UNINSTALL] Release"
		@$(MAKE) -C build/Release uninstall

package: build/Release
		@echo "[PACKAGE] Release"
		@$(MAKE) -C build/Release package

test: debug
		@echo "[TEST] Debug"
		@$(MAKE) -C build/Debug test

build/Debug:
		@mkdir -p $@
		@cd $@ && cmake -DCMAKE_BUILD_TYPE=Debug $(CMAKEFLAGS) ../../

build/Release:
		@mkdir -p $@
		@cd $@ && cmake -DCMAKE_BUILD_TYPE=Release $(CMAKEFLAGS) ../../

clean:
		@echo "[CLEAN]"
		@rm -Rf build

.PHONY: clean


text:
package com.baidubce.services.iotdm.model.v3.rules;

import com.baidubce.model.AbstractBceResponse;

import java.util.List;

public class DeviceRuleResponse extends AbstractBceResponse {
    /**
     * ID of Device Rule .
     */
    private String id;
    /**
     * Device name of Device Rule .
     */
    private String deviceName;
    /**
     * Name of Device Rule .
     */
    private String name;
    /**
     * List of Device Rule Source detail .
     */
    private List<DeviceRuleSourceDetail> sources;
    /**
     * List of Device Rule destination detail .
     */
    private List<DeviceRuleDestinationDetail> destinations;
    /**
     * Whether open Device Rule or not .
     */
    private Boolean enable;
    /**
     * Create time of Device Rule .
     */
    private Long createTime;
    /**
     * Update time of Device Rule .
     */
    private Long updateTime;

    public String getId() {
        return id;
    }

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

    public String getDeviceName() {
        return deviceName;
    }

    public void setDeviceName(String deviceName) {
        this.deviceName = deviceName;
    }

    public String getName() {
        return name;
    }

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

    public List<DeviceRuleSourceDetail> getSources() {
        return sources;
    }

    public void setSources(List<DeviceRuleSourceDetail> sources) {
        this.sources = sources;
    }

    public List<DeviceRuleDestinationDetail> getDestinations() {
        return destinations;
    }

    public void setDestinations(List<DeviceRuleDestinationDetail> destinations) {
        this.destinations = destinations;
    }

    public Boolean getEnable() {
        return enable;
    }

    public void setEnable(Boolean enable) {
        this.enable = enable;
    }

    public Long getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Long createTime) {
        this.createTime = createTime;
    }

    public Long getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Long updateTime) {
        this.updateTime = updateTime;
    }
}


text:
package org.apache.activemq.artemis.core.protocol.core.impl.wireformat;

import org.apache.activemq.artemis.api.core.ActiveMQBuffer;
import org.apache.activemq.artemis.api.core.Pair;
import org.apache.activemq.artemis.api.core.TransportConfiguration;
import org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl;

public class ClusterTopologyChangeMessage extends PacketImpl
{
   protected boolean exit;

   protected String nodeID;

   protected Pair<TransportConfiguration, TransportConfiguration> pair;

   protected boolean last;

   // Static --------------------------------------------------------

   // Constructors --------------------------------------------------

   public ClusterTopologyChangeMessage(final String nodeID, final Pair<TransportConfiguration, TransportConfiguration> pair, final boolean last)
   {
      super(CLUSTER_TOPOLOGY);

      this.nodeID = nodeID;

      this.pair = pair;

      this.last = last;

      this.exit = false;
   }

   public ClusterTopologyChangeMessage(final String nodeID)
   {
      super(CLUSTER_TOPOLOGY);

      this.exit = true;

      this.nodeID = nodeID;
   }

   public ClusterTopologyChangeMessage()
   {
      super(CLUSTER_TOPOLOGY);
   }

   // Public --------------------------------------------------------

   /**
    * @param clusterTopologyV2
    */
   public ClusterTopologyChangeMessage(byte clusterTopologyV2)
   {
      super(clusterTopologyV2);
   }

   public String getNodeID()
   {
      return nodeID;
   }

   public Pair<TransportConfiguration, TransportConfiguration> getPair()
   {
      return pair;
   }

   public boolean isLast()
   {
      return last;
   }

   public boolean isExit()
   {
      return exit;
   }

   @Override
   public void encodeRest(final ActiveMQBuffer buffer)
   {
      buffer.writeBoolean(exit);
      buffer.writeString(nodeID);
      if (!exit)
      {
         if (pair.getA() != null)
         {
            buffer.writeBoolean(true);
            pair.getA().encode(buffer);
         }
         else
         {
            buffer.writeBoolean(false);
         }
         if (pair.getB() != null)
         {
            buffer.writeBoolean(true);
            pair.getB().encode(buffer);
         }
         else
         {
            buffer.writeBoolean(false);
         }
         buffer.writeBoolean(last);
      }
   }

   @Override
   public void decodeRest(final ActiveMQBuffer buffer)
   {
      exit = buffer.readBoolean();
      nodeID = buffer.readString();
      if (!exit)
      {
         boolean hasLive = buffer.readBoolean();
         TransportConfiguration a;
         if (hasLive)
         {
            a = new TransportConfiguration();
            a.decode(buffer);
         }
         else
         {
            a = null;
         }
         boolean hasBackup = buffer.readBoolean();
         TransportConfiguration b;
         if (hasBackup)
         {
            b = new TransportConfiguration();
            b.decode(buffer);
         }
         else
         {
            b = null;
         }
         pair = new Pair<TransportConfiguration, TransportConfiguration>(a, b);
         last = buffer.readBoolean();
      }
   }

   @Override
   public int hashCode()
   {
      final int prime = 31;
      int result = super.hashCode();
      result = prime * result + (exit ? 1231 : 1237);
      result = prime * result + (last ? 1231 : 1237);
      result = prime * result + ((nodeID == null) ? 0 : nodeID.hashCode());
      result = prime * result + ((pair == null) ? 0 : pair.hashCode());
      return result;
   }

   @Override
   public boolean equals(Object obj)
   {
      if (this == obj)
      {
         return true;
      }
      if (!super.equals(obj))
      {
         return false;
      }
      if (!(obj instanceof ClusterTopologyChangeMessage))
      {
         return false;
      }
      ClusterTopologyChangeMessage other = (ClusterTopologyChangeMessage) obj;
      if (exit != other.exit)
      {
         return false;
      }
      if (last != other.last)
      {
         return false;
      }
      if (nodeID == null)
      {
         if (other.nodeID != null)
         {
            return false;
         }
      }
      else if (!nodeID.equals(other.nodeID))
      {
         return false;
      }
      if (pair == null)
      {
         if (other.pair != null)
         {
            return false;
         }
      }
      else if (!pair.equals(other.pair))
      {
         return false;
      }
      return true;
   }
}


text:
namespace sky {
namespace shell {

class PlatformViewMac : public PlatformView {
 public:
  explicit PlatformViewMac(const Config& config);
  ~PlatformViewMac() override;
  void SurfaceCreated(gfx::AcceleratedWidget widget);
  void SurfaceDestroyed(void);

 private:
  DISALLOW_COPY_AND_ASSIGN(PlatformViewMac);
};

}  // namespace shell
}  // namespace sky

#endif  // SKY_SHELL_PLATFORM_VIEW_MAC_H_


text:
package my.stqa.addressbook.tests;

import my.stqa.addressbook.model.ContactData;
import org.testng.annotations.*;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

/**
 * Created by Євгеній on 20.03.2016.
 */
public class ContactViewTests extends TestBase {

    @BeforeMethod
    public void testsInit() {
        /** Pre-conditions: goto and creation of a record if there is no any **/
        app.navigateTo().mainPage();
        if (app.contact().all().size() == 0) {
            app.navigateTo().contactCreationPage();
            app.contact().createContact(new ContactData()
                    .withFirstName("Name")
                    .withSurName("Surname")
                    .withHomeAddress("City, Street")
                    .withHomePhone("+1234567890")
                    .withEmail("name.surname@gmail.com"));
        }

    }

    @Test
    public void testContactView(){

        ContactData contact = app.contact().all().iterator().next();
        String dataFromEditForm = app.contact().mergedDataFromEditForm(contact);
        String dataFromViewPage = app.contact().mergedDataFromViewPage(contact);

        assertThat(dataFromViewPage, equalTo(dataFromEditForm));
    }

}


text:
from __future__ import unicode_literals

from ..compat import (
    compat_urllib_parse,
)
from .common import InfoExtractor

class EHowIE(InfoExtractor):
    IE_NAME = 'eHow'
    _VALID_URL = r'https?://(?:www\.)?ehow\.com/[^/_?]*_(?P<id>[0-9]+)'
    _TEST = {
        'url': 'http://www.ehow.com/video_12245069_hardwood-flooring-basics.html',
        'md5': '9809b4e3f115ae2088440bcb4efbf371',
        'info_dict': {
            'id': '12245069',
            'ext': 'flv',
            'title': 'Hardwood Flooring Basics',
            'description': 'Hardwood flooring may be time consuming, but its ultimately a pretty straightforward concept. Learn about hardwood flooring basics with help from a hardware flooring business owner in this free video...',
            'uploader': 'Erick Nathan',
        }
    }

    def _real_extract(self, url):
        video_id = self._match_id(url)
        webpage = self._download_webpage(url, video_id)
        video_url = self._search_regex(
            r'(?:file|source)=(http[^\'"&]*)', webpage, 'video URL')
        final_url = compat_urllib_parse.unquote(video_url)
        uploader = self._html_search_meta('uploader', webpage)
        title = self._og_search_title(webpage).replace(' | eHow', '')

        return {
            'id': video_id,
            'url': final_url,
            'title': title,
            'thumbnail': self._og_search_thumbnail(webpage),
            'description': self._og_search_description(webpage),
            'uploader': uploader,
        }


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycologia 39(3): 346 (1947)

#### Original name
Selenophoma linicola Vanterp., 1947

### Remarks
null


text:
extern zend_class_entry *zendframework_stdlib_parameterobjectinterface_ce;

ZEPHIR_INIT_CLASS(ZendFramework_Stdlib_ParameterObjectInterface);

ZEND_BEGIN_ARG_INFO_EX(arginfo_zendframework_stdlib_parameterobjectinterface___set, 0, 0, 2)
	ZEND_ARG_INFO(0, key)
	ZEND_ARG_INFO(0, value)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_zendframework_stdlib_parameterobjectinterface___get, 0, 0, 1)
	ZEND_ARG_INFO(0, key)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_zendframework_stdlib_parameterobjectinterface___isset, 0, 0, 1)
	ZEND_ARG_INFO(0, key)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_zendframework_stdlib_parameterobjectinterface___unset, 0, 0, 1)
	ZEND_ARG_INFO(0, key)
ZEND_END_ARG_INFO()

ZEPHIR_INIT_FUNCS(zendframework_stdlib_parameterobjectinterface_method_entry) {
	PHP_ABSTRACT_ME(ZendFramework_Stdlib_ParameterObjectInterface, __set, arginfo_zendframework_stdlib_parameterobjectinterface___set)
	PHP_ABSTRACT_ME(ZendFramework_Stdlib_ParameterObjectInterface, __get, arginfo_zendframework_stdlib_parameterobjectinterface___get)
	PHP_ABSTRACT_ME(ZendFramework_Stdlib_ParameterObjectInterface, __isset, arginfo_zendframework_stdlib_parameterobjectinterface___isset)
	PHP_ABSTRACT_ME(ZendFramework_Stdlib_ParameterObjectInterface, __unset, arginfo_zendframework_stdlib_parameterobjectinterface___unset)
  PHP_FE_END
};


text:
package info.joriki.sfnt;

import java.io.File;
import java.io.DataInput;
import java.io.IOException;

import java.util.HashMap;
import java.util.Set;
import java.util.Iterator;

import info.joriki.io.Util;
import info.joriki.io.SeekableFile;
import info.joriki.io.FullySeekableDataInput;

import info.joriki.cff.CFFFont;
import info.joriki.cff.CFFFontSet;

import info.joriki.font.DescribedFont;
import info.joriki.font.GlyphProvider;

import info.joriki.util.Assertions;
import info.joriki.util.General;

import info.joriki.graphics.Transformation;

import info.joriki.opentype.GlyphPositioningTable;
import info.joriki.opentype.GlyphSubstitutionTable;
import info.joriki.truetype.GlyphTable;
import info.joriki.truetype.LocationTable;
import info.joriki.truetype.ControlValueTable;
import info.joriki.truetype.ByteCodeInterpreter;

public class SFNTFile extends SFNTDocument implements DescribedFont
{
  class HeaderEntry
  {
    String id;
    int checksum;
    int offset;
    int length;

    HeaderEntry (DataInput in) throws IOException
    {
      id = Util.readString (in,4);
      checksum = in.readInt ();
      offset = in.readInt ();
      length = in.readInt ();
    }
  }

  HashMap entries = new HashMap ();

  FullySeekableDataInput in;

  public SFNTFile (String filename) throws IOException
  {
    this (new File (filename));
  }

  public SFNTFile (File file) throws IOException
  {
    this (new SeekableFile (file,"r"));
  }

  public SFNTFile (FullySeekableDataInput in) throws IOException
  {
    super (in.readInt ());

    this.in = in;

    int ntable = in.readShort ();             // numTables
    new BinarySearchData (ntable,unitSize).assertFrom (in);

    for (int i = 0;i < ntable;i++)
      {
        HeaderEntry entry = new HeaderEntry (in);
        if (entry.length == 0) {
	  String id = entry.id;
          // accessintel-31134_92.pdf
          if (id.equals (NAME))
            continue;
          // fpgm: viasatellite200607_4.pdf
          // cvt and prep: p. 48 in ticket 44489
	  if (!(id.equals (FPGM) || id.equals (CVT) || id.equals (PREP) || id.equals ("glyf")))
	    throw new Error ("empty SFNT table");
        }
        entries.put (entry.id,entry);
      }
  }

//  FP 08/01/2014 removed method identical to overridden method
//  int checksum (byte [] data)
//  {
//    SFNTChecksumStream checksumStream = new SFNTChecksumStream ();
//    checksumStream.write (data);
//    return checksumStream.checksum;
//  }

  public byte [] getRawData (String id) throws IOException
  {
    HeaderEntry entry = (HeaderEntry) entries.get (id);
    if (entry == null)
      return null;
    in.seek (entry.offset);
    return Util.readBytes (in,entry.length);
  }

  public void removeTable (String id)
  {
    super.removeTable (id);
    entries.remove (id);
  }

  public SFNTTable getTable (String id)
  {
    SFNTTable table = super.getTable (id);
    if (table != null)
      return table;

    HeaderEntry entry = (HeaderEntry) entries.get (id);
    if (entry == null)
      return null;

    table = getTable (entry);
    addTable (table);
    return table;
  }

  private SFNTTable getTable (HeaderEntry entry)
  {
    String id = entry.id;

    SFNTTable aux = null;
    SFNTTable auy = null;
    if (id.equals (GLYF))
      {
        aux = getTable (LOCA);
        auy = getTable (HMTX);
      }
    else if (id.equals (HMTX))
      aux = getTable (HHEA);
    else if (id.equals (LOCA))
      aux = getTable (HEAD);

    int length = entry.length;

    try {
      in.pushOffset (entry.offset);
      try {
        if (id.equals (CMAP))
          return new CMap (in,length);
        else if (id.equals (CVT))
          return new ControlValueTable (in,length);
        else if (id.equals (GLYF))
          return new GlyphTable (in,(LocationTable) aux,(HorizontalMetrics) auy);
        else if (id.equals (HEAD))
          return new SFNTHeader (in);
        else if (id.equals (HHEA))
          return new HorizontalHeader (in);
        else if (id.equals (HMTX))
          return new HorizontalMetrics (in,(HorizontalHeader) aux,length);
        else if (id.equals (LOCA))
          return new LocationTable (in,(SFNTHeader) aux,length);
        else if (id.equals (MAXP))
          return new MaximumProfile (in);
        else if (id.equals (NAME))
          return new NamingTable (in,length);
        else if (id.equals (POST))
          return new PostScriptTable (in);
        else if (id.equals (OS2))
          return new OS2Table (in,length);
        // OpenType tables
        else if (id.equals (GPOS))
          return new GlyphPositioningTable (in);
        else if (id.equals (GSUB))
          return new GlyphSubstitutionTable (in);
        else
          return new GenericTable (in,id,length);
      } finally {
        in.popOffset ();
      }
    } catch (IOException ioe) {
      ioe.printStackTrace ();
      return null;
    }
  }

  public Set getIDs ()
  {
    Set ids = super.getIDs ();

    ids.addAll (entries.keySet ());

    return ids;
  }

  public void rewrite ()
  {
    Iterator iterator = entries.keySet ().iterator ();
    while (iterator.hasNext ())
      getTable ((String) iterator.next ());
  }

  public SFNTHeader getHeader ()
  {
    return (SFNTHeader) getTable (HEAD);
  }

  public double [] getFontBBox ()
  {
    return getHeader ().bbox ();
  }

  public double [] getFontMatrix ()
  {
    return Transformation.scalingBy (1. / getHeader ().unitsPerEm).matrix;
  }

  public String getName ()
  {
    NamingTable namingTable = (NamingTable) getTable (NAME);
    return namingTable == null ? null : namingTable.getPostScriptName ();
  }

  public String getNotice ()
  {
    NamingTable namingTable = (NamingTable) getTable (NAME);
    if (namingTable == null)
      return null;
    String notice = namingTable.getTradeMark ();
    if (notice == null)
      notice = namingTable.getCopyrightNotice ();
    return notice == null ? null : General.replace
      (General.replace
       (notice,
        (char) 0xa8,"(R)"),
       (char) 0xa9,"(C)");
  }

  public String getWeight ()
  {
    OS2Table os2Table = (OS2Table) getTable (OS2);
    return os2Table == null ? null : os2Table.getWeight ();
  }

  public static void main (String [] args) throws IOException
  {
    int arg = 0;

    SFNTFile file = new SFNTFile (args [arg++]);
    if (args [arg].charAt (0) == '-')
      {
        CMap cmap = null;
        CMapTable subtable = null;
        CFFFontSet fontSet = null;
        CFFFont font = null;
        while (arg < args.length && args [arg].charAt (0) == '-')
          {
            switch (args [arg++].charAt (1))
              {
              case 'a' : // strip table
                file.removeTable (args [arg++]);
                break;
              case 'b' : // show metric info
                System.out.println ("units per em : " + file.getHeader ().unitsPerEm);
                System.out.println ("bbox : " + General.toString (file.getFontBBox ()));
                HorizontalHeader hhea = (HorizontalHeader) file.getTable (HHEA);
                OS2Table os2 = (OS2Table) file.getTable (OS2);
                System.out.println ("ascent : " + hhea.ascent);
                System.out.println ("descent : " + hhea.descent);
                System.out.println ("lineGap : " + hhea.lineGap);
                System.out.println ("sTypoAscender = " + os2.sTypoAscender);
                System.out.println ("sTypoDescender = " + os2.sTypoDescender);
                System.out.println ("usWinAscent = " + os2.usWinAscent);
                System.out.println ("usWinDescent = " + os2.usWinDescent);
                System.out.println ("sxHeight = " + os2.sxHeight);
                System.out.println ("sCapHeight = " + os2.sCapHeight);
                System.out.println ("yStrikeoutPosition = " + os2.yStrikeoutPosition);
                break;
              case 'c' : // list cmap
                int platform = Integer.parseInt (args [arg++]);
                int encoding = Integer.parseInt (args [arg++]);
                int language = Integer.parseInt (args [arg++]);
                cmap = (CMap) file.getTable (CMAP);
                subtable = cmap.getTable (platform,encoding,language);
                subtable.printTo (System.out);
                break;
              case 'e' : // import charstring from another CFF file
                fontSet = new CFFFontSet
                  (Util.toByteArray (file.getTable (CFF)));
                font = fontSet.getOnlyFont ();
                CFFFontSet other = new CFFFontSet (args [arg++]);
                CFFFont otherFont = other.getOnlyFont ();
                byte [] charstr = otherFont.getCharString (Integer.parseInt (args [arg++]));
                font.setCharString (Integer.parseInt (args [arg++]),charstr);
                file.addTable (new GenericTable (CFF,fontSet.toByteArray ()));
                break;
              case 'i' : // import cff file
                file.addTable (new GenericTable (CFF,Util.undump (args [arg++])));
                break;
              case 'l' : // dump tables
                Iterator idIterator = file.getIDs ().iterator ();
                while (idIterator.hasNext ())
                  {
                    String id = (String) idIterator.next ();
                    if (id.indexOf ('/') == -1)
                      Util.dump (file.getRawData (id),id + ".dmp");
                  }
                break;
              case 'm' : // modify cmap
                char code = args [arg++].charAt (0);
                int index = Integer.parseInt (args [arg++]);
                ByteEncodingTable byteTable = new ByteEncodingTable (subtable);
                byteTable.map (code,index);
                SegmentMappingTable segmentTable = new SegmentMappingTable (byteTable);
                cmap.addEntry (segmentTable);
                break;
              case 'n' : // new cmap with only one entry
                ByteEncodingTable emptyTable = new ByteEncodingTable (0,3,0);
                emptyTable.map ('N',49);
                cmap.addEntry (new SegmentMappingTable (emptyTable));
                break;
              case 'p' : // peek at table
                file.getTable (args [arg++]);
                break;
              case 'q' : // peek and dump
                String which = args [arg++];
                Util.dump (file.getRawData (which),which + ".dmp");
                SFNTTable table = file.getTable (which);
                Util.dump (table,which + ".out");
                break;
              case 'r' : // replace cmap table
                SFNTFile cmapFile = new SFNTFile (args [arg++]);
                file.addTable (cmapFile.getTable (CMAP));
                break;
              case 's' : // byte table morph
                SFNTFile morphFile = new SFNTFile (args [arg++]);
                CMap morphMap = (CMap) morphFile.getTable (CMAP);
                CMapTable morphTable = morphMap.getTable (0,3,0);
                ByteEncodingTable newTable = new ByteEncodingTable (subtable);
                for (char i = 1;i < 256;i++)
                  {
                    newTable.map (i,morphTable.getGlyphIndex (i));
                    cmap.addEntry (new SegmentMappingTable (newTable));
                    Util.dump (file,"morph" + ((int) i) + ".cef");
                  }
                break;
              case 'x' : // extract table
                String id = args [arg++];
                String dump = args [arg++];
                Util.dump (file.getRawData (id),dump);
                break;
              default :
                throw new Error ("option " + args [arg-1].charAt (1));
              }
          }
      }
    if (arg != args.length)
      Util.dump (file,args [arg]);
  }

  ByteCodeInterpreter byteCodeInterpreter;

  public GlyphProvider getGlyphProvider (Object glyphSelector)
  {
    if (byteCodeInterpreter == null)
      byteCodeInterpreter = new ByteCodeInterpreter (this);
    ((GlyphTable) getTable (GLYF)).getOutline (((Integer) glyphSelector).intValue ()).
      interpret (byteCodeInterpreter);
    return byteCodeInterpreter;
  }
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vortex.tasks;

import java.io.Serializable;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.Map.Entry;
import sandbox.clustering.Datapoint;
import sandbox.clustering.Dataset;
import util.MatrixOp;
import util.logger;

/**
 *
 * @author Nikolay
 */
public class GabrielNeighborTaskAngular {

    private static final long serialVersionUID = 1L;
    private int centerID;
    private Dataset ds;
    //private int instanceNum;
    private final double searchDistLimit = -1;
    private int NNNtoAdd = 0;
    double trim_alpha = 0;

    boolean NNNfilter=true;

    public class NeighborInfo implements Serializable {

        private static final long serialVersionUID = 1L;
        public int[] gabrielNeighbors;
        public int[] sortedDatapointIDs;
    }

    public void cancel() {
        Thread.currentThread().interrupt();
    }
    /*
     * Returns the set of IDs of gabriel neighbors of sortedUnityLenArrayLists[0] in the array of sortedUnityLenArrayLists
     * localObjects - NDataset;
     */

    public GabrielNeighborTaskAngular(int dpID, int instanceNum, int NNNtoAdd) {
        centerID = dpID;
        //this.instanceNum = instanceNum;
        this.NNNtoAdd = 0;// NNNtoAdd;        this.NNNtoAdd = 0;// NNNtoAdd;

    }

    public void injectReusableObject(Object localObjects) {
        ds = (Dataset) localObjects;
    }

    public int[] execute() {
        double[] mid;
        double[] center = null;

        Datapoint[] dp = Arrays.copyOf(ds.getDatapoints(), ds.getDatapoints().length);
        //NNNtoAdd = ds.getDimension()*2;
        ArrayList<Datapoint> neighbors = new ArrayList<>();

        for (Datapoint d : dp) {
            if (d.getID() == centerID) {
                center = d.getUnityLengthVector();
            }
        }

        ArrayList<Entry<Datapoint, Double>> sorted = new ArrayList<>();

        for (Datapoint d : dp) {
            double correl = Math.min(1.0, MatrixOp.mult(center, d.getUnityLengthVector()));
            if (correl > searchDistLimit && correl < 1.0 - 1E-10) {
                sorted.add(new SimpleEntry<>(d, correl));
            }
        }

        Collections.sort(sorted, new Comparator<Entry<Datapoint, Double>>() {
            @Override
            public int compare(Entry<Datapoint, Double> o1, Entry<Datapoint, Double> o2) {
                return (int) Math.signum(o2.getValue() - o1.getValue());
            }
        });

        int maxIdx = Math.min(ds.getNumDimensions() * 25, sorted.size());

        dp = new Datapoint[maxIdx];
        for (int i = 0; i < dp.length; i++) {
            dp[i] = sorted.get(i).getKey();
        }

        for (int y = 0; y < maxIdx; y++) {
            boolean YisNeighbor = true;
            if (y < NNNtoAdd) {
                neighbors.add(dp[y]);
                continue;
            } else {
                //   if(true)break;
            }
            /*
             if(y >= NNNtoAdd){
             break;
             }*/

            Datapoint anotherDP = dp[y];
            Datapoint testedDP;
            Datapoint nnOfTheMid = null;

            double[] anotherArrayList = anotherDP.getUnityLengthVector();

            mid = MatrixOp.toUnityLen(MatrixOp.sum(center, anotherArrayList));

            double cosBetween = Math.min(1.0, Math.min(MatrixOp.mult(mid, center), MatrixOp.mult(mid, anotherArrayList)));
//            assert MatrixOp.mult(mid, center) == Kernel.getEuclideanCosine(new DenseDoubleMatrix1D(mid), new DenseDoubleMatrix1D(center));
            double testedCosToMid = 0;
            double nnCosToMid = -1;
            for (int i = 0; i < maxIdx + neighbors.size(); i++) {
                if (i < neighbors.size()) {
                    testedDP = neighbors.get(i);
                } else {
                    testedDP = dp[i - neighbors.size()];
                }
                if (testedDP.equals(anotherDP)) {
                    continue;
                }
                testedCosToMid = Math.min(1.0, MatrixOp.mult(mid, testedDP.getUnityLengthVector()));
                if (testedCosToMid > nnCosToMid) {
                    nnOfTheMid = testedDP;
                    nnCosToMid = testedCosToMid;
                    if (testedCosToMid > cosBetween) {
                        YisNeighbor = false;
                        break;
                    }
                }
            }

            if (YisNeighbor && nnOfTheMid != null && trim_alpha > 0.000001) {
                //double angToMid = 0;
                double a, b, c;
                int dim = ds.getNumDimensions();
                int j;
                double[] midShiftedToNN = new double[dim];
                //double shiftVecLen, tga, cosBeta, shift;
                //shift = (Math.acos(cosBetween) / 10.0);
                //weight = shift/angToMid;
                //double trim_alpha = 0.000;
                //tga = Math.tan(shift);
                //cosBeta = Math.cos(angToMid);

                //double[] shiftVec = new double[dim];

                //for (j = 0; j < dim; j++) {
                //    shiftVec[j] = nnOfTheMid.getUnityLengthVector()[j] - mid[j] * cosBeta;
                // }

                //  shiftVecLen = MatrixOp.lenght(shiftVec);

                for (j = 0; j < dim; j++) {
                    midShiftedToNN[j] = (mid[j] * (1 - trim_alpha)) + (nnOfTheMid.getUnityLengthVector()[j] * trim_alpha); //(tga * shiftVec[j]) / shiftVecLen;
                }

                c = Math.min(1.0, MatrixOp.mult(nnOfTheMid.getUnityLengthVector(), midShiftedToNN));
                a = Math.min(1.0, MatrixOp.mult(center, midShiftedToNN));// lenShifted;
                b = Math.min(1.0, MatrixOp.mult(anotherArrayList, midShiftedToNN));

                if (c > a || c > b) {
                    YisNeighbor = false;
                }
            }
            if (YisNeighbor) {
                neighbors.add(dp[y]);
            }
        }

        if (neighbors.isEmpty()) {
            logger.print("Zero neighbors!!" + centerID);
        }

        /*
         for (int i = 0; i < ds.getDimension()/2; i++) {
         filtered.add(dp[i]);
         }*/
        if (NNNfilter) {
            LinkedList<Datapoint> filtered = new LinkedList<>();
            for (int i = 0; i < Math.min(neighbors.size() + 1, dp.length); i++) {
                if (neighbors.contains(dp[i])) {
                    filtered.add(dp[i]);
                }
            }
            neighbors.clear();
            neighbors.addAll(filtered);
        }
        if (neighbors.isEmpty()) {
            logger.print("Zero neighbors!!" + centerID, neighbors.size());
        }

        //logger.print("GabrielNeighborTaskAngular ended, found " + filtered.size() + " neighbors");
        int[] res = new int[neighbors.size()];
        for (int i = 0; i < neighbors.size(); i++) {
            res[i] = neighbors.get(i).getID();
        }
        return res;
    }
}


text:
namespace Eigen
{

template<unsigned int modular_exponent, unsigned int modular_decrement>
struct NumTraits<sonic_socket::IntModuloMersenne<modular_exponent, modular_decrement>>
{
    typedef sonic_socket::IntModuloMersenne<modular_exponent, modular_decrement> Real;
    typedef sonic_socket::IntModuloMersenne<modular_exponent, modular_decrement> Nested;

    enum {
        IsComplex = 0,
        IsInteger = 0,
        IsSigned = 0,
        RequireInitialization = 0,
        ReadCost = 1,
        AddCost = 2,
        MulCost = 3
    };
};

}

#endif // SONICSOCKET_EIGEN_H


text:
package org.jboss.arquillian.impl.client.container;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.logging.Logger;

import org.jboss.arquillian.impl.configuration.ContainerDefImpl;
import org.jboss.arquillian.impl.configuration.api.ArquillianDescriptor;
import org.jboss.arquillian.impl.configuration.api.ContainerDef;
import org.jboss.arquillian.impl.configuration.api.GroupDef;
import org.jboss.arquillian.impl.domain.ContainerRegistry;
import org.jboss.arquillian.spi.ServiceLoader;
import org.jboss.arquillian.spi.client.container.DeployableContainer;
import org.jboss.arquillian.spi.core.Instance;
import org.jboss.arquillian.spi.core.InstanceProducer;
import org.jboss.arquillian.spi.core.annotation.ApplicationScoped;
import org.jboss.arquillian.spi.core.annotation.Inject;
import org.jboss.arquillian.spi.core.annotation.Observes;

/**
 * ContainerRegistryCreator
 *
 * @author Aslak Knutsen
 * @version $Revision: $
 */
public class ContainerRegistryCreator
{
   private static final String ARQUILLIAN_LAUNCH_PROPERTY = "arquillian.launch";
   private static final String ARQUILLIAN_LAUNCH_DEFAULT = "arquillian.launch";

   private Logger log = Logger.getLogger(ContainerRegistryCreator.class.getName());

   @Inject @ApplicationScoped
   private InstanceProducer<ContainerRegistry> registry;

   @Inject
   private Instance<ServiceLoader> loader;

   public void createRegistry(@Observes ArquillianDescriptor event)
   {
      ContainerRegistry reg = new ContainerRegistry();
      ServiceLoader serviceLoader = loader.get();

      String activeConfiguration = getActivatedConfiguration();
      for(ContainerDef container : event.getContainers())
      {
         if(
               (activeConfiguration != null && activeConfiguration.equals(container.getContainerName())) ||
               (activeConfiguration == null && container.isDefault()))
         {
            reg.create(container, serviceLoader);
         }
      }
      if(activeConfiguration != null)
      {
         for(GroupDef group : event.getGroups())
         {
            if(activeConfiguration.equals(group.getGroupName()))
            {
               for(ContainerDef container : group.getGroupContainers())
               {
                  reg.create(container, serviceLoader);
               }
            }
         }
      }
      else if(reg.getContainers().size() == 0)
      {
         try
         {
            DeployableContainer<?> deployableContainer = serviceLoader.onlyOne(DeployableContainer.class);
            if(deployableContainer != null)
            {
               reg.create(new ContainerDefImpl("arquillian.xml").setContainerName("default"), serviceLoader);
            }
         }
         catch (Exception e)
         {
            // ignore
         }
      }

      // export
      registry.set(reg);
   }

   private String getActivatedConfiguration()
   {
      try
      {
         if(System.getProperty(ARQUILLIAN_LAUNCH_PROPERTY) != null)
         {
            return System.getProperty(ARQUILLIAN_LAUNCH_PROPERTY);
         }

         return readActivatedValue(
               new BufferedReader(
                     new InputStreamReader(
                           Thread.currentThread().getContextClassLoader().getResourceAsStream(ARQUILLIAN_LAUNCH_DEFAULT))));

      }
      catch (Exception e)
      {
         log.info("Could not read active container configuration: " + e.getMessage());
      }
      return null;
   }

   private String readActivatedValue(BufferedReader reader)
      throws Exception
   {
      String value;
      try
      {
         while( (value = reader.readLine()) != null)
         {
            if(value.startsWith("#"))
            {
               continue;
            }
            return value;
         }
      }
      finally
      {
         reader.close();
      }
      return null;
   }
}


text:
(function () {
  var ga = window.ga || function () {}
  var track = function (fields) {
    ga('send', fields)
  }

    // Page Tracking
    // track({
    //   hitType: 'pageview',
    //   page: window.location.pathname,
    //   title: document.title
    // })

    // Screen Tracking
  track({
    hitType: 'screenview',
    screenName: document.title
  })

  // User Timings
  // try {
  //   window.addEventListener('load', function () {
  //     var t = window.performance.timing
  //     setTimeout(function () {
  //       track({
  //         hitType: 'timing',
  //         timingCategory: 'All resources finished loading',
  //         timingVar: 'load',
  //         timingValue: t.loadEventEnd - t.navigationStart
  //       })
  //     }, 1000)
  //   })
  // } catch (e) {
  //   track({
  //     hitType: 'exception',
  //     exDescription: e.message,
  //     exFatal: false
  //   })
  // }
}())


text:
@interface LJLrcView : DRNRealTimeBlurView

@property(nonatomic,copy)NSString *lrcname;

@property (nonatomic, assign) NSTimeInterval currentTime;

@end


text:
require 'rspec/expectations'

Gurke.configure do |c|
  c.include RSpec::Matchers
end


text:
[![Code Climate](https://codeclimate.com/github/rafaelcamargo/ng-surprise/badges/gpa.svg)](https://codeclimate.com/github/rafaelcamargo/ng-surprise)
[![Test Coverage](https://codeclimate.com/github/rafaelcamargo/ng-surprise/badges/coverage.svg)](https://codeclimate.com/github/rafaelcamargo/ng-surprise/coverage)
[![Build Status](https://travis-ci.org/rafaelcamargo/ng-surprise.svg?branch=master)](https://travis-ci.org/rafaelcamargo/ng-surprise)

This is a AngularJS module to put Easter eggs in your application. Sometimes you need an Easter egg to allow your dev staff to skip some *configuration step* or close an *uncloseable* modal in your app. So, ng-surprise is an easy way to do that.

## Demo
You can see ng-surprise in action on http://rafaelcamargo.github.io/ng-surprise

## Installation
```
npm install ng-surprise --save
```
Once `ng-surprise` dependency is installed, declare the *ngSurprise* module as your app dependency:
```javascript
var app = angular.module('App', ['ngSurprise']);
```

## Usage
Wherever in your application, you can inform an **action** and a **trigger** to be performed:
```html
<div data-surprise="showSomething" data-surprise-trigger="38,38,38,37"></div>
```

### Action
Should be a function in your scope:
```javascript
$scope.showSomething = function(){
  alert('Gotcha!');
};
```

### Trigger
Should be a sequence of keycodes to be performed by the user. It's not an Array. It should be necessarily a String with keycodes separeted by comma with no spaces between them. The event attribute responsible to inform which code user has performed is `keydown`. You can easily discover the keycodes you want to use as your trigger on the following page: http://www.w3.org/2002/09/tests/keys.html

## Release History
- 2017/05/20 **v0.3.0** : Removed bower.json and locked angular on version 1.4.9
- 2015/08/09 **v0.2.0** : Unit tests added
- 2015/07/29 **v0.1.0** : Initial release *tests still in progress*


text:
<?php

namespace RenatoMarinho\LaravelPageSpeed\Test;

use RenatoMarinho\LaravelPageSpeed\ServiceProvider;
use Orchestra\Testbench\TestCase as Orchestra;

abstract class TestDisabledMiddlewareCase extends Orchestra
{
    protected function getPackageProviders($app)
    {
        return [ServiceProvider::class];
    }
}


text:
using namespace std;

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        int overflow = 0;

        if(digits.empty()) {
            digits.push_back(0);
            return digits;
        }

        int last_pos = digits.size() - 1;
        int value = digits[last_pos]+1;
        overflow = value/10;
        digits[last_pos] = value % 10;

        for(int i = digits.size()-2; i>=0; i--) {
            value = digits[i] + overflow;
            digits[i] = value % 10;
            overflow = value / 10;
        }
        if (overflow != 0) digits.insert(digits.begin(), overflow);

        return digits;
    }
};


text:
#include "signal/sigset/sigset_agent.h"

#include <stdio.h>
#include <errno.h>

/********************************************************************/
/**                         Agent Commands                         **/
/********************************************************************/

static TACommandVerdict sigaddset_cmd(TAThread thread,TAInputStream stream)
{
    // Prepare
    sigset_t* set;
    int signo, res;
    errno = 0;

    set = (sigset_t*) readPointer(&stream);
    signo = readInt(&stream);

    START_TARGET_OPERATION(thread);

    // Execute
    res = sigaddset(set, signo);

    END_TARGET_OPERATION(thread);

    // Response
    writeInt(thread, res);
    writeInt(thread, errno);
    sendResponse(thread);

    return taDefaultVerdict;
}

static TACommandVerdict sigandset_cmd(TAThread thread,TAInputStream stream)
{
    // Prepare
    sigset_t* set,* left,* right;
    int res;
    errno = 0;

    set = (sigset_t*) readPointer(&stream);
    left = (sigset_t*) readPointer(&stream);
    right = (sigset_t*) readPointer(&stream);

    START_TARGET_OPERATION(thread);

    // Execute
    res = sigandset(set, left, right);

    // Response
    END_TARGET_OPERATION(thread);

    writeInt(thread, res);
    writeInt(thread, errno);
    sendResponse(thread);

    return taDefaultVerdict;
}

static TACommandVerdict sigdelset_cmd(TAThread thread,TAInputStream stream)
{
    // Prepare
    sigset_t* set;
    int signo, res;
    errno = 0;

    set = (sigset_t*) readPointer(&stream);
    signo = readInt(&stream);

    START_TARGET_OPERATION(thread);

    // Execute
    res = sigdelset(set, signo);

    END_TARGET_OPERATION(thread);

    // Response
    writeInt(thread, res);
    writeInt(thread, errno);
    sendResponse(thread);

    return taDefaultVerdict;
}

static TACommandVerdict sigemptyset_cmd(TAThread thread,TAInputStream stream)
{
    // Prepare
    sigset_t* set;
    int res;
    errno = 0;

    set = (sigset_t*) readPointer(&stream);

    START_TARGET_OPERATION(thread);

    // Execute
    res = sigemptyset(set);

    END_TARGET_OPERATION(thread);

    // Response
    writeInt(thread, res);
    writeInt(thread, errno);
    sendResponse(thread);

    return taDefaultVerdict;
}

static TACommandVerdict sigfillset_cmd(TAThread thread,TAInputStream stream)
{

    // Prepare
    sigset_t* set;
    int res;
    errno = 0;

    set = (sigset_t*) readPointer(&stream);

    START_TARGET_OPERATION(thread);

    // Execute
    res = sigfillset(set);

    END_TARGET_OPERATION(thread);

    // Response
    writeInt(thread, res);
    writeInt(thread, errno);
    sendResponse(thread);

    return taDefaultVerdict;

    return taDefaultVerdict;
}

static TACommandVerdict sigisemptyset_cmd(TAThread thread,TAInputStream stream)
{
    // Prepare
    sigset_t* set;
    int res;
    errno = 0;

    set = (sigset_t*) readPointer(&stream);

    START_TARGET_OPERATION(thread);

    // Execute
    res = sigisemptyset(set);

    END_TARGET_OPERATION(thread);

    // Response
    writeInt(thread, res);
    writeInt(thread, errno);
    sendResponse(thread);

    return taDefaultVerdict;
}

static TACommandVerdict sigismember_cmd(TAThread thread,TAInputStream stream)
{
    // Prepare
    sigset_t* set;
    int res, signo;
    errno = 0;

    set = (sigset_t*) readPointer(&stream);
    signo = readInt(&stream);

    START_TARGET_OPERATION(thread);

    // Execute
    res = sigismember(set, signo);

    END_TARGET_OPERATION(thread);

    // Response
    writeInt(thread, res);
    writeInt(thread, errno);
    sendResponse(thread);

    return taDefaultVerdict;
}

static TACommandVerdict sigorset_cmd(TAThread thread,TAInputStream stream)
{
    // Prepare
    sigset_t* set,* left,* right;
    int res;
    errno = 0;

    set = (sigset_t*) readPointer(&stream);
    left = (sigset_t*) readPointer(&stream);
    right = (sigset_t*) readPointer(&stream);

    START_TARGET_OPERATION(thread);

    // Execute
    res = sigorset(set, left, right);

    END_TARGET_OPERATION(thread);

    // Response
    writeInt(thread, res);
    writeInt(thread, errno);
    sendResponse(thread);

    return taDefaultVerdict;
}

/*
static TACommandVerdict get_SIGRT_const_cmd(TAThread thread,TAInputStream stream)
{
    // Prepare
    int min, max;

    START_TARGET_OPERATION(thread);

    // Execute
    min = __libc_current_sigrtmin();
    max = __libc_current_sigrtmax();

    END_TARGET_OPERATION(thread);

    writeInt(thread, min);
    writeInt(thread, max);
    sendResponse(thread);
}*/

/********************************************************************/
/**                      Agent Initialization                      **/
/********************************************************************/
void register_signal_sigset_commands(void)
{
    ta_register_command("sigaddset",sigaddset_cmd);
    ta_register_command("sigandset",sigandset_cmd);
    ta_register_command("sigdelset",sigdelset_cmd);
    ta_register_command("sigemptyset",sigemptyset_cmd);
    ta_register_command("sigfillset",sigfillset_cmd);
    ta_register_command("sigisemptyset",sigisemptyset_cmd);
    ta_register_command("sigismember",sigismember_cmd);
    ta_register_command("sigorset",sigorset_cmd);
//    ta_register_command("get_SIGRT_const", get_SIGRT_const_cmd);
}


text:
package com.trunk.rx.json.element;

import rx.Observable;

public class JsonNull extends JsonElement {

  private static final class Holder {
    private static final JsonNull INSTANCE = new JsonNull();
  }

  public static JsonNull instance() {
    return Holder.INSTANCE;
  }

  public JsonNull() {
    super(Observable.just(com.trunk.rx.json.token.JsonNull.instance()));
  }
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/divide"
    android:orientation="vertical"
    tools:context="net.coding.program.project.detail.file.ShareFileLinkActivity">

    <include layout="@layout/divide_top_15" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="@dimen/padding_12"
        android:text="该链接适用于所有人,无需登录。"
        android:textColor="@color/font_3"
        android:textSize="15sp" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/list_item_selector"
        android:minHeight="50dp"
        android:paddingLeft="@dimen/padding_12"
        android:paddingRight="@dimen/padding_12">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:text="共享链接"
            android:textColor="@color/font_1"
            android:textSize="15sp" />

        <android.support.v7.widget.SwitchCompat
            android:id="@+id/clickSettingShare"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            app:theme="@style/Widget_Switch"
            android:buttonTint="@color/font_green"
            app:colorControlActivated="@color/font_green" />

    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/layoutShareLink"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/list_item_selector"
        android:minHeight="50dp"
        android:paddingLeft="@dimen/padding_12"
        android:paddingRight="@dimen/padding_12">

        <include layout="@layout/divide_line_1" />

        <TextView
            android:id="@+id/linkContent"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginRight="60dp"
            android:ellipsize="end"
            android:lines="1"
            android:text="linkContent"
            android:textColor="@color/font_1"
            android:textSize="15sp" />

        <TextView
            android:id="@+id/clickShareLink"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:background="@drawable/round_rect_shape_green2"
            android:button="@null"
            android:paddingBottom="6dp"
            android:paddingLeft="9dp"
            android:paddingRight="9dp"
            android:paddingTop="6dp"
            android:text="拷贝"
            android:textColor="@color/white"
            android:textSize="14sp" />

    </RelativeLayout>

    <include layout="@layout/divide_bottom_15" />

</LinearLayout>


text:
<img src="https://wezro.com/syntax/syntaxfile.png" width="30%" align="right">
Syntax is an in-development command-line utility to make writing CSS easier. Syntax is written in Python and is designed for speed and ease of use. Syntax is planned to have: variables, functions, nested elements, and uses an indented syntax similar to Python. Currently it is not suggested to use Syntax as a replacement to the preprocessor you are using right now, as it is missing some key features such as functions and calculations, though feedback and testing is appreciated.

##Usage

To use Syntax, you first need to tell Syntax what directory to use. To do this, type `dir [directory]`.

After this, you can start listening for changes in that directory, type `watch`. Then Syntax will now start looking for .syn/.syntax files, and will create or modify their CSS counterparts.

##Example File

```
@myVariable: 10%

body
  padding: @myVariable
  p
    font-size: @myVariable
```


text:
'use strict';

var spawn = require('child_process').spawn,
    os = require('os'),
    Q = require('q');

function isWindows () {
    return os.platform().indexOf('win') === 0;
}

function run (command, args, options) {
    var deferred = Q.defer(),
        npmFailure = false,
        proc;

    if (isWindows()) {
        // spawn on Windows requires an exe
        args.unshift(command);
        args.unshift('/c');
        command = 'cmd.exe';
    }

    proc = spawn(command, args, options);

    proc.stdout.on('data', function (data) {
        console.log(data.toString('utf8').trim());
    });

    proc.stderr.on('data', function (data) {
        console.error(data.toString('utf8').trim());
        if (data.toString('utf8').indexOf('npm ERR!') >= 0) {
            // Hack; dpl returns 0 exit code on npm publish failure
            npmFailure = true;
        }
    });

    proc.on('close', function (exitCode) {
        if (exitCode === 0 && !npmFailure) {
            deferred.resolve();
        }
        else {
            deferred.reject(npmFailure ? 1 : exitCode);
        }
    });

    return deferred.promise;
}

module.exports = {
    run: run
};


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Puccinia aecidii-trientalis Tranzschel

### Remarks
null


text:
<?php

	/**
	 * This exception extends the PHP Exception class and should be thrown when a query fails so
	 * that a developer can properly handle that exception.
	 *
	 * See http://www.php.net/Exception for more information.
	 */
	class QueryFailedException extends Exception
	{

	} // QueryFailedException()

?>


text:
<?php

declare(strict_types=1);

namespace Hostnet\Component\EntityPlugin;

use Composer\Composer;
use Composer\Config;
use Composer\Downloader\DownloadManager;
use Composer\EventDispatcher\EventDispatcher;
use Composer\IO\NullIO;
use Composer\Package\RootPackage;
use Composer\Repository\InstalledArrayRepository;
use Composer\Repository\RepositoryManager;
use Composer\Util\HttpDownloader;
use Hostnet\Component\EntityPlugin\Mock\Installer as MockInstaller;
use phpunit\framework\TestCase;
use Prophecy\PhpUnit\ProphecyTrait;

/**
 * @covers \Hostnet\Component\EntityPlugin\Installer
 * @covers \Hostnet\Component\EntityPlugin\Installer
 */
class InstallerTest extends TestCase
{
    use ProphecyTrait;

    private $working_dir;

    protected function setUp(): void
    {
        $this->working_dir = __DIR__ . '/..';
    }

    public function testGetInstallPath(): void
    {
        $empty                = $this->prophesize('Hostnet\Component\EntityPlugin\EmptyGenerator')->reveal();
        $reflection_generator = $this->prophesize(ReflectionGenerator::class)->reveal();
        $installer            = new Installer(
            $this->mockIO(),
            $this->mockComposer(),
            [],
            $empty,
            $reflection_generator
        );

        $root_package = new RootPackage('hostnet/root-package', '1', '1');
        $this->assertEquals('.', $installer->getInstallPath($root_package));

        $installer = new MockInstaller($this->mockIO(), $this->mockComposer(), [], $empty, $reflection_generator);

        $package = $this->createMock('Composer\Package\PackageInterface');
        $package->expects($this->once())->method('getPrettyName')->will($this->returnValue('prettyName'));
        $this->assertEquals($this->working_dir . '/vendor/prettyName', $installer->getInstallPath($package));
        $this->assertEquals(1, $installer->initialize_vendor_dir_called);
    }

    public function testGetSourcePath(): void
    {
        $empty                = $this->prophesize('Hostnet\Component\EntityPlugin\EmptyGenerator')->reveal();
        $reflection_generator = $this->prophesize(ReflectionGenerator::class)->reveal();
        $installer            = new Installer(
            $this->mockIO(),
            $this->mockComposer(),
            [],
            $empty,
            $reflection_generator
        );

        $root_package = new RootPackage('hostnet/root-package', '1', '1');
        $this->assertEquals('./src', $installer->getSourcePath($root_package));
        $root_package->setExtra(['entity-bundle-dir' => 'src/Hostnet/FooBundle']);

        $this->assertEquals('./src/Hostnet/FooBundle', $installer->getSourcePath($root_package));
    }

    private function mockComposer(): Composer
    {
        $composer = new Composer();
        $composer->setPackage(new RootPackage('hostnet/root-package', '1', '1'));
        $composer->setConfig($this->mockConfig());
        $composer->setRepositoryManager($this->mockRepositoryManager());
        $composer->setEventDispatcher(new EventDispatcher($composer, $this->mockIO()));
        $composer->setDownloadManager($this->prophesize(DownloadManager::class)->reveal());

        return $composer;
    }

    private function mockRepositoryManager(): RepositoryManager
    {
        $config             = $this->mockConfig();
        $io                 = $this->mockIO();
        $http_downloader    = new HttpDownloader($io, $config);
        $repository_manager = new RepositoryManager($io, $config, $http_downloader);
        $repository_manager->setLocalRepository(new InstalledArrayRepository());

        return $repository_manager;
    }

    private function mockIO(): NullIO
    {
        return new NullIO();
    }

    private function mockConfig(): Config
    {
        return new Config(true, $this->working_dir);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <dimen name="shortcut_item_padding">4px</dimen>
    <dimen name="bar_width">72px</dimen>
    <dimen name="image_padding_left_right">8px</dimen>
    <dimen name="image_width_height">64px</dimen>
    <dimen name="footer_height">72px</dimen>
    <dimen name="footer_button_margin_left_right">8px</dimen>
    <dimen name="footer_button_margin_top_bottom">6px</dimen>
    <dimen name="image_button_width">60px</dimen>
    <dimen name="image_button_height">60px</dimen>
    <dimen name="list_item_image_margin_top_bottom">10px</dimen>
    <dimen name="list_item_padding_right">15px</dimen>
    <dimen name="list_item_padding_left">12px</dimen>
    <dimen name="changelog_padding_left_right">20dp</dimen>
    <dimen name="changelog_padding_top">3dp</dimen>
    <dimen name="changelog_padding_bottom">5dp</dimen>
</resources>


text:
/*
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
*/
/*
    Created on : 14/04/2017, 13:31:47
    Author     : VAIO
*/

.bgVentana{
    background-color: rgba(20,15,15,0.4);
    width: 100%;
    height: 100%;
    position: absolute;
    margin: 0px;
    padding-top: 2%;
    display: none;
}

.ventana{
    background-color: white;
    border-radius: 3px;
    padding: 15px;
    text-align: center;
    color: black;
    width: 40%;
    height: auto;
    margin: 0 auto;
    position: static;
}

.Search{
    background-color: rgba(255,255,255,0.3);
    padding-left: 10px;
    color: white;
    height: 28px;
    width: 350px;
    border: none;
    border-radius: 2px;
    font-family: normal;
}

.Search:focus{
    background-color: white;
    color: rgb(100,100,100);
}

.Submit{
    width: 80px;
    height: 30px;
    padding: 2px;;
    border-radius: 2px;
    background-color: #ff2533;
    border: none;
    margin-left: 5px;
    color: white;
    font-family: normal;
}

.Submit:active{
    background-color: #d11f2a;
}

.Submit:hover{
    background-color: #d11f2a;
    cursor: pointer;
}


text:
package com.aj.partner;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.Logger;

/*
 * Utility class for Webservice
 */
public class WebserviceUtility {

	private static final Logger logger = (Logger) LogManager.getLogger(WebserviceUtility.class.getName());

	// Converts 15 char salesforce id to 18 char id
	  static String convertto18CharId(String original15charId){

	    if(original15charId == null || original15charId.isEmpty()) return null;
	    original15charId = original15charId.trim();
	    if(original15charId.length() != 15) return null;

	    final String BASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456";
	    StringBuilder result = new StringBuilder();

	    try {
	        for(int i = 0; i < 3; i++){
	            StringBuilder tempString = new StringBuilder(original15charId.substring(i*5, i*5+5));
	            tempString.reverse();
	            String binary = "";
	            for(char ch: tempString.toString().toCharArray()) {
	                binary += Character.isUpperCase(ch) ? '1' : '0';
	            }
	            result.append(BASE.charAt(Integer.parseInt(binary,2)));
	        }
	    } catch(Exception ex) {
	          ex.printStackTrace();
	    }

	    if(result.length() == 0) return null;

	    return original15charId + result.toString();

	  }

}


text:
/*
 *   NOTE: this node.js has nothing to do with server-side Node.js
 */

( function (Dataflow) {

    var Node = Dataflow.prototype.module("node");

    // Dependencies
    var Input = Dataflow.prototype.module("input");
    var Output = Dataflow.prototype.module("output");

    Node.Model = Backbone.Model.extend({
        defaults: function () {
            return {
                label: "",
                description: "",
                icon: "",
                type: "test",
                resultTypes: "",
                x: 200,
                y: 100,
                state: {},
                selected: false
            };
        },
        getIcon: function () {
            if (this.get('icon')) {
                return this.get('icon');
            }
            // console.log(this)
            var node = this.parentGraph.dataflow.node(this.get('type'));

            if (!node || !node.icon) {
                return '';
            }
            return node.icon;
        },
        initialize: function () {
            this.parentGraph = this.get("parentGraph");
            this.type = this.get("type");

            // here we parse the resultType from the options
            this.resultTypes = this.get("resultTypes");

            var self = this;
            // this.set("selected", true)
            // self.selected = this.get("selected");

            // Default label to type
            if (this.get("label") === "") {
                this.set({
                    "label": this.get("type")
                });
            }

            // Convert inputs array to backbone collection
            var inputArray = this.inputs;
            this.inputs = new Input.Collection();
            this.inputs.parentNode = this;
            for (var i = 0; i < inputArray.length; i++) {
                var input = inputArray[i];

                // Save defaults to state
                var state = this.get("state");
                if (input.value !== undefined && state[input.id] === undefined) {
                    state[input.id] = input.value;
                }

                input.parentNode = this;
                input = new Input.Model(input);
                this.inputs.add(input);
            }

            // Convert outputs array to backbone collection
            var outputArray = this.outputs;
            this.outputs = new Output.Collection();
            this.outputs.parentNode = this;
            for (i = 0; i < outputArray.length; i++) {
                var output = outputArray[i];
                output.parentNode = this;
                output = new Output.Model(output);
                this.outputs.add(output);
            }

            // Selection event
            this.on("change:selected", this.changeSelected, this);
        },
        changeSelected: function () {
            if (this.get("selected")) {
                this.parentGraph.trigger("select:node", this);
            }
        },
        setState: function (name, value) {
            var state = this.get("state");
            if (state[name] === value) {
                return;
            }
            state[name] = value;
            if (this["input" + name]) {
                this["input" + name](value, this, name);
            }
            _.defer(function () {
                UIListener().updateFieldValue(name, value);
            });
            this.trigger("change:state", name, value); //TODO: design this
        },
        setBang: function (name) {
            if (this["input" + name]) {
                this["input" + name]("bang", this);
            }
            this.trigger("bang", name);
        },
        send: function (name, value) {
            // This isn't the only way that values are sent, see github.com/forresto/dataflow-webaudio
            // Values sent here will not be `set()` on the recieving node
            // The listener is set up in Edge/initialize

            // To make this synchronous
            // this.trigger("send:"+name, value);

            // Otherwise, to make this safe for infinite loops
            var self = this;
            _.defer(function () {
                self.trigger("send:" + name, value);
            });
        },
        recieve: function (name, value, port) {
            //console.log("recieve",name,value,this)
            // The listener is set up in Edge/initialize
            if (typeof this["input" + name] === "function") {
                this["input" + name](value, this, port);
            } else {
                this["_" + name] = value;
            }
        },
        remove: function () {
            // Node removed from graph's nodes collection
            this.inputs.each(function (input) {
                input.remove();
            });
            this.outputs.each(function (output) {
                output.remove();
            });
            this.unload();
            this.collection.remove(this);
            this.trigger('remove');
        },
        unload: function () {
            // Stop any processes that need to be stopped
        },
        toString: function () {
            return this.id + " (" + this.type + ")";
        },
        toJSON: function () {
            return {
                id: this.get("id"),
                label: this.get("label"),
                resultTypes: this.get("resultTypes"),
                type: this.get("type"),
                x: this.get("x"),
                y: this.get("y"),
                state: this.get("state")
            };
        },
        inputs: [
            // {
            //   id: "input",
            //   type: "all"
            // }
        ],
        outputs: [
            // {
            //   id:"output",
            //   type: "all"
            // }
        ]
    });

    Node.Collection = Backbone.Collection.extend({
        model: Node.Model,
        comparator: function (node) {
            // Sort nodes by x position
            return node.get("x");
        }
    });

}(Dataflow) );


text:
<?php

class Renderobject {

	var $is_cached = false;
	var $error_message = "";
	var $results = null;
	var $page = 1;
    var $number_of_pages = 0;
    var $number_of_results = 0;

    var $query_type = 0;
	var $title = 'Results';

    var $datapoints = [];
    var $columns = [];
    var $is_series_list = false; // TODO switch to enum
    var $start_pagination = 1;
    var $end_pagination = 1;
    var $timestamp_column = -1;
    var $timestamp = 0;

    /**
We need this data in the template and setting it here makes the access easiest. We cannot set these data in the class definition because
it must not contain runtime dependant variables in the member initialization. See here:
*/
    public function __construct()
    {
        $this->user = $_SESSION['user'];
        $this->host = $_SESSION['host'];
        $this->database = $_SESSION['database'];
        $this->viewerversion = VERSION;
    }
}
?>


text:
<!--
  ~ Copyright 2016 Red Hat, Inc. and/or its affiliates
  ~ and other contributors as indicated by the @author tags.
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~ http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<section id="social-spi">
    <title>Social Provider SPI</title>
    <para>
        Keycloak provides an SPI to make it easy to add additional social providers. This is done by implementing
        <literal>org.keycloak.social.SocialProvider</literal> in <literal>social/core</literal>
        and adding a provider configuration file (<literal>META-INF/services/org.keycloak.social.SocialProvider</literal>).
    </para>
    <para>
        A good reference for implementing a Social Provider is the Google provider which you can find in <literal>social/google</literal>
        on GitHub or in the source download.
    </para>
</section>