text:
This module implements raw sockets for [Node.js][nodejs].

*This module has been created primarily to facilitate implementation of the
[net-ping][net-ping] module.*

This module is installed using [node package manager (npm)][npm]:

    # This module contains C++ source code which will be compiled
    # during installation using node-gyp.  A suitable build chain
    # must be configured before installation.

    npm install raw-socket

It is loaded using the `require()` function:

    var raw = require ("raw-socket");

Raw sockets can then be created, and data sent using [Node.js][nodejs]
`Buffer` objects:

    var socket = raw.createSocket ({protocol: raw.Protocol.None});

    socket.on ("message", function (buffer, source) {
        console.log ("received " + buffer.length + " bytes from " + source);
    });

    socket.send (buffer, 0, buffer.length, "1.1.1.1", function (error, bytes) {
        if (error)
            console.log (error.toString ());
    });

[nodejs]: http://nodejs.org "Node.js"
[net-ping]: https://npmjs.org/package/net-ping "net-ping"
[npm]: https://npmjs.org/ "npm"

# Network Protocol Support

The raw sockets exposed by this module support IPv4 and IPv6.

Raw sockets are created using the operating systems `socket()` function, and
the socket type `SOCK_RAW` specified.

# Raw Socket Behaviour

Raw sockets behave in different ways depending on operating system and
version, and may support different socket options.

Some operating system versions may restrict the use of raw sockets to
privileged users.  If this is the case an exception will be thrown on socket
creation using a message similar to `Operation not permitted` (this message
is likely to be different depending on operating system version).

For MAC OS X platforms, when raw socket creation fails, this module will
re-attempt to create a socket using the `SOCK_DGRAM` socket type for when the
protocol specified is `IPPROTO_ICMP` before throwing an exception.  This
interface on the MAC OS X platform provides non-privileged users access to the
ICMP protocol without requiring root-level access.  More information on this
subject can be found in the MAC OS X [documentation][mac-osx-icmp-ref].

[mac-osx-icmp-ref]: https://developer.apple.com/library/mac/documentation/Darwin/Reference/Manpages/man4/icmp.4.html

The appropriate operating system documentation should be consulted to
understand how raw sockets will behave before attempting to use this module.

# Keeping The [Node.js][nodejs] Event Loop Alive

This module uses the `libuv` library to integrate into the [Node.js][nodejs]
event loop - this library is also used by [Node.js][nodejs].  An underlying
 `libuv` library `poll_handle_t` event watcher is used to monitor the
underlying operating system raw socket used by a socket object.

All the while a socket object exists, and the sockets `close()` method has not
been called, the raw socket will keep the [Node.js][nodejs] event loop alive
which will prevent a program from exiting.

This module exports four methods which a program can use to control this
behaviour.

The `pauseRecv()` and `pauseSend()` methods stop the underlying `poll_handle_t`
event watcher used by a socket from monitoring for readable and writeable
events.  While the `resumeRecv()` and `resumeSend()` methods start the
underlying `poll_handle_t` event watcher used by a socket allowing it to
monitor for readable and writeable events.

Each socket object also exports the `recvPaused` and `sendPaused` boolean
attributes to determine the state of the underlying `poll_handle_t` event
watcher used by a socket.

Socket creation can be expensive on some platforms, and the above methods offer
an alternative to closing and deleting a socket to prevent it from keeping the
[Node.js][nodejs] event loop alive.

The [Node.js][nodejs] [net-ping][net-ping] module offers a concrete example
of using these methods.  Since [Node.js][nodejs] offers no raw socket support
this module is used to implement ICMP echo (ping) support.  Once all ping
requests have been processed by the [net-ping][net-ping] module the
`pauseRecv()` and `pauseSend()` methods are used to allow a program to exit if
required.

The following example stops the underlying `poll_handle_t` event watcher used
by a socket from generating writeable events, however since readable events
will still be watched for the program will not exit immediately:

    if (! socket.recvPaused)
        socket.pauseRecv ();

The following can the be used to resume readable events:

    if (socket.recvPaused)
        socket.resumeRecv ();

The following example stops the underlying `poll_handle_t` event watcher used
by a socket from generating both readable and writeable events, if no other
event watchers have been setup (e.g. `setTimeout()`) the program will exit.

    if (! socket.recvPaused)
        socket.pauseRecv ();
    if (! socket.sendPaused)
        socket.pauseSend ();

The following can the be used to resume both readable and writeable events:

    if (socket.recvPaused)
        socket.resumeRecv ();
    if (socket.sendPaused)
        socket.resumeSend ();

When data is sent using a sockets `send()` method the `resumeSend()` method
will be called if the sockets `sendPaused` attribute is `true`, however the
`resumeRecv()` method will not be called regardless of whether the sockets
`recvPaused` attribute is `true` or `false`.

[nodejs]: http://nodejs.org "Node.js"
[net-ping]: http://npmjs.org/package/net-ping "net-ping"

# Constants

The following sections describe constants exported and used by this module.

## raw.AddressFamily

This object contains constants which can be used for the `addressFamily`
option to the `createSocket()` function exposed by this module.  This option
specifies the IP protocol version to use when creating the raw socket.

The following constants are defined in this object:

 * `IPv4` - IPv4 protocol
 * `IPv6` - IPv6 protocol

## raw.Protocol

This object contains constants which can be used for the `protocol` option to
the `createSocket()` function exposed by this module.  This option specifies
the protocol number to place in the protocol field of IP headers generated by
the operating system.

The following constants are defined in this object:

 * `None` - protocol number 0
 * `ICMP` - protocol number 1
 * `TCP` - protocol number 6
 * `UDP` - protocol number 17
 * `ICMPv6` - protocol number 58

## raw.SocketLevel

This object contains constants which can be used for the `level` parameter to
the `getOption()` and `setOption()` methods exposed by this module.

The following constants are defined in this object:

 * `SOL_SOCKET`
 * `IPPROTO_IP`
 * `IPPROTO_IPV6`

## raw.SocketOption

This object contains constants which can be used for the `option` parameter to
the `getOption()` and `setOption()` methods exposed by this module.

The following constants are defined in this object:

 * `SO_RCVBUF`
 * `SO_RCVTIMEO`
 * `SO_SNDBUF`
 * `SO_SNDTIMEO`
 * `IP_HDRINCL`
 * `IP_OPTIONS`
 * `IP_TOS`
 * `IP_TTL`
 * `IPV6_TTL`
 * `IPV6_UNICAST_HOPS`
 * `IPV6_V6ONLY`

*The `IPV6_TTL` socket option is not known to be defined by any operating
system, it is provided in convenience to be synonymous with IPv4*

For Windows platforms the following constant is also defined:

 * `IPV6_HDRINCL`

For Linux platforms the following constant is also defined:

 * `SO_BINDTODEVICE`

# Using This Module

Raw sockets are represented by an instance of the `Socket` class.  This
module exports the `createSocket()` function which is used to create
instances of the `Socket` class.

The module also exports a number of stubs which call through to a number of
functions provided by the operating system, i.e. `htonl()`.

This module also exports a function to generate protocol checksums.

## raw.createChecksum (bufferOrObject, [bufferOrObject, ...])

The `createChecksum()` function creates and returns a 16 bit one's complement
of the one's complement sum for all the data specified in one or more
[Node.js][nodejs] `Buffer` objects.  This is useful for creating checksums for
protocols such as IP, TCP, UDP and ICMP.

The `bufferOrObject` parameter can be one of two types.  The first is a
[Node.js][nodejs] `Buffer` object.  In this case a checksum is calculated from
all the data it contains.  The `bufferOrObject` parameter can also be an
object which must contain the following attributes:

 * `buffer` - A [Node.js][nodejs] `Buffer` object which contains data which
   to generate a checksum for
 * `offset` - Skip this number of bytes from the beginning of `buffer`
 * `length` - Only generate a checksum for this number of bytes in `buffer`
   from `offset`

The second parameter type provides control over how much of the data in a
[Node.js][nodejs] `Buffer` object a checksum should be generated for.

When more than one parameter is passed a single checksum is calculated as if
the data in in all parameters were in a single buffer.  This is useful for
when calulating checksums for TCP and UDP for example - where a psuedo header
must be created and used for checksum calculation.

In this case two buffers can be passed, the first containing the psuedo header
and the second containing the real TCP packet, and the offset and length
parameters used to specify the bounds of the TCP packet payload.

The following example generates a checksum for a TCP packet and its psuedo
header:

    var sum = raw.createChecksum (pseudo_header, {buffer: tcp_packet,
            offset: 20, length: tcp_packet.length - 20});

Both buffers will be treated as one, i.e. as if the data at offset `20` in
`tcp_packet` had followed all data in `pseudo_header` - as if they were one
buffer.

## raw.writeChecksum (buffer, offset, checksum)

The `writeChecksum()` function writes a checksum created by the
`raw.createChecksum()` function to the [Node.js][nodejs] `Buffer` object
`buffer` at offsets `offset` and `offset` + 1.

The following example generates and writes a checksum at offset `2` in a
[Node.js][nodejs] `Buffer` object:

    raw.writeChecksum (buffer, 2, raw.createChecksum (buffer));

## raw.htonl (uint32)

The `htonl()` function converts a 32 bit unsigned integer from host byte
order to network byte order and returns the result.  This function is simply
a stub through to the operating systems `htonl()` function.

## raw.htons (uint16)

The `htons()` function converts a 16 bit unsigned integer from host byte
order to network byte order and returns the result.  This function is simply
a stub through to the operating systems `htons()` function.

## raw.ntohl (uint32)

The `ntohl()` function converts a 32 bit unsigned integer from network byte
order to host byte order and returns the result.  This function is simply
a stub through to the operating systems `ntohl()` function.

## raw.ntohs (uint16)

The `ntohs()` function converts a 16 bit unsigned integer from network byte
order to host byte order and returns the result.  This function is simply
a stub through to the operating systems `ntohs()` function.

## raw.createSocket ([options])

The `createSocket()` function instantiates and returns an instance of the
`Socket` class:

    // Default options
    var options = {
        addressFamily: raw.AddressFamily.IPv4,
        protocol: raw.Protocol.None,
        bufferSize: 4096,
        generateChecksums: false,
        checksumOffset: 0
    };

    var socket = raw.createSocket (options);

The optional `options` parameter is an object, and can contain the following
items:

 * `addressFamily` - Either the constant `raw.AddressFamily.IPv4` or the
   constant `raw.AddressFamily.IPv6`, defaults to the constant
   `raw.AddressFamily.IPv4`
 * `protocol` - Either one of the constants defined in the `raw.Protocol`
   object or the protocol number to use for the socket, defaults to the
   consant `raw.Protocol.None`
 * `bufferSize` - Size, in bytes, of the sockets internal receive buffer,
   defaults to 4096
 * `generateChecksums` - Either `true` or `false` to enable or disable the
   automatic checksum generation feature, defaults to `false`
 * `checksumOffset` - When `generateChecksums` is `true` specifies how many
   bytes to index into the send buffer to write automatically generated
   checksums, defaults to `0`

An exception will be thrown if the underlying raw socket could not be created.
The error will be an instance of the `Error` class.

The `protocol` parameter, or its default value of the constant
`raw.Protocol.None`, will be specified in the protocol field of each IP
header.

## socket.on ("close", callback)

The `close` event is emitted by the socket when the underlying raw socket
is closed.

No arguments are passed to the callback.

The following example prints a message to the console when the socket is
closed:

    socket.on ("close", function () {
        console.log ("socket closed");
    });

## socket.on ("error", callback)

The `error` event is emitted by the socket when an error occurs sending or
receiving data.

The following arguments will be passed to the `callback` function:

 * `error` - An instance of the `Error` class, the exposed `message` attribute
   will contain a detailed error message.

The following example prints a message to the console when an error occurs,
after which the socket is closed:

    socket.on ("error", function (error) {
        console.log (error.toString ());
        socket.close ();
    });

## socket.on ("message", callback)

The `message` event is emitted by the socket when data has been received.

The following arguments will be passed to the `callback` function:

 * `buffer` - A [Node.js][nodejs] `Buffer` object containing the data
   received, the buffer will be sized to fit the data received, that is the
   `length` attribute of buffer will specify how many bytes were received
 * `address` - For IPv4 raw sockets the dotted quad formatted source IP
   address of the message, e.g `192.168.1.254`, for IPv6 raw sockets the
   compressed formatted source IP address of the message, e.g.
   `fe80::a00:27ff:fe2a:3427`

The following example prints received messages in hexadecimal to the console:

    socket.on ("message", function (buffer, address) {
        console.log ("received " + buffer.length + " bytes from " + address
                + ": " + buffer.toString ("hex"));
    });

## socket.generateChecksums (generate, offset)

The `generateChecksums()` method is used to specify whether automatic checksum
generation should be performed by the socket.

The `generate` parameter is either `true` or `false` to enable or disable the
feature.  The optional `offset` parameter specifies how many bytes to index
into the send buffer when writing the generated checksum to the send buffer.

The following example enables automatic checksum generation at offset 2
resulting in checksums being written to byte 3 and 4 of the send buffer
(offsets start from 0, meaning byte 1):

    socket.generateChecksums (true, 2);

## socket.getOption (level, option, buffer, length)

The `getOption()` method gets a socket option using the operating systems
`getsockopt()` function.

The `level` parameter is one of the constants defined in the `raw.SocketLevel`
object.  The `option` parameter is one of the constants defined in the
`raw.SocketOption` object.  The `buffer` parameter is a [Node.js][nodejs]
`Buffer` object where the socket option value will be written.  The `length`
parameter specifies the size of the `buffer` parameter.

If an error occurs an exception will be thrown, the exception will be an
instance of the `Error` class.

The number of bytes written into the `buffer` parameter is returned, and can
differ from the amount of space available.

The following example retrieves the current value of `IP_TTL` socket option:

    var level = raw.SocketLevel.IPPROTO_IP;
    var option = raw.SocketOption.IP_TTL;

    # IP_TTL is a signed integer on some platforms so a 4 byte buffer is used
    var buffer = new Buffer (4);

    var written = socket.getOption (level, option, buffer, buffer.length);

    console.log (buffer.toString ("hex"), 0, written);

## socket.send (buffer, offset, length, address, beforeCallback, afterCallback)

The `send()` method sends data to a remote host.

The `buffer` parameter is a [Node.js][nodejs] `Buffer` object containing the
data to be sent.  The `length` parameter specifies how many bytes from
`buffer`, beginning at offset `offset`, to send.  For IPv4 raw sockets the
`address` parameter contains the dotted quad formatted IP address of the
remote host to send the data to, e.g `192.168.1.254`, for IPv6 raw sockets the
`address` parameter contains the compressed formatted IP address of the remote
host to send the data to, e.g. `fe80::a00:27ff:fe2a:3427`.  If provided the
optional `beforeCallback` function is called right before the data is actually
sent using the underlying raw socket, giving users the opportunity to perform
pre-send actions such as setting a socket option, e.g. the IP header TTL.  No
arguments are passed to the `beforeCallback` function.  The `afterCallback`
function is called once the data has been sent.  The following arguments will
be passed to the `afterCallback` function:

 * `error` - Instance of the `Error` class, or `null` if no error occurred
 * `bytes` - Number of bytes sent

The following example sends a ICMP ping message to a remote host, before the
request is actually sent the IP header TTL is modified, and modified again
after the data has been sent:

    // ICMP echo (ping) request, checksum should be ok
    var buffer = new Buffer ([
            0x08, 0x00, 0x43, 0x52, 0x00, 0x01, 0x0a, 0x09,
            0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
            0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70,
            0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x61,
            0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69]);

    var socketLevel = raw.SocketLevel.IPPROTO_IP
    var socketOption = raw.SocketOption.IP_TTL;

    function beforeSend () {
        socket.setOption (socketLevel, socketOption, 1);
    }

    function afterSend (error, bytes) {
        if (error)
            console.log (error.toString ());
        else
            console.log ("sent " + bytes + " bytes");

        socket.setOption (socketLevel, socketOption, 1);
    }

    socket.send (buffer, 0, buffer.length, target, beforeSend, afterSend);

## socket.setOption (level, option, buffer, length)

The `setOption()` method sets a socket option using the operating systems
`setsockopt()` function.

The `level` parameter is one of the constants defined in the `raw.SocketLevel`
object.  The `option` parameter is one of the constants defined in the
`raw.SocketOption` object.  The `buffer` parameter is a [Node.js][nodejs]
`Buffer` object where the socket option value is specified.  The `length`
parameter specifies how much space the option value occupies in the `buffer`
parameter.

If an error occurs an exception will be thrown, the exception will be an
instance of the `Error` class.

The following example sets the value of `IP_TTL` socket option to `1`:

    var level = raw.SocketLevel.IPPROTO_IP;
    var option = raw.SocketOption.IP_TTL;

    # IP_TTL is a signed integer on some platforms so a 4 byte buffer is used,
    # x86 computers use little-endian format so specify bytes reverse order
    var buffer = new Buffer ([0x01, 0x00, 0x00, 0x00]);

    socket.setOption (level, option, buffer, buffer.length);

To avoid dealing with endianess the `setOption()` method supports a three
argument form which can be used for socket options requiring a 32bit unsigned
integer value (for example the `IP_TTL` socket option used in the previous
example).  Its signature is as follows:

    socket.setOption (level, option, value)

The previous example can be re-written to use this form:

    var level = raw.SocketLevel.IPPROTO_IP;
    var option = raw.SocketOption.IP_TTL;

    socket.setOption (level, option, 1);

# Example Programs

Example programs are included under the modules `example` directory.

# Bugs & Known Issues

None, yet!

Bug reports should be sent to <stephen.vickers.sv@gmail.com>.

# Changes

## Version 1.0.0 - 29/01/2013

 * Initial release

## Version 1.0.1 - 01/02/2013

 * Move `SOCKET_ERRNO` define from `raw.cc` to `raw.h`
 * Error in exception thrown by `SocketWrap::New` in `raw.cc` stated that two
   arguments were required, this should be one
 * Corrections to the README.md
 * Missing includes causes compilation error on some systems (maybe Node
   version dependant)

## Version 1.0.2 - 02/02/2013

 * Support automatic checksum generation

## Version 1.1.0 - 13/02/2013

 * The [net-ping][net-ping] module is now implemented so update the note about
   it in the first section of the README.md
 * Support IPv6
 * Support the `IP_HDRINCL` socket option via the `noIpHeader` option to the
   `createSocket()` function and the `noIpHeader()` method exposed by the
   `Socket` class

## Version 1.1.1 - 14/02/2013

 * IP addresses not being validated

## Version 1.1.2 - 15/02/2013

 * Default protocol option to `createSession()` was incorrect in the README.md
 * The `session.on("message")` example used `message` instead of `buffer` in
   the README.md

## Version 1.1.3 - 04/03/2013

 * `raw.Socket.onSendReady()` emit's an error when `raw.SocketWrap.send()`
   throws an exception when it should call the `req.callback` callback
 * Added the `pauseRecv()`, `resumeRecv()`, `pauseSend()` and `resumeSend()`
   methods

[net-ping]: https://npmjs.org/package/net-ping "net-ping"

## Version 1.1.4 - 05/03/2013

 * Cleanup documentation for the `pauseSend()`, `pauseRecv()`, `resumeSend()`
   and `resumeRecv()` methods in the README.md

## Version 1.1.5 - 09/05/2013

 * Reformated lines in the README.md file inline with the rest of the file
 * Removed the `noIpHeader()` method (the `setOption()` method should be
   used to configure the `IP_HDRINCL` socket option - and possibly
   `IPV6_HDRINCL` on Windows platforms), and removed the `Automatic IP Header
   Generation` section from the README.md file
 * Added the `setOption()` and `getOption()` methods, and added the
   `SocketLevel` and `SocketOption` constants
 * Tidied up the example program `ping-no-ip-header.js` (now uses the
   `setOption()` method to configure the `IP_HDRINCL` socket option)
 * Tidied up the example program `ping6-no-ip-header.js` (now uses the
   `setOption()` method to configure the `IPV6_HDRINCL` socket option)
 * Added the example program `get-option.js`
 * Added the example program `ping-set-option-ip-ttl.js`
 * Use MIT license instead of GPL

## Version 1.1.6 - 18/05/2013

 * Added the `beforeCallback` parameter to the `send()` method, and renamed the
   `callback` parameter to `afterCallback`
 * Fixed a few typos in the README.md file
 * Modified the example program `ping-set-option-ip-ttl.js` to use the
   `beforeCallback` parameter to the `send()` method
 * The example program `ping6-no-ip-header.js` was not passing the correct
   arguments to the `setOption()` method

## Version 1.1.7 - 23/06/2013

 * Added the `htonl()`, `htons()`, `ntohl()`, and `ntohs()` functions, and
   associated example programs
 * Added the `createChecksum()` function, and associated example program

## Version 1.1.8 - 01/07/2013

 * Added the `writeChecksum()` function
 * Removed the "Automated Checksum Generation" feature - this has been
   replaced with the `createChecksum()` and `writeChecksum()` functions

## Version 1.2.0 - 02/07/2013

 * Up version number to 1.2.0 (we should have done this for 1.1.8 because it
   introduced some API breaking changes)

## Version 1.2.1 - 15/08/2013

 * Receiving `Assertion '!(handle->flags & (UV_CLOSING | UV_CLOSED))' failed`
   error after a number of pings - the underlying `uv_poll_t` handle was being
   closed twice

## Version 1.2.2 - 21/09/2013

 * Using uint16_t instead of uint32_t on line 87 in src/raw.cc for a value
   that is out of range
 * raw::SocketWrap::pause() only uses the first argument
 * Delete uv_poll_t watcher in uv_close() OnClose callback instead of in the
   wrapped C++ objects deconstructor

## Version 1.3.0 - 10/07/2015

 * Support Node.js 0.12.x using the Native Abstractions for Node interface
 * Added export for the `SO_BINDTODEVICE` socket option for Linux platforms
 * On MAC OS X platforms re-attempt to create a socket using `SOCK_DGRAM`
   instead of `SOCK_RAW` when `IPPROTO_ICMP` was requested by the user, this
   provides non-privileged users access to the ICMP protocol on this platform

## Version 1.3.1 - 10/07/2015

 * Missing bracket for when compiling under the MAC OS X platform :(

## Version 1.3.2 - 03/08/2015

 * Add version dependency "<2.0.0" for the "nan" module to prevent build
   failures during installation because of breaking API changes

## Version 1.3.3 - 22/09/2015

 * Host repository on GitHub

## Version 1.4.0 - 09/10/2015

 * Support Native Abstractions for Node 2.x
 * Add-on module crashes when emitting `close` events during garbage collection
   of a wrapped object
 * Support Node.js 4.x

## Version 1.5.0 - 15/05/2016

 * Require nan 2.3.x to support node version 6

## Version 1.5.1 - 16/11/2016

 * Explicitly publish to npm using UNIX line endings

# Roadmap

Suggestions and requirements should be sent to <stephen.vickers.sv@gmail.com>.

# License

Copyright (c) 2013 Stephen Vickers

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

# Author

Stephen Vickers <stephen.vickers.sv@gmail.com>


text:
package file

import (
	"io/ioutil"
	"os"

	"github.com/coreos/ignition/config/validate/report"
	"github.com/coreos/ignition/internal/config/types"
	"github.com/coreos/ignition/internal/providers/util"
	"github.com/coreos/ignition/internal/resource"
)

const (
	cfgFilenameEnvVar = "IGNITION_CONFIG_FILE"
	defaultFilename   = "config.ign"
)

func FetchConfig(f resource.Fetcher) (types.Config, report.Report, error) {
	filename := os.Getenv(cfgFilenameEnvVar)
	if filename == "" {
		filename = defaultFilename
		f.Logger.Info("using default filename")
	}
	f.Logger.Info("using config file at %q", filename)

	rawConfig, err := ioutil.ReadFile(filename)
	if err != nil {
		f.Logger.Err("couldn't read config %q: %v", filename, err)
		return types.Config{}, report.Report{}, err
	}
	return util.ParseConfig(f.Logger, rawConfig)
}

redpajama_set_name: RedPajamaGithub


text:
update ACT_GE_PROPERTY set VALUE_ = '6.3.1.0' where NAME_ = 'identitylink.schema.version';

update ACT_GE_PROPERTY set VALUE_ = '6.3.1.0' where NAME_ = 'task.schema.version';

update ACT_GE_PROPERTY set VALUE_ = '6.3.1.0' where NAME_ = 'variable.schema.version';

alter table ACT_RU_HISTORY_JOB add column SCOPE_TYPE_ varchar(255);

update ACT_GE_PROPERTY set VALUE_ = '6.3.1.0' where NAME_ = 'job.schema.version';
alter table ACT_RE_DEPLOYMENT add column PARENT_DEPLOYMENT_ID_ varchar(255);

update ACT_GE_PROPERTY set VALUE_ = '6.3.1.0' where NAME_ = 'schema.version';

update ACT_ID_PROPERTY set VALUE_ = '6.3.1.0' where NAME_ = 'schema.version';

CREATE TABLE ACT_APP_DATABASECHANGELOGLOCK (ID INT NOT NULL, LOCKED BIT(1) NOT NULL, LOCKGRANTED datetime NULL, LOCKEDBY VARCHAR(255) NULL, CONSTRAINT PK_ACT_APP_DATABASECHANGELOGLOCK PRIMARY KEY (ID));

DELETE FROM ACT_APP_DATABASECHANGELOGLOCK;

INSERT INTO ACT_APP_DATABASECHANGELOGLOCK (ID, LOCKED) VALUES (1, 0);

UPDATE ACT_APP_DATABASECHANGELOGLOCK SET LOCKED = 1, LOCKEDBY = '192.168.1.5 (192.168.1.5)', LOCKGRANTED = '2019-03-13 21:04:09.790' WHERE ID = 1 AND LOCKED = 0;

CREATE TABLE ACT_APP_DATABASECHANGELOG (ID VARCHAR(255) NOT NULL, AUTHOR VARCHAR(255) NOT NULL, FILENAME VARCHAR(255) NOT NULL, DATEEXECUTED datetime NOT NULL, ORDEREXECUTED INT NOT NULL, EXECTYPE VARCHAR(10) NOT NULL, MD5SUM VARCHAR(35) NULL, DESCRIPTION VARCHAR(255) NULL, COMMENTS VARCHAR(255) NULL, TAG VARCHAR(255) NULL, LIQUIBASE VARCHAR(20) NULL, CONTEXTS VARCHAR(255) NULL, LABELS VARCHAR(255) NULL, DEPLOYMENT_ID VARCHAR(10) NULL);

CREATE TABLE ACT_APP_DEPLOYMENT (ID_ VARCHAR(255) NOT NULL, NAME_ VARCHAR(255) NULL, CATEGORY_ VARCHAR(255) NULL, KEY_ VARCHAR(255) NULL, DEPLOY_TIME_ datetime NULL, TENANT_ID_ VARCHAR(255) DEFAULT '' NULL, CONSTRAINT PK_ACT_APP_DEPLOYMENT PRIMARY KEY (ID_));

CREATE TABLE ACT_APP_DEPLOYMENT_RESOURCE (ID_ VARCHAR(255) NOT NULL, NAME_ VARCHAR(255) NULL, DEPLOYMENT_ID_ VARCHAR(255) NULL, RESOURCE_BYTES_ LONGBLOB NULL, CONSTRAINT PK_APP_DEPLOYMENT_RESOURCE PRIMARY KEY (ID_));

ALTER TABLE ACT_APP_DEPLOYMENT_RESOURCE ADD CONSTRAINT ACT_FK_APP_RSRC_DPL FOREIGN KEY (DEPLOYMENT_ID_) REFERENCES ACT_APP_DEPLOYMENT (ID_);

CREATE INDEX ACT_IDX_APP_RSRC_DPL ON ACT_APP_DEPLOYMENT_RESOURCE(DEPLOYMENT_ID_);

CREATE TABLE ACT_APP_APPDEF (ID_ VARCHAR(255) NOT NULL, REV_ INT NOT NULL, NAME_ VARCHAR(255) NULL, KEY_ VARCHAR(255) NOT NULL, VERSION_ INT NOT NULL, CATEGORY_ VARCHAR(255) NULL, DEPLOYMENT_ID_ VARCHAR(255) NULL, RESOURCE_NAME_ VARCHAR(4000) NULL, DESCRIPTION_ VARCHAR(4000) NULL, TENANT_ID_ VARCHAR(255) DEFAULT '' NULL, CONSTRAINT PK_ACT_APP_APPDEF PRIMARY KEY (ID_));

ALTER TABLE ACT_APP_APPDEF ADD CONSTRAINT ACT_FK_APP_DEF_DPLY FOREIGN KEY (DEPLOYMENT_ID_) REFERENCES ACT_APP_DEPLOYMENT (ID_);

CREATE INDEX ACT_IDX_APP_DEF_DPLY ON ACT_APP_APPDEF(DEPLOYMENT_ID_);

INSERT INTO ACT_APP_DATABASECHANGELOG (ID, AUTHOR, FILENAME, DATEEXECUTED, ORDEREXECUTED, MD5SUM, DESCRIPTION, COMMENTS, EXECTYPE, CONTEXTS, LABELS, LIQUIBASE, DEPLOYMENT_ID) VALUES ('1', 'flowable', 'org/flowable/app/db/liquibase/flowable-app-db-changelog.xml', NOW(), 1, '7:ec9776f6c57a3953c7d27499108df3d1', 'createTable tableName=ACT_APP_DEPLOYMENT; createTable tableName=ACT_APP_DEPLOYMENT_RESOURCE; addForeignKeyConstraint baseTableName=ACT_APP_DEPLOYMENT_RESOURCE, constraintName=ACT_FK_APP_RSRC_DPL, referencedTableName=ACT_APP_DEPLOYMENT; createIndex...', '', 'EXECUTED', NULL, NULL, '3.5.3', '2507450274');

UPDATE ACT_APP_DATABASECHANGELOGLOCK SET LOCKED = 0, LOCKEDBY = NULL, LOCKGRANTED = NULL WHERE ID = 1;

UPDATE ACT_CMMN_DATABASECHANGELOGLOCK SET LOCKED = 1, LOCKEDBY = '192.168.1.5 (192.168.1.5)', LOCKGRANTED = '2019-03-13 21:04:10.536' WHERE ID = 1 AND LOCKED = 0;

CREATE TABLE ACT_CMMN_HI_PLAN_ITEM_INST (ID_ VARCHAR(255) NOT NULL, REV_ INT NOT NULL, NAME_ VARCHAR(255) NULL, STATE_ VARCHAR(255) NULL, CASE_DEF_ID_ VARCHAR(255) NULL, CASE_INST_ID_ VARCHAR(255) NULL, STAGE_INST_ID_ VARCHAR(255) NULL, IS_STAGE_ BIT(1) NULL, ELEMENT_ID_ VARCHAR(255) NULL, ITEM_DEFINITION_ID_ VARCHAR(255) NULL, ITEM_DEFINITION_TYPE_ VARCHAR(255) NULL, CREATED_TIME_ datetime NULL, LAST_AVAILABLE_TIME_ datetime NULL, LAST_ENABLED_TIME_ datetime NULL, LAST_DISABLED_TIME_ datetime NULL, LAST_STARTED_TIME_ datetime NULL, LAST_SUSPENDED_TIME_ datetime NULL, COMPLETED_TIME_ datetime NULL, OCCURRED_TIME_ datetime NULL, TERMINATED_TIME_ datetime NULL, EXIT_TIME_ datetime NULL, ENDED_TIME_ datetime NULL, LAST_UPDATED_TIME_ datetime NULL, START_USER_ID_ VARCHAR(255) NULL, REFERENCE_ID_ VARCHAR(255) NULL, REFERENCE_TYPE_ VARCHAR(255) NULL, TENANT_ID_ VARCHAR(255) DEFAULT '' NULL, CONSTRAINT PK_ACT_CMMN_HI_PLAN_ITEM_INST PRIMARY KEY (ID_));

ALTER TABLE ACT_CMMN_RU_MIL_INST ADD TENANT_ID_ VARCHAR(255) DEFAULT '' NULL;

ALTER TABLE ACT_CMMN_HI_MIL_INST ADD TENANT_ID_ VARCHAR(255) DEFAULT '' NULL;

INSERT INTO ACT_CMMN_DATABASECHANGELOG (ID, AUTHOR, FILENAME, DATEEXECUTED, ORDEREXECUTED, MD5SUM, DESCRIPTION, COMMENTS, EXECTYPE, CONTEXTS, LABELS, LIQUIBASE, DEPLOYMENT_ID) VALUES ('4', 'flowable', 'org/flowable/cmmn/db/liquibase/flowable-cmmn-db-changelog.xml', NOW(), 4, '7:894e6e444f72422bf34e4ade89dc8451', 'createTable tableName=ACT_CMMN_HI_PLAN_ITEM_INST; addColumn tableName=ACT_CMMN_RU_MIL_INST; addColumn tableName=ACT_CMMN_HI_MIL_INST', '', 'EXECUTED', NULL, NULL, '3.5.3', '2507450625');

UPDATE ACT_CMMN_DATABASECHANGELOGLOCK SET LOCKED = 0, LOCKEDBY = NULL, LOCKGRANTED = NULL WHERE ID = 1;

UPDATE ACT_DMN_DATABASECHANGELOGLOCK SET LOCKED = 1, LOCKEDBY = '192.168.1.5 (192.168.1.5)', LOCKGRANTED = '2019-03-13 21:04:10.789' WHERE ID = 1 AND LOCKED = 0;

ALTER TABLE ACT_DMN_DECISION_TABLE DROP COLUMN PARENT_DEPLOYMENT_ID_;

INSERT INTO ACT_DMN_DATABASECHANGELOG (ID, AUTHOR, FILENAME, DATEEXECUTED, ORDEREXECUTED, MD5SUM, DESCRIPTION, COMMENTS, EXECTYPE, CONTEXTS, LABELS, LIQUIBASE, DEPLOYMENT_ID) VALUES ('4', 'flowable', 'org/flowable/dmn/db/liquibase/flowable-dmn-db-changelog.xml', NOW(), 4, '7:b8d3d5a3efb71aef7578e1130a38fde2', 'dropColumn columnName=PARENT_DEPLOYMENT_ID_, tableName=ACT_DMN_DECISION_TABLE', '', 'EXECUTED', NULL, NULL, '3.5.3', '2507450821');

UPDATE ACT_DMN_DATABASECHANGELOGLOCK SET LOCKED = 0, LOCKEDBY = NULL, LOCKGRANTED = NULL WHERE ID = 1;

UPDATE ACT_FO_DATABASECHANGELOGLOCK SET LOCKED = 1, LOCKEDBY = '192.168.1.5 (192.168.1.5)', LOCKGRANTED = '2019-03-13 21:04:10.921' WHERE ID = 1 AND LOCKED = 0;

ALTER TABLE ACT_FO_FORM_DEFINITION DROP COLUMN PARENT_DEPLOYMENT_ID_;

INSERT INTO ACT_FO_DATABASECHANGELOG (ID, AUTHOR, FILENAME, DATEEXECUTED, ORDEREXECUTED, MD5SUM, DESCRIPTION, COMMENTS, EXECTYPE, CONTEXTS, LABELS, LIQUIBASE, DEPLOYMENT_ID) VALUES ('3', 'flowable', 'org/flowable/form/db/liquibase/flowable-form-db-changelog.xml', NOW(), 3, '7:6d80a1fd28201ae354e73bd7c5cf8595', 'dropColumn columnName=PARENT_DEPLOYMENT_ID_, tableName=ACT_FO_FORM_DEFINITION', '', 'EXECUTED', NULL, NULL, '3.5.3', '2507450951');

UPDATE ACT_FO_DATABASECHANGELOGLOCK SET LOCKED = 0, LOCKEDBY = NULL, LOCKGRANTED = NULL WHERE ID = 1;

UPDATE ACT_CO_DATABASECHANGELOGLOCK SET LOCKED = 1, LOCKEDBY = '192.168.1.5 (192.168.1.5)', LOCKGRANTED = '2019-03-13 21:04:11.036' WHERE ID = 1 AND LOCKED = 0;

UPDATE ACT_CO_DATABASECHANGELOGLOCK SET LOCKED = 0, LOCKEDBY = NULL, LOCKGRANTED = NULL WHERE ID = 1;


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>TestRPC | Soltsice</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="shortcut icon" href="../assets/favicon.ico">
	<link rel="stylesheet" href="../assets/css/main.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					Soltsice

						Options

								All

Public

Public/Protected

All

							<input type="checkbox" id="tsd-filter-inherited" checked />
							Inherited
							<input type="checkbox" id="tsd-filter-only-exported" />
							Only exported

					Menu

					Globals

					TestRPC

Class TestRPC

Hierarchy

						TestRPC

Index

Constructors

constructor

Methods

advance<wbr>ToBlock

increase<wbr>Time

increase<wbr>Time<wbr>To

mine

revert

snapshot

Constructors

constructor

new <wbr>TestRPC(w3?: W3): TestRPC

Defined in TestRPC.ts:5

Parameters

Optional w3: W3

Returns TestRPC

Methods

advance<wbr>ToBlock

advance<wbr>ToBlock(blockNumber: number): Promise<void>

Defined in TestRPC.ts:107

Parameters

blockNumber: number

Returns Promise<void>

increase<wbr>Time

increase<wbr>Time(seconds: number): Promise<number>

Defined in TestRPC.ts:57

Jump forward in time. Takes one parameter, which is the amount of time to increase in seconds.
									Returns the total time adjustment, in seconds.

Parameters

seconds: number

Returns Promise<number>

increase<wbr>Time<wbr>To

increase<wbr>Time<wbr>To(target: number): Promise<number>

Defined in TestRPC.ts:80

Beware that due to the need of calling two separate testrpc methods and rpc calls overhead
										it's hard to increase time precisely to a target point so design your test to tolerate
									small fluctuations from time to time.

Parameters

target: number

time in seconds

Returns Promise<number>

mine

mine(): Promise<void>

Defined in TestRPC.ts:92

Force a block to be mined. Takes no parameters. Mines a block independent of whether or not mining is started or stopped.

Returns Promise<void>

revert

revert(snapshotId?: undefined | string): Promise<boolean>

Defined in TestRPC.ts:38

Revert the state of the blockchain to a previous snapshot.
										Takes a single parameter, which is the snapshot id to revert to.
									If no snapshot id is passed it will revert to the latest snapshot. Returns true.

Parameters

Optional snapshotId: undefined | string

Returns Promise<boolean>

snapshot

snapshot(): Promise<string>

Defined in TestRPC.ts:17

Snapshot the state of the blockchain at the current block. Takes no parameters.
									Returns the integer id of the snapshot created.

Returns Promise<string>

						Globals

						Bot<wbr>Manageable

						JsonRPCError

						JsonRPCRequest

						JsonRPCResponse

						Multi<wbr>Ownable

						Multi<wbr>Sig<wbr>Wallet

						Ownable

						Soltsice<wbr>Contract

						Storage

						Storage<wbr>Factory

						TestRPC

								constructor

								advance<wbr>ToBlock

								increase<wbr>Time

								increase<wbr>Time<wbr>To

								mine

								revert

								snapshot

						W3

						is<wbr>Production

						mainnet<wbr>Storage<wbr>Factory

						rinkeby<wbr>Storage<wbr>Factory

						ropsten<wbr>Storage<wbr>Factory

						test<wbr>Accounts

						test<wbr>Private<wbr>Keys

						get<wbr>Storage

						toBN

Legend

Module

Object literal

Variable

Function

Function with type parameter

Index signature

Type alias

Enumeration

Enumeration member

Property

Method

Interface

Interface with type parameter

Constructor

Property

Method

Index signature

Class

Class with type parameter

Constructor

Property

Method

Accessor

Index signature

Inherited constructor

Inherited property

Inherited method

Inherited accessor

Protected property

Protected method

Protected accessor

Private property

Private method

Private accessor

Static property

Static method

With  by


text:
<?xml version="1.0" encoding="UTF-8"?>
<module codename="org.netbeans.modules.db.kit">
    <module_version install_time="1370465467250" last="true" origin="installer" specification_version="1.21.1">
        <file crc="3756709269" name="config/Modules/org-netbeans-modules-db-kit.xml"/>
        <file crc="16055345" name="modules/locale/org-netbeans-modules-db-kit_ja.jar"/>
        <file crc="2043661182" name="modules/locale/org-netbeans-modules-db-kit_pt_BR.jar"/>
        <file crc="3063592977" name="modules/locale/org-netbeans-modules-db-kit_ru.jar"/>
        <file crc="1052423906" name="modules/locale/org-netbeans-modules-db-kit_zh_CN.jar"/>
        <file crc="609540071" name="modules/org-netbeans-modules-db-kit.jar"/>
    </module_version>
</module>


text:
class OSGFTextFileLoader
	:public OSGFComponent
{
public:
class Loader
{
public:
	virtual void Execute(std::vector<char*>& ch,
		OSGFTextFileLoader& l)=0;
	void operator()(std::vector<char*>& ch
		,OSGFTextFileLoader& l)
	{
		Execute(ch,l);
	}
};
typedef std::map<std::string,Loader*> LoadersMap;
typedef std::pair<std::string,Loader*> p;
public:
	OSGFTextFileLoader(Game& game)
		:OSGFComponent(game),mFileName()
	{

	}
	OSGFTextFileLoader(Game& game,std::string fileName)
		:OSGFComponent(game)
	{
		SplitFilename(fileName);
	}
	OSGFTextFileLoader(const OSGFTextFileLoader& l)
		:OSGFComponent(l),mFileName(l.mFileName),mPathToFile(l.mPathToFile),
		mLoaders(l.mLoaders)
	{

	}
	virtual void Initialize()
	{
		if(IsInitialized())return;
		OSGFComponent::Initialize();
		InitLoaders();
		if(mFileName!="")
			LoadFile(mFileName);
	}
	virtual void LoadFile(const std::string& fileName)
	{
		if(mFileName == "")
			SplitFilename(fileName);
	}
	const std::string& GetFileName()const
	{
		return mFileName;
	}
	std::string GetFile()const
	{
		return mPathToFile+mFileName;
	}
	const std::string& GetPathToFile()const
	{
		return mPathToFile;
	}
protected:
	void PutLoader(const std::string& name,Loader* loader)
	{
		mLoaders.insert(p(name,loader));
	}
	void OnMissingLoader(std::vector<char*> ch)
	{
		char* str = new char[20+strlen(ch[0])];
		sprintf(str,"Unknown command %s\n",ch[0]);
		OutputDebugStringA(str);
		delete str;
	}
	void ExecLoader(const std::string& name,
		std::vector<char*>& ch,OSGFTextFileLoader& l)
	{
		Loader* load = mLoaders[name];
		if(load!=0)
			load->Execute(ch,l);
		else
			OnMissingLoader(ch);
	}
	void ClearLoaders()
	{
		mLoaders.clear();
	}
	virtual void InitLoaders()=0;
private:
	void SplitFilename (const std::string& str)
	{
	  size_t found;
	  found=str.find_last_of("/\\");
	  mPathToFile = str.substr(0,found);
	  mPathToFile+='/';
	  mFileName = str.substr(found+1);
	}
	std::string mFileName;
	std::string mPathToFile;
	LoadersMap mLoaders;
};


text:
namespace {
std::string GenerateEventJs(const std::string& name) {
  std::string result;
  std::string defineJs =
    "var event = new Event('tizenhwkey');"
    "function defineProps(val) {"
    "  Object.defineProperty(event, 'keyName', {"
    "    enumerable: false,"
    "    configurable: false,"
    "    writable: false,"
    "    value: val"
    "  });"
    "}";
  std::string nameJs = "defineProps('" + name + "');";
  std::string dispatchJs = "document.dispatchEvent(event);";
  result += defineJs;
  result += nameJs;
  result += dispatchJs;

  return result;
}
}  // namespace

namespace xwalk {

XWalkRenderViewExtTizen::XWalkRenderViewExtTizen(
    content::RenderView* render_view)
    : content::RenderViewObserver(render_view) {
  render_view_ = render_view;
  DCHECK(render_view_);
}

XWalkRenderViewExtTizen::~XWalkRenderViewExtTizen() {
}

// static
void XWalkRenderViewExtTizen::RenderViewCreated(
    content::RenderView* render_view) {
  new XWalkRenderViewExtTizen(render_view);  // |render_view| takes ownership.
}

bool XWalkRenderViewExtTizen::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(XWalkRenderViewExtTizen, message)
    IPC_MESSAGE_HANDLER(ViewMsg_HWKeyPressed,
                        OnHWKeyPressed)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void XWalkRenderViewExtTizen::OnHWKeyPressed(int keycode) {
  std::string event_name;
  if (keycode == ui::VKEY_BACK) {
    event_name = "back";
  } else if (keycode == ui::VKEY_HOME) {
    event_name = "menu";
  } else {
    LOG(INFO) << "Unknown input key code, only support 'back' & 'menu'"
                  "at present.";
    return;
  }

  content::RenderFrame* render_frame = render_view_->GetMainRenderFrame();
  blink::WebLocalFrame* web_frame = render_frame->GetWebFrame();
  blink::WebScriptSource source =
      blink::WebScriptSource(base::ASCIIToUTF16(GenerateEventJs(event_name)));
  web_frame->executeScript(source);
}

}  // namespace xwalk


text:
package org.intellij.images.actions;

import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.openapi.actionSystem.ActionPlaces;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.EnvironmentUtil;
import org.intellij.images.ImagesBundle;
import org.intellij.images.fileTypes.ImageFileTypeManager;
import org.intellij.images.options.Options;
import org.intellij.images.options.OptionsManager;
import org.intellij.images.options.impl.OptionsConfigurabe;

import java.io.File;
import java.util.Map;
import java.util.Set;

/**
 * Open image file externally.
 *
 * @author Alexey Efimov
 */
public final class EditExternallyAction extends AnAction {
  public void actionPerformed(AnActionEvent e) {
    Project project = e.getData(PlatformDataKeys.PROJECT);
    VirtualFile[] files = e.getData(PlatformDataKeys.VIRTUAL_FILE_ARRAY);
    Options options = OptionsManager.getInstance().getOptions();
    String executablePath = options.getExternalEditorOptions().getExecutablePath();
    if (StringUtil.isEmpty(executablePath)) {
      Messages.showErrorDialog(project,
                               ImagesBundle.message("error.empty.external.editor.path"),
                               ImagesBundle.message("error.title.empty.external.editor.path"));
      OptionsConfigurabe.show(project);
    }
    else {
      if (files != null) {
        Map<String, String> env = EnvironmentUtil.getEnviromentProperties();
        Set<String> varNames = env.keySet();
        for (String varName : varNames) {
          if (SystemInfo.isWindows) {
            executablePath = StringUtil.replace(executablePath, "%" + varName + "%", env.get(varName), true);
          }
          else {
            executablePath = StringUtil.replace(executablePath, "${" + varName + "}", env.get(varName), false);
          }
        }
        executablePath = FileUtil.toSystemDependentName(executablePath);
        File executable = new File(executablePath);
        GeneralCommandLine commandLine = new GeneralCommandLine();
        final String path = executable.exists() ? executable.getAbsolutePath() : executablePath;
        if (SystemInfo.isMac) {
          commandLine.setExePath("open");
          commandLine.addParameter("-a");
          commandLine.addParameter(path);
        } else {
          commandLine.setExePath(path);
        }

        ImageFileTypeManager typeManager = ImageFileTypeManager.getInstance();
        for (VirtualFile file : files) {
          if (file.isInLocalFileSystem() && typeManager.isImage(file)) {
            commandLine.addParameter(VfsUtil.virtualToIoFile(file).getAbsolutePath());
          }
        }
        commandLine.setWorkingDirectory(new File(executablePath).getParentFile());

        try {
          commandLine.createProcess();
        }
        catch (ExecutionException ex) {
          Messages.showErrorDialog(project,
                                   ex.getLocalizedMessage(),
                                   ImagesBundle.message("error.title.launching.external.editor"));
          OptionsConfigurabe.show(project);
        }
      }
    }
  }

  public void update(AnActionEvent e) {
    super.update(e);

    VirtualFile[] files = e.getData(PlatformDataKeys.VIRTUAL_FILE_ARRAY);
    final boolean isEnabled = isImages(files);
    if (e.getPlace().equals(ActionPlaces.PROJECT_VIEW_POPUP)) {
      e.getPresentation().setVisible(isEnabled);
    }
    else {
      e.getPresentation().setEnabled(isEnabled);
    }
  }

  private static boolean isImages(VirtualFile[] files) {
    boolean isImagesFound = false;
    if (files != null) {
      ImageFileTypeManager typeManager = ImageFileTypeManager.getInstance();
      for (VirtualFile file : files) {
        boolean isImage = typeManager.isImage(file);
        isImagesFound |= isImage;
        if (!file.isInLocalFileSystem() || !isImage) {
          return false;
        }
      }
    }
    return isImagesFound;
  }
}


text:
screen -dmS node1 expect ${1}/start_cli.sh ${1}/node1/neo-cli/ wallet1.db3 one
screen -dmS node2 expect ${1}/start_cli.sh ${1}/node2/neo-cli/ wallet2.db3 two
screen -dmS node3 expect ${1}/start_cli.sh ${1}/node3/neo-cli/ wallet3.db3 three
screen -dmS node4 expect ${1}/start_cli.sh ${1}/node4/neo-cli/ wallet4.db3 four

sleep infinity


text: Native code of a SOFA Spatializer as a Plugin for Unity


text:
---
id: children-undefined
title: this.props.children undefined
layout: tips
permalink: children-undefined.html
prev: references-to-components.html
---

You can't access the children of your component through `this.props.children`. `this.props.children` designates the children being **passed onto you** by the owner:

```js
/** @jsx React.DOM */

var App = React.createClass({
  componentDidMount: function() {
    // This doesn't refer to the `span`s! It refers to the children between
    // last line's `<App></App>`, which are undefined.
    console.log(this.props.children);
  },

  render: function() {
    return <div><span/><span/></div>;
  }
});

React.renderComponent(<App></App>, mountNode);
```

To access your own subcomponents (the `span`s), place [refs](http://facebook.github.io/react/docs/more-about-refs.html) on them.


text:
<?php

namespace Bonsi\GetResponse\Newsletter\Exceptions;

use Exception;

class InvalidNewsletterList extends Exception
{
    /**
     * @return static
     */
    public static function noListsDefined()
    {
        return new static('There are no lists defined');
    }

    /**
     * @param string $name
     *
     * @return static
     */
    public static function noListWithName($name)
    {
        return new static("There is no list named `{$name}`");
    }

    /**
     * @param $defaultListName
     *
     * @return static
     */
    public static function defaultListDoesNotExist($defaultListName)
    {
        return new static("Could not find a default list named `{$defaultListName}`");
    }
}


text:
from __future__ import annotations

from pendulum.formatting.formatter import Formatter

__all__ = ["Formatter"]


text:
package handlersocket

type Result struct {
	rowsAffected int64
}


text:
    {{ $field['label'] }}
    <input
        type="range"
        class="form-control"

        @foreach ($field as $attribute => $value)
            {{ $attribute }}="{{ $value }}"
        @endforeach
        >


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using GOBaseLibrary.Interfaces;

namespace GOBaseLibrary.Common
{
    [Serializable]
    [ComVisible(false)]
    public struct PriorityQueueItem<TValue, TPriority>
    {
        private TValue _value;
        public TValue Value
        {
            get { return _value; }
        }

        private TPriority _priority;
        public TPriority Priority
        {
            get { return _priority; }
        }

        public PriorityQueueItem(TValue val, TPriority pri)
        {
            this._value = val;
            this._priority = pri;
        }
    }

    [Serializable]
    [ComVisible(false)]
    public class PriorityQueue<TValue, TPriority> : ICollection,
        IEnumerable<PriorityQueueItem<TValue, TPriority>>
    {
        private PriorityQueueItem<TValue, TPriority>[] items;

        private const Int32 DefaultCapacity = 16;
        private Int32 capacity;
        private Int32 numItems;

        private Comparison<TPriority> compareFunc;

        /// <summary>
        /// Initializes a new instance of the PriorityQueue class that is empty,
        /// has the default initial capacity, and uses the default IComparer.
        /// </summary>
        public PriorityQueue()
            : this(DefaultCapacity, Comparer<TPriority>.Default)
        {
        }

        public PriorityQueue(Int32 initialCapacity)
            : this(initialCapacity, Comparer<TPriority>.Default)
        {
        }

        public PriorityQueue(IComparer<TPriority> comparer)
            : this(DefaultCapacity, comparer)
        {
        }

        public PriorityQueue(int initialCapacity, IComparer<TPriority> comparer)
        {
            Init(initialCapacity, new Comparison<TPriority>(comparer.Compare));
        }

        public PriorityQueue(Comparison<TPriority> comparison)
            : this(DefaultCapacity, comparison)
        {
        }

        public PriorityQueue(int initialCapacity, Comparison<TPriority> comparison)
        {
            Init(initialCapacity, comparison);
        }

        private void Init(int initialCapacity, Comparison<TPriority> comparison)
        {
            numItems = 0;
            compareFunc = comparison;
            SetCapacity(initialCapacity);
        }

        public int Count
        {
            get { return numItems; }
        }

        public int Capacity
        {
            get { return items.Length; }
            set { SetCapacity(value); }
        }

        private void SetCapacity(int newCapacity)
        {
            int newCap = newCapacity;
            if (newCap < DefaultCapacity)
                newCap = DefaultCapacity;

            // throw exception if newCapacity < NumItems
            if (newCap < numItems)
                throw new ArgumentOutOfRangeException("newCapacity", "New capacity is less than Count");

            this.capacity = newCap;
            if (items == null)
            {
                items = new PriorityQueueItem<TValue, TPriority>[newCap];
                return;
            }

            // Resize the array.
            Array.Resize<PriorityQueueItem<TValue, TPriority>>(ref items, newCap);
        }

        public void Enqueue(PriorityQueueItem<TValue, TPriority> newItem)
        {
            if (numItems == capacity)
            {
                // need to increase capacity
                // grow by 50 percent
                SetCapacity((3 * Capacity) / 2);
            }

            int i = numItems;
            ++numItems;
            while ((i > 0) && (compareFunc(items[(i - 1) / 2].Priority, newItem.Priority) < 0))
            {
                items[i] = items[(i - 1) / 2];
                i = (i - 1) / 2;
            }
            items[i] = newItem;
            //if (!VerifyQueue())
            //{
            //    Console.WriteLine("ERROR: Queue out of order!");
            //}
        }

        public void Enqueue(TValue value, TPriority priority)
        {
            Enqueue(new PriorityQueueItem<TValue, TPriority>(value, priority));
        }

        private PriorityQueueItem<TValue, TPriority> RemoveAt(Int32 index)
        {
            PriorityQueueItem<TValue, TPriority> o = items[index];
            --numItems;
            // move the last item to fill the hole
            PriorityQueueItem<TValue, TPriority> tmp = items[numItems];
            // If you forget to clear this, you have a potential memory leak.
            items[numItems] = default(PriorityQueueItem<TValue, TPriority>);
            if (numItems > 0 && index != numItems)
            {
                // If the new item is greater than its parent, bubble up.
                int i = index;
                int parent = (i - 1) / 2;
                while (compareFunc(tmp.Priority, items[parent].Priority) > 0)
                {
                    items[i] = items[parent];
                    i = parent;
                    parent = (i - 1) / 2;
                }

                // if i == index, then we didn't move the item up
                if (i == index)
                {
                    // bubble down ...
                    while (i < (numItems) / 2)
                    {
                        int j = (2 * i) + 1;
                        if ((j < numItems - 1) && (compareFunc(items[j].Priority, items[j + 1].Priority) < 0))
                        {
                            ++j;
                        }
                        if (compareFunc(items[j].Priority, tmp.Priority) <= 0)
                        {
                            break;
                        }
                        items[i] = items[j];
                        i = j;
                    }
                }
                // Be sure to store the item in its place.
                items[i] = tmp;
            }
            //if (!VerifyQueue())
            //{
            //    Console.WriteLine("ERROR: Queue out of order!");
            //}
            return o;
        }

        // Function to check that the queue is coherent.
        public bool VerifyQueue()
        {
            int i = 0;
            while (i < numItems / 2)
            {
                int leftChild = (2 * i) + 1;
                int rightChild = leftChild + 1;
                if (compareFunc(items[i].Priority, items[leftChild].Priority) < 0)
                {
                    return false;
                }
                if (rightChild < numItems && compareFunc(items[i].Priority, items[rightChild].Priority) < 0)
                {
                    return false;
                }
                ++i;
            }
            return true;
        }

        public PriorityQueueItem<TValue, TPriority> Dequeue()
        {
            if (Count == 0)
                throw new InvalidOperationException("The queue is empty");
            return RemoveAt(0);
        }

        /// <summary>
        /// Removes the item with the specified value from the queue.
        /// The passed equality comparison is used.
        /// </summary>
        /// <param name="item">The item to be removed.</param>
        /// <param name="comp">An object that implements the IEqualityComparer interface
        /// for the type of item in the collection.</param>
        public void Remove(TValue item, IEqualityComparer comparer)
        {
            // need to find the PriorityQueueItem that has the Data value of o
            for (int index = 0; index < numItems; ++index)
            {
                if (comparer.Equals(item, items[index].Value))
                {
                    RemoveAt(index);
                    return;
                }
            }
            throw new ApplicationException("The specified itemm is not in the queue.");
        }

        /// <summary>
        /// Removes the item with the specified value from the queue.
        /// The default type comparison function is used.
        /// </summary>
        /// <param name="item">The item to be removed.</param>
        public void Remove(TValue item)
        {
            Remove(item, EqualityComparer<TValue>.Default);
        }

        public PriorityQueueItem<TValue, TPriority> Peek()
        {
            if (Count == 0)
                throw new InvalidOperationException("The queue is empty");
            return items[0];
        }

        // Clear
        public void Clear()
        {
            for (int i = 0; i < numItems; ++i)
            {
                items[i] = default(PriorityQueueItem<TValue, TPriority>);
            }
            numItems = 0;
            TrimExcess();
        }

        /// <summary>
        /// Set the capacity to the actual number of items, if the current
        /// number of items is less than 90 percent of the current capacity.
        /// </summary>
        public void TrimExcess()
        {
            if (numItems < (float)0.9 * capacity)
            {
                SetCapacity(numItems);
            }
        }

        // Contains
        public bool Contains(TValue o)
        {
            foreach (PriorityQueueItem<TValue, TPriority> x in items)
            {
                if (x.Value == null)
                    continue;

                if (x.Value.Equals(o))
                    return true;

                IGossip rumor = (IGossip)x.Value;
                if (rumor.Id == (o as IGossip).Id)
                    return true;
            }
            return false;
        }

        public void CopyTo(PriorityQueueItem<TValue, TPriority>[] array, int arrayIndex)
        {
            if (array == null)
                throw new ArgumentNullException("array");
            if (arrayIndex < 0)
                throw new ArgumentOutOfRangeException("arrayIndex", "arrayIndex is less than 0.");
            if (array.Rank > 1)
                throw new ArgumentException("array is multidimensional.");
            if (numItems == 0)
                return;
            if (arrayIndex >= array.Length)
                throw new ArgumentException("arrayIndex is equal to or greater than the length of the array.");
            if (numItems > (array.Length - arrayIndex))
                throw new ArgumentException("The number of elements in the source ICollection is greater than the available space from arrayIndex to the end of the destination array.");

            for (int i = 0; i < numItems; i++)
            {
                array[arrayIndex + i] = items[i];
            }
        }

        #region ICollection Members

        public void CopyTo(Array array, int index)
        {
            this.CopyTo((PriorityQueueItem<TValue, TPriority>[])array, index);
        }

        public bool IsSynchronized
        {
            get { return false; }
        }

        public object SyncRoot
        {
            get { return items.SyncRoot; }
        }

        #endregion

        #region IEnumerable<PriorityQueueItem<TValue,TPriority>> Members

        public IEnumerator<PriorityQueueItem<TValue, TPriority>> GetEnumerator()
        {
            for (int i = 0; i < numItems; i++)
            {
                yield return items[i];
            }
        }

        #endregion

        #region IEnumerable Members

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        #endregion
    }
}


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

<title>com.mapzen.tangram (tangram 0.2-SNAPSHOT API)</title>
<meta name="date" content="2016-04-25">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package com.mapzen.tangram

Interface Summary

Interface
Description

MapController.FeaturePickListener

Interface for a callback to receive information about features picked from the map

MapView.OnMapReadyCallback

Interface for receiving a MapController once it is ready to be used

TouchInput.DoubleTapResponder

Interface for responding to a double-tap gesture

TouchInput.LongPressResponder

Interface for responding to a long press gesture

TouchInput.PanResponder

Interface for responding to a panning (dragging) gesture

TouchInput.RotateResponder

Interface for responding to a rotation gesture

TouchInput.ScaleResponder

Interface for responding to a scaling (pinching) gesture

TouchInput.ShoveResponder

Interface for responding to a shove (two-finger vertical drag) gesture

TouchInput.TapResponder

Interface for responding to a tap gesture

Class Summary

Class
Description

ConfigChooser

ConfigChooser is a convenience class for configuring a GLSurfaceView.

HttpHandler

HttpHandler is a class for customizing HTTP requests for map resources, it can be
 extended to override the request or caching behavior.

LngLat

LngLat represents a geographic coordinate with longitude and latitude.

MapController

MapController is the main class for interacting with a Tangram map.

MapData

MapData is a named collection of drawable map features.

MapView

MapView is a View for displaying a Tangram map.

TouchInput

TouchInput collects touch data, applies gesture detectors, resolves simultaneous
 detection, and calls the appropriate input responders.

Enum Summary

Enum
Description

MapController.DebugFlag

Options for enabling debug rendering features

MapController.EaseType

Options for interpolating map parameters

TouchInput.Gestures

List of gestures that can be detected and responded to

Package

Class

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes


text:
package metadata.etl.lineage;

import akka.actor.UntypedActor;
import java.io.PrintWriter;
import java.io.StringWriter;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by zsun on 9/16/15.
 */
@Slf4j
public class AzLineageExtractorActor extends UntypedActor {

  public AzLineageExtractorActor() {
    super();
  }

  @Override
  public void onReceive(Object message) {
    try {
      if (message instanceof AzExecMessage) {
        log.debug("Recieved a message : " + message.toString());
        AzLineageExtractor.extract((AzExecMessage) message);
      } else {
        log.error("Not an AzExecMessage message");
      }
    } catch (Exception e) {
      log.error("Actor failed!");
      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw);
      e.printStackTrace(pw);
      log.error(sw.toString());
      e.printStackTrace();
    } finally {
      log.debug("Actor finished for message : " + message.toString());
      getSender().tell("finished", null);
    }
  }
}


text:
module ChunkyPNG
  class Canvas

    # Module that adds some primitive drawing methods to {ChunkyPNG::Canvas}.
    #
    # All of these methods change the current canvas instance and do not create
    # a new one, even though the method names do not end with a bang.
    #
    # @note Drawing operations will not fail when something is drawn outside of
    #   the bounds of the canvas; these pixels will simply be ignored.
    # @see ChunkyPNG::Canvas
    module Drawing

      # Composes a pixel on the canvas by alpha blending a color with its
      # background color.
      #
      # @param [Integer] x The x-coordinate of the pixel to blend.
      # @param [Integer] y The y-coordinate of the pixel to blend.
      # @param [Integer] color The foreground color to blend with
      # @return [Integer] The composed color.
      def compose_pixel(x, y, color)
        return unless include_xy?(x, y)
        compose_pixel_unsafe(x, y, ChunkyPNG::Color.parse(color))
      end

      # Composes a pixel on the canvas by alpha blending a color with its
      # background color, without bounds checking.
      #
      # @param (see #compose_pixel)
      # @return [Integer] The composed color.
      def compose_pixel_unsafe(x, y, color)
        set_pixel(x, y, ChunkyPNG::Color.compose(color, get_pixel(x, y)))
      end

      # Draws a Bezier curve
      # @param [Array, Point] A collection of control points
      # @return [Chunky:PNG::Canvas] Itself, with the curve drawn
      def bezier_curve(points, stroke_color = ChunkyPNG::Color::BLACK)
        points = ChunkyPNG::Vector(*points)
        case points.length
          when 0, 1; return self
          when 2; return line(points[0].x, points[0].y, points[1].x, points[1].y, stroke_color)
        end

        curve_points = Array.new

        t     = 0
        n     = points.length - 1
        bicof = 0

        while t <= 100
          cur_p = ChunkyPNG::Point.new(0,0)

          # Generate a float of t.
          t_f = t / 100.00

          cur_p.x += ((1 - t_f) ** n) * points[0].x
          cur_p.y += ((1 - t_f) ** n) * points[0].y

          for i in 1...points.length - 1
            bicof = binomial_coefficient(n , i)

            cur_p.x += (bicof * (1 - t_f) ** (n - i)) *  (t_f ** i) * points[i].x
            cur_p.y += (bicof * (1 - t_f) ** (n - i)) *  (t_f ** i) * points[i].y
            i += 1
          end

          cur_p.x += (t_f ** n) * points[n].x
          cur_p.y += (t_f ** n) * points[n].y

          curve_points << cur_p

          bicof = 0
          t += 1
        end

        curve_points.each_cons(2) do |p1, p2|
          line_xiaolin_wu(p1.x.round, p1.y.round, p2.x.round, p2.y.round, stroke_color)
        end

        self
      end

      # Draws an anti-aliased line using Xiaolin Wu's algorithm.
      #
      # @param [Integer] x0 The x-coordinate of the first control point.
      # @param [Integer] y0 The y-coordinate of the first control point.
      # @param [Integer] x1 The x-coordinate of the second control point.
      # @param [Integer] y1 The y-coordinate of the second control point.
      # @param [Integer] stroke_color The color to use for this line.
      # @param [true, false] inclusive Whether to draw the last pixel. Set to
      #   false when drawing multiple lines in a path.
      # @return [ChunkyPNG::Canvas] Itself, with the line drawn.
      def line_xiaolin_wu(x0, y0, x1, y1, stroke_color, inclusive = true)
        stroke_color = ChunkyPNG::Color.parse(stroke_color)

        dx = x1 - x0
        sx = dx < 0 ? -1 : 1
        dx *= sx
        dy = y1 - y0
        sy = dy < 0 ? -1 : 1
        dy *= sy

        if dy == 0 # vertical line
          x0.step(inclusive ? x1 : x1 - sx, sx) do |x|
            compose_pixel(x, y0, stroke_color)
          end

        elsif dx == 0 # horizontal line
          y0.step(inclusive ? y1 : y1 - sy, sy) do |y|
            compose_pixel(x0, y, stroke_color)
          end

        elsif dx == dy # diagonal
          x0.step(inclusive ? x1 : x1 - sx, sx) do |x|
            compose_pixel(x, y0, stroke_color)
            y0 += sy
          end

        elsif dy > dx  # vertical displacement
          compose_pixel(x0, y0, stroke_color)
          e_acc = 0
          e = ((dx << 16) / dy.to_f).round
          (dy - 1).downto(0) do |i|
            e_acc_temp, e_acc = e_acc, (e_acc + e) & 0xffff
            x0 += sx if e_acc <= e_acc_temp
            w = 0xff - (e_acc >> 8)
            compose_pixel(x0, y0, ChunkyPNG::Color.fade(stroke_color, w))
            if inclusive || i > 0
              compose_pixel(x0 + sx,
                            y0 + sy,
                            ChunkyPNG::Color.fade(stroke_color, 0xff - w))
            end
            y0 += sy
          end
          compose_pixel(x1, y1, stroke_color) if inclusive

        else # horizontal displacement
          compose_pixel(x0, y0, stroke_color)
          e_acc = 0
          e = ((dy << 16) / dx.to_f).round
          (dx - 1).downto(0) do |i|
            e_acc_temp, e_acc = e_acc, (e_acc + e) & 0xffff
            y0 += sy if e_acc <= e_acc_temp
            w = 0xff - (e_acc >> 8)
            compose_pixel(x0, y0, ChunkyPNG::Color.fade(stroke_color, w))
            if inclusive || i > 0
              compose_pixel(x0 + sx,
                            y0 + sy,
                            ChunkyPNG::Color.fade(stroke_color, 0xff - w))
            end
            x0 += sx
          end
          compose_pixel(x1, y1, stroke_color) if inclusive
        end

        self
      end

      alias_method :line, :line_xiaolin_wu

      # Draws a polygon on the canvas using the stroke_color, filled using the
      # fill_color if any.
      #
      # @param [Array, String] The control point vector. Accepts everything
      #   {ChunkyPNG.Vector} accepts.
      # @param [Integer] stroke_color The stroke color to use for this polygon.
      # @param [Integer] fill_color The fill color to use for this polygon.
      # @return [ChunkyPNG::Canvas] Itself, with the polygon drawn.
      def polygon(path,
                  stroke_color = ChunkyPNG::Color::BLACK,
                  fill_color   = ChunkyPNG::Color::TRANSPARENT)

        vector = ChunkyPNG::Vector(*path)
        if path.length < 3
          raise ArgumentError, 'A polygon requires at least 3 points'
        end

        stroke_color = ChunkyPNG::Color.parse(stroke_color)
        fill_color   = ChunkyPNG::Color.parse(fill_color)

        # Fill
        unless fill_color == ChunkyPNG::Color::TRANSPARENT
          vector.y_range.each do |y|
            intersections = []
            vector.edges.each do |p1, p2|
              if (p1.y < y && p2.y >= y) || (p2.y < y && p1.y >= y)
                intersections << (p1.x + (y - p1.y).to_f / (p2.y - p1.y) * (p2.x - p1.x)).round
              end
            end

            intersections.sort!
            0.step(intersections.length - 1, 2) do |i|
              intersections[i].upto(intersections[i + 1]) do |x|
                compose_pixel(x, y, fill_color)
              end
            end
          end
        end

        # Stroke
        vector.each_edge do |(from_x, from_y), (to_x, to_y)|
          line(from_x, from_y, to_x, to_y, stroke_color, false)
        end

        self
      end

      # Draws a rectangle on the canvas, using two control points.
      #
      # @param [Integer] x0 The x-coordinate of the first control point.
      # @param [Integer] y0 The y-coordinate of the first control point.
      # @param [Integer] x1 The x-coordinate of the second control point.
      # @param [Integer] y1 The y-coordinate of the second control point.
      # @param [Integer] stroke_color The line color to use for this rectangle.
      # @param [Integer] fill_color The fill color to use for this rectangle.
      # @return [ChunkyPNG::Canvas] Itself, with the rectangle drawn.
      def rect(x0, y0, x1, y1,
               stroke_color = ChunkyPNG::Color::BLACK,
               fill_color   = ChunkyPNG::Color::TRANSPARENT)

        stroke_color = ChunkyPNG::Color.parse(stroke_color)
        fill_color   = ChunkyPNG::Color.parse(fill_color)

        # Fill
        unless fill_color == ChunkyPNG::Color::TRANSPARENT
          [x0, x1].min.upto([x0, x1].max) do |x|
            [y0, y1].min.upto([y0, y1].max) do |y|
              compose_pixel(x, y, fill_color)
            end
          end
        end

        # Stroke
        line(x0, y0, x0, y1, stroke_color, false)
        line(x0, y1, x1, y1, stroke_color, false)
        line(x1, y1, x1, y0, stroke_color, false)
        line(x1, y0, x0, y0, stroke_color, false)

        self
      end

      # Draws a circle on the canvas.
      #
      # @param [Integer] x0 The x-coordinate of the center of the circle.
      # @param [Integer] y0 The y-coordinate of the center of the circle.
      # @param [Integer] radius The radius of the circle from the center point.
      # @param [Integer] stroke_color The color to use for the line.
      # @param [Integer] fill_color The color to use that fills the circle.
      # @return [ChunkyPNG::Canvas] Itself, with the circle drawn.
      def circle(x0, y0, radius,
                 stroke_color = ChunkyPNG::Color::BLACK,
                 fill_color   = ChunkyPNG::Color::TRANSPARENT)

        stroke_color = ChunkyPNG::Color.parse(stroke_color)
        fill_color   = ChunkyPNG::Color.parse(fill_color)

        f = 1 - radius
        ddF_x = 1
        ddF_y = -2 * radius
        x = 0
        y = radius

        compose_pixel(x0, y0 + radius, stroke_color)
        compose_pixel(x0, y0 - radius, stroke_color)
        compose_pixel(x0 + radius, y0, stroke_color)
        compose_pixel(x0 - radius, y0, stroke_color)

        lines = [radius - 1] unless fill_color == ChunkyPNG::Color::TRANSPARENT

        while x < y

          if f >= 0
            y -= 1
            ddF_y += 2
            f += ddF_y
          end

          x += 1
          ddF_x += 2
          f += ddF_x

          unless fill_color == ChunkyPNG::Color::TRANSPARENT
            lines[y] = lines[y] ? [lines[y], x - 1].min : x - 1
            lines[x] = lines[x] ? [lines[x], y - 1].min : y - 1
          end

          compose_pixel(x0 + x, y0 + y, stroke_color)
          compose_pixel(x0 - x, y0 + y, stroke_color)
          compose_pixel(x0 + x, y0 - y, stroke_color)
          compose_pixel(x0 - x, y0 - y, stroke_color)

          unless x == y
            compose_pixel(x0 + y, y0 + x, stroke_color)
            compose_pixel(x0 - y, y0 + x, stroke_color)
            compose_pixel(x0 + y, y0 - x, stroke_color)
            compose_pixel(x0 - y, y0 - x, stroke_color)
          end
        end

        unless fill_color == ChunkyPNG::Color::TRANSPARENT
          lines.each_with_index do |length, y_offset|
            if length > 0
              line(x0 - length, y0 - y_offset, x0 + length, y0 - y_offset, fill_color)
            end
            if length > 0 && y_offset > 0
              line(x0 - length, y0 + y_offset, x0 + length, y0 + y_offset, fill_color)
            end
          end
        end

        self
      end

      private

      # Calculates the binomial coefficient for n over k.
      #
      # @param [Integer] n first parameter in coeffient (the number on top when
      #   looking at the mathematic formula)
      # @param [Integer] k k-element, second parameter in coeffient (the number
      #   on the bottom when looking at the mathematic formula)
      # @return [Integer] The binomial coeffcient of (n,k)
      def binomial_coefficient(n, k)
        return  1 if n == k || k == 0
        return  n if k == 1
        return -1 if n < k

        # calculate factorials
        fact_n = (2..n).inject(1) { |carry, i| carry * i }
        fact_k = (2..k).inject(1) { |carry, i| carry * i }
        fact_n_sub_k = (2..(n - k)).inject(1) { |carry, i| carry * i }

        fact_n / (fact_k * fact_n_sub_k)
      end
    end
  end
end


text:
+++
author = "Philipp Fromme"
categories = ["Modeling"]
tags = ["BPMN 2.0", "Tooling", "Release Note", "Camunda Modeler"]
date = "2017-06-01T15:00:00+01:00"
title = "Camunda Modeler 1.8.1 Released"
+++

We are happy to announce the Camunda Modeler version 1.8.1 release!

This patch release comes with a number of improvements both in the Camunda Modeler itself and in the libraries it builds upon, such as [bpmn-js](https://github.com/bpmn-io/bpmn-js), [bpmn-js-properties-panel](https://github.com/bpmn-io/bpmn-js-properties-panel) and [diagram-js](https://github.com/bpmn-io/diagram-js).

[Download](https://camunda.org/bpmn/tool/) the new version from [camunda.org](https://camunda.org/bpmn/tool/).

<!--more-->

<style>
  @media(min-width: 900px) {
    figure.main.teaser.headline {
      margin-left: -120px !important;
      margin-right: -120px !important;
    }
  }
</style>

{{< figure class="main teaser no-border" src="minimap-persistance.gif" alt="Camunda Modeler Clone BPMN Implementation Details" caption="Open/closed state of the minimap is now being persisted." >}}

## Improvements

Most notably in this patch release, the minimap is now closed by default. We've added an icon to it so you can find it easily when it's closed. Furthermore, the open/close state of the minimap is now being persisted in the same way it is for the properties panel. If you create a new diagram or open an existing one the minimap will be open/closed depending on if you opened/closed it before.

With version 1.8.0 of the Camunda Modeler, we introduced plugins, which allow you to change the modeler's appearance and behavior and add new features by simply copying the directory containing the plugin into the `plugins` directory of the Camunda Modeler. In order to make finding this folder easier, we've added it by default to the modeler's directory. Additionally, we've improved the [documentation](https://github.com/camunda/camunda-modeler/tree/master/docs/plugins) for plugins.

Thanks to a contribution by [Jia Huang](https://github.com/iamfat) bpmn-js-properties-panel and dmn-js can now be internationalized. What's even better is that with plugins internationalization is as simple as adding a plugin to the modeler (the necessary plugin points are going to be created soon).

## Bug Fixes

We have included a number of bug fixes in the libraries the Camunda Modeler builds upon, therefore further improving the modeling experience. These include [diagram-js](https://github.com/bpmn-io/diagram-js), [diagram-js-minimap](https://github.com/bpmn-io/diagram-js-minimap), [bpmn-js](https://github.com/bpmn-io/bpmn-js), [bpmn-js-properties-panel](https://github.com/bpmn-io/bpmn-js-properties-panel) and [dmn-js](https://github.com/bpmn-io/dmn-js).

## What's next?

In our next milestone we will focus on reworking text annotations and further improving the usability of the Camunda Modeler.

Do you miss anything or spot a bug? Or do you have feedback on the latest addition of the minimap or pluggability? Reach out to us via [our forums](https://forum.camunda.org/c/modeler) or tweet us [@CamundaBPM](https://twitter.com/CamundaBPM).


text:
<!doctype html>

    <title>Code coverage report for js/errors.js</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="../prettify.css" />
    <link rel="stylesheet" href="../base.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1">

      all files / js/ errors.js

        76.67%
        Statements
        23/30

        50%
        Branches
        3/6

        66.67%
        Functions
        4/6

        76.67%
        Lines
        23/30

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105

4×

12×

12×
12×

12×
12×

10×

10×

10×
10×
10×

4×
4×

2×
2×
2×

4×
4×

4×
4×

4×
4×

4×

/**
 * Модуль, содержащий всякие полезные переменные и функции
 * @module Errors
 */
define([], function() {

    function CustomError(property) {
        this.name = this.name || "CustomError";

        this.property = property;
        this.message = this.name + ": " + property;

        Eif (Error.captureStackTrace) {
            Error.captureStackTrace(this, CustomError);
        } else {
            this.stack = (new Error()).stack;
        }
    }

    /**
     * @class
     * Класс ошибки, означающий неправильно переданный в функцию аргумент
     * @param {string} argName - название аргумента
     * @param {Object} arg - значение аргумента
     * @constructor module:Errors~ArgumentError
     */
    function ArgumentError(argName, arg) {
        Iif (typeof arg === 'function') {
            arg = 'function() {...}';
        } else {
            arg = JSON.stringify(arg);
        }
        arg = 'wrong function argument "' + argName + '": ' + arg;
        this.name = 'ArgumentError';
        CustomError.apply(this, [arg]);
    }
    ArgumentError.prototype = Object.create(CustomError.prototype);
    ArgumentError.prototype.constructor = ArgumentError;

    /**
     * @class
     * Класс ошибки, означающий, что путь от одной модели до другой модели не был найден
     * @param {ScreenModel} fromScreen - модель, из которой осуществлялся поиск
     * @param {ScreenModel} toScreen - модель, в которую осуществлялся поиск
     * @constructor module:Errors~PathNotFoundError
     */
    function PathNotFoundError(fromScreen, toScreen) {
        this.name = 'PathNotFoundError';
        var arg = 'path not found: from ' + fromScreen.toString() + ' to ' + toScreen.toString();
        CustomError.apply(this, [arg]);
    }
    PathNotFoundError.prototype = Object.create(CustomError.prototype);
    PathNotFoundError.prototype.constructor = PathNotFoundError;

    /**
     * @class
     * Класс ошибки, означающий критическую ошибку логики
     * @param {string} property - подробности ошибки
     * @constructor module:Errors~FatalError
     */
    function FatalError(property) {
        this.name = 'FatalError';
        CustomError.apply(this, arguments);
    }
    FatalError.prototype = Object.create(CustomError.prototype);
    FatalError.prototype.constructor = FatalError;

    /**
     * @class
     * Класс ошибки, означающий, что функция интерфейса еще не реализована
     * @param {string} module - название интерфейса
     * @param {string} functionName - название функции
     * @constructor module:Errors~NotRealizedError
     */
    function NotRealizedError(module, functionName) {
        this.name = 'NotRealizedError';
        var arg = 'Not realized ' + module + ':' + functionName;
        CustomError.apply(this, [arg]);
    }
    NotRealizedError.prototype = Object.create(CustomError.prototype);
    NotRealizedError.prototype.constructor = NotRealizedError;

    return /** @alias module:Errors */ {
        /**
         * Класс ошибки, означающий неправильно переданный в функцию аргумент
         * @type {module:Errors~ArgumentError}
         */
        ArgumentError: ArgumentError,
        /**
         * Класс ошибки, означающий, что путь от одной модели до другой модели не был найден
         * @type {module:Errors~PathNotFoundError}
         */
        PathNotFoundError: PathNotFoundError,
        /**
         * Класс ошибки, означающий, что функция интерфейса еще не реализована
         * @type {module:Errors~NotRealizedError}
         */
        NotRealizedError: NotRealizedError,
        /**
         * Класс ошибки, означающий критическую ошибку логики
         * @type {module:Errors~FatalError}
         */
        FatalError: FatalError
    };
});

  Code coverage
  generated by istanbul at Mon Mar 27 2017 01:49:59 GMT+0300 (MSK)


text:
package burai.com.file;

@FunctionalInterface
public interface FileOperation {

    public abstract boolean operate();

}


text:
import { OnChanges, TemplateRef, ViewContainerRef } from '@angular/core';
/**
 * Creates and inserts an embedded view based on a prepared `TemplateRef`.
 * You can attach a context object to the `EmbeddedViewRef` by setting `[ngOutletContext]`.
 * `[ngOutletContext]` should be an object, the object's keys will be the local template variables
 * available within the `TemplateRef`.
 *
 * Note: using the key `$implicit` in the context object will set it's value as default.
 *
 * ### Syntax
 *
 * ```
 * <template [ngTemplateOutlet]="templateRefExpression"
 *           [ngOutletContext]="objectExpression">
 * </template>
 * ```
 *
 * @experimental
 */
export declare class NgTemplateOutlet implements OnChanges {
    private _viewContainerRef;
    private _viewRef;
    private _context;
    private _templateRef;
    constructor(_viewContainerRef: ViewContainerRef);
    ngOutletContext: Object;
    ngTemplateOutlet: TemplateRef<Object>;
    ngOnChanges(): void;
}


text:
var AA = require('../../index'),
    Cluster = AA.Cluster,
    ConnectionConfig = AA.ConnectionConfig;
var MockServerBuilder = require('../mocks/MockServerBuilder');
var childProcess = require('child_process');
var fs = require('fs');
var ConfigurationError = require('../../lib/ConfigurationError');
var _ = require('underscore');
var when = require('when');

var clusterSize = 4;
var sslSize = 2;
var portGenerator = __dirname+'/../mocks/bin/port';

module.exports = {
    testNonHttp: {
        setUp: function(callback) {
            this.cluster = new Cluster('h1','h2:8080',['h3','https://h4'],'http://h5');
            callback();
        },
        testConstructor: function(test) {
            test.expect(1);
            test.strictEqual(_(this.cluster.hosts).size(),5,"Constructor: should have 5 hosts");
            test.done();
        },
        testGetURIs: function(test) {
            test.expect(2);
            var hosts = this.cluster.getURIs();
            test.strictEqual(hosts.length,5,"getURIs(): should have 5 hosts");
            test.strictEqual(_.intersection(hosts,['http://h1','http://h2:8080','http://h3','https://h4','http://h5']).length,5,
                "getURIs(): hosts are h1-h5");
            test.done();
        },
        testAddURIs: function(test) {
            test.expect(2);
            this.cluster.addURIs('host');
            test.equal(_(this.cluster.getURIs()).indexOf('http://host')>-1,true,"addURIs(): 'host' should be added");
            this.cluster.addURIs(['host2','http://host3'],'https://host4');
            test.equal(_.intersection(this.cluster.getURIs(),['http://host2','http://host3','https://host4']).length,3,
                "addURIs(): host2-host4 should be added");
            test.done();
        }
    },
    testHttp: {
        setUp: function(callback) {
            var that = this;
            this.servers = [];
            var done =  _.after(clusterSize,callback);
            childProcess.execFile(portGenerator,[clusterSize],function(error,stdout){
                if(error) throw error;
                var ports = stdout.split(" ").map(function(str){
                    return parseInt(str.trim());
                });
                var hosts = [];
                for(var i=0;i<clusterSize;i++) {
                    hosts.push('http'+(i<sslSize ? 's' : '')+'://localhost:'+ports[i]);
                }
                that.cluster = new Cluster(hosts);
                ports.forEach(function(p,i) {
                    var builder = (new MockServerBuilder);
                    builder.addPath('GET','/analytics/api/schema').
                        addResponse('',{
                            status: 200,
                            headers: {
                                'Content-type': 'application/json'
                            },
                            body: fs.readFileSync(__dirname+'/../mocks/json/schema.json')
                        });
                    that.servers.push(builder.listen(p,{protocol: (i<sslSize ? 'https' : 'http')}));
                });
                that.servers.forEach(function(s){
                    s.on('listening',done);
                });
            });
            process.on('SIGTERM',function(){
                var after = _.after(clusterSize,function(){
                    process.exit(1);
                });
                that.servers.forEach(function(s){
                    try {
                        s.close(after);
                    } catch(e) {
                        //server not running
                        after();
                    }
                });

            });
        },
        testGetSession: function(test) {
            test.expect(2);
            test.ok(this.cluster.getSession(),"getSession(): should return truthy value");
            test.ok(this.cluster.config, "getSession(): should set a default config");
            test.done();
        },
        testApiCall: {
            testApiCallWithoutSession: function(test) {
                test.expect(1);
                var that = this;
                test.throws(function(){
                    that.cluster.apiCall('GET')('schema');
                },ConfigurationError,"apiCall() without session: should throw a ConfigurationError");
                test.done();
            },
            testApiCallWithSession: {
                setUp: function(callback) {
                    var config = new ConnectionConfig({
                        SSL_PFX: __dirname+'/../mocks/ssl/mycert.pfx',
                        SSL_PASSPHRASE: 'password'
                    });
                    this.cluster.getSession(config);
                    callback();
                },
                testApiCallWithHostsDown: function(test) {
                    test.expect(2);
                    var that = this;
                    var numberOfHostsDown = Math.floor(Math.random()*clusterSize + 1);
                    var done = _.after(numberOfHostsDown,function(){
                        that.cluster.apiCall('GET')('schema').then(function(res){
                            test.ok(numberOfHostsDown < clusterSize,
                                "apiCall() with hosts down: number of hosts down < clusterSize");
                            test.ok(res,"apiCall('GET')('schema') should succeed");
                            test.done();
                        },function(err){
                            test.strictEqual(numberOfHostsDown,clusterSize,
                                "apiCall() with hosts down: number of hosts down == clusterSize");
                            test.equal(err.message,'No available hosts!');
                            test.done();
                        });
                    });
                    for(var i=0;i<numberOfHostsDown;i++) {
                        this.servers[i].close(done);
                    }
                },
                testApiCallUndefinedMethod: function(test) {
                    this.cluster.apiCall('METH')('schema')
                        .then(function(res){
                            throw new Error("apiCall('METH') should not succeed");
                        },function(err){
                            test.ok(err,"apiCall('METH') should fail");
                            test.equal(err.message,"Invalid http method");
                        }).then(null,test.ifError).ensure(test.done);
                },
                testApiCallBadEndpoint: function(test) {
                    this.cluster.apiCall('GET')('schem')
                        .then(function(res){
                            throw new Error("apiCall('GET')('schem') has a bad endpoint and shouldn't succeed");
                        },function(err){
                            test.ok(err,"apiCall('GET')('schem') should fail");
                            test.equal(err.statusCode,404);
                        })
                        .then(null,test.ifError).ensure(test.done);
                }
            }
        },
        testSelectHost: {
            setUp: function(callback) {
                var config = new ConnectionConfig({
                    HOST_TIMEOUT: 2
                });
                this.cluster.getSession(config);
                callback();
            },
            testSelectHostWithAllHostsUp: function(test) {
                var host = this.cluster.selectHost();
                test.ok(host,"selectHost(): Test that return value truthy");
                test.done();
            },
            testSelectHostWithSomeHostsDown: {
                setUp: function(callback) {
                    this.downHosts = Math.floor(clusterSize/2);
                    var cluster = this.cluster;
                    var done = _.after(this.downHosts,function(){
                        var promises = [];
                        var attempts = 10;
                        for(var i=0;i<10;i++) {
                            promises.push(cluster.apiCall('GET')('schema'));
                        }
                        when.all(promises).ensure(function(){
                            callback();
                        });
                    });
                    for(var i=0;i<this.downHosts;i++) {
                        this.servers[i].close(done);
                    }
                },
                testSelectHost: function(test) {
                    var host = this.cluster.selectHost();
                    test.ok(host,"selectHost(): should succeed with some hosts down");
                    test.equal(host.down,undefined);
                    test.done();
                }
            }
        },
        tearDown: function(callback) {
            var done = _.after(clusterSize,callback);
            this.servers.forEach(function(s){
                try {
                    s.close(done);
                } catch(e) {
                    //server not running
                    done();
                }
            });
        }
    }
};


text:
namespace GuruComponents.Netrix.VmlDesigner.Elements
{
    /// <summary>
    /// This is the handler definition for the collection insertion event.
    /// </summary>
    public delegate void CollectionInsertHandler(int index, object @value);
    /// <summary>
    /// This is the handler definition for the collection remove event.
    /// </summary>
    public delegate void CollectionRemoveHandler(int index, object @value);
    /// <summary>
    /// This is the handler definition for the collection clear event.
    /// </summary>
    public delegate void CollectionClearHandler();
}


text:
body {
    background-color: #FF6666;
}

#header {
    background-image: url('../img/menu.png');
    background-repeat: no-repeat;
    background-size: 2rem;
    background-position: 0.5rem center;
}
ul {
    text-align: left;
}


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

using System.Diagnostics.CodeAnalysis;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.LanguageService;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.LanguageService;
using Microsoft.CodeAnalysis.UseNullPropagation;

namespace Microsoft.CodeAnalysis.CSharp.UseNullPropagation
{
    [DiagnosticAnalyzer(LanguageNames.CSharp)]
    internal class CSharpUseNullPropagationDiagnosticAnalyzer :
        AbstractUseNullPropagationDiagnosticAnalyzer<
            SyntaxKind,
            ExpressionSyntax,
            StatementSyntax,
            ConditionalExpressionSyntax,
            BinaryExpressionSyntax,
            InvocationExpressionSyntax,
            ConditionalAccessExpressionSyntax,
            ElementAccessExpressionSyntax,
            MemberAccessExpressionSyntax,
            IfStatementSyntax,
            ExpressionStatementSyntax>
    {
        protected override SyntaxKind IfStatementSyntaxKind => SyntaxKind.IfStatement;

        protected override bool ShouldAnalyze(Compilation compilation)
            => compilation.LanguageVersion() >= LanguageVersion.CSharp6;

        protected override ISyntaxFacts GetSyntaxFacts()
            => CSharpSyntaxFacts.Instance;

        protected override bool IsInExpressionTree(SemanticModel semanticModel, SyntaxNode node, INamedTypeSymbol? expressionTypeOpt, CancellationToken cancellationToken)
            => node.IsInExpressionTree(semanticModel, expressionTypeOpt, cancellationToken);

        protected override bool TryAnalyzePatternCondition(
            ISyntaxFacts syntaxFacts, ExpressionSyntax conditionNode,
            [NotNullWhen(true)] out ExpressionSyntax? conditionPartToCheck, out bool isEquals)
        {
            conditionPartToCheck = null;
            isEquals = true;

            if (conditionNode is not IsPatternExpressionSyntax patternExpression)
                return false;

            var pattern = patternExpression.Pattern;
            if (pattern is UnaryPatternSyntax(SyntaxKind.NotPattern) notPattern)
            {
                isEquals = false;
                pattern = notPattern.Pattern;
            }

            if (pattern is not ConstantPatternSyntax constantPattern)
                return false;

            if (!syntaxFacts.IsNullLiteralExpression(constantPattern.Expression))
                return false;

            conditionPartToCheck = patternExpression.Expression;
            return true;
        }

        protected override bool TryGetPartsOfIfStatement(
            IfStatementSyntax ifStatement,
            [NotNullWhen(true)] out ExpressionSyntax? condition,
            [NotNullWhen(true)] out StatementSyntax? trueStatement)
        {
            // has to be of the form:
            //
            //   if (...)
            //      statement
            //
            // or
            //
            //   if (...)
            //   {
            //       statement
            //   }

            condition = ifStatement.Condition;

            trueStatement = null;
            if (ifStatement.Else == null)
            {
                if (ifStatement.Statement is BlockSyntax block)
                {
                    if (block.Statements.Count == 1)
                        trueStatement = block.Statements[0];
                }
                else
                {
                    trueStatement = ifStatement.Statement;
                }
            }

            return trueStatement != null;
        }
    }
}