text:
package org.apache.tez.common;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.service.CompositeService;
import org.apache.hadoop.util.ShutdownHookManager;
import org.apache.hadoop.yarn.event.Dispatcher;
import org.apache.hadoop.yarn.event.Event;
import org.apache.hadoop.yarn.event.EventHandler;
import org.apache.hadoop.yarn.exceptions.YarnRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;

/**
 * Dispatches {@link Event}s in a separate thread. Currently only single thread
 * does that. Potentially there could be multiple channels for each event type
 * class and a thread pool can be used to dispatch the events.
 */
@SuppressWarnings({"rawtypes", "unchecked"})
@Private
public class AsyncDispatcher extends CompositeService implements Dispatcher {

  private static final Logger LOG = LoggerFactory.getLogger(AsyncDispatcher.class);

  private final String name;
  private final BlockingQueue<Event> eventQueue;
  private volatile boolean stopped = false;

  // Configuration flag for enabling/disabling draining dispatcher's events on
  // stop functionality.
  private volatile boolean drainEventsOnStop = false;

  // Indicates all the remaining dispatcher's events on stop have been drained
  // and processed.
  private volatile boolean drained = true;
  private Object waitForDrained = new Object();

  // For drainEventsOnStop enabled only, block newly coming events into the
  // queue while stopping.
  private volatile boolean blockNewEvents = false;
  private EventHandler handlerInstance = new GenericEventHandler();

  private Thread eventHandlingThread;
  protected final Map<Class<? extends Enum>, EventHandler> eventHandlers = Maps.newHashMap();
  protected final Map<Class<? extends Enum>, AsyncDispatcher> eventDispatchers = Maps.newHashMap();
  protected final Map<Class<? extends Enum>, AsyncDispatcherConcurrent> concurrentEventDispatchers =
      Maps.newHashMap();

  private boolean exitOnDispatchException;

  public AsyncDispatcher(String name) {
    this(name, new LinkedBlockingQueue<Event>());
  }

  public AsyncDispatcher(String name, BlockingQueue<Event> eventQueue) {
    super(name);
    this.name = name;
    this.eventQueue = eventQueue;
  }

  public Runnable createThread() {
    return new Runnable() {
      @Override
      public void run() {
        while (!stopped && !Thread.currentThread().isInterrupted()) {
          drained = eventQueue.isEmpty();
          // blockNewEvents is only set when dispatcher is draining to stop,
          // adding this check is to avoid the overhead of acquiring the lock
          // and calling notify every time in the normal run of the loop.
          if (blockNewEvents) {
            synchronized (waitForDrained) {
              if (drained) {
                waitForDrained.notify();
              }
            }
          }
          Event event;
          try {
            event = eventQueue.take();
          } catch(InterruptedException ie) {
            if (!stopped) {
              LOG.warn("AsyncDispatcher thread interrupted", ie);
            }
            return;
          }
          if (event != null) {
            dispatch(event);
          }
        }
      }
    };
  }

  @Override
  protected void serviceInit(Configuration conf) throws Exception {
    // TODO TEZ-2049 remove YARN reference
    this.exitOnDispatchException =
        conf.getBoolean(Dispatcher.DISPATCHER_EXIT_ON_ERROR_KEY,
          Dispatcher.DEFAULT_DISPATCHER_EXIT_ON_ERROR);
    super.serviceInit(conf);
  }

  @Override
  protected void serviceStart() throws Exception {
    eventHandlingThread = new Thread(createThread());
    eventHandlingThread.setName("Dispatcher thread: " + name);
    eventHandlingThread.start();

    //start all the components
    super.serviceStart();
  }

  public void setDrainEventsOnStop() {
    drainEventsOnStop = true;
  }

  @Override
  protected void serviceStop() throws Exception {
    if (drainEventsOnStop) {
      blockNewEvents = true;
      LOG.info("AsyncDispatcher is draining to stop, ignoring any new events.");
      synchronized (waitForDrained) {
        while (!drained && eventHandlingThread.isAlive()) {
          waitForDrained.wait(1000);
          LOG.info("Waiting for AsyncDispatcher to drain.");
        }
      }

    }
    stopped = true;
    if (eventHandlingThread != null) {
      eventHandlingThread.interrupt();
      try {
        eventHandlingThread.join();
      } catch (InterruptedException ie) {
        LOG.warn("Interrupted Exception while stopping", ie);
      }
    }

    // stop all the components
    super.serviceStop();
  }

  protected void dispatch(Event event) {
    //all events go thru this loop
    if (LOG.isDebugEnabled()) {
      LOG.debug("Dispatching the event " + event.getClass().getName() + "."
          + event.toString());
    }

    Class<? extends Enum> type = event.getType().getDeclaringClass();

    try{
      EventHandler handler = eventHandlers.get(type);
      if(handler != null) {
        handler.handle(event);
      } else {
        throw new Exception("No handler for registered for " + type);
      }
    } catch (Throwable t) {
      LOG.error("Error in dispatcher thread", t);
      // If serviceStop is called, we should exit this thread gracefully.
      if (exitOnDispatchException
          && (ShutdownHookManager.get().isShutdownInProgress()) == false
          && stopped == false) {
        Thread shutDownThread = new Thread(createShutDownThread());
        shutDownThread.setName("AsyncDispatcher ShutDown handler");
        shutDownThread.start();
      }
    }
  }

  private void checkForExistingHandler(Class<? extends Enum> eventType) {
    EventHandler<Event> registeredHandler = (EventHandler<Event>) eventHandlers.get(eventType);
    Preconditions.checkState(registeredHandler == null,
        "Cannot register same event on multiple dispatchers");
  }

  private void checkForExistingDispatcher(Class<? extends Enum> eventType) {
    AsyncDispatcher registeredDispatcher = eventDispatchers.get(eventType);
    Preconditions.checkState(registeredDispatcher == null,
        "Multiple dispatchers cannot be registered for: " + eventType.getName());
  }

  private void checkForExistingConcurrentDispatcher(Class<? extends Enum> eventType) {
    AsyncDispatcherConcurrent concurrentDispatcher = concurrentEventDispatchers.get(eventType);
    Preconditions.checkState(concurrentDispatcher == null,
        "Multiple concurrent dispatchers cannot be registered for: " + eventType.getName());
  }

  private void checkForExistingDispatchers(boolean checkHandler, Class<? extends Enum> eventType) {
    if (checkHandler) {
      checkForExistingHandler(eventType);
    }
    checkForExistingDispatcher(eventType);
    checkForExistingConcurrentDispatcher(eventType);
  }

  /**
   * Add an EventHandler for events handled inline on this dispatcher
   */
  @Override
  public void register(Class<? extends Enum> eventType,
      EventHandler handler) {
    Preconditions.checkState(getServiceState() == STATE.NOTINITED);
    /* check to see if we have a listener registered */
    EventHandler<Event> registeredHandler = (EventHandler<Event>) eventHandlers.get(eventType);
    checkForExistingDispatchers(false, eventType);
    LOG.info("Registering " + eventType + " for " + handler.getClass());
    if (registeredHandler == null) {
      eventHandlers.put(eventType, handler);
    } else if (!(registeredHandler instanceof MultiListenerHandler)){
      /* for multiple listeners of an event add the multiple listener handler */
      MultiListenerHandler multiHandler = new MultiListenerHandler();
      multiHandler.addHandler(registeredHandler);
      multiHandler.addHandler(handler);
      eventHandlers.put(eventType, multiHandler);
    } else {
      /* already a multilistener, just add to it */
      MultiListenerHandler multiHandler
      = (MultiListenerHandler) registeredHandler;
      multiHandler.addHandler(handler);
    }
  }

  /**
   * Add an EventHandler for events handled in their own dispatchers with given name
   */
  public void registerAndCreateDispatcher(Class<? extends Enum> eventType,
      EventHandler handler, String dispatcherName) {
    Preconditions.checkState(getServiceState() == STATE.NOTINITED);

    /* check to see if we have a listener registered */
    checkForExistingDispatchers(true, eventType);
    LOG.info("Registering " + eventType + " for independent dispatch using: " + handler.getClass());
    AsyncDispatcher dispatcher = new AsyncDispatcher(dispatcherName);
    dispatcher.register(eventType, handler);
    eventDispatchers.put(eventType, dispatcher);
    addIfService(dispatcher);
  }

  public AsyncDispatcherConcurrent registerAndCreateDispatcher(Class<? extends Enum> eventType,
      EventHandler handler, String dispatcherName, int numThreads) {
    Preconditions.checkState(getServiceState() == STATE.NOTINITED);

    /* check to see if we have a listener registered */
    checkForExistingDispatchers(true, eventType);
    LOG.info("Registering " + eventType + " for concurrent dispatch using: " + handler.getClass());
    AsyncDispatcherConcurrent dispatcher = new AsyncDispatcherConcurrent(dispatcherName, numThreads);
    dispatcher.register(eventType, handler);
    concurrentEventDispatchers.put(eventType, dispatcher);
    addIfService(dispatcher);
    return dispatcher;
  }

  public void registerWithExistingDispatcher(Class<? extends Enum> eventType,
      EventHandler handler, AsyncDispatcherConcurrent dispatcher) {
    Preconditions.checkState(getServiceState() == STATE.NOTINITED);

    /* check to see if we have a listener registered */
    checkForExistingDispatchers(true, eventType);
    LOG.info("Registering " + eventType + " wit existing concurrent dispatch using: "
        + handler.getClass());
    dispatcher.register(eventType, handler);
    concurrentEventDispatchers.put(eventType, dispatcher);
  }

  @Override
  public EventHandler getEventHandler() {
    return handlerInstance;
  }

  class GenericEventHandler implements EventHandler<Event> {
    public void handle(Event event) {
      if (stopped) {
        return;
      }
      if (blockNewEvents) {
        return;
      }
      drained = false;

      // offload to specific dispatcher if one exists
      Class<? extends Enum> type = event.getType().getDeclaringClass();
      AsyncDispatcher registeredDispatcher = eventDispatchers.get(type);
      if (registeredDispatcher != null) {
        registeredDispatcher.getEventHandler().handle(event);
        return;
      }
      AsyncDispatcherConcurrent concurrentDispatcher = concurrentEventDispatchers.get(type);
      if (concurrentDispatcher != null) {
        concurrentDispatcher.getEventHandler().handle(event);
        return;
      }

      // no registered dispatcher. use internal dispatcher.

      /* all this method does is enqueue all the events onto the queue */
      int qSize = eventQueue.size();
      if (qSize !=0 && qSize %1000 == 0) {
        LOG.info("Size of event-queue is " + qSize);
      }
      int remCapacity = eventQueue.remainingCapacity();
      if (remCapacity < 1000) {
        LOG.warn("Very low remaining capacity in the event-queue: "
            + remCapacity);
      }
      try {
        eventQueue.put(event);
      } catch (InterruptedException e) {
        if (!stopped) {
          LOG.warn("AsyncDispatcher thread interrupted", e);
        }
        throw new YarnRuntimeException(e);
      }
    };
  }

  /**
   * Multiplexing an event. Sending it to different handlers that
   * are interested in the event.
   * @param <T> the type of event these multiple handlers are interested in.
   */
  static class MultiListenerHandler implements EventHandler<Event> {
    List<EventHandler<Event>> listofHandlers;

    public MultiListenerHandler() {
      listofHandlers = new ArrayList<EventHandler<Event>>();
    }

    @Override
    public void handle(Event event) {
      for (EventHandler<Event> handler: listofHandlers) {
        handler.handle(event);
      }
    }

    void addHandler(EventHandler<Event> handler) {
      listofHandlers.add(handler);
    }

  }

  Runnable createShutDownThread() {
    return new Runnable() {
      @Override
      public void run() {
        LOG.info("Exiting, bbye..");
        System.exit(-1);
      }
    };
  }

  @Private
  public int getQueueSize() {
    return eventQueue.size();
  }
}

redpajama_set_name: RedPajamaGithub


text:
package org.elasticsearch.client;

import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.nio.conn.SchemeIOSessionStrategy;

import java.util.Objects;

/**
 * Helps creating a new {@link RestClient}. Allows to set the most common http client configuration options when internally
 * creating the underlying {@link org.apache.http.nio.client.HttpAsyncClient}. Also allows to provide an externally created
 * {@link org.apache.http.nio.client.HttpAsyncClient} in case additional customization is needed.
 */
public final class RestClientBuilder {
    public static final int DEFAULT_CONNECT_TIMEOUT_MILLIS = 1000;
    public static final int DEFAULT_SOCKET_TIMEOUT_MILLIS = 30000;
    public static final int DEFAULT_MAX_RETRY_TIMEOUT_MILLIS = DEFAULT_SOCKET_TIMEOUT_MILLIS;
    public static final int DEFAULT_CONNECTION_REQUEST_TIMEOUT_MILLIS = 500;
    public static final int DEFAULT_MAX_CONN_PER_ROUTE = 10;
    public static final int DEFAULT_MAX_CONN_TOTAL = 30;

    private static final Header[] EMPTY_HEADERS = new Header[0];

    private final HttpHost[] hosts;
    private int maxRetryTimeout = DEFAULT_MAX_RETRY_TIMEOUT_MILLIS;
    private Header[] defaultHeaders = EMPTY_HEADERS;
    private RestClient.FailureListener failureListener;
    private HttpClientConfigCallback httpClientConfigCallback;
    private RequestConfigCallback requestConfigCallback;
    private String pathPrefix;

    /**
     * Creates a new builder instance and sets the hosts that the client will send requests to.
     *
     * @throws NullPointerException if {@code hosts} or any host is {@code null}.
     * @throws IllegalArgumentException if {@code hosts} is empty.
     */
    RestClientBuilder(HttpHost... hosts) {
        Objects.requireNonNull(hosts, "hosts must not be null");
        if (hosts.length == 0) {
            throw new IllegalArgumentException("no hosts provided");
        }
        for (HttpHost host : hosts) {
            Objects.requireNonNull(host, "host cannot be null");
        }
        this.hosts = hosts;
    }

    /**
     * Sets the default request headers, which will be sent along with each request.
     *

     * Request-time headers will always overwrite any default headers.
     *
     * @throws NullPointerException if {@code defaultHeaders} or any header is {@code null}.
     */
    public RestClientBuilder setDefaultHeaders(Header[] defaultHeaders) {
        Objects.requireNonNull(defaultHeaders, "defaultHeaders must not be null");
        for (Header defaultHeader : defaultHeaders) {
            Objects.requireNonNull(defaultHeader, "default header must not be null");
        }
        this.defaultHeaders = defaultHeaders;
        return this;
    }

    /**
     * Sets the {@link RestClient.FailureListener} to be notified for each request failure
     *
     * @throws NullPointerException if {@code failureListener} is {@code null}.
     */
    public RestClientBuilder setFailureListener(RestClient.FailureListener failureListener) {
        Objects.requireNonNull(failureListener, "failureListener must not be null");
        this.failureListener = failureListener;
        return this;
    }

    /**
     * Sets the maximum timeout (in milliseconds) to honour in case of multiple retries of the same request.
     * {@link #DEFAULT_MAX_RETRY_TIMEOUT_MILLIS} if not specified.
     *
     * @throws IllegalArgumentException if {@code maxRetryTimeoutMillis} is not greater than 0
     */
    public RestClientBuilder setMaxRetryTimeoutMillis(int maxRetryTimeoutMillis) {
        if (maxRetryTimeoutMillis <= 0) {
            throw new IllegalArgumentException("maxRetryTimeoutMillis must be greater than 0");
        }
        this.maxRetryTimeout = maxRetryTimeoutMillis;
        return this;
    }

    /**
     * Sets the {@link HttpClientConfigCallback} to be used to customize http client configuration
     *
     * @throws NullPointerException if {@code httpClientConfigCallback} is {@code null}.
     */
    public RestClientBuilder setHttpClientConfigCallback(HttpClientConfigCallback httpClientConfigCallback) {
        Objects.requireNonNull(httpClientConfigCallback, "httpClientConfigCallback must not be null");
        this.httpClientConfigCallback = httpClientConfigCallback;
        return this;
    }

    /**
     * Sets the {@link RequestConfigCallback} to be used to customize http client configuration
     *
     * @throws NullPointerException if {@code requestConfigCallback} is {@code null}.
     */
    public RestClientBuilder setRequestConfigCallback(RequestConfigCallback requestConfigCallback) {
        Objects.requireNonNull(requestConfigCallback, "requestConfigCallback must not be null");
        this.requestConfigCallback = requestConfigCallback;
        return this;
    }

    /**
     * Sets the path's prefix for every request used by the http client.
     *

     * For example, if this is set to "/my/path", then any client request will become "/my/path/" + endpoint.
     *

     * In essence, every request's {@code endpoint} is prefixed by this {@code pathPrefix}. The path prefix is useful for when
     * Elasticsearch is behind a proxy that provides a base path; it is not intended for other purposes and it should not be supplied in
     * other scenarios.
     *
     * @throws NullPointerException if {@code pathPrefix} is {@code null}.
     * @throws IllegalArgumentException if {@code pathPrefix} is empty, only '/', or ends with more than one '/'.
     */
    public RestClientBuilder setPathPrefix(String pathPrefix) {
        Objects.requireNonNull(pathPrefix, "pathPrefix must not be null");
        String cleanPathPrefix = pathPrefix;

        if (cleanPathPrefix.startsWith("/") == false) {
            cleanPathPrefix = "/" + cleanPathPrefix;
        }

        // best effort to ensure that it looks like "/base/path" rather than "/base/path/"
        if (cleanPathPrefix.endsWith("/")) {
            cleanPathPrefix = cleanPathPrefix.substring(0, cleanPathPrefix.length() - 1);

            if (cleanPathPrefix.endsWith("/")) {
                throw new IllegalArgumentException("pathPrefix is malformed. too many trailing slashes: [" + pathPrefix + "]");
            }
        }

        if (cleanPathPrefix.isEmpty() || "/".equals(cleanPathPrefix)) {
            throw new IllegalArgumentException("pathPrefix must not be empty or '/': [" + pathPrefix + "]");
        }

        this.pathPrefix = cleanPathPrefix;
        return this;
    }

    /**
     * Creates a new {@link RestClient} based on the provided configuration.
     */
    public RestClient build() {
        if (failureListener == null) {
            failureListener = new RestClient.FailureListener();
        }
        CloseableHttpAsyncClient httpClient = createHttpClient();
        RestClient restClient = new RestClient(httpClient, maxRetryTimeout, defaultHeaders, hosts, pathPrefix, failureListener);
        httpClient.start();
        return restClient;
    }

    private CloseableHttpAsyncClient createHttpClient() {
        //default timeouts are all infinite
        RequestConfig.Builder requestConfigBuilder = RequestConfig.custom()
                .setConnectTimeout(DEFAULT_CONNECT_TIMEOUT_MILLIS)
                .setSocketTimeout(DEFAULT_SOCKET_TIMEOUT_MILLIS)
                .setConnectionRequestTimeout(DEFAULT_CONNECTION_REQUEST_TIMEOUT_MILLIS);
        if (requestConfigCallback != null) {
            requestConfigBuilder = requestConfigCallback.customizeRequestConfig(requestConfigBuilder);
        }

        HttpAsyncClientBuilder httpClientBuilder = HttpAsyncClientBuilder.create().setDefaultRequestConfig(requestConfigBuilder.build())
                //default settings for connection pooling may be too constraining
                .setMaxConnPerRoute(DEFAULT_MAX_CONN_PER_ROUTE).setMaxConnTotal(DEFAULT_MAX_CONN_TOTAL);
        if (httpClientConfigCallback != null) {
            httpClientBuilder = httpClientConfigCallback.customizeHttpClient(httpClientBuilder);
        }
        return httpClientBuilder.build();
    }

    /**
     * Callback used the default {@link RequestConfig} being set to the {@link CloseableHttpClient}
     * @see HttpClientBuilder#setDefaultRequestConfig
     */
    public interface RequestConfigCallback {
        /**
         * Allows to customize the {@link RequestConfig} that will be used with each request.
         * It is common to customize the different timeout values through this method without losing any other useful default
         * value that the {@link RestClientBuilder} internally sets.
         */
        RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder requestConfigBuilder);
    }

    /**
     * Callback used to customize the {@link CloseableHttpClient} instance used by a {@link RestClient} instance.
     * Allows to customize default {@link RequestConfig} being set to the client and any parameter that
     * can be set through {@link HttpClientBuilder}
     */
    public interface HttpClientConfigCallback {
        /**
         * Allows to customize the {@link CloseableHttpAsyncClient} being created and used by the {@link RestClient}.
         * Commonly used to customize the default {@link org.apache.http.client.CredentialsProvider} for authentication
         * or the {@link SchemeIOSessionStrategy} for communication through ssl without losing any other useful default
         * value that the {@link RestClientBuilder} internally sets, like connection pooling.
         */
        HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder);
    }
}


text:
/**
 * @file zhttpd.h
 * @brief http protocol parse functions header.
 * @author 招牌疯子 zp@buaa.us
 * @version 3.0.0
 * @date 2014-08-14
 */

#ifndef ZHTTPD_H
#define ZHTTPD_H

#include <wand/magick_wand.h>
#include "libevhtp/evhtp.h"
#include "multipart-parser-c/multipart_parser.h"

typedef struct zimg_headers_s zimg_headers_t;

typedef struct {
    char key[128];
    char value[512];
} zimg_header_t;

struct zimg_headers_s {
    zimg_header_t *value;
    zimg_headers_t *next;
};

typedef struct {
    uint n;
    zimg_headers_t *headers;
} zimg_headers_conf_t;

int on_header_field(multipart_parser* p, const char *at, size_t length);
int on_header_value(multipart_parser* p, const char *at, size_t length);
int on_chunk_data(multipart_parser* p, const char *at, size_t length);
int zimg_etag_set(evhtp_request_t *request, char *buff, size_t len);
zimg_headers_conf_t * conf_get_headers(const char *hdr_str);
void free_headers_conf(zimg_headers_conf_t *hcf);
void add_info(MagickWand *im, evhtp_request_t *req);
void dump_request_cb(evhtp_request_t *req, void *arg);
void echo_cb(evhtp_request_t *req, void *arg);
void post_request_cb(evhtp_request_t *req, void *arg);
void get_request_cb(evhtp_request_t *req, void *arg);
void admin_request_cb(evhtp_request_t *req, void *arg);
void info_request_cb(evhtp_request_t *req, void *arg);

#endif


text:
#region WatiN Copyright (C) 2006-2011 Jeroen van Menen

//Copyright 2006-2011 Jeroen van Menen
//
//   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.

#endregion Copyright

using System;
using System.IO;
using System.Text;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
using WatiN.Core.Constraints;
using WatiN.Core.UnitTests.TestUtils;

namespace WatiN.Core.UnitTests.AttributeConstraintTests
{
    [TestFixture]
    public class FindBySelectorTests :BaseWithBrowserTests
    {
        [Test]
        public void Should_filter_input_elements_with_given_selector_filter()
        {
            ExecuteTest(browser =>
                            {
                                // GIVEN
                                var querySelectorConstraint = new QuerySelectorConstraint("input");

                                // WHEN
                                var elements = browser.Elements.Filter(querySelectorConstraint);

                                // THEN
                                Assert.That(elements.Count, Is.EqualTo(19));
                            });
        }

        [Test]
        public void Should_find_element()
        {
            ExecuteTest(browser =>
                            {
                                // GIVEN
                                var querySelectorConstraint = new QuerySelectorConstraint("#popupid");

                                // WHEN
                                var element = browser.Element(querySelectorConstraint);

                                // THEN
                                Assert.That(element.Exists, Is.True);
                                Assert.That(element.Id, Is.EqualTo("popupid"));
                            });
        }

        [Test]
        public void Should_not_find_div_when_given_selector_returns_an_input()
        {
            ExecuteTest(browser =>
                            {
                                // GIVEN
                                var querySelectorConstraint = new QuerySelectorConstraint("input");

                                // WHEN
                                var div = browser.Div(querySelectorConstraint);

                                // THEN
                                Assert.That(div.Exists, Is.False);
                            });
        }

        [Test]
        public void Should_only_element_inside_container_element()
        {
            ExecuteTest(browser =>
            {
                // GIVEN
                var querySelectorConstraint = new QuerySelectorConstraint("#popupid");
                var containerElement = browser.Form("Form");

                // WHEN
                var element = containerElement.Element(querySelectorConstraint);

                // THEN
                Assert.That(element.Exists, Is.True);
                Assert.That(element.Id, Is.EqualTo("popupid"));
            });
        }

        [Test]
        public void Should_not_find_element_not_inside_container_element()
        {
            ExecuteTest(browser =>
            {
                // GIVEN
                var querySelectorConstraint = new QuerySelectorConstraint("#popupid");
                var containerElement = browser.Form("FormInputElement");

                // WHEN
                var element = containerElement.Element(querySelectorConstraint);

                // THEN
                Assert.That(element.Exists, Is.False);
            });
        }

        [Test]
        public void Should_be_able_to_use_single_quotes_in_selector_string()
        {
            ExecuteTest(browser =>
            {
                // GIVEN
                var querySelectorConstraint = new QuerySelectorConstraint("input[name='textinput1']");

                // WHEN
                var element = browser.Element(querySelectorConstraint);

                // THEN
                Assert.That(element.Exists, Is.True);
            });
        }

        [Test]
        public void Should_be_able_to_use_escaped_single_quotes_in_selector_string()
        {
            ExecuteTest(browser =>
            {
                // GIVEN
                var querySelectorConstraint = new QuerySelectorConstraint("input[name=\'textinput1\']");

                // WHEN
                var element = browser.Element(querySelectorConstraint);

                // THEN
                Assert.That(element.Exists, Is.True);
            });
        }

        [Test]
        public void Should_be_able_to_use_double_quotes_in_selector_string()
        {
            ExecuteTest(browser =>
            {
                // GIVEN
                var querySelectorConstraint = new QuerySelectorConstraint("input[name=\"textinput1\"]");

                // WHEN
                var element = browser.Element(querySelectorConstraint);

                // THEN
                Assert.That(element.Exists, Is.True);
            });
        }

        [Test]
        public void Should_return_selector_string_when_calling_WriteDescriptionTo()
        {
            // GIVEN
            var constraint = new QuerySelectorConstraint(".Return >this");
            var sb = new StringBuilder();

            // WHEN
            constraint.WriteDescriptionTo(new StringWriter(sb));

            // THEN
            Assert.That(sb.ToString(), Is.EqualTo("Selector = '.Return >this'"));
        }

        [Test, Ignore("Bug: Queryselector can't be used to find Frames in IE")]
        public void Should_find_frame()
        {
            ExecuteTest(browser =>
            {
                // GIVEN
                browser.GoTo(FramesetURI);

                // WHEN
                var frame = browser.Frame(Find.BySelector(""));

                // THEN
                Assert.That(frame == null);
            });
        }

        [Test, Ignore("Bug: Queryselector can't be used to find Frames in IE")]
        public void Should_find_element_in_frame()
        {
            ExecuteTest(browser =>
            {
                // GIVEN
                browser.GoTo(FramesetURI);
                var frame = browser.Frame("mainid");

                // WHEN
                var link = frame.Link(Find.BySelector("#Microsoft"));

                // THEN
                Assert.That(link.Exists);
                Assert.That(link.Id, Is.EqualTo("Microsoft"));
            });
        }

        [Test, Ignore("Bug: Queryselector not working with Frames in IE")]
        public void Should_find_element_in_frame_within_frame()
        {
            ExecuteTest(browser =>
            {
                // GIVEN
                browser.GoTo(FramesetWithinFramesetURI);
                var frame1 = browser.Frame("mainid");
                Console.WriteLine(frame1.FrameElement.GetJavascriptElementReference());
                var frame2 = frame1.Frame("mainid");
                var javascriptElementReference = frame2.FrameElement.GetJavascriptElementReference();
                Console.WriteLine(javascriptElementReference);

                // WHEN
                var link = frame2.Link(Find.BySelector("#Microsoft"));

                // THEN
                Assert.That(link.Exists);
            });
        }

        public override Uri TestPageUri
        {
            get { return MainURI; }
        }
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using UnityEditor;

namespace Microsoft.MixedReality.Toolkit.Input.Editor
{
    [CustomEditor(typeof(MixedRealityControllerVisualizer), true)]
    public class MixedRealityControllerVisualizerInspector : ControllerPoseSynchronizerInspector { }
}


text:
package com.creditease.dbus.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

/**
 * This is Description
 *
 * @author xiancangao
 * @date 2018/10/29
 */
public class JsonFormatUtils {

    public static String toPrettyFormat(String json) {
        JsonParser jsonParser = new JsonParser();
        JsonObject jsonObject = jsonParser.parse(json).getAsJsonObject();
        Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
        return gson.toJson(jsonObject);
    }

}


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

<!--
    Copyright (C) 2014 Samsung Electronics. All Rights Reserved. Source code
    is 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.

    IMPORTANT LICENSE NOTE: The IMAGES AND RESOURCES are licensed under the
    Creative Commons BY-NC-SA 3.0 License
    (http://creativecommons.org/licenses/by-nc-sa/3.0/). The source code
    is allows commercial re-use, but IMAGES and RESOURCES forbids it.
-->
<manifest
    package="com.samsung.mpl.gearinputprovider"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:versionCode="1"
    android:versionName="1.0.5">

    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="com.samsung.accessory.permission.ACCESSORY_FRAMEWORK"/>
    <uses-permission android:name="com.samsung.wmanager.APP"/>
    <uses-permission android:name="com.samsung.wmanager.ENABLE_NOTIFICATION"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        <service android:name="com.samsung.mpl.gearinputprovider.backend.InputProviderService">
            <intent-filter>
                <action
                    android:name="com.samsung.mpl.gearinputprovider.backend.InputProviderService"/>
            </intent-filter>
        </service>

        <receiver android:name="com.samsung.android.sdk.accessory.ServiceConnectionIndicationBroadcastReceiver">
            <intent-filter>
                <action android:name="android.accessory.service.action.ACCESSORY_SERVICE_CONNECTION_IND"/>
            </intent-filter>
        </receiver>
        <receiver android:name="com.samsung.android.sdk.accessory.RegisterUponInstallReceiver">
            <intent-filter>
                <action android:name="android.accessory.device.action.REGISTER_AFTER_INSTALL"/>
            </intent-filter>
        </receiver>
        <receiver android:name="com.samsung.android.sdk.accessoryfiletransfer.SAFileTransferIncomingRequestReceiver">
            <intent-filter>
                <action android:name="com.samsung.accessory.ftconnection"/>
            </intent-filter>
        </receiver>

        <meta-data
            android:name="AccessoryServicesLocation"
            android:value="/res/xml/accessoryservices.xml"/>
    </application>

</manifest>


text:
ACCEPTED

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

#### Published in
null

#### Original name
Cassia astrochiton H.S.Irwin & Barneby

### Remarks
null


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>freeseawind.lf.basic.rootpane 类分层结构 (LittleLuck 2.0.0 API)</title>
<meta name="date" content="2016-10-02">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

您的浏览器已禁用 JavaScript。

概览

程序包

类

使用

树

已过时

索引

帮助

上一个

下一个

框架

无框架

所有类

程序包freeseawind.lf.basic.rootpane的分层结构

程序包分层结构:

所有程序包

类分层结构

java.lang.Object

freeseawind.lf.layout.AbstractLayout (implements java.awt.LayoutManager2)

freeseawind.lf.basic.rootpane.LuckBgPanelLayout

freeseawind.lf.basic.rootpane.LuckRootPaneLayout

freeseawind.lf.basic.rootpane.LuckMetalRootPaneLayout

freeseawind.lf.basic.rootpane.LuckTitlePanelLayout

java.awt.Component (implements java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable)

java.awt.Container

javax.swing.JComponent (implements java.io.Serializable)

javax.swing.JPanel (implements javax.accessibility.Accessible)

freeseawind.swing.LuckPanel (implements freeseawind.lf.canvas.LuckCanvas)

freeseawind.lf.basic.rootpane.LuckBackgroundPanel

freeseawind.lf.basic.rootpane.LuckTitlePanel

javax.swing.plaf.ComponentUI

javax.swing.plaf.RootPaneUI

javax.swing.plaf.basic.BasicRootPaneUI (implements java.beans.PropertyChangeListener)

freeseawind.lf.basic.rootpane.LuckRootPaneUI

freeseawind.lf.basic.rootpane.LuckMetalRootPaneUI

freeseawind.lf.cfg.LuckResourceBundle

freeseawind.lf.basic.rootpane.LuckRootPaneUIBundle

概览

程序包

类

使用

树

已过时

索引

帮助

上一个

下一个

框架

无框架

所有类

Copyright © 2016. All Rights Reserved.


text:
/** @jsx React.DOM */

var ClientPage = React.createClass({

   render: function() {
    return (

MQTT client AirVantage

        <SendData />

        <ReceiveTasks />

    );
  }
});

var SendData = React.createClass({

	getInitialState: function() {
    	return {data: [], selected: []};
  	},

	addData: function(e) {
	    e.preventDefault();
	    var path = this.refs.newpath.getDOMNode().value.trim();
	    if (!path) {
	      return;
	    }
	    // TODO check unicity
	    var newData = this.state.data;
	    newData.push({label: path, path: path});
	    this.setState({data: newData});
	    return;
  	},

  	onDataChange: function(data, selected) {
  		var newSelected = this.state.selected;
  		var oldIdx;
  		for(s in newSelected) {
  			if(newSelected[s].path == data.path) {
  				oldIdx = s;
  			}
  		}
  		if(oldIdx) {
  			newSelected.splice(oldIdx, 1);
  		}
  		if(selected) {
  			newSelected.push(data);
  		}

  		this.setState({selected: newSelected});
  	},

  	send: function() {
  		console.log(this.state.selected);

  		$.ajax({
			type: "POST",
		    url: "/api/publish",
		    data: JSON.stringify(this.state.selected),
		    dataType: "json",
		    contentType: 'application/json; charset=utf-8',
		    success: function(data) {
		       console.log("youpi");
		    }.bind(this),
		    error: function(xhr, status, err) {
		       console.error(status, err.toString());
		    }.bind(this)
	    });
  	},

  	render: function() {
	    return (

Send data

		        <form className="form-horizontal" onSubmit={this.addData}>

					      	<input className="form-control" id="path" placeholder="Enter a new data path..." ref="newpath"/>

					    	<button type="submit" className="btn btn-default">Add</button>

				</form>
		        <DataList data={this.state.data} onDataChange={this.onDataChange}/>
		       	<button disabled={this.state.selected.length == 0} className="btn btn-lg btn-default center-block" onClick={this.send}>Send {this.state.selected.length} data</button>

	    );
  	}
});

var DataList = React.createClass({

   	handleDataChange: function(data, selected) {
    	this.props.onDataChange(data, selected);
    },

  	render: function() {
	    return (

				{this.props.data.map(function(data, index) {
				    return (
				    	<Data label={data.label} path={data.path} key={index} onDataChange={this.handleDataChange}/>
				    );
				}, this)}

	    );
	}
});

var Data = React.createClass({

  handleChange: function(e) {
  	this.props.onDataChange({path: this.props.path, value: this.refs.value.getDOMNode().value}, this.refs.checkbox.getDOMNode().checked);
  },

  render: function() {

  	var style = {
  		marginBottom: '5px'
	};

	var checkbox = {
  		marginTop: '10px'
	};

    return (

				<input type="checkbox" onChange={this.handleChange} ref="checkbox" style={checkbox}/>

Path

{this.props.label}

Value

			   		<input className="form-control" id="value" ref="value" onChange={this.handleChange}/>

    );
  }
});

var ReceiveTasks = React.createClass({

	getInitialState: function() {
    	return {tasks: []};
  	},

	componentDidMount: function() {
		// Let us open a web socket
		var ws = new WebSocket("ws://localhost:8000/api/ws/tasks");
		ws.onopen = function() {
			console.log("WS connected");
		};
		ws.onmessage = function (evt) {
			var received_msg = JSON.parse(evt.data);
			console.log("WS message: " + received_msg);

			var newtasks = this.state.tasks;
			for(i in received_msg) {
				console.log(received_msg[i]);
				newtasks.push(received_msg[i]);
			}

			this.setState({tasks: newtasks});
		}.bind(this);
		ws.onclose = function() {
			console.log("WS connection is closed...");
		};
	},

	render: function() {
		return (

Receive tasks

				<TaskList tasks={this.state.tasks}/>

		);
	}
});

var TaskList = React.createClass({

	render: function() {
	    return (

				{this.props.tasks.map(function(task, index) {
				    return (
				    	<Task task={task} key={index} />
				    );
				}, this)}

	    );
  	}
});

var Task = React.createClass({

	type: function(task) {
		if(task['command']) {
	 		return "Command";
	 	}
	 	else if(task['write']) {
	 		return "Write";
	 	}
	},

	details: function(task) {
		var details = ""
		if(task['command']) {
			details = details.concat("Name: " + task.command.id);
			if(task.command.params && !jQuery.isEmptyObject(task.command.params)) {
				details = details.concat(" - Parameters: ");
				var params = [];
				for(i in task.command.params) {
					params.push(i + "=" + task.command.params[i]);
				}
				details = details.concat(params.join(", "));
			}
	 	}
	 	else if(task['write']) {
	 		details = details.concat("Settings: ");
	 		var settings = [];
	 		for(i in task.write) {
	 			var setting = task.write[i];
	 			var path = Object.keys(setting)[0];
	 			settings.push(path + "=" + setting[path]);
	 		}
	 		details = details.concat(settings.join(", "));
	 	}
	 	return details;
	},

 	render: function() {

	    return (

					{new Date(this.props.task.timestamp).toLocaleString()}

					{this.type(this.props.task)}

					{this.details(this.props.task)}

	    );
  	}
});

React.renderComponent(
  <ClientPage />, document.getElementById('content')
);


text:
module WebSocket
  module Client
    module Simple

      def self.connect(url, options={})
        client = ::WebSocket::Client::Simple::Client.new
        yield client if block_given?
        client.connect url, options
        return client
      end

      class Client
        include EventEmitter
        attr_reader :url, :handshake

        def connect(url, options={})
          return if @socket
          @url = url
          uri = URI.parse url
          @socket = TCPSocket.new(uri.host,
                                  uri.port || (uri.scheme == 'wss' ? 443 : 80))
          if ['https', 'wss'].include? uri.scheme
            ctx = OpenSSL::SSL::SSLContext.new
            ctx.ssl_version = options[:ssl_version] || 'SSLv23'
            ctx.verify_mode = options[:verify_mode] || OpenSSL::SSL::VERIFY_NONE #use VERIFY_PEER for verification
            cert_store = OpenSSL::X509::Store.new
            cert_store.set_default_paths
            ctx.cert_store = cert_store
            @socket = ::OpenSSL::SSL::SSLSocket.new(@socket, ctx)
            @socket.connect
          end
          @handshake = ::WebSocket::Handshake::Client.new :url => url, :headers => options[:headers]
          @handshaked = false
          @pipe_broken = false
          frame = ::WebSocket::Frame::Incoming::Client.new
          @closed = false
          once :__close do |err|
            close
            emit :close, err
          end

          @thread = Thread.new do
            while !@closed do
              begin
                unless recv_data = @socket.getc
                  sleep 1
                  next
                end
                unless @handshaked
                  @handshake << recv_data
                  if @handshake.finished?
                    @handshaked = true
                    emit :open
                  end
                else
                  frame << recv_data
                  while msg = frame.next
                    emit :message, msg
                  end
                end
              rescue => e
                emit :error, e
              end
            end
          end

          @socket.write @handshake.to_s
        end

        def send(data, opt={:type => :text})
          return if !@handshaked or @closed
          type = opt[:type]
          frame = ::WebSocket::Frame::Outgoing::Client.new(:data => data, :type => type, :version => @handshake.version)
          begin
            @socket.write frame.to_s
          rescue Errno::EPIPE => e
            @pipe_broken = true
            emit :__close, e
          end
        end

        def close
          return if @closed
          if !@pipe_broken
            send nil, :type => :close
          end
          @closed = true
          @socket.close if @socket
          @socket = nil
          emit :__close
          Thread.kill @thread if @thread
        end

        def open?
          @handshake.finished? and !@closed
        end

      end

    end
  end
end


text:
package main.game;

import main.game.entity.EntityPlayer;
import main.game.world.World;

public class GameManger {

    private static int offsetX, offsetY;
    private static EntityPlayer player;
    private static boolean running, isFullscreen, vsync;
    private static World world;

    public static int getOffsetX() {
        return offsetX;
    }

    public static int getOffsetY() {
        return offsetY;
    }

    public static EntityPlayer getPlayer() {
        return player;
    }

    public static World getWorld() {
        return world;
    }

    public static boolean isFullscreen() {
        return isFullscreen;
    }

    public static boolean isRunning() {
        return running;
    }

    public static boolean isVSyncEnabled() {
        return vsync;
    }

    public static void setFullscreen(boolean isFullscreen) {
        GameManger.isFullscreen = isFullscreen;
    }

    public static void setOffsetX(int offsetX) {
        GameManger.offsetX = offsetX;
    }

    public static void setOffsetY(int offsetY) {
        GameManger.offsetY = offsetY;
    }

    public static void setPlayer(EntityPlayer player) {
        GameManger.player = player;
    }

    public static void setRunning(boolean running) {
        GameManger.running = running;
    }

    public static void setVsyncEnabled(boolean vsync) {
        GameManger.vsync = vsync;
    }

    public static void setWorld(World world) {
        GameManger.world = world;
    }

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Spectral Cow | Paranormal Investigations Vancouver</title>
<meta name="keywords" content="" />
<meta name="description" content="" />

<link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:200,300,400,600,700,900" rel="stylesheet" />
<link href="http://css.spectralcow.com/default.css" rel="stylesheet" type="text/css" media="all" />
<link href="http://css.spectralcow.com/fonts.css" rel="stylesheet" type="text/css" media="all" />

    <?php include_once("includes/analytics.php") ?>

SpectralCow

Homepage

			    <?php foreach($upperNav as $navLocation => $navParams):
			        if($navParams['current']):?>

<a href="/<?php echo $navParams['uri'];?>/" accesskey="4" title="<?php echo $navParams['title'];?>"><?php echo $navParams['text'];?>

                    <?php else:?>

<a href="/<?php echo $navParams['uri'];?>/" accesskey="4" title="<?php echo $navParams['title'];?>"><?php echo $navParams['text'];?>

				<?php endif;
				endforeach; ?>

<?php echo $PageContent['content']; ?>

Where did the name 'SpectralCow' come from?

Funny you should ask, and Greg, if you're out there buddy, this is for you..

				  click here for the story

What are ways in which I can cleanse my home of negative energies?

There is a plethora of techniques for dissipating negative energies in your home.

			    click here for info			    .

Is this s*** for realz?

You know, if you had asked me this years ago I would have scoffed at the idea - until I started having experiences of my own.

				  real ghost stories

Do you charge for your services?

In general, our services to validate or debunk are purely voluntary - we do not solicit donations nor gas money (unless you're way out of town..). But some of our other services require serious effort...

				  click here to see what we offer

I see dead people, and they're everywhere

			if only people knew  how true to real form that statement is in real life...

Similar Services

					are there other groups out there offering this service?

Yes. We are not alone (pun intended). We are not in competition with other groups and usually we work alongside them in various investigations. Below is a list of teams offering similar services

				Other Paranormal Groups

House Cleansings

					I have recently moved and I'm uncomfortable with

how the place feels. Can you help?

Yes! Often, the residual energy of previous occupants (I mean live ones) can remain in a location long after the previous occupant has moved out. We can help to remove the residual energies and set up a nice, comfortable vibration in the home for you.

			  cleansing vibrations in a home

Copyright (c) 2013 spectralcow.com. All rights reserved. | Website by www.quantumunit.com.


text:
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/text_message"
        android:text="@string/input_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <EditText
        android:id="@+id/edit_message"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/text_message"
        android:inputType="text"
        />
    <Button
        android:id="@+id/button_start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/edit_message"
        android:text="@string/start"/>

</RelativeLayout>


text:
package org.elasticsearch.script.expression;

import java.io.IOException;
import org.apache.lucene.expressions.Bindings;
import org.apache.lucene.expressions.Expression;
import org.apache.lucene.expressions.SimpleBindings;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.search.DoubleValues;
import org.apache.lucene.search.DoubleValuesSource;
import org.elasticsearch.script.GeneralScriptException;
import org.elasticsearch.script.TermsSetQueryScript;

/**
 * A bridge to evaluate an {@link Expression} against {@link Bindings} in the context
 * of a {@link TermsSetQueryScript}.
 */
class ExpressionTermSetQueryScript implements TermsSetQueryScript.LeafFactory {

    final Expression exprScript;
    final SimpleBindings bindings;
    final DoubleValuesSource source;

    ExpressionTermSetQueryScript(Expression e, SimpleBindings b) {
        exprScript = e;
        bindings = b;
        source = exprScript.getDoubleValuesSource(bindings);
    }

    @Override
    public TermsSetQueryScript newInstance(final LeafReaderContext leaf) throws IOException {
        return new TermsSetQueryScript() {
            // Fake the scorer until setScorer is called.
            DoubleValues values = source.getValues(leaf, null);

            @Override
            public Number execute() {
                try {
                    return values.doubleValue();
                } catch (Exception exception) {
                    throw new GeneralScriptException("Error evaluating " + exprScript, exception);
                }
            }

            @Override
            public void setDocument(int d) {
                try {
                    values.advanceExact(d);
                } catch (IOException e) {
                    throw new IllegalStateException("Can't advance to doc using " + exprScript, e);
                }
            }
        };
    }

}


text:
namespace NodeGames.Network.Network
{
    public struct NetworkConfiguration
    {
        public int ClientPort;
        public int ServerPort;
        public float ServerTick;
        public string ConnectionIp;
        public NetworkType Type;
        public bool ExternalIp;
    }
}


text:
using System;

namespace HouraiTeahouse {

    //TODO: Document
    public interface IRegistrar<in T> {

        void Register(T obj);
        bool Unregister(T obj);

    }

    //TODO: Document
    public interface IResettable {

        void OnReset();

    }

    public interface IUniqueEntity<out T> {

        T ID { get; }

    }

    public interface INameable {

        string Name { get; }

    }

    public interface IResolvable {

        void Resolve();

    }

    public interface IResolvable<in T> : IResolvable {

        void Resolve(T value);

    }

    public interface IRejectable {

        void Reject(Exception error);

    }

}


text:
/**
 * Created by g.kosharov on 16.7.2016
 */

import mongoose from 'mongoose'
const Schema = mongoose.Schema;

var Message = new Schema({
    id: String,
    gameID: String,
    addedNumber: Number, //[-1, 0, 1]
    result: Number,
    user: { type: Schema.ObjectId, ref: 'User' },
    time: String
});

export default mongoose.model('Message', Message);


text:
from dispel4py.base import SimpleFunctionPE
from dispel4py.workflow_graph import WorkflowGraph
from dispel4py.seismo.seismo import *
import obspy
from obspy.core import read
import os
import sys
import pickle
import xml.etree.ElementTree as ET
from dispel4py.base import create_iterative_chain, ConsumerPE, IterativePE

from . import RectangularDomain, CircularDomain, Restrictions, DownloadHelper
from obspy.fdsn.header import URL_MAPPINGS

class WatchDirectory(IterativePE):
    def __init__(self, index):
        IterativePE.__init__(self)
        # self._add_input('input')
        # self._add_output('output')
        self.index = index

    def _process(self, inputs):

        directory = inputs
        print
        "DIRECOTRY: " + str(directory)
        for dir_entry in os.listdir(directory[self.index]):

            dir_entry_path = os.path.join(directory[self.index], dir_entry)
            if os.path.isfile(dir_entry_path):
                self.write('output', dir_entry_path)

def waveform_reader(data):
    filename = data
    st = read(filename)
    prov = {'location': "file://" + socket.gethostname() + "/" + filename, 'format': 'application/octet-stream',
            'metadata': {'prov:type': 'observed-waveform'}}

    return {'_d4p_prov': prov, '_d4p_data': st}

def stationxml_reader(data):
    filename = data
    # st = read(filename)
    tree = ET.parse(filename)
    root = tree.getroot()
    scode = ''
    ncode = ''
    n = root.find('{http://www.fdsn.org/xml/station/1}Network')
    ncode = n.get('code')
    s = n.find('{http://www.fdsn.org/xml/station/1}Station')
    scode = s.get('code')
    prov = {'location': "file://" + socket.gethostname() + "/" + filename, 'format': 'application/xml',
            'metadata': {'prov:type': 'stationxml', 'station': scode, 'network': ncode}}

    return {'_d4p_prov': prov, '_d4p_data': data}

def plot_stream(stream, output_dir, source, tag):
    stats = stream[0].stats
    filename = source + "-%s.%s.%s.%s.png" % (
        stats['network'], stats['station'], stats['channel'], tag)

    path = os.environ['STAGED_DATA'] + '/' + output_dir

    if not os.path.exists(path):
        try:
            os.makedirs(path)
        except:
            pass
    dest = os.path.join(path, filename)
    stream.plot(outfile=dest)
    prov = {'location': "file://" + socket.gethostname() + "/" + dest, 'format': 'image/png',
            'metadata': {'prov:type': tag}}
    return {'_d4p_prov': prov, '_d4p_data': stream}

# Rectangular domain containing parts of southern Germany.
def download_data(data):
    # A fix for globe to access the data values if the whole data gets assigned to the property input
    if 'input' in data:
        data = data['input']

    # solverType is used to differentiate between globe and cartesian runs
    # solverType,networks and stations are initially defined as None in order to support the reusability of older cartesian runs
    solverType = None
    networks=None
    stations=None
    if data.has_key('solverType'):
        solverType = data['solverType'];

    if data.has_key('networks'):
        networks = data['networks'];

    if data.has_key('stations'):
        stations = data['stations'];

    if solverType == "SPECFEM3D_GLOBE":
        endtime = obspy.UTCDateTime(data['ORIGIN_TIME']) + (float(data['RECORD_LENGTH_IN_MINUTES']) * 60) + 300
    else:
        endtime = obspy.UTCDateTime(data['ORIGIN_TIME']) + float(data['DT']) * int(data['NSTEP']) + 300
    print solverType

    if solverType == "SPECFEM3D_GLOBE" and (float(data['minlongitude']) < -180 or float(data['maxlongitude']) > 180):
        domain = CircularDomain(
            latitude=float(data['latitude']),
            longitude=float(data['longitude']),
            minradius=float(data['minradius']),
            maxradius=float(data['maxradius']))

    else:
        domain = RectangularDomain(
            minlatitude=float(data['minlatitude']),
            maxlatitude=float(data['maxlatitude']),
            minlongitude=float(data['minlongitude']),
            maxlongitude=float(data['maxlongitude']))

    restrictions = Restrictions(
        # Get data for a whole yearlatitude.
        starttime=obspy.UTCDateTime(data['ORIGIN_TIME']) - 300,
        endtime=endtime,
        # Considering the enormous amount of data associated with continuous
        # requests, you might want to limit the data based on SEED identifiers.
        # If the location code is specified, the location priority list is not
        # used; the same is true for the channel argument and priority list.
        network=networks, station=stations, location=None, channel=None,
        # The typical use case for such a data set are noise correlations where
        # gaps are dealt with at a later stage.
        reject_channels_with_gaps=True,
        # Same is true with the minimum length. Any data during a day might be
        # useful.
        minimum_length=0.99,
        # Guard against the same station having different names.
        minimum_interstation_distance_in_m=data[
            'minimum_interstation_distance_in_m'],
        channel_priorities=data['channel_priorities'],
        location_priorities=data['location_priorities']

    )
    print
    "TIME WIND:" + str((str(restrictions.starttime), str(restrictions.endtime)))
    dlh = DownloadHelper(providers=["IRIS"]) if solverType == "SPECFEM3D_GLOBE" else DownloadHelper()

    mseed_path = os.environ['STAGED_DATA'] + "/" + data['mseed_path']
    stationxml_path = os.environ['STAGED_DATA'] + "/" + data['stationxml_path']
    if not os.path.exists(stationxml_path):
        try:
            os.makedirs(stationxml_path)
        except:
            pass

    report = dlh.download(
        domain=domain, restrictions=restrictions,
        mseed_path=mseed_path,
        stationxml_path=stationxml_path)

    download_report = []
    # Bit of a hack!
    URL_MAPPINGS["INGV"] = "http://webservices.rm.ingv.it"
    for r in report:
        for station in r["data"]:
            download_report.append({"provider": r["client"],
                                    "provider_url": URL_MAPPINGS[r["client"]],
                                    "station": "%s.%s" % (station.network, station.station)})

    prov = {'location': ["file://" + socket.gethostname() + "/" + os.environ['STAGED_DATA'] + "/" + data['mseed_path'],
                         "file://" + socket.gethostname() + "/" + os.environ['STAGED_DATA'] + "/" + data[
                             'stationxml_path']], 'format': 'multipart/mixed', 'metadata': download_report}

    return {'_d4p_prov': prov, '_d4p_data': [os.environ['STAGED_DATA'] + "/" + data['mseed_path'],
                                             os.environ['STAGED_DATA'] + "/" + data['stationxml_path']]}

waveformr = SimpleFunctionPE(waveform_reader)
xmlr = SimpleFunctionPE(stationxml_reader)
downloadPE = SimpleFunctionPE(download_data)

processes = [waveform_reader,
             (plot_stream, {"source": "waveform_reader", "output_dir": "./output-images", "tag": "observed-image"})]

# processes.append((fn, params))
chain = create_iterative_chain(processes, FunctionPE_class=SimpleFunctionPE)

watcher = WatchDirectory(0)
watcher_xml = WatchDirectory(1)
downloadPE.name = "downloadPE"
graph = WorkflowGraph()
graph.add(downloadPE)

graph.connect(downloadPE, 'output', watcher, "input")
graph.connect(downloadPE, 'output', watcher_xml, "input")
graph.connect(watcher, 'output', chain, "input")
graph.connect(watcher_xml, 'output', xmlr, "input")

# injectProv(graph,SeismoPE)
# graph=attachProvenanceRecorderPE(graph,ProvenanceRecorderToFileBulk,username=os.environ['USER_NAME'],runId=os.environ['RUN_ID'])

# Store to local path
ProvenancePE.PROV_PATH = os.environ['PROV_PATH']

# Size of the provenance bulk before sent to storage or sensor
ProvenancePE.BULK_SIZE = 20
injectProv(graph, (SeismoPE,), save_mode=ProvenancePE.SAVE_MODE_FILE,
           controlParameters={'username': os.environ['USER_NAME'], 'runId': os.environ['RUN_ID'],
                              'outputdest': os.environ['STAGED_DATA']})

# for lcoal test with full provenance generation and upload to local repository
# Store via service
# ProvenancePE.REPOS_URL='http://127.0.0.1:8082/workflow/insert'
# rid='DOWNLOAD_VERCE_'+getUniqueId()
# profile_prov_run(graph,None,provImpClass=(SeismoPE,),save_mode='service',input=[{'test':'1','blah':'3'}],username="aspinuso",workflowId="173",description="test",system_id="xxxx",workflowName="download",runId=rid,w3c_prov=False)


text:
#include <linux/err.h>
#include <linux/kernel.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_platform.h>
#include <linux/memory.h>
#include <linux/msm_tsens.h>
#include <linux/msm_thermal.h>
#include <linux/clk/msm-clk-provider.h>
#include <linux/regulator/rpm-smd-regulator.h>
#include <asm/mach/map.h>
#include <asm/mach/arch.h>
#include <mach/board.h>
#include <mach/gpiomux.h>
#include <mach/msm_iomap.h>
#include <mach/msm_memtypes.h>
#include <mach/restart.h>
#include <soc/qcom/socinfo.h>
#include <soc/qcom/smem.h>
#include <soc/qcom/spm.h>
#include <soc/qcom/pm.h>
#include <soc/qcom/rpm-smd.h>
#include <mach/msm_smd.h>
#include "board-dt.h"
#include "clock.h"
#include "platsmp.h"

static struct of_dev_auxdata msmsamarium_auxdata_lookup[] __initdata = {
	OF_DEV_AUXDATA("qcom,msm-sdcc", 0xF9824000, \
			"msm_sdcc.1", NULL),
	OF_DEV_AUXDATA("qcom,sdhci-msm", 0xF9824900,
			"msm_sdcc.1", NULL),
	OF_DEV_AUXDATA("qcom,msm-sdcc", 0xF98A4000, \
			"msm_sdcc.2", NULL),
	OF_DEV_AUXDATA("qcom,sdhci-msm", 0xF98A4900,
			"msm_sdcc.2", NULL),
	OF_DEV_AUXDATA("qcom,hsusb-otg", 0xF9A55000, "msm_otg", NULL),
	OF_DEV_AUXDATA("qcom,spi-qup-v2", 0xF9923000, \
			"spi_qsd.1", NULL),
	{},
};

void __init msmsamarium_reserve(void)
{
	of_scan_flat_dt(dt_scan_for_memory_reserve, NULL);
}

static void __init msmsamarium_early_memory(void)
{
	of_scan_flat_dt(dt_scan_for_memory_hole, NULL);
}

/*
 * Used to satisfy dependencies for devices that need to be
 * run early or in a particular order. Most likely your device doesn't fall
 * into this category, and thus the driver should not be added here. The
 * EPROBE_DEFER can satisfy most dependency problems.
 */
void __init msmsamarium_add_drivers(void)
{
	msm_smd_init();
	msm_rpm_driver_init();
	msm_pm_sleep_status_init();
	rpm_smd_regulator_driver_init();
	msm_spm_device_init();
	if (of_board_is_rumi())
		msm_clock_init(&msmsamarium_rumi_clock_init_data);
	else
		msm_clock_init(&msmsamarium_clock_init_data);
	tsens_tm_init_driver();
	msm_thermal_device_init();
}

static void __init msmsamarium_map_io(void)
{
	msm_map_msmsamarium_io();
}

void __init msmsamarium_init(void)
{
	struct of_dev_auxdata *adata = msmsamarium_auxdata_lookup;

	/*
	 * populate devices from DT first so smem probe will get called as part
	 * of msm_smem_init.  socinfo_init needs smem support so call
	 * msm_smem_init before it.
	 */
	board_dt_populate(adata);

	msm_smem_init();

	if (socinfo_init() < 0)
		pr_err("%s: socinfo_init() failed\n", __func__);

	msmsamarium_init_gpiomux();
	msmsamarium_add_drivers();
}

void __init msmsamarium_init_very_early(void)
{
	msmsamarium_early_memory();
}

static const char *msmsamarium_dt_match[] __initconst = {
	"qcom,msmsamarium",
	"qcom,apqsamarium",
	NULL
};

DT_MACHINE_START(MSMSAMARIUM_DT, "Qualcomm MSM Samarium(Flattened Device Tree)")
	.map_io			= msmsamarium_map_io,
	.init_machine		= msmsamarium_init,
	.dt_compat		= msmsamarium_dt_match,
	.reserve		= msmsamarium_reserve,
	.init_very_early	= msmsamarium_init_very_early,
	.restart		= msm_restart,
	.smp			= &msm8962_smp_ops,
MACHINE_END


text: this is file 134


text:
import unittest
from test_dist_base import TestDistBase
import paddle

paddle.enable_static()

class TestDistMnistNCCL2BackWardDeps(TestDistBase):
    def _setup_config(self):
        self._sync_mode = True
        self._use_reduce = False
        self._use_reader_alloc = False
        self._nccl2_mode = True
        self._enable_backward_deps = True

    def test_dist_train(self):
        import paddle.fluid as fluid

        if fluid.core.is_compiled_with_cuda():
            self.check_with_place("dist_mnist.py", delta=1e-5)

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


text:
YELLOW='\e[93m'
RED='\e[91m'
ENDCOLOR='\033[0m'
CYAN='\e[96m'
GREEN='\e[92m'
SCRIPTPATH=$(pwd)

function pause(){
   read -p "$*"
}

clear
echo
echo -e $RED
echo -e " ┬ ┬┬ ┬┬ ┬ ┬ ┬┌┬┐┌─┐┌─┐┌┐ ┌─┐┌─┐┬┌┐┌┌┐┌┌─┐┬─┐ ┌─┐┌─┐┌┬┐"
echo -e " │││││││││ ├─┤ │ ├─┘│  ├┴┐├┤ │ ┬│││││││├┤ ├┬┘ │  │ ││││"
echo -e " └┴┘└┴┘└┴┘o┴ ┴ ┴ ┴  └─┘└─┘└─┘└─┘┴┘└┘┘└┘└─┘┴└─o└─┘└─┘┴ ┴"
echo -e $CYAN
echo -e "                __  ___             "
echo -e "  /\ |_ _ |\/|./     | _  _ ||_/.|_ "
echo -e " /--\|_(_)|  ||\__   |(_)(_)|| \||_ "
echo
echo -e $GREEN'AtoMiC SickRage Backup Script'$ENDCOLOR
echo
echo -e $YELLOW'--->SickRage backup will start soon. Please read the following carefully.'$ENDCOLOR

echo -e '1. The script has been confirmed to work on Ubuntu variants, Mint, and Ubuntu Server.'
echo -e '2. While several testing runs identified no known issues, '$CYAN'www.htpcBeginner.com'$ENDCOLOR' or the authors cannot be held accountable for any problems that might occur due to the script.'
echo -e '3. If you did not run this script with sudo, you maybe asked for your root password during installation.'
echo -e '4. Best used to backup SickRage installed using AtoMiC ToolKit or '$CYAN'www.htpcBeginner.com'$ENDCOLOR' guides.'

echo

read -p 'Type y/Y and press [ENTER] to AGREE and continue with the installation or any other key to exit: '
RESP=${REPLY,,}

if [ "$RESP" != "y" ]
then
	echo -e $RED'So you chickened out. May be you will try again later.'$ENDCOLOR
	echo
	pause 'Press [Enter] key to continue...'
	cd $SCRIPTPATH
	sudo ./setup.sh
	exit 0
fi

echo

echo -n 'Type the username of the user you run SickRage as and press [ENTER]. Typically, this is your system login name (IMPORTANT! Ensure correct spelling and case): '
read UNAME

if [ ! -d "/home/$UNAME" ] || [ -z "$UNAME" ]; then
	echo -e $RED'Bummer! You may not have entered your username correctly. Exiting now. Please rerun script.'$ENDCOLOR
	echo
	pause 'Press [Enter] key to continue...'
	cd $SCRIPTPATH
	sudo ./setup.sh
	exit 0
fi
UGROUP=($(id -gn $UNAME))

echo
sleep 1

echo -e $YELLOW'--->Creating a list of files to backup...'$ENDCOLOR
cd $SCRIPTPATH
cp sickrage-backup-files sr-backup-files
sudo sed -i 's/UNAME/'$UNAME'/g' sr-backup-files  || { echo -e $RED'Replacing username in backup list failed.'$ENDCOLOR ; exit 1; }

echo
sleep 1

echo -e $YELLOW'--->Backing up files...'$ENDCOLOR
BFN=sickrage_`date '+%m-%d-%Y_%H-%M'`
tar -zcvf $BFN.tar.gz --files-from sr-backup-files || { echo -e $RED'Creating tar file failed.'$ENDCOLOR ; exit 1; }
echo
echo -e "Following files were backed up:"
cat sr-backup-files
rm sr-backup-files

echo
sleep 1
echo -e $YELLOW'--->Moving backup file to '$CYAN'/home/'$UNAME'/'$BFN'.tar.gz...'$ENDCOLOR
sudo chown $UNAME:$UGROUP $BFN.tar.gz
sudo chmod 755 $BFN.tar.gz
mv $BFN.tar.gz /home/$UNAME/

sleep 1

echo
echo -e $GREEN'--->All done. '$ENDCOLOR
echo -e 'SickRage files backed up. You can use the restore utility to restore it on a new computer.'
echo
echo -e $YELLOW'If this script worked for you, please visit '$CYAN'http://www.htpcBeginner.com'$YELLOW' and like/follow us.'$ENDCOLOR
echo -e $YELLOW'Thank you for using the AtoMiC SickRage Backup script from www.htpcBeginner.com.'$ENDCOLOR
echo

pause 'Press [Enter] key to continue...'

cd $SCRIPTPATH
sudo ./setup.sh
exit 0


text:
<?php

namespace Seahinet\Admin\ViewModel\Catalog\Grid;

use Seahinet\Admin\ViewModel\Grid as PGrid;
use Seahinet\Catalog\Model\Product;
use Seahinet\Lib\Bootstrap;
use Seahinet\Lib\Model\Collection\Eav\Attribute as Collection;

class Attribute extends PGrid
{

    protected $action = [
        'getEditAction' => 'Admin\\Catalog\\Attribute::edit',
        'getDeleteAction' => 'Admin\\Catalog\\Attribute::delete'
    ];
    protected $translateDomain = 'eav';

    public function getEditAction($item)
    {
        return 'getAdminUrl(':ADMIN/catalog_attribute/edit/?id=') . $item['id'] . '" title="' . $this->translate('Edit') .
                '">' .
                $this->translate('Edit') . '';
    }

    public function getDeleteAction($item)
    {
        return 'getAdminUrl(':ADMIN/catalog_attribute/delete/') . '" data-method="delete" data-params="id=' . $item['id'] .
                '&csrf=' . $this->getCsrfKey() . '" title="' . $this->translate('Delete') .
                '">' .
                $this->translate('Delete') . '';
    }

    protected function prepareColumns()
    {
        return [
            'code' => [
                'label' => 'Code',
                'sortby' => 'eav_attribute:code'
            ],
            'label' => [
                'label' => 'Label'
            ],
            'type' => [
                'label' => 'Type',
                'type' => 'select',
                'options' => [
                    'varchar' => 'Charector',
                    'int' => 'Integer',
                    'decimal' => 'Decimal',
                    'text' => 'Text',
                    'datetime' => 'Date/Time'
                ]
            ],
            'searchable' => [
                'label' => 'Searchable',
                'type' => 'select',
                'options' => [
                    1 => 'Yes',
                    0 => 'No'
                ]
            ],
            'filterable' => [
                'label' => 'Filterable',
                'type' => 'select',
                'options' => [
                    1 => 'Yes',
                    0 => 'No'
                ]
            ],
            'sortable' => [
                'label' => 'Sortable',
                'type' => 'select',
                'options' => [
                    1 => 'Yes',
                    0 => 'No'
                ]
            ],
            'comparable' => [
                'label' => 'Comparable',
                'type' => 'select',
                'options' => [
                    1 => 'Yes',
                    0 => 'No'
                ]
            ]
        ];
    }

    protected function prepareCollection($collection = null)
    {
        $collection = new Collection;
        $collection->withLabel(Bootstrap::getLanguage()->getId())
                ->join('eav_entity_type', 'eav_entity_type.id=eav_attribute.type_id', [], 'left')
                ->where(['eav_entity_type.code' => Product::ENTITY_TYPE]);
        if (!$this->getQuery('desc')) {
            $this->query['desc'] = 'eav_attribute.created_at';
        }
        return parent::prepareCollection($collection);
    }

}


text:
package org.elasticsearch.xpack.watcher.transform;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.collect.MapBuilder;
import org.elasticsearch.common.util.CollectionUtils;
import org.elasticsearch.common.xcontent.support.XContentMapValues;
import org.elasticsearch.plugins.Plugin;
import org.elasticsearch.protocol.xpack.watcher.PutWatchResponse;
import org.elasticsearch.script.MockScriptPlugin;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.xcontent.XContentType;
import org.elasticsearch.xpack.core.watcher.transport.actions.execute.ExecuteWatchRequestBuilder;
import org.elasticsearch.xpack.core.watcher.transport.actions.put.PutWatchRequestBuilder;
import org.elasticsearch.xpack.watcher.support.search.WatcherSearchTemplateRequest;
import org.elasticsearch.xpack.watcher.test.AbstractWatcherIntegrationTestCase;
import org.elasticsearch.xpack.watcher.test.WatcherMockScriptPlugin;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

import static java.util.Collections.singletonMap;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.elasticsearch.search.builder.SearchSourceBuilder.searchSource;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures;
import static org.elasticsearch.xpack.watcher.actions.ActionBuilders.indexAction;
import static org.elasticsearch.xpack.watcher.client.WatchSourceBuilders.watchBuilder;
import static org.elasticsearch.xpack.watcher.input.InputBuilders.searchInput;
import static org.elasticsearch.xpack.watcher.input.InputBuilders.simpleInput;
import static org.elasticsearch.xpack.watcher.test.WatcherTestUtils.templateRequest;
import static org.elasticsearch.xpack.watcher.transform.TransformBuilders.chainTransform;
import static org.elasticsearch.xpack.watcher.transform.TransformBuilders.scriptTransform;
import static org.elasticsearch.xpack.watcher.transform.TransformBuilders.searchTransform;
import static org.elasticsearch.xpack.watcher.trigger.TriggerBuilders.schedule;
import static org.elasticsearch.xpack.watcher.trigger.schedule.Schedules.interval;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.is;

public class TransformIntegrationTests extends AbstractWatcherIntegrationTestCase {

    @Override
    protected Collection<Class<? extends Plugin>> nodePlugins() {
        return CollectionUtils.appendToCopy(super.pluginTypes(), CustomScriptPlugin.class);
    }

    @Override
    protected Path nodeConfigPath(int nodeOrdinal) {
        final Path config = createTempDir().resolve("config");
        final Path scripts = config.resolve("scripts");

        try {
            Files.createDirectories(scripts);

            // When using the MockScriptPlugin we can map File scripts to inline scripts:
            // the name of the file script is used in test method while the source of the file script
            // must match a predefined script from CustomScriptPlugin.pluginScripts() method
            Files.write(scripts.resolve("my-script.mockscript"), "['key3' : ctx.payload.key1 + ctx.payload.key2]".getBytes("UTF-8"));
        } catch (final IOException e) {
            throw new UncheckedIOException(e);
        }

        return config;
    }

    public static class CustomScriptPlugin extends WatcherMockScriptPlugin {

        @Override
        protected Map<String, Function<Map<String, Object>, Object>> pluginScripts() {
            Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>();

            scripts.put("['key3' : ctx.payload.key1 + ctx.payload.key2]", vars -> {
                int key1 = (int) XContentMapValues.extractValue("ctx.payload.key1", vars);
                int key2 = (int) XContentMapValues.extractValue("ctx.payload.key2", vars);
                return singletonMap("key3", key1 + key2);
            });

            scripts.put("['key4' : ctx.payload.key3 + 10]", vars -> {
                int key3 = (int) XContentMapValues.extractValue("ctx.payload.key3", vars);
                return singletonMap("key4", key3 + 10);
            });

            return scripts;
        }
    }

    public void testScriptTransform() throws Exception {
        final Script script;
        if (randomBoolean()) {
            logger.info("testing script transform with an inline script");
            script = mockScript("['key3' : ctx.payload.key1 + ctx.payload.key2]");
        } else {
            logger.info("testing script transform with an indexed script");
            assertAcked(client().admin().cluster().preparePutStoredScript().setId("my-script").setContent(new BytesArray("""
                {
                  "script": {
                    "lang": "%s",
                    "source": "['key3' : ctx.payload.key1 + ctx.payload.key2]"
                  }
                }""".formatted(MockScriptPlugin.NAME)), XContentType.JSON).get());
            script = new Script(ScriptType.STORED, null, "my-script", Collections.emptyMap());
        }

        // put a watch that has watch level transform:
        PutWatchResponse putWatchResponse = new PutWatchRequestBuilder(client(), "_id1").setSource(
            watchBuilder().trigger(schedule(interval("5s")))
                .input(simpleInput(MapBuilder.<String, Object>newMapBuilder().put("key1", 10).put("key2", 10)))
                .transform(scriptTransform(script))
                .addAction("_id", indexAction("output1"))
        ).get();
        assertThat(putWatchResponse.isCreated(), is(true));
        // put a watch that has a action level transform:
        putWatchResponse = new PutWatchRequestBuilder(client(), "_id2").setSource(
            watchBuilder().trigger(schedule(interval("5s")))
                .input(simpleInput(MapBuilder.<String, Object>newMapBuilder().put("key1", 10).put("key2", 10)))
                .addAction("_id", scriptTransform(script), indexAction("output2"))
        ).get();
        assertThat(putWatchResponse.isCreated(), is(true));

        executeWatch("_id1");
        executeWatch("_id2");
        refresh();

        assertWatchWithMinimumPerformedActionsCount("_id1", 1, false);
        assertWatchWithMinimumPerformedActionsCount("_id2", 1, false);
        refresh();

        SearchResponse response = client().prepareSearch("output1").get();
        assertNoFailures(response);
        assertThat(response.getHits().getTotalHits().value, greaterThanOrEqualTo(1L));
        assertThat(response.getHits().getAt(0).getSourceAsMap().size(), equalTo(1));
        assertThat(response.getHits().getAt(0).getSourceAsMap().get("key3").toString(), equalTo("20"));

        response = client().prepareSearch("output2").get();
        assertNoFailures(response);
        assertThat(response.getHits().getTotalHits().value, greaterThanOrEqualTo(1L));
        assertThat(response.getHits().getAt(0).getSourceAsMap().size(), equalTo(1));
        assertThat(response.getHits().getAt(0).getSourceAsMap().get("key3").toString(), equalTo("20"));
    }

    public void testSearchTransform() throws Exception {
        createIndex("my-condition-index", "my-payload-index");
        ensureGreen("my-condition-index", "my-payload-index");

        indexDoc("my-payload-index", "mytestresult");
        refresh();

        WatcherSearchTemplateRequest inputRequest = templateRequest(searchSource().query(matchAllQuery()), "my-condition-index");
        WatcherSearchTemplateRequest transformRequest = templateRequest(searchSource().query(matchAllQuery()), "my-payload-index");

        PutWatchResponse putWatchResponse = new PutWatchRequestBuilder(client(), "_id1").setSource(
            watchBuilder().trigger(schedule(interval("5s")))
                .input(searchInput(inputRequest))
                .transform(searchTransform(transformRequest))
                .addAction("_id", indexAction("output1"))
        ).get();
        assertThat(putWatchResponse.isCreated(), is(true));
        putWatchResponse = new PutWatchRequestBuilder(client(), "_id2").setSource(
            watchBuilder().trigger(schedule(interval("5s")))
                .input(searchInput(inputRequest))
                .addAction("_id", searchTransform(transformRequest), indexAction("output2"))
        ).get();
        assertThat(putWatchResponse.isCreated(), is(true));

        executeWatch("_id1");
        executeWatch("_id2");
        refresh();

        assertWatchWithMinimumPerformedActionsCount("_id1", 1, false);
        assertWatchWithMinimumPerformedActionsCount("_id2", 1, false);
        refresh();

        SearchResponse response = client().prepareSearch("output1").get();
        assertNoFailures(response);
        assertThat(response.getHits().getTotalHits().value, greaterThanOrEqualTo(1L));
        assertThat(response.getHits().getAt(0).getSourceAsString(), containsString("mytestresult"));

        response = client().prepareSearch("output2").get();
        assertNoFailures(response);
        assertThat(response.getHits().getTotalHits().value, greaterThanOrEqualTo(1L));
        assertThat(response.getHits().getAt(0).getSourceAsString(), containsString("mytestresult"));
    }

    public void testChainTransform() throws Exception {
        Script script1 = mockScript("['key3' : ctx.payload.key1 + ctx.payload.key2]");
        Script script2 = mockScript("['key4' : ctx.payload.key3 + 10]");

        // put a watch that has watch level transform:
        PutWatchResponse putWatchResponse = new PutWatchRequestBuilder(client(), "_id1").setSource(
            watchBuilder().trigger(schedule(interval("5s")))
                .input(simpleInput(MapBuilder.<String, Object>newMapBuilder().put("key1", 10).put("key2", 10)))
                .transform(chainTransform(scriptTransform(script1), scriptTransform(script2)))
                .addAction("_id", indexAction("output1"))
        ).get();
        assertThat(putWatchResponse.isCreated(), is(true));
        // put a watch that has a action level transform:
        putWatchResponse = new PutWatchRequestBuilder(client(), "_id2").setSource(
            watchBuilder().trigger(schedule(interval("5s")))
                .input(simpleInput(MapBuilder.<String, Object>newMapBuilder().put("key1", 10).put("key2", 10)))
                .addAction("_id", chainTransform(scriptTransform(script1), scriptTransform(script2)), indexAction("output2"))
        ).get();
        assertThat(putWatchResponse.isCreated(), is(true));

        executeWatch("_id1");
        executeWatch("_id2");
        refresh();

        assertWatchWithMinimumPerformedActionsCount("_id1", 1, false);
        assertWatchWithMinimumPerformedActionsCount("_id2", 1, false);
        refresh();

        SearchResponse response = client().prepareSearch("output1").get();
        assertNoFailures(response);
        assertThat(response.getHits().getTotalHits().value, greaterThanOrEqualTo(1L));
        assertThat(response.getHits().getAt(0).getSourceAsMap().size(), equalTo(1));
        assertThat(response.getHits().getAt(0).getSourceAsMap().get("key4").toString(), equalTo("30"));

        response = client().prepareSearch("output2").get();
        assertNoFailures(response);
        assertThat(response.getHits().getTotalHits().value, greaterThanOrEqualTo(1L));
        assertThat(response.getHits().getAt(0).getSourceAsMap().size(), equalTo(1));
        assertThat(response.getHits().getAt(0).getSourceAsMap().get("key4").toString(), equalTo("30"));
    }

    private void executeWatch(String watchId) {
        new ExecuteWatchRequestBuilder(client(), watchId).setRecordExecution(true).get();
    }
}


text:
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */

package com.sun.org.apache.xerces.internal.util;

import com.sun.org.apache.xerces.internal.xni.NamespaceContext;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.TreeSet;
import java.util.Vector;
import javax.xml.XMLConstants;

/**
 *
A read-only XNI wrapper around a JAXP NamespaceContext.

 *
 * @author Michael Glavassevich, IBM
 *
 * @LastModified: Oct 2017
 */
public final class JAXPNamespaceContextWrapper implements NamespaceContext {

    private javax.xml.namespace.NamespaceContext fNamespaceContext;
    private SymbolTable fSymbolTable;
    private List<String> fPrefixes;
    private final Vector<String> fAllPrefixes = new Vector<>();

    private int[] fContext = new int[8];
    private int fCurrentContext;

    public JAXPNamespaceContextWrapper(SymbolTable symbolTable) {
        setSymbolTable(symbolTable);
    }

    public void setNamespaceContext(javax.xml.namespace.NamespaceContext context) {
        fNamespaceContext = context;
    }

    public javax.xml.namespace.NamespaceContext getNamespaceContext() {
        return fNamespaceContext;
    }

    public void setSymbolTable(SymbolTable symbolTable) {
        fSymbolTable = symbolTable;
    }

    public SymbolTable getSymbolTable() {
        return fSymbolTable;
    }

    public void setDeclaredPrefixes(List<String> prefixes) {
        fPrefixes = prefixes;
    }

    public List<String> getDeclaredPrefixes() {
        return fPrefixes;
    }

    /*
     * NamespaceContext methods
     */

    public String getURI(String prefix) {
        if (fNamespaceContext != null) {
            String uri = fNamespaceContext.getNamespaceURI(prefix);
            if (uri != null && !XMLConstants.NULL_NS_URI.equals(uri)) {
                return (fSymbolTable != null) ? fSymbolTable.addSymbol(uri) : uri.intern();
            }
        }
        return null;
    }

    public String getPrefix(String uri) {
        if (fNamespaceContext != null) {
            if (uri == null) {
                uri = XMLConstants.NULL_NS_URI;
            }
            String prefix = fNamespaceContext.getPrefix(uri);
            if (prefix == null) {
                prefix = XMLConstants.DEFAULT_NS_PREFIX;
            }
            return (fSymbolTable != null) ? fSymbolTable.addSymbol(prefix) : prefix.intern();
        }
        return null;
    }

    public Enumeration<String> getAllPrefixes() {
        // There may be duplicate prefixes in the list so we
        // first transfer them to a set to ensure uniqueness.
        return Collections.enumeration(new TreeSet<String>(fAllPrefixes));
    }

    public void pushContext() {
        // extend the array, if necessary
        if (fCurrentContext + 1 == fContext.length) {
            int[] contextarray = new int[fContext.length * 2];
            System.arraycopy(fContext, 0, contextarray, 0, fContext.length);
            fContext = contextarray;
        }
        // push context
        fContext[++fCurrentContext] = fAllPrefixes.size();
        if (fPrefixes != null) {
            fAllPrefixes.addAll(fPrefixes);
        }
    }

    public void popContext() {
        fAllPrefixes.setSize(fContext[fCurrentContext--]);
    }

    public boolean declarePrefix(String prefix, String uri) {
        return true;
    }

    public int getDeclaredPrefixCount() {
        return (fPrefixes != null) ? fPrefixes.size() : 0;
    }

    public String getDeclaredPrefixAt(int index) {
        return fPrefixes.get(index);
    }

    public void reset() {
        fCurrentContext = 0;
        fContext[fCurrentContext] = 0;
        fAllPrefixes.clear();
    }

} // JAXPNamespaceContextWrapper


text:
package com.amazonaws.services.ec2.model.transform;

import java.util.ArrayList;

import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;

import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Unmarshaller;

import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;

/**
 * AllowedPrincipal StAX Unmarshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AllowedPrincipalStaxUnmarshaller implements Unmarshaller<AllowedPrincipal, StaxUnmarshallerContext> {

    public AllowedPrincipal unmarshall(StaxUnmarshallerContext context) throws Exception {
        AllowedPrincipal allowedPrincipal = new AllowedPrincipal();
        int originalDepth = context.getCurrentDepth();
        int targetDepth = originalDepth + 1;

        if (context.isStartOfDocument())
            targetDepth += 1;

        while (true) {
            XMLEvent xmlEvent = context.nextEvent();
            if (xmlEvent.isEndDocument())
                return allowedPrincipal;

            if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {

                if (context.testExpression("principalType", targetDepth)) {
                    allowedPrincipal.setPrincipalType(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("principal", targetDepth)) {
                    allowedPrincipal.setPrincipal(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("servicePermissionId", targetDepth)) {
                    allowedPrincipal.setServicePermissionId(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("tagSet", targetDepth)) {
                    allowedPrincipal.withTags(new ArrayList<Tag>());
                    continue;
                }

                if (context.testExpression("tagSet/item", targetDepth)) {
                    allowedPrincipal.withTags(TagStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }

                if (context.testExpression("serviceId", targetDepth)) {
                    allowedPrincipal.setServiceId(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }
            } else if (xmlEvent.isEndElement()) {
                if (context.getCurrentDepth() < originalDepth) {
                    return allowedPrincipal;
                }
            }
        }
    }

    private static AllowedPrincipalStaxUnmarshaller instance;

    public static AllowedPrincipalStaxUnmarshaller getInstance() {
        if (instance == null)
            instance = new AllowedPrincipalStaxUnmarshaller();
        return instance;
    }
}


text:
#include "ewk_main.h"

#include <Ecore.h>
#include <Ecore_Evas.h>
#include <Ecore_IMF.h>
#include <Edje.h>
#include <Eina.h>
#include <Evas.h>

#if defined(HAVE_ECORE_X)
#include <Ecore_X.h>
#endif

#include "public/ewk_log.h"
#include "private/webview_delegate_ewk.h"
#include "private/ewk_private.h"
#include "private/ewk_main_private.h"

// TODO: remove dependency
#include <../impl/command_line_efl.h>
#include <../impl/eweb_context.h>
#include <../impl/ewk_global_data.h>

static int _ewkInitCount = 0;

/////////////////////////////////////////////////////////////////////////////
//private function declaration here
static void _ewk_init_web_engine(void);
static void _ewk_shutdown_web_engine(void);

extern std::string g_homeDirectory;

/**
 * \var     _ewk_log_dom
 * @brief   the log domain identifier that is used with EINA's macros
 */
int _ewk_log_dom = -1;

int ewk_init(void)
{
  if (_ewkInitCount)
      return ++_ewkInitCount;

  if (!eina_init())
      goto error_eina;

  _ewk_log_dom = eina_log_domain_register("ewebview-blink", EINA_COLOR_ORANGE);
  if (_ewk_log_dom < 0) {
      EINA_LOG_CRIT("could not register log domain 'ewebview-blink'");
      goto error_log_domain;
  }

  if (!evas_init()) {
      CRITICAL("could not init evas.");
      goto error_evas;
  }

  if (!ecore_init()) {
      CRITICAL("could not init ecore.");
      goto error_ecore;
  }

  if (!ecore_evas_init()) {
      CRITICAL("could not init ecore_evas.");
      goto error_ecore_evas;
  }

  if (!ecore_imf_init()) {
      CRITICAL("could not init ecore_imf.");
      goto error_ecore_imf;
  }

#if defined(HAVE_ECORE_X)
  if (!ecore_x_init(0)) {
      CRITICAL("could not init ecore_x.");
      goto error_ecore_x;
  }
#endif

  if (!edje_init()) {
      CRITICAL("Could not init edje.");
      goto error_edje;
  }

  // FIXME: do we need glib integration like WebKit?
#if 0
#if !GLIB_CHECK_VERSION(2, 35, 0)
  g_type_init();
#endif

  if (!ecore_main_loop_glib_integrate()) {
      WARN("Ecore was not compiled with GLib support, some plugins will not "
          "work (ie: Adobe Flash)");
  }
#endif

  _ewk_init_web_engine();
  return ++_ewkInitCount;

error_edje:
#if defined(HAVE_ECORE_X)
  ecore_x_shutdown();
error_ecore_x:
#endif
  ecore_imf_shutdown();
error_ecore_imf:
  ecore_evas_shutdown();
error_ecore_evas:
  ecore_shutdown();
error_ecore:
  evas_shutdown();
error_evas:
  eina_log_domain_unregister(_ewk_log_dom);
  _ewk_log_dom = -1;
error_log_domain:
  eina_shutdown();
error_eina:
  return 0;
}

int ewk_shutdown(void)
{
  if (!_ewkInitCount || --_ewkInitCount)
      return _ewkInitCount;

  _ewk_shutdown_web_engine();

  edje_shutdown();
#if defined(HAVE_ECORE_X)
  ecore_x_shutdown();
#endif
  ecore_imf_shutdown();
  ecore_evas_shutdown();
  ecore_shutdown();
  evas_shutdown();
  eina_log_domain_unregister(_ewk_log_dom);
  _ewk_log_dom = -1;
  eina_shutdown();

  return 0;
}

void ewk_set_arguments(int argc, char** argv)
{
    CommandLineEfl::Init(argc, argv);
}

void ewk_home_directory_set(const char* path)
{
  if (!path)
    g_homeDirectory.clear();
  else
    g_homeDirectory = path;
}

/////////////////////////////////////////////////////////////////////////////////////////////
//Private functions implementations for ewk_main module

//Initialize web engine
void _ewk_init_web_engine()
{
  if(!WebViewDelegate::IsDelegateRegistered()) {
    WebViewDelegate::RegisterDelegate(
      const_cast<WebViewDelegateEwk*>(&WebViewDelegateEwk::GetInstance()));
  }
}

void _ewk_shutdown_web_engine(void)
{
  //TODO: any web engine destroy to be done here
  CommandLineEfl::Shutdown();
  EwkGlobalData::Delete();
}


text:
namespace palo {

bool MemInfo::_s_initialized = false;
int64_t MemInfo::_s_physical_mem = -1;

void MemInfo::init() {
    // Read from /proc/meminfo
    std::ifstream meminfo("/proc/meminfo", std::ios::in);
    std::string line;

    while (meminfo.good() && !meminfo.eof()) {
        getline(meminfo, line);
        std::vector<std::string> fields;
        boost::split(fields, line, boost::is_any_of(" "), boost::token_compress_on);

        // We expect lines such as, e.g., 'MemTotal: 16129508 kB'
        if (fields.size() < 3) {
            continue;
        }

        if (fields[0].compare("MemTotal:") != 0) {
            continue;
        }

        StringParser::ParseResult result;
        int64_t mem_total_kb = StringParser::string_to_int<int64_t>(fields[1].data(),
                               fields[1].size(), &result);

        if (result == StringParser::PARSE_SUCCESS) {
            // Entries in /proc/meminfo are in KB.
            _s_physical_mem = mem_total_kb * 1024L;
        }

        break;
    }

    if (meminfo.is_open()) {
        meminfo.close();
    }

    if (_s_physical_mem == -1) {
        LOG(WARNING) << "Could not determine amount of physical memory on this machine.";
    }

    LOG(INFO) << "Physical Memory: "
              << PrettyPrinter::print(_s_physical_mem, TUnit::BYTES);

    _s_initialized = true;
}

std::string MemInfo::debug_string() {
    DCHECK(_s_initialized);
    std::stringstream stream;
    stream << "Mem Info: " << PrettyPrinter::print(_s_physical_mem, TUnit::BYTES)
           << std::endl;
    return stream.str();
}

}