text:
#include "uv.h"
#include "internal.h"

#include <stddef.h> /* NULL */
#include <stdio.h> /* printf */
#include <stdlib.h>
#include <string.h> /* strerror */
#include <errno.h>
#include <assert.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <limits.h> /* INT_MAX, PATH_MAX */
#include <sys/uio.h> /* writev */

#ifdef __linux__
# include <sys/ioctl.h>
#endif

#ifdef __sun
# include <sys/types.h>
# include <sys/wait.h>
#endif

#ifdef __APPLE__
# include <mach-o/dyld.h> /* _NSGetExecutablePath */
# include <sys/filio.h>
# include <sys/ioctl.h>
#endif

#ifdef __FreeBSD__
# include <sys/sysctl.h>
# include <sys/filio.h>
# include <sys/ioctl.h>
# include <sys/wait.h>
#endif

static void uv__run_pending(uv_loop_t* loop);

/* Verify that uv_buf_t is ABI-compatible with struct iovec. */
STATIC_ASSERT(sizeof(uv_buf_t) == sizeof(struct iovec));
STATIC_ASSERT(sizeof(&((uv_buf_t*) 0)->base) ==
              sizeof(((struct iovec*) 0)->iov_base));
STATIC_ASSERT(sizeof(&((uv_buf_t*) 0)->len) ==
              sizeof(((struct iovec*) 0)->iov_len));
STATIC_ASSERT(offsetof(uv_buf_t, base) == offsetof(struct iovec, iov_base));
STATIC_ASSERT(offsetof(uv_buf_t, len) == offsetof(struct iovec, iov_len));

uint64_t uv_hrtime(void) {
  return uv__hrtime();
}

void uv_close(uv_handle_t* handle, uv_close_cb close_cb) {
  assert(!(handle->flags & (UV_CLOSING | UV_CLOSED)));

  handle->flags |= UV_CLOSING;
  handle->close_cb = close_cb;

  switch (handle->type) {
  case UV_NAMED_PIPE:
    uv__pipe_close((uv_pipe_t*)handle);
    break;

  case UV_TTY:
    uv__stream_close((uv_stream_t*)handle);
    break;

  case UV_TCP:
    uv__tcp_close((uv_tcp_t*)handle);
    break;

  case UV_UDP:
    uv__udp_close((uv_udp_t*)handle);
    break;

  case UV_PREPARE:
    uv__prepare_close((uv_prepare_t*)handle);
    break;

  case UV_CHECK:
    uv__check_close((uv_check_t*)handle);
    break;

  case UV_IDLE:
    uv__idle_close((uv_idle_t*)handle);
    break;

  case UV_ASYNC:
    uv__async_close((uv_async_t*)handle);
    break;

  case UV_TIMER:
    uv__timer_close((uv_timer_t*)handle);
    break;

  case UV_PROCESS:
    uv__process_close((uv_process_t*)handle);
    break;

  case UV_FS_EVENT:
    uv__fs_event_close((uv_fs_event_t*)handle);
    break;

  case UV_POLL:
    uv__poll_close((uv_poll_t*)handle);
    break;

  case UV_FS_POLL:
    uv__fs_poll_close((uv_fs_poll_t*)handle);
    break;

  case UV_SIGNAL:
    uv__signal_close((uv_signal_t*) handle);
    /* Signal handles may not be closed immediately. The signal code will */
    /* itself close uv__make_close_pending whenever appropriate. */
    return;

  default:
    assert(0);
  }

  uv__make_close_pending(handle);
}

void uv__make_close_pending(uv_handle_t* handle) {
  assert(handle->flags & UV_CLOSING);
  assert(!(handle->flags & UV_CLOSED));
  handle->next_closing = handle->loop->closing_handles;
  handle->loop->closing_handles = handle;
}

static void uv__finish_close(uv_handle_t* handle) {
  /* Note: while the handle is in the UV_CLOSING state now, it's still possible
   * for it to be active in the sense that uv__is_active() returns true.
   * A good example is when the user calls uv_shutdown(), immediately followed
   * by uv_close(). The handle is considered active at this point because the
   * completion of the shutdown req is still pending.
   */
  assert(handle->flags & UV_CLOSING);
  assert(!(handle->flags & UV_CLOSED));
  handle->flags |= UV_CLOSED;

  switch (handle->type) {
    case UV_PREPARE:
    case UV_CHECK:
    case UV_IDLE:
    case UV_ASYNC:
    case UV_TIMER:
    case UV_PROCESS:
    case UV_FS_EVENT:
    case UV_FS_POLL:
    case UV_POLL:
    case UV_SIGNAL:
      break;

    case UV_NAMED_PIPE:
    case UV_TCP:
    case UV_TTY:
      uv__stream_destroy((uv_stream_t*)handle);
      break;

    case UV_UDP:
      uv__udp_finish_close((uv_udp_t*)handle);
      break;

    default:
      assert(0);
      break;
  }

  uv__handle_unref(handle);
  QUEUE_REMOVE(&handle->handle_queue);

  if (handle->close_cb) {
    handle->close_cb(handle);
  }
}

static void uv__run_closing_handles(uv_loop_t* loop) {
  uv_handle_t* p;
  uv_handle_t* q;

  p = loop->closing_handles;
  loop->closing_handles = NULL;

  while (p) {
    q = p->next_closing;
    uv__finish_close(p);
    p = q;
  }
}

int uv_is_closing(const uv_handle_t* handle) {
  return uv__is_closing(handle);
}

int uv_backend_fd(const uv_loop_t* loop) {
  return loop->backend_fd;
}

int uv_backend_timeout(const uv_loop_t* loop) {
  if (loop->stop_flag != 0)
    return 0;

  if (!uv__has_active_handles(loop) && !uv__has_active_reqs(loop))
    return 0;

  if (!QUEUE_EMPTY(&loop->idle_handles))
    return 0;

  if (loop->closing_handles)
    return 0;

  return uv__next_timeout(loop);
}

static int uv__loop_alive(uv_loop_t* loop) {
  return uv__has_active_handles(loop) ||
         uv__has_active_reqs(loop) ||
         loop->closing_handles != NULL;
}

int uv_run(uv_loop_t* loop, uv_run_mode mode) {
  int timeout;
  int r;

  r = uv__loop_alive(loop);
  while (r != 0 && loop->stop_flag == 0) {
    UV_TICK_START(loop, mode);

    uv__update_time(loop);
    uv__run_timers(loop);
    uv__run_idle(loop);
    uv__run_prepare(loop);
    uv__run_pending(loop);

    timeout = 0;
    if ((mode & UV_RUN_NOWAIT) == 0)
      timeout = uv_backend_timeout(loop);

    uv__io_poll(loop, timeout);
    uv__run_check(loop);
    uv__run_closing_handles(loop);

    if (mode == UV_RUN_ONCE) {
      /* UV_RUN_ONCE implies forward progess: at least one callback must have
       * been invoked when it returns. uv__io_poll() can return without doing
       * I/O (meaning: no callbacks) when its timeout expires - which means we
       * have pending timers that satisfy the forward progress constraint.
       *
       * UV_RUN_NOWAIT makes no guarantees about progress so it's omitted from
       * the check.
       */
      uv__update_time(loop);
      uv__run_timers(loop);
    }

    r = uv__loop_alive(loop);
    UV_TICK_STOP(loop, mode);

    if (mode & (UV_RUN_ONCE | UV_RUN_NOWAIT))
      break;
  }

  /* The if statement lets gcc compile it to a conditional store. Avoids
   * dirtying a cache line.
   */
  if (loop->stop_flag != 0)
    loop->stop_flag = 0;

  return r;
}

void uv_update_time(uv_loop_t* loop) {
  uv__update_time(loop);
}

int uv_is_active(const uv_handle_t* handle) {
  return uv__is_active(handle);
}

/* Open a socket in non-blocking close-on-exec mode, atomically if possible. */
int uv__socket(int domain, int type, int protocol) {
  int sockfd;
  int err;

#if defined(SOCK_NONBLOCK) && defined(SOCK_CLOEXEC)
  sockfd = socket(domain, type | SOCK_NONBLOCK | SOCK_CLOEXEC, protocol);
  if (sockfd != -1)
    return sockfd;

  if (errno != EINVAL)
    return -errno;
#endif

  sockfd = socket(domain, type, protocol);
  if (sockfd == -1)
    return -errno;

  err = uv__nonblock(sockfd, 1);
  if (err == 0)
    err = uv__cloexec(sockfd, 1);

  if (err) {
    close(sockfd);
    return err;
  }

#if defined(SO_NOSIGPIPE)
  {
    int on = 1;
    setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, &on, sizeof(on));
  }
#endif

  return sockfd;
}

int uv__accept(int sockfd) {
  int peerfd;
  int err;

  assert(sockfd >= 0);

  while (1) {
#if defined(__linux__)
    static int no_accept4;

    if (no_accept4)
      goto skip;

    peerfd = uv__accept4(sockfd,
                         NULL,
                         NULL,
                         UV__SOCK_NONBLOCK|UV__SOCK_CLOEXEC);
    if (peerfd != -1)
      return peerfd;

    if (errno == EINTR)
      continue;

    if (errno != ENOSYS)
      return -errno;

    no_accept4 = 1;
skip:
#endif

    peerfd = accept(sockfd, NULL, NULL);
    if (peerfd == -1) {
      if (errno == EINTR)
        continue;
      return -errno;
    }

    err = uv__cloexec(peerfd, 1);
    if (err == 0)
      err = uv__nonblock(peerfd, 1);

    if (err) {
      close(peerfd);
      return err;
    }

    return peerfd;
  }
}

#if defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__)

int uv__nonblock(int fd, int set) {
  int r;

  do
    r = ioctl(fd, FIONBIO, &set);
  while (r == -1 && errno == EINTR);

  if (r)
    return -errno;

  return 0;
}

int uv__cloexec(int fd, int set) {
  int r;

  do
    r = ioctl(fd, set ? FIOCLEX : FIONCLEX);
  while (r == -1 && errno == EINTR);

  if (r)
    return -errno;

  return 0;
}

#else /* !(defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__)) */

int uv__nonblock(int fd, int set) {
  int flags;
  int r;

  do
    r = fcntl(fd, F_GETFL);
  while (r == -1 && errno == EINTR);

  if (r == -1)
    return -errno;

  /* Bail out now if already set/clear. */
  if (!!(r & O_NONBLOCK) == !!set)
    return 0;

  if (set)
    flags = r | O_NONBLOCK;
  else
    flags = r & ~O_NONBLOCK;

  do
    r = fcntl(fd, F_SETFL, flags);
  while (r == -1 && errno == EINTR);

  if (r)
    return -errno;

  return 0;
}

int uv__cloexec(int fd, int set) {
  int flags;
  int r;

  do
    r = fcntl(fd, F_GETFD);
  while (r == -1 && errno == EINTR);

  if (r == -1)
    return -errno;

  /* Bail out now if already set/clear. */
  if (!!(r & FD_CLOEXEC) == !!set)
    return 0;

  if (set)
    flags = r | FD_CLOEXEC;
  else
    flags = r & ~FD_CLOEXEC;

  do
    r = fcntl(fd, F_SETFD, flags);
  while (r == -1 && errno == EINTR);

  if (r)
    return -errno;

  return 0;
}

#endif /* defined(__linux__) || defined(__FreeBSD__) || defined(__APPLE__) */

/* This function is not execve-safe, there is a race window
 * between the call to dup() and fcntl(FD_CLOEXEC).
 */
int uv__dup(int fd) {
  int err;

  fd = dup(fd);

  if (fd == -1)
    return -errno;

  err = uv__cloexec(fd, 1);
  if (err) {
    close(fd);
    return err;
  }

  return fd;
}

int uv_cwd(char* buffer, size_t size) {
  if (buffer == NULL)
    return -EINVAL;

  if (size == 0)
    return -EINVAL;

  if (getcwd(buffer, size) == NULL)
    return -errno;

  return 0;
}

int uv_chdir(const char* dir) {
  if (chdir(dir))
    return -errno;

  return 0;
}

void uv_disable_stdio_inheritance(void) {
  int fd;

  /* Set the CLOEXEC flag on all open descriptors. Unconditionally try the
   * first 16 file descriptors. After that, bail out after the first error.
   */
  for (fd = 0; ; fd++)
    if (uv__cloexec(fd, 1) && fd > 15)
      break;
}

static void uv__run_pending(uv_loop_t* loop) {
  QUEUE* q;
  uv__io_t* w;

  while (!QUEUE_EMPTY(&loop->pending_queue)) {
    q = QUEUE_HEAD(&loop->pending_queue);
    QUEUE_REMOVE(q);
    QUEUE_INIT(q);

    w = QUEUE_DATA(q, uv__io_t, pending_queue);
    w->cb(loop, w, UV__POLLOUT);
  }
}

static unsigned int next_power_of_two(unsigned int val) {
  val -= 1;
  val |= val >> 1;
  val |= val >> 2;
  val |= val >> 4;
  val |= val >> 8;
  val |= val >> 16;
  val += 1;
  return val;
}

static void maybe_resize(uv_loop_t* loop, unsigned int len) {
  uv__io_t** watchers;
  unsigned int nwatchers;
  unsigned int i;

  if (len <= loop->nwatchers)
    return;

  nwatchers = next_power_of_two(len);
  watchers = realloc(loop->watchers, nwatchers * sizeof(loop->watchers[0]));

  if (watchers == NULL)
    abort();

  for (i = loop->nwatchers; i < nwatchers; i++)
    watchers[i] = NULL;

  loop->watchers = watchers;
  loop->nwatchers = nwatchers;
}

void uv__io_init(uv__io_t* w, uv__io_cb cb, int fd) {
  assert(cb != NULL);
  assert(fd >= -1);
  QUEUE_INIT(&w->pending_queue);
  QUEUE_INIT(&w->watcher_queue);
  w->cb = cb;
  w->fd = fd;
  w->events = 0;
  w->pevents = 0;

#if defined(UV_HAVE_KQUEUE)
  w->rcount = 0;
  w->wcount = 0;
#endif /* defined(UV_HAVE_KQUEUE) */
}

void uv__io_start(uv_loop_t* loop, uv__io_t* w, unsigned int events) {
  assert(0 == (events & ~(UV__POLLIN | UV__POLLOUT)));
  assert(0 != events);
  assert(w->fd >= 0);
  assert(w->fd < INT_MAX);

  w->pevents |= events;
  maybe_resize(loop, w->fd + 1);

#if !defined(__sun)
  /* The event ports backend needs to rearm all file descriptors on each and
   * every tick of the event loop but the other backends allow us to
   * short-circuit here if the event mask is unchanged.
   */
  if (w->events == w->pevents) {
    if (w->events == 0 && !QUEUE_EMPTY(&w->watcher_queue)) {
      QUEUE_REMOVE(&w->watcher_queue);
      QUEUE_INIT(&w->watcher_queue);
    }
    return;
  }
#endif

  if (QUEUE_EMPTY(&w->watcher_queue))
    QUEUE_INSERT_TAIL(&loop->watcher_queue, &w->watcher_queue);

  if (loop->watchers[w->fd] == NULL) {
    loop->watchers[w->fd] = w;
    loop->nfds++;
  }
}

void uv__io_stop(uv_loop_t* loop, uv__io_t* w, unsigned int events) {
  assert(0 == (events & ~(UV__POLLIN | UV__POLLOUT)));
  assert(0 != events);

  if (w->fd == -1)
    return;

  assert(w->fd >= 0);

  /* Happens when uv__io_stop() is called on a handle that was never started. */
  if ((unsigned) w->fd >= loop->nwatchers)
    return;

  w->pevents &= ~events;

  if (w->pevents == 0) {
    QUEUE_REMOVE(&w->watcher_queue);
    QUEUE_INIT(&w->watcher_queue);

    if (loop->watchers[w->fd] != NULL) {
      assert(loop->watchers[w->fd] == w);
      assert(loop->nfds > 0);
      loop->watchers[w->fd] = NULL;
      loop->nfds--;
      w->events = 0;
    }
  }
  else if (QUEUE_EMPTY(&w->watcher_queue))
    QUEUE_INSERT_TAIL(&loop->watcher_queue, &w->watcher_queue);
}

void uv__io_close(uv_loop_t* loop, uv__io_t* w) {
  uv__io_stop(loop, w, UV__POLLIN | UV__POLLOUT);
  QUEUE_REMOVE(&w->pending_queue);
}

void uv__io_feed(uv_loop_t* loop, uv__io_t* w) {
  if (QUEUE_EMPTY(&w->pending_queue))
    QUEUE_INSERT_TAIL(&loop->pending_queue, &w->pending_queue);
}

int uv__io_active(const uv__io_t* w, unsigned int events) {
  assert(0 == (events & ~(UV__POLLIN | UV__POLLOUT)));
  assert(0 != events);
  return 0 != (w->pevents & events);
}


text:
/**
 * Package for bank test task.
 *
 * @author Kseniya Shustova (mailto:shustovakv@mail.ru)
 * @version $Id$
 * @since 0.1
 */

package ru.job4j.bank;

redpajama_set_name: RedPajamaGithub


text:
// Example: Handling Datastore Entity Types with Magnolify

// Datastore `Entity` is a Protobuf type and very verbose. By using
// [Magnolify](https://github.com/spotify/magnolify), one can seamlessly
// convert between case classes and Datastore `Entity` types.
package com.spotify.scio.examples.extra

import com.google.datastore.v1.client.DatastoreHelper.makeKey
import com.google.datastore.v1.Query
import com.spotify.scio._
import com.spotify.scio.datastore._
import com.spotify.scio.examples.common.ExampleData
import magnolify.datastore._

object MagnolifyDatastoreExample {
  val kind = "magnolify"
  // Define case class representation of Datastore entities
  case class WordCount(word: String, count: Long)
  // `DatastoreType` provides mapping between case classes and Datatore entities
  val wordCountType: EntityType[WordCount] = EntityType[WordCount]
}

// ## Magnolify Datastore Write Example
// Count words and save result to Datastore

// Usage:

// `sbt "runMain com.spotify.scio.examples.extra.MagnolifyDatastoreWriteExample
// --project=[PROJECT] --runner=DataflowRunner --zone=[ZONE]
// --input=gs://apache-beam-samples/shakespeare/kinglear.txt
// --output=[PROJECT]"`
object MagnolifyDatastoreWriteExample {
  def main(cmdlineArgs: Array[String]): Unit = {
    import MagnolifyDatastoreExample._

    val (sc, args) = ContextAndArgs(cmdlineArgs)
    sc.textFile(args.getOrElse("input", ExampleData.KING_LEAR))
      .flatMap(_.split("[^a-zA-Z']+").filter(_.nonEmpty))
      .countByValue
      .map { t =>
        // Convert case class to `Entity.Builder`
        wordCountType
          .to(WordCount.tupled(t))
          // Set entity key
          .setKey(makeKey(kind, t._1))
          .build()
      }
      .saveAsDatastore(args("output"))
    sc.run()
    ()
  }
}

// ## Magnolify Datastore Read Example
// Read word count result back from Datastore

// Usage:

// `sbt "runMain com.spotify.scio.examples.extra.MagnolifyDatastoreReadExample
// --project=[PROJECT] --runner=DataflowRunner --zone=[ZONE]
// --input=[PROJECT]
// --output=gs://[BUCKET]/[PATH]/wordcount"`
object MagnolifyDatastoreReadExample {
  def main(cmdlineArgs: Array[String]): Unit = {
    import MagnolifyDatastoreExample._

    val (sc, args) = ContextAndArgs(cmdlineArgs)
    sc.datastore(args("input"), Query.getDefaultInstance)
      // Convert `Entity` to case class
      .map(e => wordCountType(e))
      .map(wc => wc.word + ": " + wc.count)
      .saveAsTextFile(args("output"))
    sc.run()
    ()
  }
}


text: Web application for experimental soccer odds analyzer.


text:
package com.infinityraider.infinitylib.utility;

@FunctionalInterface
public interface CoordinateConsumer {
    void accept(double x, double y, double z);
}


text:
<?xml version='1.0' encoding='UTF-8'?>
<!-- Copyright FUJITSU LIMITED 2017-->

<dataset>
  <Organization
    tkey="10"
    version="0"
    organizationid="CUSTOMER1"
    name="OrgA"
    registrationdate="1234"/>

  <Technicalproduct
    tkey="1000"
    provisioningurl="testurl"
    technicalproductid="tpid1"
    technicalproductversion="1.0 9 9"
    version="1"
    organizationkey="10"/>

  <Technicalproduct
    tkey="1001"
    provisioningurl="testurl"
    technicalproductid="tpid1 1.0"
    technicalproductversion="9 9"
    version="1"
    organizationkey="10"/>

  <Technicalproduct
    tkey="1002"
    provisioningurl="testurl"
    technicalproductid="tpid1 1.0 9"
    technicalproductversion="9"
    version="1"
    organizationkey="10"/>

  <Technicalproducthistory
    tkey="100"
    provisioningurl="testurl"
    technicalproductid="tpid1"
    technicalproductversion="1.0 9 9"
    moddate="2011-05-5 14:30:00"
    modtype="modtype"
    moduser="moduser"
    objkey="1001"
    objversion="1"
    organizationobjkey="10"
    invocationdate="2011-05-5 14:30:00"/>

  <Technicalproducthistory
    tkey="101"
    provisioningurl="testurl"
    technicalproductid="tpid1 1.0"
    technicalproductversion="9 9"
    moddate="2011-05-5 14:30:00"
    modtype="modtype"
    moduser="moduser"
    objkey="1002"
    objversion="1"
    organizationobjkey="10"
    invocationdate="2011-05-5 14:30:00"/>

</dataset>


text:
namespace Forum.App.Contracts
{
	public interface ITextAreaFactory
	{
		ITextInputArea CreateTextArea(IForumReader reader, int x, int y, bool isPost = true);
	}
}


text:
import unittest

import numpy as np
import paddle
import paddle.static
from paddle.fluid.tests.unittests.ipu.op_test_ipu import IPUOpTest

class TestBase(IPUOpTest):
    def setUp(self):
        self.set_atol()
        self.set_test_op()
        self.set_training()
        self.set_data_feed()
        self.set_feed_attr()

    def set_test_op(self):
        self.op = paddle.abs
        self.op_attrs = {}

    def set_data_feed(self):
        data = np.random.uniform(size=[1, 3, 10, 10])
        self.feed_fp32 = {'in_0': data.astype(np.float32)}
        self.feed_fp16 = {'in_0': data.astype(np.float16)}

    def set_feed_attr(self):
        self.feed_shape = [x.shape for x in self.feed_fp32.values()]
        self.feed_list = list(self.feed_fp32.keys())

    @IPUOpTest.static_graph
    def build_model(self):
        x = paddle.static.data(
            name=self.feed_list[0], shape=self.feed_shape[0], dtype='float32'
        )
        out = self.op(x, **self.op_attrs)
        self.fetch_list = [out.name]

    def run_model(self, exec_mode):
        self.run_op_test(exec_mode)

    def test(self):
        for m in IPUOpTest.ExecutionMode:
            if not self.skip_mode(m):
                self.build_model()
                self.run_model(m)
        self.check()

class TestAcos(TestBase):
    @property
    def fp16_enabled(self):
        return False

    def set_atol(self):
        super().set_atol()
        self.atol = 1e-6

    def set_test_op(self):
        self.op = paddle.acos
        self.op_attrs = {}

class TestAsin(TestAcos):
    def set_test_op(self):
        self.op = paddle.asin
        self.op_attrs = {}

class TestSinh(TestAcos):
    def set_test_op(self):
        self.op = paddle.sinh
        self.op_attrs = {}

class TestAtan(TestBase):
    def set_test_op(self):
        self.op = paddle.atan
        self.op_attrs = {}

class TestCeil(TestBase):
    def set_test_op(self):
        self.op = paddle.ceil
        self.op_attrs = {}

class TestCos(TestBase):
    def set_test_op(self):
        self.op = paddle.cos
        self.op_attrs = {}

class TestCosh(TestBase):
    def set_test_op(self):
        self.op = paddle.cosh
        self.op_attrs = {}

class TestErf(TestBase):
    def set_test_op(self):
        self.op = paddle.erf
        self.op_attrs = {}

class TestExp(TestBase):
    def set_test_op(self):
        self.op = paddle.exp
        self.op_attrs = {}

class TestFloor(TestBase):
    @property
    def fp16_enabled(self):
        return False

    def set_test_op(self):
        self.op = paddle.floor
        self.op_attrs = {}

class TestLog(TestBase):
    def set_test_op(self):
        self.op = paddle.log
        self.op_attrs = {}

class TestReciprocal(TestBase):
    def set_test_op(self):
        self.op = paddle.reciprocal
        self.op_attrs = {}

class TestRelu(TestBase):
    def set_test_op(self):
        self.op = paddle.fluid.layers.relu
        self.op_attrs = {}

class TestRound(TestBase):
    def set_test_op(self):
        self.op = paddle.round
        self.op_attrs = {}

class TestSigmoid(TestBase):
    def set_test_op(self):
        self.op = paddle.nn.functional.sigmoid
        self.op_attrs = {}

class TestSign(TestBase):
    def set_test_op(self):
        self.op = paddle.sign
        self.op_attrs = {}

class TestSin(TestBase):
    def set_test_op(self):
        self.op = paddle.sin
        self.op_attrs = {}

class TestSoftplus(TestBase):
    def set_test_op(self):
        self.op = paddle.nn.functional.softplus
        self.op_attrs = {}

class TestSoftsign(TestBase):
    def set_test_op(self):
        self.op = paddle.nn.functional.softsign
        self.op_attrs = {}

class TestSqrt(TestBase):
    def set_test_op(self):
        self.op = paddle.sqrt
        self.op_attrs = {}

class TestTan(TestBase):
    def set_test_op(self):
        self.op = paddle.tan
        self.op_attrs = {}

class TestTanh(TestBase):
    def set_test_op(self):
        self.op = paddle.tanh
        self.op_attrs = {}

if __name__ == "__main__":
    unittest.main()


text:
/* eslint-disable */
import 'babel-polyfill';
import './tools';
import 'jquery-form';
import Backbone from 'backbone';
import Wreqr from 'backbone.wreqr';
import Marionette from 'backbone.marionette';
import '../lib/l20n.min.js';
import SmoothScrollPolyfill from 'smoothscroll-polyfill';

import 'ionicons/css/ionicons.css';
import 'font-awesome/css/font-awesome.min.css';
import 'bootstrap-webpack';
import 'awesome-bootstrap-checkbox/awesome-bootstrap-checkbox.css';
import 'bootstrap-filestyle';
import 'bootstrap-more/bootstrap-more.css';
import 'bootstrap-more/bootstrap-more.js';
import 'leaflet/dist/leaflet.css';

import CONST from 'const';
import GlobalRouter from 'router/global';
import UserModel from 'model/user';
import UserThemeCollection from 'collection/userTheme';
import UserFavoriteThemes from 'core/userFavoriteThemes';
import UserFavoriteThemesDataCollection from 'collection/userFavoriteThemesData';
import ThemeModel from 'model/theme';
import OwnerCollection from 'collection/owner';
import NonOsmDataCollection from 'collection/nonOsmData';
import OsmCacheCollection from 'collection/osmCache';
import LayerCollection from 'collection/layer';
import Behaviors from './behavior';
import { getUserInfoFromId } from 'helper/osmUsers';
import IDPresetsHelper from 'helper/iDPresets';
/* eslint-enable */

export default Marionette.Application.extend({
  regions: {
    root: '#rg_root'
  },

  initialize(window) {
    window.document.l10n.addEventListener('error', err => {
      console.error(`L20n: ${err}`); // eslint-disable-line
    });

    window.document.l10n.addEventListener('warning', err => {
      console.warn(`L20n: ${err}`); // eslint-disable-line
    });

    SmoothScrollPolyfill.polyfill();

    this._radio = Wreqr.radio.channel('global');

    this._radio.vent.on('session:logged', () => {
      this._isLogged = true;
      window.document.body.classList.add('user_logged');
    });

    this._radio.vent.on('session:unlogged', () => {
      this._isLogged = false;
      window.document.body.classList.remove('user_logged');
      this._user = new UserModel();
    });

    Marionette.Behaviors.behaviorsLookup = Behaviors;

    this._isLogged = false;
    this._isThemePage = false;
    this._isHomePage = false;
    this._window = window;
    this._tempLayerCollection = new LayerCollection();

    if (window.MAPCONTRIB) {
      this._config = MAPCONTRIB.config;
      this._version = MAPCONTRIB.version;
      this._user = new UserModel(JSON.parse(unescape(MAPCONTRIB.user)));

      this._tiles = {
        ...CONST.map.tiles,
        ...this._config.customTiles
      };

      if (MAPCONTRIB.user) {
        this._user = new UserModel(JSON.parse(unescape(MAPCONTRIB.user)));
      }

      if (MAPCONTRIB.userThemes) {
        this._userThemes = new UserThemeCollection(
          JSON.parse(unescape(MAPCONTRIB.userThemes))
        );
      }

      if (MAPCONTRIB.userFavoriteThemesData) {
        this._userFavoriteThemes = new UserFavoriteThemes(
          this._user,
          new UserFavoriteThemesDataCollection(
            JSON.parse(unescape(MAPCONTRIB.userFavoriteThemesData))
          )
        );
      }

      if (MAPCONTRIB.theme) {
        this._theme = new ThemeModel(JSON.parse(unescape(MAPCONTRIB.theme)));
      }

      if (MAPCONTRIB.owners) {
        this._owners = new OwnerCollection(
          JSON.parse(unescape(MAPCONTRIB.owners))
        );
      }

      if (MAPCONTRIB.unknownOwners) {
        const unknownOwners = JSON.parse(unescape(MAPCONTRIB.unknownOwners));

        unknownOwners.map(osmUserId => {
          getUserInfoFromId(osmUserId).then(userInfos => {
            this._owners.add({
              osmId: userInfos.id,
              displayName: userInfos.displayName,
              avatar: userInfos.avatar
            });
          });
        });
      }

      if (MAPCONTRIB.nonOsmData) {
        this._nonOsmData = new NonOsmDataCollection(
          JSON.parse(unescape(MAPCONTRIB.nonOsmData))
        );
      }

      if (MAPCONTRIB.osmCache) {
        this._osmCache = new OsmCacheCollection(
          JSON.parse(unescape(MAPCONTRIB.osmCache))
        );
      }

      if (MAPCONTRIB.iDPresets) {
        this._iDPresetsHelper = new IDPresetsHelper(
          JSON.parse(unescape(MAPCONTRIB.iDPresets))
        );

        $.get({
          async: false,
          url: `${CONST.apiPath}/iDPresets/locale`,
          data: { locales: document.l10n.supportedLocales },
          success: this.onReceiveIDPresetsLocale.bind(this)
        });
      }
    }

    const bodyClasses = window.document.body.className.split(' ');
    if (bodyClasses.indexOf('page_home') > -1) {
      this._isHomePage = true;
    } else if (bodyClasses.indexOf('page_theme') > -1) {
      this._isThemePage = true;
    }
  },

  getWindow() {
    return this._window;
  },

  getDocument() {
    return this._window.document;
  },

  getRouter() {
    return this._router;
  },

  getUser() {
    return this._user;
  },

  getUserThemes() {
    return this._userThemes;
  },

  getOwners() {
    return this._owners;
  },

  getUserFavoriteThemes() {
    return this._userFavoriteThemes;
  },

  getConfig() {
    return this._config;
  },

  getVersion() {
    return this._version;
  },

  getTheme() {
    return this._theme;
  },

  getTiles() {
    return this._tiles;
  },

  getTempLayerCollection() {
    return this._tempLayerCollection;
  },

  getNonOsmData() {
    return this._nonOsmData;
  },

  getOsmCache() {
    return this._osmCache;
  },

  getIDPresetsHelper() {
    return this._iDPresetsHelper;
  },

  isLogged() {
    return this._isLogged;
  },

  isThemePage() {
    return this._isThemePage;
  },

  isHomePage() {
    return this._isHomePage;
  },

  onStart(options) {
    const Router = options.router;
    const RootView = options.rootView;

    if (this._user && this._user.get('_id')) {
      this._radio.vent.trigger('session:logged');
    }

    this._globalRouter = new GlobalRouter(this);

    if (Router) {
      this._router = new Router(this);
      this._radio.reqres.setHandler('router', () => this._router);
    }

    Backbone.history.start();

    this.getRegion('root').show(new RootView({ app: this }));
  },

  onReceiveIDPresetsLocale(response) {
    this._iDPresetsHelper.setLocaleStrings(JSON.parse(response));

    this._radio.vent.trigger('iDPresets:loaded');
  }
});


text:
namespace {

const char kManifest[] =
    "{"
    " \"version\" : \"1.0.0.0\","
    " \"manifest_version\" : 2,"
    " \"name\" : \"Test\","
    " \"chrome_settings_overrides\" : {"
    "   \"homepage\" : \"http://www.homepage.com\","
    "   \"search_provider\" : {"
    "        \"name\" : \"first\","
    "        \"keyword\" : \"firstkey\","
    "        \"search_url\" : \"http://www.foo.com/s?q={searchTerms}\","
    "        \"favicon_url\" : \"http://www.foo.com/favicon.ico\","
    "        \"suggest_url\" : \"http://www.foo.com/s?q={searchTerms}\","
    "        \"encoding\" : \"UTF-8\","
    "        \"is_default\" : true"
    "    },"
    "   \"startup_pages\" : [\"http://www.startup.com\"]"
    "  }"
    "}";

const char kPrepopulatedManifest[] =
    "{"
    " \"version\" : \"1.0.0.0\","
    " \"manifest_version\" : 2,"
    " \"name\" : \"Test\","
    " \"chrome_settings_overrides\" : {"
    "   \"search_provider\" : {"
    "        \"search_url\" : \"http://www.foo.com/s?q={searchTerms}\","
    "        \"prepopulated_id\" : 3,"
    "        \"is_default\" : true"
    "    }"
    "  }"
    "}";

const char kBrokenManifestEmpty[] = R"(
{
  "version" : "1.0.0.0",
  "manifest_version" : 2,
  "name" : "Test",
  "chrome_settings_overrides" : {}
})";

const char kBrokenManifestHomepage[] = R"(
{
  "version" : "1.0.0.0",
  "manifest_version" : 2,
  "name" : "Test",
  "chrome_settings_overrides" : {
    "homepage" : "{invalid}"
  }
})";

const char kBrokenManifestStartupPages[] = R"(
{
  "version" : "1.0.0.0",
  "manifest_version" : 2,
  "name" : "Test",
  "chrome_settings_overrides" : {
    "startup_pages" : ["{invalid}"]
  }
})";

const char kManifestBrokenHomepageButCorrectStartupPages[] = R"(
{
  "version" : "1.0.0.0",
  "manifest_version" : 2,
  "name" : "Test",
  "chrome_settings_overrides" : {
    "homepage" : "{invalid}",
    "startup_pages" : ["http://www.startup.com"]
  }
})";

const char kManifestBrokenStartupPagesButCorrectHomepage[] = R"(
{
  "version" : "1.0.0.0",
  "manifest_version" : 2,
  "name" : "Test",
  "chrome_settings_overrides" : {
    "homepage": "http://www.homepage.com",
    "startup_pages" : ["{invalid}"]
  }
})";

using extensions::DictionaryBuilder;
using extensions::Extension;
using extensions::Manifest;
using extensions::SettingsOverrides;
using extensions::api::manifest_types::ChromeSettingsOverrides;
namespace manifest_keys = extensions::manifest_keys;

scoped_refptr<Extension> CreateExtension(const base::DictionaryValue& manifest,
                                         std::string* error) {
  scoped_refptr<Extension> extension =
      Extension::Create(base::FilePath(FILE_PATH_LITERAL("//nonexistent")),
                        extensions::mojom::ManifestLocation::kInvalidLocation,
                        manifest, Extension::NO_FLAGS, error);
  return extension;
}

scoped_refptr<Extension> CreateExtension(base::StringPiece manifest,
                                         std::string* error) {
  JSONStringValueDeserializer json(manifest);
  std::unique_ptr<base::Value> root(json.Deserialize(nullptr, error));
  if (!root) {
    ADD_FAILURE() << "Could not deserialize manifest";
    return nullptr;
  }
  if (!root->is_dict()) {
    ADD_FAILURE() << "Manifest isn't a Dictionary";
    return nullptr;
  }
  return CreateExtension(*static_cast<base::DictionaryValue*>(root.get()),
                         error);
}

scoped_refptr<Extension> CreateExtensionWithSearchProvider(
    std::unique_ptr<base::DictionaryValue> search_provider,
    std::string* error) {
  DictionaryBuilder manifest;
  manifest.Set("name", "name")
      .Set("manifest_version", 2)
      .Set("version", "0.1")
      .Set("description", "desc")
      .Set("chrome_settings_overrides",
           DictionaryBuilder()
               .Set("search_provider", std::move(search_provider))
               .Build());
  return CreateExtension(*manifest.Build(), error);
}

TEST(OverrideSettingsTest, ParseManifest) {
  std::string error;
  scoped_refptr<Extension> extension = CreateExtension(kManifest, &error);
  ASSERT_TRUE(extension.get());
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)
  ASSERT_TRUE(
      extension->manifest()->FindPath(manifest_keys::kSettingsOverride));

  SettingsOverrides* settings_override = static_cast<SettingsOverrides*>(
      extension->GetManifestData(manifest_keys::kSettingsOverride));
  ASSERT_TRUE(settings_override);
  ASSERT_TRUE(settings_override->search_engine);
  EXPECT_TRUE(settings_override->search_engine->is_default);
  const auto& search_engine = settings_override->search_engine;
  EXPECT_EQ("first", *search_engine->name);
  EXPECT_EQ("firstkey", *search_engine->keyword);
  EXPECT_EQ("http://www.foo.com/s?q={searchTerms}", search_engine->search_url);
  EXPECT_EQ("http://www.foo.com/favicon.ico", *search_engine->favicon_url);
  EXPECT_EQ("http://www.foo.com/s?q={searchTerms}",
            *search_engine->suggest_url);
  EXPECT_EQ("UTF-8", *search_engine->encoding);

  EXPECT_EQ(std::vector<GURL>(1, GURL("http://www.startup.com")),
            settings_override->startup_pages);

  ASSERT_TRUE(settings_override->homepage);
  EXPECT_EQ(GURL("http://www.homepage.com"), *settings_override->homepage);
#else
  EXPECT_FALSE(
      extension->manifest()->FindPath(manifest_keys::kSettingsOverride));
#endif
}

TEST(OverrideSettingsTest, ParsePrepopulatedId) {
  std::string error;
  scoped_refptr<Extension> extension =
      CreateExtension(kPrepopulatedManifest, &error);
  ASSERT_TRUE(extension.get());
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)
  ASSERT_TRUE(
      extension->manifest()->FindPath(manifest_keys::kSettingsOverride));

  SettingsOverrides* settings_override = static_cast<SettingsOverrides*>(
      extension->GetManifestData(manifest_keys::kSettingsOverride));
  ASSERT_TRUE(settings_override);
  ASSERT_TRUE(settings_override->search_engine);
  EXPECT_TRUE(settings_override->search_engine->is_default);
  const auto& search_engine = settings_override->search_engine;
  ASSERT_TRUE(search_engine->prepopulated_id);
  EXPECT_EQ("http://www.foo.com/s?q={searchTerms}", search_engine->search_url);
  EXPECT_EQ(3, *search_engine->prepopulated_id);
#else
  EXPECT_FALSE(
      extension->manifest()->FindPath(manifest_keys::kSettingsOverride));
#endif
}

TEST(OverrideSettingsTest, ParseManifestBrokenHomepageButCorrectStartupPages) {
  std::string error;
  scoped_refptr<Extension> extension =
      CreateExtension(kManifestBrokenHomepageButCorrectStartupPages, &error);
  ASSERT_TRUE(extension.get());
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)
  ASSERT_TRUE(
      extension->manifest()->FindPath(manifest_keys::kSettingsOverride));

  SettingsOverrides* settings_override = static_cast<SettingsOverrides*>(
      extension->GetManifestData(manifest_keys::kSettingsOverride));
  ASSERT_TRUE(settings_override);
  EXPECT_EQ(std::vector<GURL>(1, GURL("http://www.startup.com")),
            settings_override->startup_pages);
#else
  EXPECT_FALSE(
      extension->manifest()->FindPath(manifest_keys::kSettingsOverride));
#endif
}

TEST(OverrideSettingsTest, ParseManifestBrokenStartupPagesButCorrectHomepage) {
  std::string error;
  scoped_refptr<Extension> extension =
      CreateExtension(kManifestBrokenStartupPagesButCorrectHomepage, &error);
  ASSERT_TRUE(extension.get());
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)
  ASSERT_TRUE(
      extension->manifest()->FindPath(manifest_keys::kSettingsOverride));
  SettingsOverrides* settings_override = static_cast<SettingsOverrides*>(
      extension->GetManifestData(manifest_keys::kSettingsOverride));
  ASSERT_TRUE(settings_override);
  EXPECT_TRUE(settings_override->startup_pages.empty());
  EXPECT_EQ(GURL("http://www.homepage.com"), *settings_override->homepage);
#else
  EXPECT_FALSE(
      extension->manifest()->FindPath(manifest_keys::kSettingsOverride));
#endif
}

TEST(OverrideSettingsTest, ParseBrokenManifestEmptySettingsOverride) {
  std::string error;
  scoped_refptr<Extension> extension =
      CreateExtension(kBrokenManifestEmpty, &error);
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)
  EXPECT_FALSE(extension.get());
  EXPECT_EQ(
      extensions::ErrorUtils::FormatErrorMessage(
          extensions::manifest_errors::kInvalidEmptyDictionary,
          extensions::manifest_keys::kSettingsOverride),
      error);
#else
  ASSERT_TRUE(extension.get());
  EXPECT_FALSE(
      extension->manifest()->FindPath(manifest_keys::kSettingsOverride));
#endif
}

TEST(OverrideSettingsTest, ParseBrokenManifestHomepage) {
  std::string error;
  scoped_refptr<Extension> extension =
      CreateExtension(kBrokenManifestHomepage, &error);
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)
  EXPECT_FALSE(extension.get());
  EXPECT_EQ(extensions::ErrorUtils::FormatErrorMessage(
                extensions::manifest_errors::kInvalidHomepageOverrideURL,
                "{invalid}"),
            error);
#else
  ASSERT_TRUE(extension.get());
  EXPECT_FALSE(
      extension->manifest()->FindPath(manifest_keys::kSettingsOverride));
#endif
}

TEST(OverrideSettingsTest, ParseBrokenManifestStartupPages) {
  std::string error;
  scoped_refptr<Extension> extension =
      CreateExtension(kBrokenManifestStartupPages, &error);
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)
  EXPECT_FALSE(extension.get());
  EXPECT_EQ(
      extensions::ErrorUtils::FormatErrorMessage(
          extensions::manifest_errors::kInvalidStartupOverrideURL, "{invalid}"),
      error);
#else
  ASSERT_TRUE(extension.get());
  EXPECT_FALSE(
      extension->manifest()->FindPath(manifest_keys::kSettingsOverride));
#endif
}

TEST(OverrideSettingsTest, SearchProviderMissingKeys) {
  struct KeyValue {
    const char* key;
    const char* value;
  } kMandatorySearchProviderKeyValues[] = {
      {"name", "first"},
      {"keyword", "firstkey"},
      {"encoding", "UTF-8"},
      {"favicon_url", "http://www.foo.com/favicon.ico"},
  };

  DictionaryBuilder search_provider;
  search_provider.Set("search_url", "http://www.foo.com/s?q={searchTerms}")
      .Set("is_default", true);
  for (const KeyValue& kv : kMandatorySearchProviderKeyValues)
    search_provider.Set(kv.key, kv.value);
  std::unique_ptr<base::DictionaryValue> search_provider_with_all_keys_dict =
      search_provider.Build();

  // Missing all keys from |kMandatorySearchProviderValues|.
  for (const KeyValue& kv : kMandatorySearchProviderKeyValues) {
    SCOPED_TRACE(testing::Message()
                 << "key = " << kv.key << " value = " << kv.value);
    // Build a search provider entry with |kv.key| missing:
    std::unique_ptr<base::DictionaryValue> provider_with_missing_key =
        base::DictionaryValue::From(base::Value::ToUniquePtrValue(
            search_provider_with_all_keys_dict->Clone()));
    ASSERT_TRUE(provider_with_missing_key->RemovePath(kv.key));

    std::string error;
    scoped_refptr<Extension> extension = CreateExtensionWithSearchProvider(
        std::move(provider_with_missing_key), &error);
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)
    EXPECT_FALSE(extension.get());
    EXPECT_EQ(extensions::ErrorUtils::FormatErrorMessage(
                  extensions::manifest_errors::kInvalidSearchEngineMissingKeys,
                  kv.key),
              error);
#else
    ASSERT_TRUE(extension.get());
    EXPECT_FALSE(
        extension->manifest()->FindPath(manifest_keys::kSettingsOverride));
#endif
  }
}

}  // namespace


text:
<?php

namespace Sonata\ClassificationBundle\Entity;

use Sonata\ClassificationBundle\Model\CategoryInterface;
use Sonata\CoreBundle\Model\BaseEntityManager;
use Sonata\DoctrineORMAdminBundle\Datagrid\Pager;
use Sonata\DoctrineORMAdminBundle\Datagrid\ProxyQuery;
use Sonata\AdminBundle\Datagrid\PagerInterface;

class CategoryManager extends BaseEntityManager
{
    /**
     * @var array
     */
    protected $categories;

    /**
     * Returns a pager to iterate over the root category
     *
     * @param integer $page
     * @param integer $limit
     * @param array   $criteria
     *
     * @return mixed
     */
    public function getRootCategoriesPager($page = 1, $limit = 25, $criteria = array())
    {
        $page = (int) $page == 0 ? 1 : (int) $page;

        $queryBuiler = $this->getRepository()->createQueryBuilder()
            ->select('c')
            ->from($this->class, 'c')
            ->andWhere('c.parent IS NULL');

        $pager = new Pager($limit);
        $pager->setQuery(new ProxyQuery($queryBuiler));
        $pager->setPage($page);
        $pager->init();

        return $pager;
    }

    /**
     * @param integer $categoryId
     * @param integer $page
     * @param integer $limit
     * @param array   $criteria
     *
     * @return PagerInterface
     */
    public function getSubCategoriesPager($categoryId, $page = 1, $limit = 25, $criteria = array())
    {
        $queryBuiler = $this->getRepository()->createQueryBuilder()
            ->select('c')
            ->from($this->class, 'c')
            ->where('c.parent = :categoryId')
            ->setParameter('categoryId', $categoryId);

        $pager = new Pager($limit);
        $pager->setQuery(new ProxyQuery($queryBuiler));
        $pager->setPage($page);
        $pager->init();

        return $pager;
    }

    /**
     * @return CategoryInterface
     */
    public function getRootCategory()
    {
        $this->loadCategories();

        return $this->categories[0];
    }

    /**
     * @return array
     */
    public function getCategories()
    {
        $this->loadCategories();

        return $this->categories;
    }

    /**
     * Load all categories from the database, the current method is very efficient for < 256 categories
     *
     */
    protected function loadCategories()
    {
        if ($this->categories !== null) {
            return;
        }

        $class = $this->getClass();

        $root = $this->create();
        $root->setName('root');

        $this->categories = array(
            0 => $root
        );

        $categories = $this->getObjectManager()->createQuery(sprintf('SELECT c FROM %s c INDEX BY c.id', $class))
            ->execute();

        foreach ($categories as $category) {
            $this->categories[$category->getId()] = $category;

            $parent = $category->getParent();

            $category->disableChildrenLazyLoading();

            if (!$parent) {
                $root->addChild($category, true);

                continue;
            }

            $parent->addChild($category);
        }
    }
}


text:
from __future__ import absolute_import, division, print_function

from ._config import from_config, load_config, load_yaml_config
from ._dependencies import dependencies
from ._version import get_versions
from .core import (archive_file, ensure_proxies, promote, provenance,
                   provenance_set)
from .hashing import hash, value_repr
from .repos import (capture_set, create_set, current_config,
                    get_check_mutations, get_default_repo, get_repo_by_name,
                    load_set_by_id, load_set_by_name, load_set_by_labels,
                    get_read_only, get_use_cache, is_proxy, lazy_dict,
                    lazy_proxy_dict, load_artifact, load_proxy,
                    set_check_mutations, set_default_repo, set_run_info_fn,
                    set_read_only, set_use_cache, using_repo)
from .serializers import register_serializer

__version__ = get_versions()['version']
del get_versions


text:
/*
 * Do not modify this file. This file is generated from the cloudformation-2010-05-15.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

using Amazon.Runtime;
using Amazon.Runtime.Internal;

namespace Amazon.CloudFormation.Model
{
    ///
    /// The output for a ListStackResources action.
    ///
    public partial class ListStackResourcesResponse : AmazonWebServiceResponse
    {
        private string _nextToken;
        private List<StackResourceSummary> _stackResourceSummaries = new List<StackResourceSummary>();

        ///
        /// Gets and sets the property NextToken.
        /// <para>
        /// String that identifies the start of the next list of stack resources, if there is
        /// one.
        /// </para>
        ///
        public string NextToken
        {
            get { return this._nextToken; }
            set { this._nextToken = value; }
        }

        // Check to see if NextToken property is set
        internal bool IsSetNextToken()
        {
            return this._nextToken != null;
        }

        ///
        /// Gets and sets the property StackResourceSummaries.
        /// <para>
        /// A list of StackResourceSummary structures.
        /// </para>
        ///
        public List<StackResourceSummary> StackResourceSummaries
        {
            get { return this._stackResourceSummaries; }
            set { this._stackResourceSummaries = value; }
        }

        // Check to see if StackResourceSummaries property is set
        internal bool IsSetStackResourceSummaries()
        {
            return this._stackResourceSummaries != null && this._stackResourceSummaries.Count > 0;
        }

    }
}


text:
// Expose chromium_sqlite3_* functions from Chromium's patched SQLite.
#define CHROMIUM_SQLITE_INTERNALS

#include "modules/webdatabase/sqlite/SQLiteFileSystem.h"

#include <windows.h>
#include "public/platform/Platform.h"
#include "third_party/sqlite/sqlite3.h"

namespace blink {

// Chromium's Windows implementation of SQLite VFS
namespace {

// Opens a file.
//
// vfs - pointer to the sqlite3_vfs object.
// fileName - the name of the file.
// id - the structure that will manipulate the newly opened file.
// desiredFlags - the desired open mode flags.
// usedFlags - the actual open mode flags that were used.
int chromiumOpen(sqlite3_vfs*, const char* fileName, sqlite3_file* id, int desiredFlags, int* usedFlags)
{
    HANDLE h = Platform::current()->databaseOpenFile(String(fileName), desiredFlags);
    if (h == INVALID_HANDLE_VALUE) {
        if (desiredFlags & SQLITE_OPEN_READWRITE) {
            int newFlags = (desiredFlags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE;
            return chromiumOpen(0, fileName, id, newFlags, usedFlags);
        } else
            return SQLITE_CANTOPEN;
    }
    if (usedFlags) {
        if (desiredFlags & SQLITE_OPEN_READWRITE)
            *usedFlags = SQLITE_OPEN_READWRITE;
        else
            *usedFlags = SQLITE_OPEN_READONLY;
    }

    chromium_sqlite3_initialize_win_sqlite3_file(id, h);
    return SQLITE_OK;
}

// Deletes the given file.
//
// vfs - pointer to the sqlite3_vfs object.
// fileName - the name of the file.
// syncDir - determines if the directory to which this file belongs
//           should be synched after the file is deleted.
int chromiumDelete(sqlite3_vfs*, const char* fileName, int)
{
    return Platform::current()->databaseDeleteFile(String(fileName), false);
}

// Check the existance and status of the given file.
//
// vfs - pointer to the sqlite3_vfs object.
// fileName - the name of the file.
// flag - the type of test to make on this file.
// res - the result.
int chromiumAccess(sqlite3_vfs*, const char* fileName, int flag, int* res)
{
    DWORD attr = Platform::current()->databaseGetFileAttributes(String(fileName));
    switch (flag) {
    case SQLITE_ACCESS_READ:
    case SQLITE_ACCESS_EXISTS:
        *res = (attr != INVALID_FILE_ATTRIBUTES);
        break;
    case SQLITE_ACCESS_READWRITE:
        *res = ((attr & FILE_ATTRIBUTE_READONLY) == 0);
        break;
    default:
        return SQLITE_ERROR;
    }

    return SQLITE_OK;
}

// Turns a relative pathname into a full pathname.
//
// vfs - pointer to the sqlite3_vfs object.
// relativePath - the relative path.
// bufSize - the size of the output buffer in bytes.
// absolutePath - the output buffer where the absolute path will be stored.
int chromiumFullPathname(sqlite3_vfs* vfs, const char* relativePath, int bufSize, char* absolutePath)
{
    // The renderer process doesn't need to know the absolute path of the file
    sqlite3_snprintf(bufSize, absolutePath, "%s", relativePath);
    return SQLITE_OK;
}

// Do not allow loading libraries in the renderer.
void* chromiumDlOpen(sqlite3_vfs*, const char*)
{
    return 0;
}

void chromiumDlError(sqlite3_vfs*, int bufSize, char* errorBuffer)
{
    sqlite3_snprintf(bufSize, errorBuffer, "Dynamic loading not supported");
}

void(*chromiumDlSym(sqlite3_vfs*, void *, const char*))(void)
{
    return 0;
}

void chromiumDlClose(sqlite3_vfs*, void*)
{
}

int chromiumRandomness(sqlite3_vfs *vfs, int bufSize, char *buffer)
{
    sqlite3_vfs* wrappedVfs = static_cast<sqlite3_vfs*>(vfs->pAppData);
    return wrappedVfs->xRandomness(wrappedVfs, bufSize, buffer);
}

int chromiumSleep(sqlite3_vfs *vfs, int microseconds)
{
    sqlite3_vfs* wrappedVfs = static_cast<sqlite3_vfs*>(vfs->pAppData);
    return wrappedVfs->xSleep(wrappedVfs, microseconds);
}

int chromiumCurrentTime(sqlite3_vfs *vfs, double *prNow)
{
    sqlite3_vfs* wrappedVfs = static_cast<sqlite3_vfs*>(vfs->pAppData);
    return wrappedVfs->xCurrentTime(wrappedVfs, prNow);
}

int chromiumGetLastError(sqlite3_vfs *vfs, int e, char* s)
{
    // xGetLastError() has never been used by SQLite.  The implementation in os_win.c indicates this is a reasonable implementation.
    *s = '\0';
    return 0;
}

} // namespace

void SQLiteFileSystem::registerSQLiteVFS()
{
    sqlite3_vfs* wrappedVfs = sqlite3_vfs_find("win32");

    // These are implemented by delegating to |wrappedVfs|.
    // TODO(shess): Implement local versions.
    ASSERT(wrappedVfs->xRandomness);
    ASSERT(wrappedVfs->xSleep);
    ASSERT(wrappedVfs->xCurrentTime);

    static sqlite3_vfs chromium_vfs = {
        1,
        wrappedVfs->szOsFile,
        wrappedVfs->mxPathname,
        0,
        "chromium_vfs",
        wrappedVfs,
        chromiumOpen,
        chromiumDelete,
        chromiumAccess,
        chromiumFullPathname,
        chromiumDlOpen,
        chromiumDlError,
        chromiumDlSym,
        chromiumDlClose,
        chromiumRandomness,
        chromiumSleep,
        chromiumCurrentTime,
        chromiumGetLastError
    };
    sqlite3_vfs_register(&chromium_vfs, 0);
}

} // namespace blink


text:
package eu.arkitech.logback.common;

import ch.qos.logback.classic.Level;

public interface Callbacks
{
	public abstract void handleException (final Throwable exception, final String messageFormat, final Object ... messageArguments);

	public abstract void handleLogEvent (final Level level, final Throwable exception, final String messageFormat, final Object ... messageArguments);
}


text:
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title></title>
    <link rel="Stylesheet" href="../css/analysis.css" />

Planificar rutas

Planificar rutas determina la manera de dividir las tareas con eficiencia entre los integrantes de una plantilla móvil.

Debe proporcionar a la herramienta un conjunto de paradas y el número de vehículos disponibles para visitarlas. La herramienta asigna las paradas a los vehículos y genera rutas en las que se muestra cómo puede llegar cada vehículo a las paradas asignadas en el menor tiempo posible.

Con Planificar rutas, los trabajadores móviles pueden llegar a más ubicaciones en menos tiempo, lo que aumenta la productividad y mejora el servicio al cliente.

Inspeccionar viviendas, restaurantes u obras de construcción

Proporcionar servicios de reparación, instalación o técnicos

Entregar mercancías y paquetes pequeños

Realizar visitas de ventas

Transportar personas desde sus hogares a un evento

La salida de Planificar rutas incluye una capa de paradas codificadas por las rutas a las que están asignadas, una capa de rutas que muestra las rutas más cortas para visitar las paradas asignadas y, dependiendo de si hay alguna parada a la que no se ha podido llegar, una capa de paradas sin asignar.

Si  Usar la extensión del mapa actual se ha activado, solo se tendrán en cuenta en el análisis las entidades que estén visibles en la extensión de mapa actual.
Si no se ha activado, se tendrán en cuenta todas las entidades de la capa de entrada, aunque estén fuera de la extensión de mapa actual.

Elegir la capa de puntos que representa las paradas que se deben visitar

Elige la capa de puntos que las rutas (o vehículos) deben visitar.  Estos puntos se convierten en paradas asignadas o sin asignar en la salida.

Además de elegir una capa en el mapa, puede seleccionar  Elegir capa de análisis de atlas vivo o Elegir capa de análisis, que se encuentra al final de la lista desplegable. Esto abre una galería que contiene un conjunto de capas que resultan útiles para numerosos análisis.

La herramienta admite un máximo de 2000 entidades de entrada.

Modos de viaje para rutas

Elige tu modo de viaje.  Las rutas resultantes seguirán carreteras o caminos y respetarán las reglas aplicables, como por ejemplo las vías de sentido único y los giros prohibidos en coche o en camión.  Los modos de viaje disponibles vienen determinados por el administrador de tu organización.

Las rutas empiezan en

Especifica dónde y cuándo inician las rutas los vehículos.

Con Planificar rutas, puedes especificar una o varias ubicaciones iniciales para los vehículos.

Cuando se especifica una ubicación de punto, todos los vehículos parten de ese punto con independencia del número de vehículos disponibles. Puedes elegir una capa de puntos con un punto o agregar un punto al mapa. Para ello, elige  Agregar punto al mapa, haz clic en el botón de edición del punto adyacente y haz clic en el mapa.

Cuando se especifican varias ubicaciones, cada vehículo se tiene que asociar con su propio punto. El número de vehículos debe coincidir con el número de puntos de la capa. Elige una capa con varios puntos y especifica un campo que identifique de forma única cada ruta, cada vehículo o cada conductor en la lista desplegable  Campo de Id. de ruta.

La hora de inicio es la misma para todas las rutas. La zona horaria de la hora de inicio coincide con la zona horaria en la que se encuentran el punto o los puntos iniciales. Asegúrate de que la hora que especifiques sea local. Por ejemplo, imaginemos que estás en una ubicación con la hora estándar del pacífico o PST (UTC-8:00) y que los vehículos cuyas rutas deseas definir están estacionados en una zona con la hora estándar de las montañas o MST (UTC-7:00). Si son las 9:30 PST (10:30 MST) y tus vehículos tienen que iniciar sus rutas en 30 minutos, debes definir la hora de inicio como 11:00.

Si tus vehículos parten de diferentes zonas horarias, la hora de inicio no puede ser simultánea, tendrá un desfase. Por ejemplo, si una ruta parte de un punto en la zona PST y otra se inicia en la zona MST, y especificas las 11:00 como hora de inicio, la ruta de la zona PST comenzará a las 11:00 PST y la ruta MST comenzará a las 11:00 MST, con una hora de diferencia.

Las rutas terminan en

Especifica dónde terminan las rutas los vehículos.

Puedes configurar las rutas de modo que terminen en una de tres posibles ubicaciones:

La misma ubicación en la que empezaron, tanto si se originaron en una ubicación como si partieron de varias

Una sola ubicación

Muchas ubicaciones, es decir: un punto final para cada ruta

Activa  Volver al inicio si los vehículos inician y terminan sus rutas en las mismas ubicaciones.

Para llevar todos los vehículos hasta un punto final común que no coincida con el punto inicial, desactiva  Volver al inicio y agrega un punto al mapa o elige una capa que contenga exactamente un punto.

Para que las rutas terminen en ubicaciones únicas, desactiva  Volver al inicio y elige una capa que contenga más de un punto. El número de vehículos debe coincidir con el número de puntos de la capa elegida. En la lista desplegable Campo de Id. de ruta, elige un campo que identifique de forma única cada ruta, cada vehículo o cada conductor. Si los vehículos parten de varias ubicaciones y finalizan en varias ubicaciones, los Id. de ruta elegidos para las capas inicial y final deben coincidir.

Número máximo de vehículos para definir rutas

Especifica el número de vehículos que están disponibles para visitar las paradas. La herramienta admite un máximo de  100 vehículos.

La herramienta puede encontrar una solución que utilice menos vehículos de los especificados aquí dependiendo del número total de paradas, del número de paradas permitido para cada vehículo, de la distancia entre las paradas, del tiempo pasado en cada parada y de cualquier límite definido para el tiempo de ruta total por vehículo.

Número máximo de paradas por vehículo

Este es uno de los dos parámetros que equilibran la carga de trabajo total entre las rutas. Puedes especificar un valor comprendido entre 1 y  200.

Si reduce el número máximo de paradas que se pueden asignar a cada vehículo, es más probable que el número de paradas asignadas sea el mismo para cada uno de ellos. Esto ayuda a equilibrar la carga de trabajo entre los conductores. La desventaja, sin embargo, es que puede generar una solución que sea menos eficiente.

Si se incrementan las paradas por vehículo, la herramienta tiene más libertad para encontrar soluciones más eficientes; sin embargo, la carga de trabajo podría distribuirse de un modo desigual entre los conductores y los vehículos. Puedes equilibrar las cargas de trabajo por tiempo y por número de paradas especificando un valor para el parámetro  Limitar el tiempo de ruta total por vehículo.

Los siguientes ejemplos demuestran los efectos de limitar el número máximo de paradas por vehículo o el tiempo total por vehículo. En todos los ejemplos hay seis paradas y dos rutas que parten de la misma ubicación.

Paradas y tiempos de recorrido equilibrados por ruta:

Las paradas se encuentran a distancias más o menos similares, de modo que definir el número máximo de paradas por vehículo para distribuir de una manera uniforme la carga de trabajo genera rutas que tienen aproximadamente la misma duración.

Paradas equilibradas por ruta, pero tiempos de recorrido no equilibrados:

Cinco de las seis paradas están agrupadas cerca de la ubicación inicial, pero una parada está lejos y requiere un tiempo de recorrido mucho más largo para llegar hasta ella. Dividir las paradas de manera uniforme entre las dos rutas puede generar tiempos de recorrido desequilibrados.

Paradas no equilibradas por ruta, pero tiempos de recorrido equilibrados:

Las paradas están en la misma ubicación que en el gráfico anterior, pero al aumentar el número máximo de paradas por ruta y limitar el tiempo total de recorrido por vehículo, los tiempos de recorrido están equilibrados.

Tiempo pasado en cada parada

Define el tiempo de servicio medio esperado para cada parada. Por ejemplo, si has programado un día de trabajo para los inspectores y el tiempo medio de inspección es de 45 minutos, especifica  45.

Se entiende que el tiempo de servicio es el mismo en todas las paradas.

Limitar el tiempo de ruta total por vehículo

Especifica el tiempo máximo que una ruta debe durar de principio a fin. Esto incluye el tiempo de recorrido esperado y los tiempos de servicio pasados en las paradas de la ruta. Si los conductores no deben sobrepasar un tiempo de trabajo en un día, por ejemplo ocho horas, puedes especificar aquí ese límite.

Consulta la ayuda de  Número máximo de paradas por vehículo para obtener información sobre la manera de equilibrar las cargas de trabajo.

Nombre de capa de resultados

El nombre de la capa de entidades que se creará en  Mi contenido y se agregará al mapa. Si la capa de entidades ya existe, se le pedirá que indique otro nombre. La capa de entidades contendrá una capa para cada uno de los elementos siguientes: rutas, paradas asignadas y paradas sin asignar si alguna parada de entrada no se pudo asignar a ninguna ruta.

Si selecciona  Incluir capas de rutas, cada ruta del resultado se guarda también como una capa de rutas. Una capa de rutas incluye toda la información para una determinada ruta como, por ejemplo, las paradas asignadas a la ruta y las direcciones del viaje. Crear capas de rutas resulta útil si desea compartir rutas concretas con otros miembros de la organización o si desea modificar aún más las rutas utilizando el botón Direcciones del visor de mapas. Las capas de rutas utilizan el nombre proporcionado para la capa de entidades como un prefijo y el nombre de ruta generado como parte del análisis se agrega para crear un nombre único para cada capa de rutas.

En la lista desplegable  Guardar resultado en, puede especificar el nombre de una carpeta de Mi contenido en la que se guardarán la capa de entidades y las capas de rutas, si se han creado.


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (C) 2013 47 Degrees, LLC
  ~ http://47deg.com
  ~ hello@47deg.com
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.fortysevendeg.android</groupId>
    <artifactId>swipelistview</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>apklib</packaging>
    <name>android-swipelistview-lib</name>
    <description>An Android List View implementation with support for drawable cells and many other swipe related features</description>
    <url>https://github.com/47deg/${project.name.github}</url>
    <inceptionYear>2013</inceptionYear>

    <properties>
        <platform.version>4.1.1.4</platform.version>
        <project.name.github>android-swipelistview</project.name.github>
        <scm.branch>master</scm.branch>
        <github.global.server>github</github.global.server>
    </properties>

    <scm>
        <url>https://github.com/47deg/${project.name.github}/tree/${scm.branch}</url>
        <connection>scm:git:git://github.com/47deg/${project.name.github}.git</connection>
        <developerConnection>scm:git:ssh://git@github.com/47deg/${project.name.github}.git</developerConnection>
        <tag>HEAD</tag>
    </scm>

    <issueManagement>
        <system>Github Issue Tracking</system>
        <url>https://github.com/47deg/${project.name.github}/issues</url>
    </issueManagement>

    <distributionManagement>
        <snapshotRepository>
            <id>sonatype-nexus-snapshots</id>
            <name>Sonatype Nexus snapshot repository</name>
            <url>https://oss.sonatype.org/content/repositories/snapshots</url>
        </snapshotRepository>
        <repository>
            <id>sonatype-nexus-staging</id>
            <name>Sonatype Nexus release repository</name>
            <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
        </repository>
    </distributionManagement>

    <licenses>
        <license>
            <name>Apache 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0</url>
        </license>
    </licenses>

    <dependencies>
        <dependency>
            <groupId>com.google.android</groupId>
            <artifactId>android</artifactId>
            <version>${platform.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.google.android</groupId>
            <artifactId>support-v4</artifactId>
            <version>r7</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.nineoldandroids</groupId>
            <artifactId>library</artifactId>
            <version>2.4.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>com.jayway.maven.plugins.android.generation2</groupId>
                <artifactId>android-maven-plugin</artifactId>
                <version>3.5.0</version>
                <configuration>
                    <androidManifestFile>${project.basedir}/AndroidManifest.xml</androidManifestFile>
                    <assetsDirectory>${project.basedir}/assets</assetsDirectory>
                    <resourceDirectory>${project.basedir}/res</resourceDirectory>
                    <nativeLibrariesDirectory>${project.basedir}/src/main/native</nativeLibrariesDirectory>
                    <sdk>
                        <platform>16</platform>
                    </sdk>
                    <undeployBeforeDeploy>true</undeployBeforeDeploy>
                </configuration>
                <extensions>true</extensions>
            </plugin>

            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>com.github.github</groupId>
                <artifactId>downloads-maven-plugin</artifactId>
                <version>0.5</version>
                <configuration>
                    <description>${project.version} release of ${project.name}</description>
                    <override>true</override>
                    <includeAttached>true</includeAttached>
                    <!--<suffix>.${maven.build.timestamp}</suffix>-->
                    <includes>
                        <include>*.jar</include>
                        <include>*.apklib</include>
                    </includes>
                    <override>true</override>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-release-plugin</artifactId>
                <version>2.2.2</version>
                <configuration>
                    <arguments>-Dgpg.passphrase=${gpg.passphrase}</arguments>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
            </plugin>

        </plugins>
    </build>

    <profiles>
        <profile>
            <id>release-sign-artifacts</id>
            <activation>
                <property>
                    <name>performRelease</name>
                    <value>true</value>
                </property>
            </activation>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-gpg-plugin</artifactId>
                        <version>1.4</version>
                        <configuration>
                            <passphrase>${gpg.passphrase}</passphrase>
                        </configuration>
                        <executions>
                            <execution>
                                <id>sign-artifacts</id>
                                <phase>verify</phase>
                                <goals>
                                    <goal>sign</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

</project>


text:
let _ = require('lodash');
let async = require('async');

/**
 *
 * @param {String} name
 * @param {String} namespace
 * @param {Object=} data
 * @param {Array[Object]} events
 * @param {Object=} meta
 */
let createEvent = function (name, namespace, data, events, meta) {

    // If the model or the actions are empty then it needs to error out.
    if (_.isEmpty(name) || _.isEmpty(namespace)) {
      throw new Error('ModelEvent: Cannot create event without name or namespace');
    }

    let event = { name, namespace };

    data && (event.data = data);
    events && (event.events = events);
    meta && (event.meta = meta);

    // returns the instruction POJO.
    return event;
  },

  /**
   *
   */
  getEventName = function (event) {
    return event && event.name;
  },

  getEventNamespace = function (event) {
    return event && event.namespace;
  },

  getEventData = function (event) {
    return event && event.data;
  },

  getEventMeta = function (event) {
    return event && event.meta;
  },

  getLowLevelEvents = function (event) {
    return event && event.events;
  },

  getActor = function (event) {
    return event && event.meta && event.meta.actor;
  },

  processEvent = function (event, allowedEvents, iteratee, callback) {
    // bail out
    if (!event || !iteratee) {
      return;
    }

    // bail out
    if (!allowedEvents) {
      callback(new Error('Could not find handlers dictionary to process events'));
    }

    let lowLevelEvents;

    // if there is a handler for the current event, process with it
    if (_.includes(allowedEvents, getEventName(event))) {
      (iteratee.length < 2) && console.warn('It looks like you are trying to pass a handler to processEvent without a callback.');

      return iteratee(event, callback);
    }

    lowLevelEvents = getLowLevelEvents(event);

    // otherwise try if the low level events can be handled
    async.mapSeries(lowLevelEvents, function (event, cb) {
      return processEvent(event, allowedEvents, iteratee, cb);
    }, callback);
  };

module.exports = {
  createEvent,
  getEventName,
  getEventData,
  getEventMeta,
  getEventNamespace,
  getLowLevelEvents,
  getActor,
  processEvent
};


text:
const {Component} = require("react");
const {div} = require("react-hyperscript-helpers");
const h = require("react-hyperscript");

const KGInput = require("./kg-input");
const LBInput = require("./lb-input");

module.exports = class InputStack extends Component {
    render() {
        return div({className: "ui horizontal segments container"}, [
            div({className: "ui right aligned segment"}, [h(LBInput, this.props)]),
            div({className: "ui right aligned segment"}, [h(KGInput, this.props)])
        ]);
    }
};


text:
package org.apache.jackrabbit.oak.plugins.document;

import java.util.concurrent.Callable;

import org.apache.jackrabbit.oak.api.Type;
import org.apache.jackrabbit.oak.commons.PathUtils;
import org.apache.jackrabbit.oak.plugins.document.memory.MemoryDocumentStore;
import org.apache.jackrabbit.oak.plugins.document.util.Utils;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

import static org.apache.jackrabbit.oak.plugins.document.Collection.NODES;
import static org.apache.jackrabbit.oak.plugins.document.util.Utils.getIdFromPath;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

public class CommitValueResolverTest {

    @Rule
    public DocumentMKBuilderProvider builderProvider = new DocumentMKBuilderProvider();

    private CountingDocumentStore store = new CountingDocumentStore(new MemoryDocumentStore());

    private DocumentNodeStore ns;

    private CommitValueResolver resolver;

    @Before
    public void setup() {
        ns = builderProvider.newBuilder().setDocumentStore(store)
                .setUpdateLimit(20).setAsyncDelay(0).getNodeStore();
        resolver = newCachingCommitValueResolver(0);
    }

    @Test
    public void unknownRevision() throws Exception {
        Revision oldRevision = ns.newRevision();
        addNode("/foo");
        Revision newRevision = ns.newRevision();
        NodeDocument foo = getDocument("/foo");
        NodeDocument root = getDocument("/");
        assertNotNull(foo);
        assertNotNull(root);
        assertNull(resolver.resolve(oldRevision, foo));
        assertNull(resolver.resolve(oldRevision, root));
        assertNull(resolver.resolve(newRevision, foo));
        assertNull(resolver.resolve(newRevision, root));

        // trigger sweeper
        ns.runBackgroundOperations();

        // must still not report as committed
        foo = getDocument("/foo");
        root = getDocument("/");
        assertNotNull(foo);
        assertNotNull(root);
        assertNull(resolver.resolve(oldRevision, foo));
        assertNull(resolver.resolve(oldRevision, root));
        assertNull(resolver.resolve(newRevision, foo));
        assertNull(resolver.resolve(newRevision, root));
    }

    @Test
    public void committedTrunkCommit() throws Exception {
        Revision r = addNode("/foo");
        NodeDocument foo = getDocument("/foo");
        NodeDocument root = getDocument("/");
        assertNotNull(foo);
        assertNotNull(root);
        assertEquals("c", resolver.resolve(r, foo));
        assertEquals("c", resolver.resolve(r, root));

        // trigger sweeper
        ns.runBackgroundOperations();

        // must still report as committed
        foo = getDocument("/foo");
        root = getDocument("/");
        assertNotNull(foo);
        assertNotNull(root);
        assertEquals("c", resolver.resolve(r, foo));
        assertEquals("c", resolver.resolve(r, root));
    }

    @Test
    public void committedTrunkCommitValueMovedToPreviousDoc() throws Exception {
        Revision r = addNode("/foo");
        // add changes until the revision moves to a previous document
        assertTrue(getDocument("/").getLocalRevisions().containsKey(r));
        while (getDocument("/").getLocalRevisions().containsKey(r)) {
            someChange("/");
            ns.runBackgroundUpdateOperations();
        }
        NodeDocument foo = getDocument("/foo");
        NodeDocument root = getDocument("/");
        assertNotNull(foo);
        assertNotNull(root);
        assertEquals("c", resolver.resolve(r, foo));
        assertEquals("c", resolver.resolve(r, root));

        // trigger sweeper
        ns.runBackgroundOperations();

        // must still report as committed
        foo = getDocument("/foo");
        root = getDocument("/");
        assertNotNull(foo);
        assertNotNull(root);
        assertEquals("c", resolver.resolve(r, foo));
        assertEquals("c", resolver.resolve(r, root));
    }

    @Test
    public void committedTrunkCommitMovedToPreviousDoc() throws Exception {
        String path = "/foo";
        Revision r = addNode(path);
        removeNode(path);
        addNode(path);
        // add changes until the revision moves to a previous document
        assertTrue(getDocument("/foo").getLocalCommitRoot().containsKey(r));
        while (getDocument("/foo").getLocalCommitRoot().containsKey(r)) {
            someChange("/foo");
            ns.runBackgroundUpdateOperations();
        }
        NodeDocument foo = getDocument("/foo");
        NodeDocument root = getDocument("/");
        assertNotNull(foo);
        assertNotNull(root);
        assertEquals("c", resolver.resolve(r, foo));
        assertEquals("c", resolver.resolve(r, root));

        // trigger sweeper
        ns.runBackgroundOperations();

        // must still report as committed
        foo = getDocument("/foo");
        root = getDocument("/");
        assertNotNull(foo);
        assertNotNull(root);
        assertEquals("c", resolver.resolve(r, foo));
        assertEquals("c", resolver.resolve(r, root));
    }

    @Test
    public void branchCommit() throws Exception {
        String path = "/foo";
        NodeBuilder builder = addNodeBranched(path);
        Revision r = getDocument("/").getLocalRevisions().firstKey();
        String value = getDocument("/").getLocalRevisions()
                .entrySet().iterator().next().getValue();
        NodeDocument foo = getDocument(path);
        NodeDocument root = getDocument("/");
        assertNotNull(foo);
        assertNotNull(root);
        assertEquals(value, resolver.resolve(r, foo));
        assertEquals(value, resolver.resolve(r, root));

        // add another commit and run the sweeper
        addNode("/bar");
        ns.runBackgroundUpdateOperations();

        // must still report the same value
        foo = getDocument(path);
        root = getDocument("/");
        assertNotNull(foo);
        assertNotNull(root);
        assertEquals(value, resolver.resolve(r, foo));
        assertEquals(value, resolver.resolve(r, root));

        // now merge the branch
        TestUtils.merge(ns, builder);

        // now must report the committed revision
        foo = getDocument(path);
        root = getDocument("/");
        assertNotNull(foo);
        assertNotNull(root);
        value = foo.resolveCommitValue(r);
        assertTrue(Utils.isCommitted(value));
        assertEquals(value, root.resolveCommitValue(r));
        assertEquals(value, resolver.resolve(r, foo));
        assertEquals(value, resolver.resolve(r, root));
    }

    @Test
    public void cacheEmptyCommitValue() throws Exception {
        addNode("/foo");
        // add changes and remove commit value
        NodeBuilder builder = ns.getRoot().builder();
        builder.child("foo").setProperty("p", "v");
        builder.child("bar");
        TestUtils.merge(ns, builder);
        Revision commitRev = ns.getHeadRevision().getRevision(ns.getClusterId());
        assertNotNull(commitRev);
        UpdateOp op = new UpdateOp(Utils.getIdFromPath("/"), false);
        NodeDocument.removeRevision(op, commitRev);
        assertNotNull(store.findAndUpdate(NODES, op));

        waitABit();

        CommitValueResolver cvr = newCachingCommitValueResolver(100)
                .withEmptyCommitValueCache(true, ns.getClock(), 0);
        NodeDocument foo = getDocument("/foo");

        // resolver without negative cache will look up previous docs every time
        assertNull(resolver.resolve(commitRev, foo));
        assertThat(countDocumentLookUps(() -> resolver.resolve(commitRev, foo)), greaterThan(0));

        // resolver with negative cache will look up only the first time
        assertNull(cvr.resolve(commitRev, foo));
        assertThat(countDocumentLookUps(() -> cvr.resolve(commitRev, foo)), equalTo(0));
    }

    private int countDocumentLookUps(Callable<?> c) throws Exception {
        int numCalls = store.getNumFindCalls(NODES);
        c.call();
        return store.getNumFindCalls(NODES) - numCalls;
    }

    private void waitABit() throws InterruptedException {
        ns.getClock().getTimeIncreasing();
        ns.getClock().getTimeIncreasing();
    }

    private Revision addNode(String path) throws Exception {
        NodeBuilder builder = ns.getRoot().builder();
        NodeBuilder nb = builder;
        for (String name : PathUtils.elements(path)) {
            nb = nb.child(name);
        }
        TestUtils.merge(ns, builder);
        return ns.getHeadRevision().getRevision(ns.getClusterId());
    }

    private NodeBuilder addNodeBranched(String path) {
        NodeBuilder builder = ns.getRoot().builder();
        NodeBuilder nb = builder;
        for (String name : PathUtils.elements(path)) {
            nb = nb.child(name);
        }
        int numRevEntries = getNumRevisions("/");
        int i = 0;
        while (numRevEntries == getNumRevisions("/")) {
            nb.setProperty("p-" + i++, "v");
        }
        return builder;
    }

    private Revision removeNode(String path) throws Exception {
        NodeBuilder builder = ns.getRoot().builder();
        NodeBuilder nb = builder;
        for (String name : PathUtils.elements(path)) {
            nb = nb.child(name);
        }
        nb.remove();
        TestUtils.merge(ns, builder);
        return ns.getHeadRevision().getRevision(ns.getClusterId());
    }

    private NodeDocument getDocument(String path) {
        return ns.getDocumentStore().find(NODES, getIdFromPath(path));
    }

    private void someChange(String path) throws Exception {
        NodeBuilder builder = ns.getRoot().builder();
        NodeBuilder nb = builder;
        for (String name : PathUtils.elements(path)) {
            nb = nb.child(name);
        }
        long value = 0;
        if (nb.hasProperty("p")) {
            value = nb.getProperty("p").getValue(Type.LONG) + 1;
        }
        nb.setProperty("p", value);
        TestUtils.merge(ns, builder);
    }

    private int getNumRevisions(String path) {
        NodeDocument doc = getDocument(path);
        return doc != null ? doc.getLocalRevisions().size() : 0;
    }

    private CachingCommitValueResolver newCachingCommitValueResolver(int cacheSize) {
        return new CachingCommitValueResolver(cacheSize, () -> ns.getSweepRevisions());
    }
}


text:
print(data[0] + data[1] + data[2])

# Or we can use numpy's sum and use the "axis" argument
print(np.sum(data, axis=0))


text:
<?php
namespace frenzelgmbh\sblog\widgets;

use Yii;
use yii\helpers\Html;
use yii\data\ActiveDataProvider;
use frenzelgmbh\sblog\models\WidgetConfig;

class WidgetBlogMapRender extends \yii\base\Widget
{
	/**
	 * const WIDGET_NAME must be defined for all widgets!
	 */
	const WIDGET_NAME = 'MAPWIDGET';

	public $module = 0;
	public $id = 0;

	public function init() {
		parent::init();
		\frenzelgmbh\sblog\sblogAsset::register(\Yii::$app->view);
	}

	public function run()
	{
		$dpLocations = WidgetConfig::findRelatedModels(self::WIDGET_NAME, $this->module, $this->id);

	  	if(!is_null($dpLocations))
	  	{
			return $this->render('@frenzelgmbh/sblog/widgets/views/_mapwidget_renderer',['dpLocations'=>$dpLocations]);
		}
		else
		{
			return "";
		}
	}

}


text:
<?php

declare(strict_types=1);

namespace Doctrine\ORM\Annotation;

/**
 * @Annotation
 * @Target("METHOD")
 */
final class PreFlush implements Annotation
{
}


text:
void WidgetDestroy( GtkWidget * widget,GtkWidget ** widget_pointer )
{
 if ( !widget_pointer ) return;
 gtk_widget_hide( *widget_pointer );
 gtk_widget_destroy( *widget_pointer );
 *widget_pointer=NULL;
}

GtkWidget * AddDialogFrame( GtkWidget * parent )
{
 GtkWidget * frame;
 frame=AddFrame( NULL,GTK_SHADOW_IN,parent,1 );
 gtk_container_set_border_width( GTK_CONTAINER( frame ),1 );
 frame=AddFrame( NULL,GTK_SHADOW_NONE,frame,1 );
 frame=AddFrame( NULL,GTK_SHADOW_ETCHED_OUT,frame,1 );
 frame=AddFrame( NULL,GTK_SHADOW_NONE,frame,1 );
 return frame;
}

GtkWidget * AddFrame( const char * title,int type,GtkWidget * parent,int add )
{
 GtkWidget * frame = NULL;
 frame=gtk_frame_new( title );
 gtk_widget_set_name( frame,"frame" );
 gtk_widget_show( frame );
 gtk_frame_set_shadow_type( GTK_FRAME( frame ),type );
 if ( !parent ) return frame;
 if ( add ) gtk_container_add( GTK_CONTAINER( parent ),frame );
  else gtk_box_pack_start( GTK_BOX( parent ),frame,FALSE,FALSE,0 );
 return frame;
}

GtkWidget * AddLabel( const char * title,GtkWidget * parent )
{
 GtkWidget * label;
 label=gtk_label_new( title );
 gtk_widget_set_name( label,"label" );
 gtk_widget_show( label );
 if ( parent ) gtk_box_pack_start( GTK_BOX( parent ),label,FALSE,FALSE,0 );
 gtk_misc_set_alignment( GTK_MISC( label ),0,0.5 );
 gtk_misc_set_padding( GTK_MISC( label ),4,0 );
 return label;
}

GtkWidget * AddVBox( GtkWidget * parent,int type )
{
 GtkWidget * vbox;
 vbox=gtk_vbox_new( FALSE,0 );
 gtk_widget_set_name( vbox,"vbox" );
 gtk_widget_show( vbox );
 if ( parent )
  {
   if ( type ) gtk_box_pack_start( GTK_BOX( parent ),vbox,FALSE,FALSE,0 );
    else gtk_container_add( GTK_CONTAINER( parent ),vbox );
  }
 return vbox;
}

GtkWidget * AddHBox( GtkWidget * parent,int type )
{
 GtkWidget * hbox;
 hbox=gtk_hbox_new( FALSE,0 );
 gtk_widget_set_name( hbox,"hbox" );
 gtk_widget_show( hbox );
 if ( parent )
  {
   if ( type ) gtk_box_pack_start( GTK_BOX( parent ),hbox,FALSE,FALSE,0 );
    else gtk_container_add( GTK_CONTAINER( parent ),hbox );
  }
 return hbox;
}

GtkWidget * AddCheckButton( const char * title, GtkWidget * parent )
{
 GtkWidget * CB;
 CB=gtk_check_button_new_with_label( title );
 gtk_widget_set_name( CB,"CB" );
 gtk_widget_show( CB );
 gtk_box_pack_start( GTK_BOX( parent ),CB,FALSE,FALSE,0 );
 return CB;
}

GtkWidget * AddRadioButton( const char * title,GSList ** group,GtkWidget * parent )
{
 GtkWidget * RB;
 RB=gtk_radio_button_new_with_label( *group,title );
 *group=gtk_radio_button_group( GTK_RADIO_BUTTON( RB ) );
 gtk_widget_set_name( RB,"RB" );
 gtk_widget_show( RB );
 gtk_box_pack_start( GTK_BOX( parent ),RB,FALSE,FALSE,0 );
 return RB;
}

GtkWidget * AddSpinButton( const char * title,GtkAdjustment * adj,GtkWidget * parent )
{
 GtkWidget * SB;
 GtkWidget * label;
 label=gtk_label_new( title );
 gtk_misc_set_alignment( GTK_MISC( label ),0,0.5 );
 gtk_box_pack_start( GTK_BOX( parent ),label,FALSE,FALSE,0 );
 gtk_widget_show( label );
 SB=gtk_spin_button_new( adj,0,0 );
 gtk_widget_set_name( SB,"SB" );
 gtk_box_pack_start( GTK_BOX( parent ),SB,FALSE,FALSE,0 );
 gtk_widget_show( SB );
 return SB;
}

GtkWidget * AddButton( const char * title,GtkWidget * parent )
{
 GtkWidget * B;
 B=gtk_button_new_with_label( title );
 gtk_widget_set_name( B,"B" );
 gtk_widget_show( B );
 gtk_container_add( GTK_CONTAINER( parent ),B );
 return B;
}

GtkWidget * AddHSeparator( GtkWidget * parent )
{
 GtkWidget * hseparator;
 hseparator=gtk_hseparator_new();
 gtk_widget_set_name( hseparator,"hseparator1" );
 gtk_widget_show( hseparator );
 gtk_box_pack_start( GTK_BOX( parent ),hseparator,FALSE,FALSE,0 );
 gtk_widget_set_usize( hseparator,-2,6 );
 return hseparator;
}

GtkWidget * AddHButtonBox( GtkWidget * parent )
{
 GtkWidget * hbuttonbox;
 hbuttonbox=gtk_hbutton_box_new();
 gtk_widget_set_name( hbuttonbox,"hbuttonbox" );
 gtk_widget_show( hbuttonbox );
 gtk_box_pack_start( GTK_BOX( parent ),hbuttonbox,FALSE,FALSE,0 );
 gtk_button_box_set_child_size( GTK_BUTTON_BOX( hbuttonbox ),85,20 );
 return hbuttonbox;
}

GtkWidget * AddHScaler( GtkAdjustment * adj,GtkWidget * parent,int digit )
{
 GtkWidget * HS;
 HS=gtk_hscale_new( adj );
 gtk_widget_set_name( HS,"HS" );
 gtk_widget_show( HS );
 if ( parent ) gtk_box_pack_start( GTK_BOX( parent ),HS,TRUE,TRUE,0 );
 gtk_scale_set_value_pos( GTK_SCALE( HS ),GTK_POS_RIGHT );
 gtk_scale_set_digits( GTK_SCALE( HS ),digit );
 return HS;
}

GtkWidget * AddVScaler( GtkAdjustment * adj,GtkWidget * parent,int digit )
{
 GtkWidget * VS;
 VS=gtk_vscale_new( adj );
 gtk_widget_set_name( VS,"VS" );
 gtk_widget_show( VS );
 if ( parent ) gtk_box_pack_start( GTK_BOX( parent ),VS,TRUE,TRUE,0 );
// gtk_scale_set_value_pos( GTK_SCALE( VS ),GTK_POS_RIGHT );
 if ( digit == -1 ) gtk_scale_set_draw_value( GTK_SCALE( VS ),FALSE );
  else gtk_scale_set_digits( GTK_SCALE( VS ),digit );
 return VS;
}

GtkWidget * AddComboBox( GtkWidget * parent )
{
 GtkWidget * CB;
 CB=gtk_combo_new();
 gtk_widget_set_name( CB,"CB" );
 gtk_widget_show( CB );
 if ( parent ) gtk_box_pack_start( GTK_BOX( parent ),CB,TRUE,TRUE,0 );
 return CB;
}


text:
#include <aws/ec2/model/ReplaceNetworkAclEntryRequest.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

using namespace Aws::EC2::Model;
using namespace Aws::Utils;

ReplaceNetworkAclEntryRequest::ReplaceNetworkAclEntryRequest() :
    m_cidrBlockHasBeenSet(false),
    m_dryRun(false),
    m_dryRunHasBeenSet(false),
    m_egress(false),
    m_egressHasBeenSet(false),
    m_icmpTypeCodeHasBeenSet(false),
    m_ipv6CidrBlockHasBeenSet(false),
    m_networkAclIdHasBeenSet(false),
    m_portRangeHasBeenSet(false),
    m_protocolHasBeenSet(false),
    m_ruleAction(RuleAction::NOT_SET),
    m_ruleActionHasBeenSet(false),
    m_ruleNumber(0),
    m_ruleNumberHasBeenSet(false)
{
}

Aws::String ReplaceNetworkAclEntryRequest::SerializePayload() const
{
  Aws::StringStream ss;
  ss << "Action=ReplaceNetworkAclEntry&";
  if(m_cidrBlockHasBeenSet)
  {
    ss << "CidrBlock=" << StringUtils::URLEncode(m_cidrBlock.c_str()) << "&";
  }

  if(m_dryRunHasBeenSet)
  {
    ss << "DryRun=" << std::boolalpha << m_dryRun << "&";
  }

  if(m_egressHasBeenSet)
  {
    ss << "Egress=" << std::boolalpha << m_egress << "&";
  }

  if(m_icmpTypeCodeHasBeenSet)
  {
    m_icmpTypeCode.OutputToStream(ss, "Icmp");
  }

  if(m_ipv6CidrBlockHasBeenSet)
  {
    ss << "Ipv6CidrBlock=" << StringUtils::URLEncode(m_ipv6CidrBlock.c_str()) << "&";
  }

  if(m_networkAclIdHasBeenSet)
  {
    ss << "NetworkAclId=" << StringUtils::URLEncode(m_networkAclId.c_str()) << "&";
  }

  if(m_portRangeHasBeenSet)
  {
    m_portRange.OutputToStream(ss, "PortRange");
  }

  if(m_protocolHasBeenSet)
  {
    ss << "Protocol=" << StringUtils::URLEncode(m_protocol.c_str()) << "&";
  }

  if(m_ruleActionHasBeenSet)
  {
    ss << "RuleAction=" << RuleActionMapper::GetNameForRuleAction(m_ruleAction) << "&";
  }

  if(m_ruleNumberHasBeenSet)
  {
    ss << "RuleNumber=" << m_ruleNumber << "&";
  }

  ss << "Version=2016-11-15";
  return ss.str();
}

void  ReplaceNetworkAclEntryRequest::DumpBodyToUrl(Aws::Http::URI& uri ) const
{
  uri.SetQueryString(SerializePayload());
}


text:
package com.alexstyl.locationreminder.ui.fragment;

import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.ResultReceiver;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;

import com.alexstyl.locationreminder.BuildConfig;
import com.alexstyl.locationreminder.R;
import com.alexstyl.locationreminder.service.FetchAddressIntentService;
import com.alexstyl.locationreminder.ui.BaseFragment;

/**
 *
Created by alexstyl on 22/02/15.

 */
public class AddressFetcherFragment extends BaseFragment {

    private EditText mAddressField;
    protected Location mLastLocation;
    private AddressResultReceiver mResultReceiver;

    class AddressResultReceiver extends ResultReceiver {
        public AddressResultReceiver(Handler handler) {
            super(handler);
        }

        @Override
        protected void onReceiveResult(int resultCode, Bundle resultData) {

            // Display the address string
            // or an error message sent from the intent service.
            String mAddressOutput = resultData.getString(FetchAddressIntentService.Constants.RESULT_DATA_KEY);
//            displayAddressOutput();

            // Show a toast message if an address was found.
            if (resultCode == FetchAddressIntentService.Constants.SUCCESS_RESULT) {
                Toast.makeText(getActivity(), mAddressOutput, Toast.LENGTH_SHORT).show();
            }

        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mResultReceiver = new AddressResultReceiver(new Handler());
        if(!BuildConfig.DEBUG){
            // this is a debug fragment
            throw new RuntimeException();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_address, container, false);
        this.mAddressField = (EditText) view.findViewById(R.id.address_field);
        view.findViewById(R.id.go).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startIntentService();
            }
        });
        return view;
    }

    protected void startIntentService() {
        Intent intent = new Intent(getActivity(), FetchAddressIntentService.class);
        intent.putExtra(FetchAddressIntentService.Constants.RECEIVER, mResultReceiver);
        mLastLocation = new Location(mAddressField.getText().toString());
        mLastLocation.setLatitude(52.476660);
        mLastLocation.setLongitude(-1.898708);

        intent.putExtra(FetchAddressIntentService.Constants.LOCATION_DATA_EXTRA, mLastLocation);
        getActivity().startService(intent);
    }
}


text:
var gulp = require('gulp'),
    plugins = require('gulp-load-plugins')(),
    config = require('./../utils/config');

gulp.task('bower', function() {
    return plugins.bower({
            directory: config.vendorRoot,
        });
        // .pipe(gulp.dest(config.sourceRootDir + 'vendor/'));
});


text:
package org.apache.polygene.library.sql.generator.implementation.transformation;

import java.util.Objects;
import org.apache.polygene.library.sql.generator.Typeable;
import org.apache.polygene.library.sql.generator.implementation.transformation.spi.SQLProcessor;
import org.apache.polygene.library.sql.generator.implementation.transformation.spi.SQLProcessorAggregator;

/**
 *
 */
public abstract class AbstractProcessor<ProcessableType extends Typeable<?>>
    implements SQLProcessor
{

    private final Class<? extends ProcessableType> _type;

    public AbstractProcessor( Class<? extends ProcessableType> realType )
    {
        Objects.requireNonNull( realType, "Processable type" );
        this._type = realType;
    }

    public void process( SQLProcessorAggregator aggregator, Typeable<?> object, StringBuilder builder )
    {
        if( object != null )
        {
            this.doProcess( aggregator, this._type.cast( object ), builder );
        }
    }

    protected abstract void doProcess( SQLProcessorAggregator aggregator, ProcessableType object, StringBuilder builder );
}