text:
package org.apache.beam.runners.core;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.collect.Iterables;
import com.google.common.util.concurrent.Futures;
import java.util.concurrent.CancellationException;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.transforms.Aggregator;
import org.apache.beam.sdk.transforms.Combine;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.reflect.DoFnInvoker;
import org.apache.beam.sdk.transforms.splittabledofn.RestrictionTracker;
import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
import org.apache.beam.sdk.transforms.windowing.PaneInfo;
import org.apache.beam.sdk.util.SideInputReader;
import org.apache.beam.sdk.util.Timer;
import org.apache.beam.sdk.util.WindowedValue;
import org.apache.beam.sdk.util.state.State;
import org.apache.beam.sdk.values.PCollectionView;
import org.apache.beam.sdk.values.TupleTag;
import org.joda.time.Duration;
import org.joda.time.Instant;

/**
 * A {@link SplittableProcessElementInvoker} that requests a checkpoint after the {@link
 * DoFn.ProcessElement} call either outputs at least a given number of elements (in total over all
 * outputs), or runs for the given duration.
 */
public class OutputAndTimeBoundedSplittableProcessElementInvoker<
        InputT, OutputT, RestrictionT, TrackerT extends RestrictionTracker<RestrictionT>>
    extends SplittableProcessElementInvoker<InputT, OutputT, RestrictionT, TrackerT> {
  private final DoFn<InputT, OutputT> fn;
  private final PipelineOptions pipelineOptions;
  private final OutputWindowedValue<OutputT> output;
  private final SideInputReader sideInputReader;
  private final ScheduledExecutorService executor;
  private final int maxNumOutputs;
  private final Duration maxDuration;

  /**
   * Creates a new invoker from components.
   *
   * @param fn The original {@link DoFn}.
   * @param pipelineOptions {@link PipelineOptions} to include in the {@link DoFn.ProcessContext}.
   * @param output Hook for outputting from the {@link DoFn.ProcessElement} method.
   * @param sideInputReader Hook for accessing side inputs.
   * @param executor Executor on which a checkpoint will be scheduled after the given duration.
   * @param maxNumOutputs Maximum number of outputs, in total over all output tags, after which a
   *     checkpoint will be requested. This is a best-effort request - the {@link DoFn} may output
   *     more after receiving the request.
   * @param maxDuration Maximum duration of the {@link DoFn.ProcessElement} call after which a
   *     checkpoint will be requested. This is a best-effort request - the {@link DoFn} may run for
   *     longer after receiving the request.
   */
  public OutputAndTimeBoundedSplittableProcessElementInvoker(
      DoFn<InputT, OutputT> fn,
      PipelineOptions pipelineOptions,
      OutputWindowedValue<OutputT> output,
      SideInputReader sideInputReader,
      ScheduledExecutorService executor,
      int maxNumOutputs,
      Duration maxDuration) {
    this.fn = fn;
    this.pipelineOptions = pipelineOptions;
    this.output = output;
    this.sideInputReader = sideInputReader;
    this.executor = executor;
    this.maxNumOutputs = maxNumOutputs;
    this.maxDuration = maxDuration;
  }

  @Override
  public Result invokeProcessElement(
      DoFnInvoker<InputT, OutputT> invoker,
      final WindowedValue<InputT> element,
      final TrackerT tracker) {
    final ProcessContext processContext = new ProcessContext(element, tracker);
    DoFn.ProcessContinuation cont =
        invoker.invokeProcessElement(
            new DoFnInvoker.ArgumentProvider<InputT, OutputT>() {
              @Override
              public DoFn<InputT, OutputT>.ProcessContext processContext(
                  DoFn<InputT, OutputT> doFn) {
                return processContext;
              }

              @Override
              public RestrictionTracker<?> restrictionTracker() {
                return tracker;
              }

              // Unsupported methods below.

              @Override
              public BoundedWindow window() {
                throw new UnsupportedOperationException(
                    "Access to window of the element not supported in Splittable DoFn");
              }

              @Override
              public DoFn<InputT, OutputT>.Context context(DoFn<InputT, OutputT> doFn) {
                throw new IllegalStateException(
                    "Should not access context() from @"
                        + DoFn.ProcessElement.class.getSimpleName());
              }

              @Override
              public DoFn<InputT, OutputT>.OnTimerContext onTimerContext(
                  DoFn<InputT, OutputT> doFn) {
                throw new UnsupportedOperationException(
                    "Access to timers not supported in Splittable DoFn");
              }

              @Override
              public State state(String stateId) {
                throw new UnsupportedOperationException(
                    "Access to state not supported in Splittable DoFn");
              }

              @Override
              public Timer timer(String timerId) {
                throw new UnsupportedOperationException(
                    "Access to timers not supported in Splittable DoFn");
              }
            });
    RestrictionT residual;
    RestrictionT forcedCheckpoint = processContext.extractCheckpoint();
    if (cont.shouldResume()) {
      if (forcedCheckpoint == null) {
        // If no checkpoint was forced, the call returned voluntarily (i.e. all tryClaim() calls
        // succeeded) - but we still need to have a checkpoint to resume from.
        residual = tracker.checkpoint();
      } else {
        // A checkpoint was forced - i.e. the call probably (but not guaranteed) returned because of
        // a failed tryClaim() call.
        residual = forcedCheckpoint;
      }
    } else {
      residual = null;
    }
    return new Result(residual, cont);
  }

  private class ProcessContext extends DoFn<InputT, OutputT>.ProcessContext {
    private final WindowedValue<InputT> element;
    private final TrackerT tracker;

    private int numOutputs;
    // Checkpoint may be initiated either when the given number of outputs is reached,
    // or when the call runs for the given duration. It must be initiated at most once,
    // even if these events happen almost at the same time.
    // This is either the result of the sole tracker.checkpoint() call, or null if
    // the call completed before reaching the given number of outputs or duration.
    private RestrictionT checkpoint;
    // A handle on the scheduled action to take a checkpoint.
    private Future<?> scheduledCheckpoint;

    public ProcessContext(WindowedValue<InputT> element, TrackerT tracker) {
      fn.super();
      this.element = element;
      this.tracker = tracker;

      this.scheduledCheckpoint =
          executor.schedule(
              new Runnable() {
                @Override
                public void run() {
                  initiateCheckpoint();
                }
              },
              maxDuration.getMillis(),
              TimeUnit.MILLISECONDS);
    }

    @Nullable
    RestrictionT extractCheckpoint() {
      scheduledCheckpoint.cancel(true);
      try {
        Futures.getUnchecked(scheduledCheckpoint);
      } catch (CancellationException e) {
        // This is expected if the call took less than the maximum duration.
      }
      // By now, a checkpoint may or may not have been taken;
      // via .output() or via scheduledCheckpoint.
      synchronized (this) {
        return checkpoint;
      }
    }

    private synchronized void initiateCheckpoint() {
      // This method may be entered either via .output(), or via scheduledCheckpoint.
      // Only one of them "wins" - tracker.checkpoint() must be called only once.
      if (checkpoint == null) {
        checkpoint = checkNotNull(tracker.checkpoint());
      }
    }

    @Override
    public InputT element() {
      return element.getValue();
    }

    @Override
    public <T> T sideInput(PCollectionView<T> view) {
      return sideInputReader.get(
          view,
          view.getWindowMappingFn()
              .getSideInputWindow(Iterables.getOnlyElement(element.getWindows())));
    }

    @Override
    public Instant timestamp() {
      return element.getTimestamp();
    }

    @Override
    public PaneInfo pane() {
      return element.getPane();
    }

    @Override
    public PipelineOptions getPipelineOptions() {
      return pipelineOptions;
    }

    @Override
    public void output(OutputT output) {
      outputWithTimestamp(output, element.getTimestamp());
    }

    @Override
    public void outputWithTimestamp(OutputT value, Instant timestamp) {
      output.outputWindowedValue(value, timestamp, element.getWindows(), element.getPane());
      noteOutput();
    }

    @Override
    public <T> void sideOutput(TupleTag<T> tag, T value) {
      sideOutputWithTimestamp(tag, value, element.getTimestamp());
    }

    @Override
    public <T> void sideOutputWithTimestamp(TupleTag<T> tag, T value, Instant timestamp) {
      output.sideOutputWindowedValue(
          tag, value, timestamp, element.getWindows(), element.getPane());
      noteOutput();
    }

    private void noteOutput() {
      ++numOutputs;
      if (numOutputs >= maxNumOutputs) {
        initiateCheckpoint();
      }
    }

    @Override
    protected <AggInputT, AggOutputT> Aggregator<AggInputT, AggOutputT> createAggregator(
        String name, Combine.CombineFn<AggInputT, ?, AggOutputT> combiner) {
      throw new UnsupportedOperationException();
    }
  }
}


text:
title: Outbox
summary: 'How to configure NServiceBus to provide reliable messaging without using MSDTC or when MSDTC is not available'
tags:
- MSDTC
redirects:
 - nservicebus/no-dtc
related:
 - samples/sqltransport-nhpersistence-outbox
 - samples/sqltransport-nhpersistence-outbox-ef
---

NServiceBus Version 5 brings the option of running endpoints with the same reliability we all got accustomed to while running under DTC, but now without it.

## Supported Transports

Out of the box RabbitMQ is the only transport that is enabled automatically by default.

SqlServer is also supported but in a different way (for details, see SqlServer Transport section below).
All other transports need to be enabled explicitly using both of the following configuration settings when configuring the endpoint:

<!-- import OutboxEnablineInCode -->

and also the following configuration in the config file:

<!-- import OutboxEnablingInAppConfig -->

NOTE: It may seem extreme to require double opt-in configuration for all other transports, but this is because we want users to be very aware that this new feature should not be used with existing endpoints that currently use DTC, unless those endpoints are [idempotent](http://en.wikipedia.org/wiki/Idempotence). Otherwise, problems could arise from double-processing messages sent (via an at-least-once guarantee) more than once.

## How does it work

These feature has been implemented using both the [Outbox pattern](http://gistlabs.com/2014/05/the-outbox/) and the [Deduplication pattern](http://en.wikipedia.org/wiki/Data_deduplication#In-line_deduplication).

As a message is dequeued we check to see if we have previously processed it. If so, we then deliver any messages in the outbox for that message but do not invoke message-processing logic again. If the message wasn't previously processed, then we invoke the regular handler logic, storing all outgoing message in a durable storage in the same transaction as the users own database changes. Finally we send out all outgoing messages and update the deduplication storage.

Here is a diagram how it all works:

![No DTC Diagram](outbox.png)

## Caveats

- Both the business data and deduplication data need to share the same database
- If you're forwarding processed messages to other endpoints they need to use a different datastore since outbox records are keyed on the `MessageId`

## Using outbox with NHibernate persistence

### SQL Server Transport

SQL Server transport supports *exactly-once* message delivery without Outbox solely by means of sharing the transport connection with persistence. This mode of operation is discussed in depth in this [sample](/samples/sqltransport-nhpersistence).

### What extra tables does NHibernate outbox persistence create

To keep track duplicate messages, the NHibernate implementation of Outbox requires the creation of two additional tables in your database, these are called `OutboxRecord` and `OutboxOperation`.

### How long are the deduplication records kept

The NHibernate implementation by default keeps deduplication records for 7 days and runs the purge every 1 minute.

These default settings can be changed by specifying new defaults in the config file using [TimeStamp strings](https://msdn.microsoft.com/en-us/library/ee372286.aspx), here is how to do it:

<!-- import OutboxNHibernateTimeToKeep -->

## Using outbox with RavenDB persistence

### What extra documents does RavenDB outbox persistence create

To keep track duplicate messages, the RavenDB implementation of Outbox creates a special collection of documents inside your database, these are called `OutboxRecord`.

### How long are the deduplication records kept

The RavenDB implementation by default keeps deduplication records for 7 days and runs the purge every 1 minute.

These default settings can be changed by specifying new defaults in the settings dictionary, here is how to do it:

<!-- import OutboxRavendBTimeToKeep -->

redpajama_set_name: RedPajamaGithub


text:
<Record>
<Term>Plantar Fasciitis</Term>
<SemanticType>Disease or Syndrome</SemanticType>
<ParentTerm>Foot Diseases</ParentTerm>
<ParentTerm>Fasciitis</ParentTerm>
<ClassificationPath>Musculoskeletal Diseases/Foot Diseases/Fasciitis, Plantar</ClassificationPath>
<ClassificationPath>Musculoskeletal Diseases/Fasciitis/Fasciitis, Plantar</ClassificationPath>
<BroaderTerm>Foot Diseases</BroaderTerm>
<BroaderTerm>Musculoskeletal Diseases</BroaderTerm>
<BroaderTerm>Fasciitis</BroaderTerm>
<BroaderTerm>Fasciitis, Plantar</BroaderTerm>
<Synonym>Plantar Fasciitis</Synonym>
<Synonym>Chronic Plantar Fasciitis</Synonym>
<Synonym>Heel Spur Syndrome</Synonym>
<Description>Inflammation of the thick tissue on the bottom of the foot (plantar fascia) causing HEEL pain. The plantar fascia (also called plantar aponeurosis) are bands of fibrous tissue extending from the calcaneal tuberosity to the TOES. The etiology of plantar fasciitis remains controversial but is likely to involve a biomechanical imbalance. Though often presenting along with HEEL SPUR, they do not appear to be causally related.</Description>
<Source>MeSH</Source>
</Record>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>gridstack.js tests</title>

    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="../../../dist/gridstack.css"/>

gridstack.js tests


text:
package com.fasterxml.jackson.core;

/**
 * Exception type for parsing problems, used when non-well-formed content
 * (content that does not conform to JSON syntax as per specification)
 * is encountered.
 */
public class JsonParseException extends JsonProcessingException {
    private static final long serialVersionUID = 1L;

    public JsonParseException(String msg, JsonLocation loc) {
        super(msg, loc);
    }

    public JsonParseException(String msg, JsonLocation loc, Throwable root) {
        super(msg, loc, root);
    }
}


text:
set -e

GOPATH=/home/go
export GOPATH

WEAVE_SRC=$GOPATH/src/github.com/weaveworks/weave

if [ $# -eq 0 -o "$1" = "tests" ] ; then
    # No arguments.  Expect that the weave repo will be bind-mounted
    # into $GOPATH
    if ! [ -e $WEAVE_SRC ] ; then
        cat 2>&1 <<EOF
No container arguments supplied, and nothing at ${WEAVE_SRC}.  Please
either bind-mount the golang workspace containing weave with the
docker run -v option, e.g.:

    $ docker run -v <host gopath>:${GOPATH} \\
          -v /var/run/docker.sock:/var/run/docker.sock weaveworks/weave-build

Or supply git clone arguments to retrieve it, e.g.:

    $ docker run -v /var/run/docker.sock:/var/run/docker.sock \\
          weaveworks/weave-build https://github.com/weaveworks/weave.git
EOF
        exit 1
    fi

    # If we run make directly, any files created on the bind mount
    # will have awkward ownership.  So we switch to a user with the
    # same user and group IDs as source directory.  We have to set a
    # few things up so that sudo works without complaining later on.
    uid=$(stat --format="%u" $WEAVE_SRC)
    gid=$(stat --format="%g" $WEAVE_SRC)
    echo "weave:x:$uid:$gid::$WEAVE_SRC:/bin/sh" >>/etc/passwd
    echo "weave:*:::::::" >>/etc/shadow
    echo "weave	ALL=(ALL)	NOPASSWD: ALL" >>/etc/sudoers

    if [ "$1" = "tests" ] ; then
        su weave -c "PATH=$PATH make -C $WEAVE_SRC tests"
    else
        su weave -c "PATH=$PATH make -C $WEAVE_SRC build"
    fi
else
    # There are arguments to pass to git-clone
    mkdir -p ${WEAVE_SRC%/*}
    git clone "$@" $WEAVE_SRC
    make -C $WEAVE_SRC build
fi


text:
using Notes.Core.Models;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Notes.Core.Interfaces
{
	public interface INoteService
	{
		Task<List<Note>> GetNotesAsync(int next, int limit);
		Task<List<Note>> GetByNotebookAsync(string notebook, int next, int limit);
		Task<List<Note>> GetByTagAsync(string tag, int next, int limit);
		Task<List<Note>> GetDeletedNotes(int next, int limit);
		Task<Note> GetByIdAsync(int id);
		Task<List<DistinctAndCount>> GetMostUsedNotebooksAsync(int limit);
		Task<List<DistinctAndCount>> GetNotebooksAsync();
		Task<List<DistinctAndCount>> GetMostUsedTagsAsync(int limit);
		Task<List<DistinctAndCount>> GetTagsAsync();
		Task<Note> CreateAsync(string title, string content, string notebook, string tags);
		Task UpdateAsync(int id, string title, string content, string notebook, string tags);
		Task TrashAsync(int id, bool trash);
		Task DeleteAsync(int id);
	}
}


text:
package org.jgroups.util;

import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * Timer-like interface which allows for execution of tasks. Taks can be executed
 *

 *
one time only
 *
at recurring time intervals. Intervals can be fixed-delay or fixed-rate,
 * see {@link java.util.concurrent.ScheduledExecutorService} for details
 *
dynamic; at the end of the task execution, a task is asked what the next execution time should be. To do this,
 * method {@link org.jgroups.util.TimeScheduler.Task#nextInterval()} needs to be implemented.
 *

 *
 * @author Bela Ban
 */
public interface TimeScheduler {

    /** The interface that dynamic tasks
     * ({@link TimeScheduler#scheduleWithDynamicInterval(org.jgroups.util.TimeScheduler.Task)}) must implement */
    interface Task extends Runnable {
        /** @return the next scheduled interval in ms. If <= 0 the task will not be re-scheduled */
        long nextInterval();
    }

    /**
     * Executes command with zero required delay. This has effect equivalent to <tt>schedule(command, 0, anyUnit)</tt>.
     *
     * @param command the task to execute
     * @throws java.util.concurrent.RejectedExecutionException at discretion of <tt>RejectedExecutionHandler</tt>,
     * if task cannot be accepted for execution because the executor has been shut down.
     * @throws NullPointerException if command is null
     */
    void execute(Runnable command);

    /**
     * Creates and executes a one-shot action that becomes enabled after the given delay.
     *
     * @param command the task to execute
     * @param delay the time from now to delay execution
     * @param unit the time unit of the delay parameter
     * @return a ScheduledFuture representing pending completion of the task and whose <tt>get()</tt> method
     *         will return <tt>null</tt> upon completion
     * @throws java.util.concurrent.RejectedExecutionException if the task cannot be scheduled for execution
     * @throws NullPointerException if command is null
     */
    Future<?> schedule(Runnable command, long delay, TimeUnit unit);

    /**
     * Creates and executes a periodic action that becomes enabled first after the given initial delay, and
     * subsequently with the given delay between the termination of one execution and the commencement of the next.
     * If any execution of the task encounters an exception, subsequent executions are suppressed.
     * Otherwise, the task will only terminate via cancellation or termination of the executor.
     *
     * @param command the task to execute
     * @param initialDelay the time to delay first execution
     * @param delay the delay between the termination of one execution and the commencement of the next
     * @param unit the time unit of the initialDelay and delay parameters
     * @return a ScheduledFuture representing pending completion of the task, and whose <tt>get()</tt>
     *         method will throw an exception upon cancellation
     * @throws java.util.concurrent.RejectedExecutionException if the task cannot be scheduled for execution
     * @throws NullPointerException if command is null
     * @throws IllegalArgumentException if delay less than or equal to zero
     */
    Future<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit);

      /**
     * Creates and executes a periodic action that becomes enabled first
     * after the given initial delay, and subsequently with the given
     * period; that is executions will commence after
     * <tt>initialDelay</tt> then <tt>initialDelay+period</tt>, then
     * <tt>initialDelay + 2 * period</tt>, and so on.
     * If any execution of the task
     * encounters an exception, subsequent executions are suppressed.
     * Otherwise, the task will only terminate via cancellation or
     * termination of the executor.  If any execution of this task
     * takes longer than its period, then subsequent executions
     * may start late, but will not concurrently execute.
     *
     * @param command the task to execute
     * @param initialDelay the time to delay first execution
     * @param period the period between successive executions
     * @param unit the time unit of the initialDelay and period parameters
     * @return a ScheduledFuture representing pending completion of
     *         the task, and whose <tt>get()</tt> method will throw an
     *         exception upon cancellation
     * @throws java.util.concurrent.RejectedExecutionException if the task cannot be
     *         scheduled for execution
     * @throws NullPointerException if command is null
     * @throws IllegalArgumentException if period less than or equal to zero
     */
      Future<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit);

    /**
     * Schedule a task for execution at varying intervals. After execution, the task will get rescheduled after
     * {@link org.jgroups.util.TimeScheduler.Task#nextInterval()} milliseconds. This is delay-based and not
     * rate-based.
     * The task is never done until nextInterval() return a value <= 0 or the task is cancelled.
     * @param task the task to execute
     */
    Future<?> scheduleWithDynamicInterval(Task task);

    void setThreadFactory(ThreadFactory factory);

    /**
     * Returns a list of tasks currently waiting for execution. If there are a lot of tasks, the returned string
     * should probably only return the number of tasks rather than a full dump.
     * @return
     */
    String dumpTimerTasks();

    /**
     * Returns the configured core threads, or -1 if not applicable
     * @return
     */
    int getMinThreads();

    /** Sets the core pool size. Can be ignored if not applicable */
    void setMinThreads(int size);

    /**
     * Returns the configured max threads, or -1 if not applicable
     * @return
     */
    int getMaxThreads();

    /** Sets the max pool size. Can be ignored if not applicable */
    void setMaxThreads(int size);

    /** Returns the keep alive time (in ms) of the thread pool, or -1 if not applicable */
    long getKeepAliveTime();

    /** Sets the keep alive time (in ms) of the thread pool. Can be ignored if not applicable */
    void setKeepAliveTime(long time);

    /**
     * Returns the current threads in the pool, or -1 if not applicable
     * @return
     */
    int getCurrentThreads();

    /**
     * Returns the number of tasks currently in the queue.
     * @return The number of tasks currently in the queue.
     */
    int size();

    /**
     * Stops the scheduler if running, cancelling all pending tasks
     */
    void stop();

    /** Returns true if stop() has been called, false otherwise */
    boolean isShutdown();
}


text:
"use strict";

const HOMEPAGE = "http://www.google.com"; // TODO: maybe use cookies to set homepage?
const LOGGING = true;
var HISTORY = [];

// ================================================================
// DOM
// ================================================================

var pageSettings = [
	document.getElementById("toggleScripts"),
	document.getElementById("toggleCookies"),
	document.getElementById("toggleObjects"),
];
var UIElems = {
	refresh : document.getElementById("refresh"),
	back    : document.getElementById("back"),
	forward : document.getElementById("forward"),
	url     : document.getElementById("url"),
	frame   : document.getElementById("frame")
};

// ================================================================
// FUNCTIONS
// ================================================================

// Formats URLs to look pretty in the URL bar.
// Regex from http://stackoverflow.com/questions/736513/how-do-i-parse-a-url-into-hostname-and-path-in-javascript#answer-21553982
function prettifyURL(toPretty) {

	if (LOGGING) console.log("Prettifying " + toPretty);

	toPretty = toPretty.replace(/\r?\n|\r/g, "");
	var match = toPretty.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/);

	return "" + match[1] + "//" + match[3] +
	(match[4] ? ":" + match[4] + "" : "") +
	match[5] + "" + match[6] + match[7];

}

// Interface for the URL bar. Reasoning for this being a class is to make it into tabs later
// Get the current URL with curTab.curPage
// Set it with curTab.setPage("http://example.com")
function Tab() {
	this.curPage = "";
	this.setPage = function(newPage) {
		if (LOGGING) console.log("browserState curPage to '" + newPage + "'");
		if (newPage) {
			this.curPage = newPage;
			UIElems.url.innerHTML = prettifyURL(newPage);
		}
	};
}
var curTab = new Tab();

// Processes the links in the page within the frame.
// TODO: review and test
function processIndividualLink(linkk) {
	var tempurl = linkk.href;
	if (tempurl) {
		linkk.href = ""; // don't remove the href tag because it won't look like a link anymore
		linkk.addEventListener("click", function() {
			if (LOGGING) console.log("internal navigate to '" + tempurl + "'");
			curTab.setPage(tempurl);
			navigateTo();
		});
	}
}
function processLinks() {
	if (LOGGING) console.log("Processing links...");
	var innerDoc = UIElems.frame.contentDocument || UIElems.frame.contentWindow.document;
	console.log(innerDoc);
	var links = innerDoc.getElementsByTagName("a");
	console.log(links);
	for (var i = 0; i < links.length; i++) {
		processIndividualLink(links[i]);
	}
}

// Navigation, differs from refresh, back, and forward functions.
// Set the page with curTab.setPage("http://example.com") before calling this function
function navigateTo() {
	if (LOGGING) console.log("navigateTo");
	HISTORY.push(curTab.curPage);
	page(curTab.curPage);
}

// Reloads the page
function refresh() {
	if (LOGGING) console.log("refreshing");
	page(
		curTab.curPage
	);
}
function back() {
	if (LOGGING) console.log("going back");
	// checks if the previous item of history exists
	if (HISTORY[HISTORY.indexOf(curTab.curPage) - 1])
		page(
			HISTORY[HISTORY.indexOf(curTab.curPage) - 1]
		);
}
function forward() {
	if (LOGGING) console.log("going forward");
	// checks if the next item of history exists
	if (HISTORY[HISTORY.indexOf(curTab.curPage) + 1])
		page(
			HISTORY[HISTORY.indexOf(curTab.curPage) + 1]
		);
}

var GETData = [];
// Loads a page inside the iframe
function page(url, scriptsState, cookiesState, objectsState) {

	if (LOGGING) console.log("page '" + url + "'");

	scriptsState = scriptsState || pageSettings[0].className;
	cookiesState = cookiesState || pageSettings[1].className;
	objectsState = objectsState || pageSettings[2].className;

	GETData.url = encodeURIComponent(window.btoa(url));
	GETData.scripts = pageSettings[0].classList.contains("enabled");
	GETData.cookies = pageSettings[1].classList.contains("enabled");
	GETData.objects = pageSettings[2].classList.contains("enabled");
	GETData.base    = encodeURIComponent(window.btoa(curTab.curPage));
	//curTab.setPage(url);
	UIElems.frame.src = "page.php?url=" + GETData.url +
	"&scripts=" + GETData.scripts +
	"&cookies=" + GETData.cookies +
	"&objects=" + GETData.objects +
	"&base=" + GETData.base;

}

// ================================================================
// USER INTERFACE
// ================================================================

function toggleButton() {
	this.classList.toggle("enabled");
	this.classList.toggle("disabled");
}

for (let i = 0; i < 3; i++) {
	pageSettings[i].addEventListener("click", toggleButton);
}
UIElems.refresh.addEventListener("click", refresh);
UIElems.back.addEventListener("click", back);
UIElems.forward.addEventListener("click", forward);

UIElems.url.addEventListener("keypress", function(e) {
	if (e.keyCode == 13) { // if enter pressed
		e.preventDefault();
		curTab.setPage(UIElems.url.innerText.trim());
		navigateTo();
	}
});

UIElems.frame.addEventListener("load", function() {
	if (LOGGING) console.log("Frame page loaded");
	processLinks();
});
function init() {
	if (LOGGING) console.log("initialising");
	curTab.setPage(HOMEPAGE);
	navigateTo();
}
top.addEventListener("load", init);

/* (WIP TOOLTIP STUFF)
var toolTipElems = document.querySelectorAll("[data-tooltip]");
function toolTipMouseEnter() {
	this.childNodes.querySelector(".tooltip").style.visibility = "visible";
}
function toolTipMouseOut() {
	this.childNodes.querySelector(".tooltip").style.visibility = "hidden";
}
for (let i = 0; i < toolTipElems.length; i++) {
	var newToolTip = document.createElement("DIV");
	newToolTip.className = "tooltip";
	newToolTip.innerHTML = toolTipElems["data-tooltip"];
	toolTipElems[i].appendChild(newToolTip);
	toolTipElems[i].addEventListener("mouseenter", toolTipMouseEnter);
	toolTipElems[i].addEventListener("mouseout", toolTipMouseOut);
}
*/


text:
import { Action } from "redux";
import { ComponentProperties } from "reducers/components";
import { Dispatch } from "redux";
import { XCSpyState } from "reducers/spyReducer";
import { snapshotEntryPoint, subscribeAllStateMachines } from "../core";
import { StateMachineInstance } from "reactivexcomponent.js";

export const INITIALIZATION = "INITIALIZATION";
export const SET_CURRENT_COMPONENT = "SET_CURRENT_COMPONENT";
export const UPDATE_GRAPHIC = "UPDATE_GRAPHIC";
export const CLEAR_FINAL_STATES = "CLEAR_FINAL_STATES";
export const SET_AUTO_CLEAR = "SET_AUTO_CLEAR";

export type GlobalComponentsAction = InitializationAction | UpdateGraphicAction | ClearFinalStatesAction | SetAutoClearAction;

export interface InitializationAction extends Action {
    componentProperties: { [componentName: string]: ComponentProperties };
    projectName: string;
}

export interface UpdateGraphicAction extends Action {
    data: StateMachineInstance;
    component: string;
    stateMachine: string;
}

export interface ClearFinalStatesAction extends Action {
    component: string;
    stateMachine: string;
}

export interface SetAutoClearAction extends Action {
    autoClear: boolean;
}

export const initialization = (componentProperties: { [componentName: string]: ComponentProperties }, currentComponent: string, projectName: string): InitializationAction => {
    return {
        type: INITIALIZATION,
        componentProperties,
        projectName
    };
};

export const updateGraphic = (component: string, stateMachine: string, data: StateMachineInstance): (dispatch: Dispatch<Action<any>>, getState: () => XCSpyState) => void => {
    return (dispatch: Dispatch<Action>, getState: () => XCSpyState): void => {
        dispatch({
            type: UPDATE_GRAPHIC,
            component,
            stateMachine,
            data
        });
        if (getState().components.autoClear) {
            dispatch(clearFinalStates(component, stateMachine));
        }
    };
};

export const clearFinalStates = (component: string, stateMachine: string): ClearFinalStatesAction => {
    return {
        type: CLEAR_FINAL_STATES,
        component,
        stateMachine
    };
};

export const setAutoClear = (autoClear: boolean): SetAutoClearAction => {
    return {
        type: SET_AUTO_CLEAR,
        autoClear
    };
};

export const subscribeAllStateMachinesAction = (component: string, stateMachines: string[]): (dispatch: Dispatch<Action>) => void => {
    return (dispatch: Dispatch<Action>): void => {
        subscribeAllStateMachines(dispatch, component, stateMachines);
    };
};

export const snapshotEntryPointAction = (component: string, entryPoint: string): (dispatch: Dispatch<Action>) => void => {
    return (dispatch: Dispatch<Action>): void => {
        snapshotEntryPoint(dispatch, component, entryPoint);
    };
};


text:
.class public abstract Ljavax/crypto/CipherSpi;
.super Ljava/lang/Object;
.source "CipherSpi.java"

# direct methods
.method public constructor <init>()V
    .locals 0

    .prologue
    .line 85
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 86
    return-void
.end method

# virtual methods
.method protected engineDoFinal(Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;)I
    .locals 8
    .param p1, "input"    # Ljava/nio/ByteBuffer;
    .param p2, "output"    # Ljava/nio/ByteBuffer;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljavax/crypto/ShortBufferException;,
            Ljavax/crypto/IllegalBlockSizeException;,
            Ljavax/crypto/BadPaddingException;
        }
    .end annotation

    .prologue
    const/4 v6, 0x0

    .line 517
    if-nez p1, :cond_0

    .line 518
    new-instance v6, Ljava/lang/NullPointerException;

    const-string v7, "input == null"

    invoke-direct {v6, v7}, Ljava/lang/NullPointerException;-><init>(Ljava/lang/String;)V

    throw v6

    .line 520
    :cond_0
    if-nez p2, :cond_1

    .line 521
    new-instance v6, Ljava/lang/NullPointerException;

    const-string v7, "output == null"

    invoke-direct {v6, v7}, Ljava/lang/NullPointerException;-><init>(Ljava/lang/String;)V

    throw v6

    .line 523
    :cond_1
    invoke-virtual {p1}, Ljava/nio/ByteBuffer;->position()I

    move-result v5

    .line 524
    .local v5, "position":I
    invoke-virtual {p1}, Ljava/nio/ByteBuffer;->limit()I

    move-result v3

    .line 526
    .local v3, "limit":I
    sub-int v7, v3, v5

    if-gtz v7, :cond_2

    .line 550
    :goto_0
    return v6

    .line 532
    :cond_2
    invoke-virtual {p1}, Ljava/nio/ByteBuffer;->hasArray()Z

    move-result v7

    if-eqz v7, :cond_3

    .line 533
    invoke-virtual {p1}, Ljava/nio/ByteBuffer;->array()[B

    move-result-object v0

    .line 534
    .local v0, "bInput":[B
    invoke-virtual {p1}, Ljava/nio/ByteBuffer;->arrayOffset()I

    move-result v4

    .line 535
    .local v4, "offset":I
    add-int v6, v4, v5

    sub-int v7, v3, v5

    invoke-virtual {p0, v0, v6, v7}, Ljavax/crypto/CipherSpi;->engineDoFinal([BII)[B

    move-result-object v1

    .line 536
    .local v1, "bOutput":[B
    invoke-virtual {p1, v3}, Ljava/nio/ByteBuffer;->position(I)Ljava/nio/Buffer;

    .line 542
    .end local v4    # "offset":I
    :goto_1
    invoke-virtual {p2}, Ljava/nio/ByteBuffer;->remaining()I

    move-result v6

    array-length v7, v1

    if-ge v6, v7, :cond_4

    .line 543
    new-instance v6, Ljavax/crypto/ShortBufferException;

    const-string v7, "output buffer too small"

    invoke-direct {v6, v7}, Ljavax/crypto/ShortBufferException;-><init>(Ljava/lang/String;)V

    throw v6

    .line 538
    .end local v0    # "bInput":[B
    .end local v1    # "bOutput":[B
    :cond_3
    sub-int v7, v3, v5

    new-array v0, v7, [B

    .line 539
    .restart local v0    # "bInput":[B
    invoke-virtual {p1, v0}, Ljava/nio/ByteBuffer;->get([B)Ljava/nio/ByteBuffer;

    .line 540
    sub-int v7, v3, v5

    invoke-virtual {p0, v0, v6, v7}, Ljavax/crypto/CipherSpi;->engineDoFinal([BII)[B

    move-result-object v1

    .restart local v1    # "bOutput":[B
    goto :goto_1

    .line 546
    :cond_4
    :try_start_0
    invoke-virtual {p2, v1}, Ljava/nio/ByteBuffer;->put([B)Ljava/nio/ByteBuffer;
    :try_end_0
    .catch Ljava/nio/BufferOverflowException; {:try_start_0 .. :try_end_0} :catch_0

    .line 550
    array-length v6, v1

    goto :goto_0

    .line 547
    :catch_0
    move-exception v2

    .line 548
    .local v2, "e":Ljava/nio/BufferOverflowException;
    new-instance v6, Ljavax/crypto/ShortBufferException;

    const-string v7, "output buffer too small"

    invoke-direct {v6, v7}, Ljavax/crypto/ShortBufferException;-><init>(Ljava/lang/String;)V

    throw v6
.end method

.method protected abstract engineDoFinal([BII[BI)I
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljavax/crypto/ShortBufferException;,
            Ljavax/crypto/IllegalBlockSizeException;,
            Ljavax/crypto/BadPaddingException;
        }
    .end annotation
.end method

.method protected abstract engineDoFinal([BII)[B
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljavax/crypto/IllegalBlockSizeException;,
            Ljavax/crypto/BadPaddingException;
        }
    .end annotation
.end method

.method protected abstract engineGetBlockSize()I
.end method

.method protected abstract engineGetIV()[B
.end method

.method protected engineGetKeySize(Ljava/security/Key;)I
    .locals 1
    .param p1, "key"    # Ljava/security/Key;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/security/InvalidKeyException;
        }
    .end annotation

    .prologue
    .line 614
    new-instance v0, Ljava/lang/UnsupportedOperationException;

    invoke-direct {v0}, Ljava/lang/UnsupportedOperationException;-><init>()V

    throw v0
.end method

.method protected abstract engineGetOutputSize(I)I
.end method

.method protected abstract engineGetParameters()Ljava/security/AlgorithmParameters;
.end method

.method protected abstract engineInit(ILjava/security/Key;Ljava/security/AlgorithmParameters;Ljava/security/SecureRandom;)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/security/InvalidKeyException;,
            Ljava/security/InvalidAlgorithmParameterException;
        }
    .end annotation
.end method

.method protected abstract engineInit(ILjava/security/Key;Ljava/security/SecureRandom;)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/security/InvalidKeyException;
        }
    .end annotation
.end method

.method protected abstract engineInit(ILjava/security/Key;Ljava/security/spec/AlgorithmParameterSpec;Ljava/security/SecureRandom;)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/security/InvalidKeyException;,
            Ljava/security/InvalidAlgorithmParameterException;
        }
    .end annotation
.end method

.method protected abstract engineSetMode(Ljava/lang/String;)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/security/NoSuchAlgorithmException;
        }
    .end annotation
.end method

.method protected abstract engineSetPadding(Ljava/lang/String;)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljavax/crypto/NoSuchPaddingException;
        }
    .end annotation
.end method

.method protected engineUnwrap([BLjava/lang/String;I)Ljava/security/Key;
    .locals 1
    .param p1, "wrappedKey"    # [B
    .param p2, "wrappedKeyAlgorithm"    # Ljava/lang/String;
    .param p3, "wrappedKeyType"    # I
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/security/InvalidKeyException;,
            Ljava/security/NoSuchAlgorithmException;
        }
    .end annotation

    .prologue
    .line 597
    new-instance v0, Ljava/lang/UnsupportedOperationException;

    invoke-direct {v0}, Ljava/lang/UnsupportedOperationException;-><init>()V

    throw v0
.end method

.method protected engineUpdate(Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;)I
    .locals 9
    .param p1, "input"    # Ljava/nio/ByteBuffer;
    .param p2, "output"    # Ljava/nio/ByteBuffer;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljavax/crypto/ShortBufferException;
        }
    .end annotation

    .prologue
    const/4 v6, 0x0

    .line 333
    if-nez p1, :cond_0

    .line 334
    new-instance v6, Ljava/lang/NullPointerException;

    const-string v7, "input == null"

    invoke-direct {v6, v7}, Ljava/lang/NullPointerException;-><init>(Ljava/lang/String;)V

    throw v6

    .line 336
    :cond_0
    if-nez p2, :cond_1

    .line 337
    new-instance v6, Ljava/lang/NullPointerException;

    const-string v7, "output == null"

    invoke-direct {v6, v7}, Ljava/lang/NullPointerException;-><init>(Ljava/lang/String;)V

    throw v6

    .line 339
    :cond_1
    invoke-virtual {p1}, Ljava/nio/ByteBuffer;->position()I

    move-result v5

    .line 340
    .local v5, "position":I
    invoke-virtual {p1}, Ljava/nio/ByteBuffer;->limit()I

    move-result v3

    .line 341
    .local v3, "limit":I
    sub-int v7, v3, v5

    if-gtz v7, :cond_3

    .line 367
    :cond_2
    :goto_0
    return v6

    .line 346
    :cond_3
    invoke-virtual {p1}, Ljava/nio/ByteBuffer;->hasArray()Z

    move-result v7

    if-eqz v7, :cond_4

    .line 347
    invoke-virtual {p1}, Ljava/nio/ByteBuffer;->array()[B

    move-result-object v0

    .line 348
    .local v0, "bInput":[B
    invoke-virtual {p1}, Ljava/nio/ByteBuffer;->arrayOffset()I

    move-result v4

    .line 349
    .local v4, "offset":I
    add-int v7, v4, v5

    sub-int v8, v3, v5

    invoke-virtual {p0, v0, v7, v8}, Ljavax/crypto/CipherSpi;->engineUpdate([BII)[B

    move-result-object v1

    .line 350
    .local v1, "bOutput":[B
    invoke-virtual {p1, v3}, Ljava/nio/ByteBuffer;->position(I)Ljava/nio/Buffer;

    .line 356
    .end local v4    # "offset":I
    :goto_1
    if-eqz v1, :cond_2

    .line 359
    invoke-virtual {p2}, Ljava/nio/ByteBuffer;->remaining()I

    move-result v6

    array-length v7, v1

    if-ge v6, v7, :cond_5

    .line 360
    new-instance v6, Ljavax/crypto/ShortBufferException;

    const-string v7, "output buffer too small"

    invoke-direct {v6, v7}, Ljavax/crypto/ShortBufferException;-><init>(Ljava/lang/String;)V

    throw v6

    .line 352
    .end local v0    # "bInput":[B
    .end local v1    # "bOutput":[B
    :cond_4
    sub-int v7, v3, v5

    new-array v0, v7, [B

    .line 353
    .restart local v0    # "bInput":[B
    invoke-virtual {p1, v0}, Ljava/nio/ByteBuffer;->get([B)Ljava/nio/ByteBuffer;

    .line 354
    sub-int v7, v3, v5

    invoke-virtual {p0, v0, v6, v7}, Ljavax/crypto/CipherSpi;->engineUpdate([BII)[B

    move-result-object v1

    .restart local v1    # "bOutput":[B
    goto :goto_1

    .line 363
    :cond_5
    :try_start_0
    invoke-virtual {p2, v1}, Ljava/nio/ByteBuffer;->put([B)Ljava/nio/ByteBuffer;
    :try_end_0
    .catch Ljava/nio/BufferOverflowException; {:try_start_0 .. :try_end_0} :catch_0

    .line 367
    array-length v6, v1

    goto :goto_0

    .line 364
    :catch_0
    move-exception v2

    .line 365
    .local v2, "e":Ljava/nio/BufferOverflowException;
    new-instance v6, Ljavax/crypto/ShortBufferException;

    const-string v7, "output buffer too small"

    invoke-direct {v6, v7}, Ljavax/crypto/ShortBufferException;-><init>(Ljava/lang/String;)V

    throw v6
.end method

.method protected abstract engineUpdate([BII[BI)I
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljavax/crypto/ShortBufferException;
        }
    .end annotation
.end method

.method protected abstract engineUpdate([BII)[B
.end method

.method protected engineUpdateAAD(Ljava/nio/ByteBuffer;)V
    .locals 7
    .param p1, "input"    # Ljava/nio/ByteBuffer;

    .prologue
    .line 411
    if-nez p1, :cond_0

    .line 412
    new-instance v5, Ljava/lang/NullPointerException;

    const-string v6, "input == null"

    invoke-direct {v5, v6}, Ljava/lang/NullPointerException;-><init>(Ljava/lang/String;)V

    throw v5

    .line 414
    :cond_0
    invoke-virtual {p1}, Ljava/nio/ByteBuffer;->position()I

    move-result v4

    .line 415
    .local v4, "position":I
    invoke-virtual {p1}, Ljava/nio/ByteBuffer;->limit()I

    move-result v2

    .line 416
    .local v2, "limit":I
    sub-int v5, v2, v4

    if-gtz v5, :cond_1

    .line 431
    :goto_0
    return-void

    .line 420
    :cond_1
    invoke-virtual {p1}, Ljava/nio/ByteBuffer;->hasArray()Z

    move-result v5

    if-eqz v5, :cond_2

    .line 421
    invoke-virtual {p1}, Ljava/nio/ByteBuffer;->array()[B

    move-result-object v0

    .line 422
    .local v0, "bInput":[B
    invoke-virtual {p1}, Ljava/nio/ByteBuffer;->arrayOffset()I

    move-result v3

    .line 423
    .local v3, "offset":I
    add-int v5, v3, v4

    sub-int v6, v2, v4

    invoke-virtual {p0, v0, v5, v6}, Ljavax/crypto/CipherSpi;->engineUpdateAAD([BII)V

    .line 424
    invoke-virtual {p1, v2}, Ljava/nio/ByteBuffer;->position(I)Ljava/nio/Buffer;

    goto :goto_0

    .line 426
    .end local v0    # "bInput":[B
    .end local v3    # "offset":I
    :cond_2
    sub-int v1, v2, v4

    .line 427
    .local v1, "len":I
    new-array v0, v1, [B

    .line 428
    .restart local v0    # "bInput":[B
    invoke-virtual {p1, v0}, Ljava/nio/ByteBuffer;->get([B)Ljava/nio/ByteBuffer;

    .line 429
    const/4 v5, 0x0

    invoke-virtual {p0, v0, v5, v1}, Ljavax/crypto/CipherSpi;->engineUpdateAAD([BII)V

    goto :goto_0
.end method

.method protected engineUpdateAAD([BII)V
    .locals 2
    .param p1, "input"    # [B
    .param p2, "inputOffset"    # I
    .param p3, "inputLen"    # I

    .prologue
    .line 393
    new-instance v0, Ljava/lang/UnsupportedOperationException;

    const-string v1, "This cipher does not support Authenticated Encryption with Additional Data"

    invoke-direct {v0, v1}, Ljava/lang/UnsupportedOperationException;-><init>(Ljava/lang/String;)V

    throw v0
.end method

.method protected engineWrap(Ljava/security/Key;)[B
    .locals 1
    .param p1, "key"    # Ljava/security/Key;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljavax/crypto/IllegalBlockSizeException;,
            Ljava/security/InvalidKeyException;
        }
    .end annotation

    .prologue
    .line 569
    new-instance v0, Ljava/lang/UnsupportedOperationException;

    invoke-direct {v0}, Ljava/lang/UnsupportedOperationException;-><init>()V

    throw v0
.end method


text:
/**
 * SpringAppContextUtilTest.java
 */
package com.skycloud.jkb.component;

import static org.junit.Assert.assertNotNull;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import com.skycloud.jkb.base.BaseTest;
import com.skycloud.jkb.pojo.constant.SysConstant;
import com.skycloud.jkb.util.StringUtil;

/**
 *
 *
 * @creation 2013年12月27日 下午4:39:52
 * @modification 2013年12月27日 下午4:39:52
 * @company Skycloud
 * @author xiweicheng
 * @version 1.0
 *
 */
public class SpringAppContextUtilTest extends BaseTest {

	private static Logger logger = Logger.getLogger(SpringAppContextUtilTest.class);

	@Autowired
	SpringAppContextUtil springAppContextUtil;

	@Test
	public void testPrintSpringMgrBeans() {

		String[] beanDefinitionNames = springAppContextUtil.getApplicationContext().getBeanDefinitionNames();

		assertNotNull(springAppContextUtil.getApplicationContext());

		List<String> list = new ArrayList<>();

		for (String beanDefinitionName : beanDefinitionNames) {

			list.add(springAppContextUtil.getBean(beanDefinitionName).getClass().getName() + " [" + beanDefinitionName
					+ "]");
		}
		list.add("总数: " + list.size());

		Collections.sort(list);

		logger.info(StringUtil.join(SysConstant.NEW_LINE, list));
	}

}


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.

.. include:: ../../../common.defs

.. _admin-stats-accessing:

Accessing Statistics
********************

There are currently two methods provided with |TS| to view statistics:
:ref:`admin-stats-traffic-line` and :ref:`admin-stats-stats-over-http`.

.. _admin-stats-traffic-line:

Traffic Control
===============

The command line utility :program:`traffic_ctl` offers a text based interface
for viewing |TS| statistics. Invocation is simple and requires knowing the
specific name of the statistic you wish you view::

    traffic_ctl metric get <statistic name>

You may notice that this is the same utility, and argument, used for viewing
configuration variables of a running |TS| instance. Unlike configuration
variables, you cannot modify a statistic value with the :program:`traffic_ctl`
program.

This utility is enabled and built by default, and will be located in the
``bin/`` subdirectory of your |TS| installation. There are no required changes
to your configuration to allow :program:`traffic_ctl` to function, however it
may only be run by users with permissions to access the |TS| Unix socket. This
will typically limit use to root as well as the system user you have configured
|TS| to run under or any other system users which share the same group as you
have configured |TS| to use.

.. _admin-stats-stats-over-http:

Stats Over HTTP
===============

|TS| includes a stable plugin, :ref:`admin-plugins-stats-over-http`, which provides
HTTP access to all |TS| statistcs. The plugin returns a JSON object with all
statistics and their current values. It is not possible to return a subset of
the statistics. The plugin must be enabled before you may use it.

.. _admin-stats-stats-over-http-enabling:

Enabling Stats Over HTTP
------------------------

To enable the :ref:`admin-plugins-stats-over-http` plugin, you must add the
following to your :file:`plugin.config`::

    stats_over_http.so

Once the plugin is enabled and |TS| has reloaded, you can test that it is
working properly by issuing a simple HTTP request with ``curl``. Assuming your
|TS| installation is using the default interface and port bindings, running the
following command on the same host as |TS| should now work::

    curl http://localhost:8080/_stats

You should be presented with an HTTP response containing a single JSON object
which lists all the available statistics and their current values. If you have
configured |TS| to only listen on a specific interface, or to use a different
port, you may need to adjust the URL in the command above.

If you wish to have the stats made available at a non-default path, then that
path should be given as the sole argument to the plugin, as so::

    stats_over_http.so 81c075bc0cca1435ea899ba4ad72766b

The above :file:`plugin.config` entry will result in your |TS| statistics being
located at ``/81c075bc0cca1435ea899ba4ad72766b`` on any host and port on which
you have your |TS| instance listening.

.. _admin-stats-stats-over-http-security:

Statistics Security and Privacy
-------------------------------

Simply changing the path at which your statistics are available should be
considered very weak security. While cache objects themselves cannot be
accessed through the plugin's JSON output, and no modifications to the
configuration or operation of |TS| may be made through the plugin, the
statistics may reveal much more about your network's traffic and architecture
than you wish to be publicly available.

A better method is to use an :ref:`ACL Filter <remap-config-named-filters>` in
:file:`remap.config` to restrict access to clients. For instance, if your |TS|
host resides on a private network in the 10.1.1.0/24 IPv4 address space
listening on the address 10.1.1.10, separate from its public interface(s) used
to serve client requests, you could add the following remap configuration::

    map http://10.1.1.10/_stats http://10.1.1.10/_stats @action=deny @src_ip=0.0.0.0-255.255.255.255
    map http://10.1.1.10/_stats http://10.1.1.10/_stats @action=allow @src_ip=10.1.1.0-10.1.1.255

The above configuration sets the default policy for the entirety of IPv4 address
space to deny, but then exempts the 10.1.1.0/24 network by permitting their
requests to be processed by |TS|. If your monitoring infrastructure makes use
of locally-installed data collection agents, you may even wish to restrict
access to the Stats Over HTTP plugin to all but localhost.


text:
package org.flowable.editor.language;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.flowable.bpmn.model.BpmnModel;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.FormProperty;
import org.flowable.bpmn.model.FormValue;
import org.flowable.bpmn.model.StartEvent;
import org.flowable.bpmn.model.UserTask;
import org.junit.Test;

public class FormPropertiesConverterTest extends AbstractConverterTest {

  @Test
  public void connvertJsonToModel() throws Exception {
    BpmnModel bpmnModel = readJsonFile();
    validateModel(bpmnModel);
  }

  @Test
  public void doubleConversionValidation() throws Exception {
    BpmnModel bpmnModel = readJsonFile();
    validateModel(bpmnModel);
    bpmnModel = convertToJsonAndBack(bpmnModel);
    validateModel(bpmnModel);
  }

  protected String getResource() {
    return "test.formpropertiesmodel.json";
  }

  private void validateModel(BpmnModel model) {
    assertEquals("formPropertiesProcess", model.getMainProcess().getId());
    assertEquals("User registration", model.getMainProcess().getName());
    assertTrue(model.getMainProcess().isExecutable());

    FlowElement startFlowElement = model.getMainProcess().getFlowElement("startNode", true);
    assertNotNull(startFlowElement);
    assertTrue(startFlowElement instanceof StartEvent);
    StartEvent startEvent = (StartEvent) startFlowElement;

    List<FormProperty> formProperties = startEvent.getFormProperties();

    assertNotNull(formProperties);
    assertEquals("Invalid form properties list: ", 8 ,formProperties.size());

    for (FormProperty formProperty :formProperties) {
      if (formProperty.getId().equals("new_property_1")) {
        checkFormProperty(formProperty, "v000", true, false, false);
      } else if (formProperty.getId().equals("new_property_2")) {
        checkFormProperty(formProperty, "v001", true, false, true);
      } else if (formProperty.getId().equals("new_property_3")) {
        checkFormProperty(formProperty, "v010", true, true, false);
      } else if (formProperty.getId().equals("new_property_4")) {
        checkFormProperty(formProperty, "v011", true, true, true);
      } else if (formProperty.getId().equals("new_property_5")) {
        checkFormProperty(formProperty, "v100", true, false, false);

        List<Map<String, Object>> formValues = new ArrayList<Map<String,Object>>();
        for (FormValue formValue : formProperty.getFormValues()) {
          Map<String, Object> formValueMap = new HashMap<String, Object>();
          formValueMap.put("id", formValue.getId());
          formValueMap.put("name", formValue.getName());
          formValues.add(formValueMap);
        }
        checkFormPropertyFormValues(formValues);

      } else if (formProperty.getId().equals("new_property_6")) {
        checkFormProperty(formProperty, "v101", true, false, true);
      } else if (formProperty.getId().equals("new_property_7")) {
        checkFormProperty(formProperty, "v110", true, true, false);
      } else if (formProperty.getId().equals("new_property_8")) {
        checkFormProperty(formProperty, "v111", true, true, true);
      } else {
        fail("unexpected form property id " + formProperty.getId());
      }
    }

    FlowElement userFlowElement = model.getMainProcess().getFlowElement("userTask", true);
    assertNotNull(userFlowElement);
    assertTrue(userFlowElement instanceof UserTask);
    UserTask userTask = (UserTask) userFlowElement;

    formProperties = userTask.getFormProperties();

    assertNotNull(formProperties);
    assertEquals("Invalid form properties list: ", 8 ,formProperties.size());

    for (FormProperty formProperty :formProperties) {
      if (formProperty.getId().equals("new_property_1")) {
        checkFormProperty(formProperty, "v000", false, false, false);
      } else if (formProperty.getId().equals("new_property_2")) {
        checkFormProperty(formProperty, "v001", false, false, true);
      } else if (formProperty.getId().equals("new_property_3")) {
        checkFormProperty(formProperty, "v010", false, true, false);
      } else if (formProperty.getId().equals("new_property_4")) {
        checkFormProperty(formProperty, "v011", false, true, true);
      } else if (formProperty.getId().equals("new_property_5")) {
        checkFormProperty(formProperty, "v100", true, false, false);

        List<Map<String, Object>> formValues = new ArrayList<Map<String,Object>>();
        for (FormValue formValue : formProperty.getFormValues()) {
          Map<String, Object> formValueMap = new HashMap<String, Object>();
          formValueMap.put("id", formValue.getId());
          formValueMap.put("name", formValue.getName());
          formValues.add(formValueMap);
        }
        checkFormPropertyFormValues(formValues);

      } else if (formProperty.getId().equals("new_property_6")) {
        checkFormProperty(formProperty, "v101", true, false, true);
      } else if (formProperty.getId().equals("new_property_7")) {
        checkFormProperty(formProperty, "v110", true, true, false);
      } else if (formProperty.getId().equals("new_property_8")) {
        checkFormProperty(formProperty, "v111", true, true, true);
      } else {
        fail("unexpected form property id " + formProperty.getId());
      }
    }

  }

  private void checkFormProperty(FormProperty formProperty, String name, boolean shouldBeRequired, boolean shouldBeReadable, boolean shouldBeWritable) {
    assertEquals(name, formProperty.getName());
    assertEquals(shouldBeRequired, formProperty.isRequired());
    assertEquals(shouldBeReadable, formProperty.isReadable());
    assertEquals(shouldBeWritable, formProperty.isWriteable());
  }

  private void checkFormPropertyFormValues(List<Map<String, Object>> formValues) {
    List<Map<String, Object>> expectedFormValues = new ArrayList<Map<String,Object>>();
    Map<String, Object> formValue1 = new HashMap<String, Object>();
    formValue1.put("id", "value1");
    formValue1.put("name", "Value 1");
    Map<String, Object> formValue2 = new HashMap<String, Object>();
    formValue2.put("id", "value2");
    formValue2.put("name", "Value 2");

    Map<String, Object> formValue3 = new HashMap<String, Object>();
    formValue3.put("id", "value3");
    formValue3.put("name", "Value 3");

    Map<String, Object> formValue4 = new HashMap<String, Object>();
    formValue4.put("id", "value4");
    formValue4.put("name", "Value 4");

    expectedFormValues.add(formValue1);
    expectedFormValues.add(formValue2);
    expectedFormValues.add(formValue3);
    expectedFormValues.add(formValue4);

    assertEquals(expectedFormValues, formValues);
  }
}


text:
package lcl.android.dal;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;

import lcl.android.core.AppConfig;
import lcl.android.entity.BlogEntity;
import lcl.android.parser.BlogListXmlParser;
import lcl.android.parser.BlogXmlParser;
import lcl.android.utility.HttpUtil;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import android.content.Context;

/**
 * Blog²Ù×÷Àà
 *
 * @author walkingp
 *
 */
public class BlogHelper extends DefaultHandler {
	/**
	 * ÀëÏßÏÂÔØ
	 *
	 * @param top
	 * @return
	 */
	@SuppressWarnings("null")
	public static List<BlogEntity> DownloadOfflineBlogList(int top) {
		int pageSize = top / AppConfig.BLOG_PAGE_SIZE;
		int lastNum = pageSize % AppConfig.BLOG_PAGE_SIZE;

		List<BlogEntity> listBlogs = null;
		// ÏÂÔØÇ°¼¸Ò³
		for (int i = 0; i < pageSize; i++) {
			List<BlogEntity> list = GetBlogList(i);

			listBlogs.addAll(list);
		}
		// ÏÂÔØÊ£ÓàÄÚÈÝ
		List<BlogEntity> list = GetBlogList(pageSize);// ÏÂÔØ×îºóÒ»Ò³
		for (int i = 0, len = list.size(); i < len; i++) {
			listBlogs.addAll(list);
			if (list.get(i).GetBlogId() == lastNum) {
				break;
			}
		}
		// ÄÚÈÝ
		for (int i = 0, len = listBlogs.size(); i < len; i++) {
			String content = GetBlogContentByIdWithNet(listBlogs.get(i)
					.GetBlogId());
			listBlogs.get(i).SetBlogContent(content);

			listBlogs.get(i).SetIsFullText(true);// ¸üÐÂÈ«ÎıêÖ¾
		}

		return listBlogs;
	}

	/**
	 * ¸ù¾ÝÒ³Âë·µ»ØBlog¶ÔÏ󼯺Ï
	 *
	 * @return pageIndex:Ò³Â룬´Ó1¿ªÊ¼
	 */
	public static ArrayList<BlogEntity> GetBlogList(int pageIndex) {
		String url = AppConfig.URL_GET_BLOG_LIST.replace("{pageIndex}",
				String.valueOf(pageIndex));// Êý¾ÝµØÖ·
		String dataString = HttpUtil.geturl(url, null);

		ArrayList<BlogEntity> list = ParseString(dataString);

		return list;
	}

	/**
	 * ½«×Ö·û´®×ª»»ÎªBlog¼¯ºÏ
	 *
	 * @return
	 */
	private static ArrayList<BlogEntity> ParseString(String dataString) {
		SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
		ArrayList<BlogEntity> listBlog = new ArrayList<BlogEntity>();
		try {
			XMLReader xmlReader = saxParserFactory.newSAXParser()
					.getXMLReader();
			BlogListXmlParser handler = new BlogListXmlParser(listBlog);
			xmlReader.setContentHandler(handler);

			xmlReader.parse(new InputSource(new StringReader(dataString)));
			listBlog = handler.GetBlogList();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return listBlog;
	}

	/**
	 * ¸ù¾Ý±àºÅ»ñÈ¡²©¿ÍÄÚÈÝ
	 *
	 * @param blogId
	 * @return
	 */
	public static String GetBlogContentByIdWithNet(int blogId) {
		String blogContent = "";
		String url = "";// Config.URL_GET_BLOG_DETAIL.replace("{0}",String.valueOf(blogId));//
						// ÍøÖ·
		String xml = HttpUtil.geturl(url, null);
		if (xml == "") {
			return "";
		}
		blogContent = ParseBlogString(xml);

		return blogContent;
	}

	/**
	 * ¸ù¾Ý±àºÅ»ñÈ¡²©¿ÍÄÚÈÝ(ÏÈÈ¡±¾µØ£¬ÔÙÈ¡ÍøÂç)
	 *
	 * @param blogId
	 * @return
	 */
	public static String GetBlogById(int blogId, Context context) {
		String blogContent = "";
		// ÓÅÏÈ¿¼ÂDZ¾µØÊý¾Ý
		BlogDalHelper helper = new BlogDalHelper(context);
		BlogEntity entity = helper.GetBlogEntity(blogId);
		if (null == entity || entity.GetBlogContent().equals("")) {
			blogContent = GetBlogContentByIdWithNet(blogId);
		} else {
			blogContent = entity.GetBlogContent();
		}
		return blogContent;
	}

	/**
	 * ½«×Ö·û´®×ª»»ÎªBlog¼¯ºÏ
	 *
	 * @return
	 */
	private static String ParseBlogString(String dataString) {
		SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
		String blogContent = "";
		try {
			XMLReader xmlReader = saxParserFactory.newSAXParser()
					.getXMLReader();
			BlogXmlParser handler = new BlogXmlParser(blogContent);
			xmlReader.setContentHandler(handler);

			xmlReader.parse(new InputSource(new StringReader(dataString)));
			blogContent = handler.GetBlogContent();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return blogContent;
	}
}


text:
Bridge.merge(new System.Globalization.CultureInfo("luo-KE", true), {
    englishName: "Luo (Kenya)",
    nativeName: "Dholuo (Kenya)",

    numberFormat: Bridge.merge(new System.Globalization.NumberFormatInfo(), {
        nanSymbol: "NaN",
        negativeSign: "-",
        positiveSign: "+",
        negativeInfinitySymbol: "-∞",
        positiveInfinitySymbol: "∞",
        percentSymbol: "%",
        percentGroupSizes: [3],
        percentDecimalDigits: 2,
        percentDecimalSeparator: ".",
        percentGroupSeparator: ",",
        percentPositivePattern: 1,
        percentNegativePattern: 1,
        currencySymbol: "Ksh",
        currencyGroupSizes: [3],
        currencyDecimalDigits: 2,
        currencyDecimalSeparator: ".",
        currencyGroupSeparator: ",",
        currencyNegativePattern: 5,
        currencyPositivePattern: 1,
        numberGroupSizes: [3],
        numberDecimalDigits: 2,
        numberDecimalSeparator: ".",
        numberGroupSeparator: ",",
        numberNegativePattern: 1
    }),

    dateTimeFormat: Bridge.merge(new System.Globalization.DateTimeFormatInfo(), {
        abbreviatedDayNames: ["JMP","WUT","TAR","TAD","TAN","TAB","NGS"],
        abbreviatedMonthGenitiveNames: ["DAC","DAR","DAD","DAN","DAH","DAU","DAO","DAB","DOC","DAP","DGI","DAG",""],
        abbreviatedMonthNames: ["DAC","DAR","DAD","DAN","DAH","DAU","DAO","DAB","DOC","DAP","DGI","DAG",""],
        amDesignator: "OD",
        dateSeparator: "/",
        dayNames: ["Jumapil","Wuok Tich","Tich Ariyo","Tich Adek","Tich Ang'wen","Tich Abich","Ngeso"],
        firstDayOfWeek: 0,
        fullDateTimePattern: "dddd, d MMMM yyyy HH:mm:ss",
        longDatePattern: "dddd, d MMMM yyyy",
        longTimePattern: "HH:mm:ss",
        monthDayPattern: "MMMM d",
        monthGenitiveNames: ["Dwe mar Achiel","Dwe mar Ariyo","Dwe mar Adek","Dwe mar Ang'wen","Dwe mar Abich","Dwe mar Auchiel","Dwe mar Abiriyo","Dwe mar Aboro","Dwe mar Ochiko","Dwe mar Apar","Dwe mar gi achiel","Dwe mar Apar gi ariyo",""],
        monthNames: ["Dwe mar Achiel","Dwe mar Ariyo","Dwe mar Adek","Dwe mar Ang'wen","Dwe mar Abich","Dwe mar Auchiel","Dwe mar Abiriyo","Dwe mar Aboro","Dwe mar Ochiko","Dwe mar Apar","Dwe mar gi achiel","Dwe mar Apar gi ariyo",""],
        pmDesignator: "OT",
        rfc1123: "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'",
        shortDatePattern: "dd/MM/yyyy",
        shortestDayNames: ["JMP","WUT","TAR","TAD","TAN","TAB","NGS"],
        shortTimePattern: "HH:mm",
        sortableDateTimePattern: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
        sortableDateTimePattern1: "yyyy'-'MM'-'dd",
        timeSeparator: ":",
        universalSortableDateTimePattern: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
        yearMonthPattern: "MMMM yyyy",
        roundtripFormat: "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffzzz"
    }),

    TextInfo: Bridge.merge(new System.Globalization.TextInfo(), {
        ANSICodePage: 0,
        CultureName: "luo-KE",
        EBCDICCodePage: 500,
        IsRightToLeft: false,
        LCID: 4096,
        listSeparator: ";",
        MacCodePage: 2,
        OEMCodePage: 1,
        IsReadOnly: true
    })
});


text:
title: "Licenses"
description: "Gatling projects licenses"
lead: "Gatling is licensed under the Apache License v2.0"
date: 2021-04-20T18:30:56+02:00
lastmod: 2021-04-20T18:30:56+02:00
weight: 2100400
---

## Developer motivations

We try as much as possible to distribute Gatling and its side projects under Apache License v2.0.
As much as possible means that we sometimes have to cope with some dependencies that are not Apache License v2.0 compatible or even not open source friendly.

Copyright of the source code and the Gatling logos belongs to GatlingCorp.

## Main Gatling project

Gatling is licensed under the Apache License v2.0 available here: [HTML](http://www.apache.org/licenses/LICENSE-2.0.html) | [TXT](http://www.apache.org/licenses/LICENSE-2.0.txt)

## Highcharts based modules

The default report generation module makes use of Highcharts and Highstock, two great javascript libraries developed by Highsoft.
These libraries are neither open source, nor free for our use case.

We purchased developer licenses and got an agreement with Highsoft so we could distribute their libraries with some restrictions.
As a consequence, this module cannot be open sourced and has to be developed in a separated project : [gatling-highcharts](https://github.com/gatling/gatling-highcharts).
However, for convenience reasons, we distribute a ready to use bundle.

Making it short, we distribute this module for free with the following restrictions :

* one can not edit the source code without buying a Highcharts license for working on Gatling
* the shipped Highcharts or Highstock copies cannot be used outside of Gatling standard usage

For more information, please refer to the [gatling-highcharts license](https://github.com/gatling/gatling-highcharts/blob/main/LICENSE) or feel free to [ask](https://groups.google.com/forum/#!forum/gatling).


text:
const BaseValidator = require('./validators/base-validator');
const _ = require('lodash');

module.exports = function (options) {
    options = options || {};
    let aliases = options.aliases || require('./aliases');
    let formatter = options.formatter || require('./formatter');

    return validate;

    function validate(data, rules) {
        const promisesList = [];
        const validationErrors = {};
        const errors = [];
        const result = {};
        const validatedFields = extractValidatedFields(rules);
        const validators = initValidators(validatedFields, rules, data, validationErrors);

        for (let name in validators) {
            let fieldValidators = validators[name];
            let promise = Promise.resolve(data[name]);
            for (let validator of fieldValidators) {
                promise = promise.then(res => validator.validate(res));
            }

            promisesList.push(
                promise
                    .then(res => result[name] = res)
                    .catch(err => {
                        if (err instanceof Error) {
                            return errors.push(err);
                        }
                    })
            );
        }

        return Promise.all(promisesList)
            .then(res => {
                if (errors.length) {
                    return Promise.reject(errors[0]);
                }
                if (!_.isEmpty(validationErrors)) {
                    return Promise.reject(validationErrors);
                }
                return Promise.resolve(result);
            });
    }

    function extractValidatedFields(rules) {
        const validatedFields = {};
        for (rule of rules) {
            if (Array.isArray(rule[0])) {
                for (fieldName of rule[0]) {
                    validatedFields[fieldName] = [];
                }
            } else {
                validatedFields[rule[0]] = [];
            }
        }
        return validatedFields;
    }

    function initValidators(validatedFields, rules, data, errors) {
        for (rule of rules) {
            let options = rule[2] || {};
            options['model'] = data;
            options['errors'] = errors;
            options['formatter'] = formatter;
            if (Array.isArray(rule[0])) {
                let ruleName = rule[1];
                for (let attribute of rule[0]) {
                    validatedFields[attribute].push(createValidator(ruleName, attribute, options));
                }
            } else {
                validatedFields[rule[0]].push(createValidator(rule[1], rule[0], options));
            }
        }
        return validatedFields;
    }

    function createValidator(name, attribute, options) {
        options = options || {};
        let validator;
        if (name instanceof BaseValidator) {
            validator = ruleName;
            validator.attribute = attribute;
        } else if(typeof name === 'function') {
            options['callback'] = name;
            validator = new aliases['inline'](attribute, options);
        } else {
            validator = new aliases[name](attribute, options);
        }
        return validator;
    }
};


text:
Information Architecture

To have a little guidance in how to recombine certain information, we should think about categorizing our
different information types. By splitting our system into several pieces we may end up with a few scenarios of how
to share or combine content of our systems back again.


text:
package org.apache.myfaces.view.facelets.tag.jstl.core;

import javax.el.ELContext;
import javax.el.ValueExpression;

/**
 * @author Jacob Hookom
 * @version $Id: IndexedValueExpression.java 1187701 2011-10-22 12:21:54Z bommel $
 */
public final class IndexedValueExpression extends ValueExpression
{

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    private final Integer i;

    private final ValueExpression orig;

    /**
     *
     */
    public IndexedValueExpression(ValueExpression orig, int i)
    {
        this.i = Integer.valueOf(i);
        this.orig = orig;
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.el.ValueExpression#getValue(javax.el.ELContext)
     */
    public Object getValue(ELContext context)
    {
        Object base = this.orig.getValue(context);
        if (base != null)
        {
            context.setPropertyResolved(false);
            return context.getELResolver().getValue(context, base, i);
        }
        return null;
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.el.ValueExpression#setValue(javax.el.ELContext, java.lang.Object)
     */
    public void setValue(ELContext context, Object value)
    {
        Object base = this.orig.getValue(context);
        if (base != null)
        {
            context.setPropertyResolved(false);
            context.getELResolver().setValue(context, base, i, value);
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.el.ValueExpression#isReadOnly(javax.el.ELContext)
     */
    public boolean isReadOnly(ELContext context)
    {
        Object base = this.orig.getValue(context);
        if (base != null)
        {
            context.setPropertyResolved(false);
            return context.getELResolver().isReadOnly(context, base, i);
        }
        return true;
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.el.ValueExpression#getType(javax.el.ELContext)
     */
    public Class getType(ELContext context)
    {
        Object base = this.orig.getValue(context);
        if (base != null)
        {
            context.setPropertyResolved(false);
            return context.getELResolver().getType(context, base, i);
        }
        return null;
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.el.ValueExpression#getExpectedType()
     */
    public Class getExpectedType()
    {
        return Object.class;
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.el.Expression#getExpressionString()
     */
    public String getExpressionString()
    {
        return this.orig.getExpressionString();
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.el.Expression#equals(java.lang.Object)
     */
    public boolean equals(Object obj)
    {
        return this.orig.equals(obj);
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.el.Expression#hashCode()
     */
    public int hashCode()
    {
        return this.orig.hashCode();
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.el.Expression#isLiteralText()
     */
    public boolean isLiteralText()
    {
        return false;
    }

}


text:
"use strict";

// required to safely use 6to5/register within a browserify codebase

module.exports = function () {};

require("../../polyfill");


text:
<!DOCTYPE html>

<meta charset="utf-8">
<base href="http://euskopython.github.io/es/archive.html">
<meta name="description" content="This is the site of the Basque Python Society">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Archivo | EuskoPython</title>
<link href="../assets/css/all-nocdn.css" rel="stylesheet" type="text/css">
<meta content="#5670d4" name="theme-color">
<link rel="alternate" type="application/rss+xml" title="RSS (en)" href="../rss.xml">
<link rel="alternate" type="application/rss+xml" title="RSS (es)" href="rss.xml">
<link rel="alternate" type="application/rss+xml" title="RSS (eu)" href="../eu/rss.xml">
<link rel="canonical" href="http://euskopython.github.io/es/archive.html">

Ir al contenido principal

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-navbar" aria-controls="bs-navbar" aria-expanded="false">
            Toggle navigation

            </button>

                EuskoPython

Archivo (activo)

Etiquetas

Canal RSS

English

Euskara

Archivo

2012
            (1)

            Contents © 2015         Basque Python Society - Powered by         Nikola


text:
package org.openkilda.wfm.topology.flowhs.fsm.create.action;

import static java.lang.String.format;

import org.openkilda.floodlight.api.response.SpeakerFlowSegmentResponse;
import org.openkilda.floodlight.flow.response.FlowErrorResponse;
import org.openkilda.persistence.PersistenceManager;
import org.openkilda.wfm.topology.flowhs.fsm.create.FlowCreateFsm;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class OnReceivedDeleteResponseAction extends OnReceivedInstallResponseAction {
    public OnReceivedDeleteResponseAction(PersistenceManager persistenceManager) {
        super(persistenceManager);
    }

    @Override
    protected void handleResponse(FlowCreateFsm stateMachine, SpeakerFlowSegmentResponse response) {
        if (response.isSuccess()) {
            stateMachine.saveActionToHistory("Rule was deleted",
                    format("The rule was deleted: switch %s, cookie %s", response.getSwitchId(), response.getCookie()));
        } else {
            FlowErrorResponse errorResponse = (FlowErrorResponse) response;
            stateMachine.getFailedCommands().add(errorResponse.getCommandId());
            stateMachine.saveErrorToHistory("Failed to delete rule",
                    format("Failed to delete the rule: commandId %s, switch %s. Error: %s",
                            errorResponse.getCommandId(), errorResponse.getSwitchId(), errorResponse));
        }
    }
}


text:
package me.kafeitu.activiti.web.chapter7;

import me.kafeitu.activiti.chapter6.util.UserUtil;
import me.kafeitu.activiti.chapter7.entity.Leave;
import me.kafeitu.activiti.chapter7.service.LeaveManager;
import me.kafeitu.activiti.chapter7.service.LeaveWorkflowService;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.identity.User;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.BooleanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 请假控制器
 *
 * @author henryyan
 */
@Controller
@RequestMapping(value = "/chapter7/leave")
public class LeaveController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private LeaveManager leaveManager;

    @Autowired
    private LeaveWorkflowService leaveService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private RuntimeService runtimeService;

    @RequestMapping(value = {"apply", ""})
    public String createForm(Model model) {
        model.addAttribute("leave", new Leave());
        return "/chapter7/leave/leave-apply";
    }

    /**
     * 启动请假流程
     */
    @RequestMapping(value = "start", method = RequestMethod.POST)
    public String startWorkflow(Leave leave, RedirectAttributes redirectAttributes, HttpSession session) {
        try {
            User user = UserUtil.getUserFromSession(session);
            Map<String, Object> variables = new HashMap<String, Object>();
            ProcessInstance processInstance = leaveService.startWorkflow(leave, user.getId(), variables);
            redirectAttributes.addFlashAttribute("message", "流程已启动,流程ID:" + processInstance.getId());
        } catch (ActivitiException e) {
            if (e.getMessage().indexOf("no processes deployed with key") != -1) {
                logger.warn("没有部署流程!", e);
                redirectAttributes.addFlashAttribute("error", "没有部署请假流程");
            } else {
                logger.error("启动请假流程失败:", e);
                redirectAttributes.addFlashAttribute("error", "系统内部错误!");
            }
        } catch (Exception e) {
            logger.error("启动请假流程失败:", e);
            redirectAttributes.addFlashAttribute("error", "系统内部错误!");
        }
        return "redirect:/chapter7/leave/apply";
    }

    /**
     * 任务列表
     *
     * @param leave
     */
    @RequestMapping(value = "task/list")
    public ModelAndView taskList(HttpSession session) {
        ModelAndView mav = new ModelAndView("/chapter7/leave/leave-task-list");
        String userId = UserUtil.getUserFromSession(session).getId();
        List<Leave> results = leaveService.findTodoTasks(userId);
        mav.addObject("records", results);
        return mav;
    }

    /**
     * 签收任务
     */
    @RequestMapping(value = "task/claim/{id}")
    public String claim(@PathVariable("id") String taskId, HttpSession session, RedirectAttributes redirectAttributes) {
        String userId = UserUtil.getUserFromSession(session).getId();
        taskService.claim(taskId, userId);
        redirectAttributes.addFlashAttribute("message", "任务已签收");
        return "redirect:/chapter7/leave/task/list";
    }

    /**
     * 任务列表
     *
     * @param leave
     */
    @RequestMapping(value = "task/view/{taskId}")
    public ModelAndView showTaskView(@PathVariable("taskId") String taskId) {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        String processInstanceId = task.getProcessInstanceId();
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        Leave leave = leaveManager.get(new Long(processInstance.getBusinessKey()));
        ModelAndView mav = new ModelAndView("/chapter7/leave/task-" + task.getTaskDefinitionKey());
        mav.addObject("leave", leave);
        mav.addObject("task", task);
        return mav;
    }

    /**
     * 完成任务
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "task/complete/{id}", method = {RequestMethod.POST, RequestMethod.GET})
    @SuppressWarnings("unchecked")
    public String complete(@PathVariable("id") String taskId, @RequestParam(value = "saveEntity", required = false) String saveEntity,
                           @ModelAttribute("preloadLeave") Leave leave, HttpServletRequest request, RedirectAttributes redirectAttributes) {
        boolean saveEntityBoolean = BooleanUtils.toBoolean(saveEntity);
        Map<String, Object> variables = new HashMap<String, Object>();
        Enumeration<String> parameterNames = request.getParameterNames();
        try {
            while (parameterNames.hasMoreElements()) {
                String parameterName = (String) parameterNames.nextElement();
                if (parameterName.startsWith("p_")) {
                    // 参数结构:p_B_name,p为参数的前缀,B为类型,name为属性名称
                    String[] parameter = parameterName.split("_");
                    if (parameter.length == 3) {
                        String paramValue = request.getParameter(parameterName);
                        Object value = paramValue;
                        if (parameter[1].equals("B")) {
                            value = BooleanUtils.toBoolean(paramValue);
                        } else if (parameter[1].equals("DT")) {
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                            value = sdf.parse(paramValue);
                        }
                        variables.put(parameter[2], value);
                    } else {
                        throw new RuntimeException("invalid parameter for activiti variable: " + parameterName);
                    }
                }
            }
            leaveService.complete(leave, saveEntityBoolean, taskId, variables);
            redirectAttributes.addFlashAttribute("message", "任务已完成");
        } catch (Exception e) {
            logger.error("error on complete task {}, variables={}", new Object[]{taskId, variables, e});
            request.setAttribute("error", "完成任务失败");
        }
        return "redirect:/chapter7/leave/task/list";
    }

    /**
     * 自动绑定页面字段
     */
    @ModelAttribute("preloadLeave")
    public Leave getLeave(@RequestParam(value = "id", required = false) Long id, HttpSession session) {
        if (id != null) {
            return leaveManager.get(id);
        }
        return new Leave();
    }

}


text:
package org.grobid.core.annotations;

import static org.grobid.core.utilities.TeiValues.ATTR_ID;
import static org.grobid.core.utilities.TeiValues.W3C_NAMESPACE;
import static org.grobid.core.utilities.TeiValues.XML;

import javax.xml.namespace.QName;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.StartElement;

import org.apache.commons.lang3.builder.HashCodeBuilder;

/**
 * Contains the information of a paragraph.
 *
 * @author Damien
 *
 */
public class Paragraph implements Cloneable {

	/**
	 * QName for attribute id of paragraph.
	 */
	private static final QName paragraphIdQName = new QName(W3C_NAMESPACE, ATTR_ID, XML);

	/**
	 * The id.
	 */
	protected String id;

	/**
	 * The gorn index.
	 */
	protected String gornIdx;

	/**
	 * The StartElement.
	 */
	protected StartElement startTag;

	/**
	 * The start position in Description.
	 */
	protected int positionStart;

	/**
	 * The end position in Description.
	 */
	protected int positionEnd;

	/**
	 * If the paragraph is annotated.
	 */
	protected boolean isAnnotated;

	/**
	 * The description pointer. This field is used by the method equals. In
	 * Description, an indexOf is done to get the paragraph corresponding to the
	 * description pointer.
	 */
	protected int descriptionPointer;

	/**
	 * Empty constructor.
	 */
	public Paragraph() {

	}

	/**
	 * Constructor.
	 *
	 * @param pId
	 *            The id.
	 * @param pGornIdx
	 *            The gorn index.
	 * @param pAttributes
	 *            The attributes.
	 * @param pPositionStart
	 *            the start position.
	 * @param pPositionEnd
	 *            The end position.
	 */
	public Paragraph(final String pId, final String pGornIdx, final int pPositionStart, int pPositionEnd, final StartElement pStartTag,
			final boolean pIsAnnotated) {
		id = pId;
		gornIdx = pGornIdx;
		positionStart = pPositionStart;
		positionEnd = pPositionEnd;
		startTag = pStartTag;
		isAnnotated = pIsAnnotated;
	}

	/**
	 * This field is used by the method equals. In Description, an indexOf is
	 * done to get the paragraph corresponding to the description pointer.
	 *
	 * @param pDescriptionPointer
	 *            The pointer of Description.
	 */
	public Paragraph(final int pDescriptionPointer) {
		descriptionPointer = pDescriptionPointer;
	}

	/**
	 * {@Inherited}
	 */
	@Override
	public Paragraph clone() {
		return new Paragraph(id, gornIdx, positionStart, positionEnd, startTag, isAnnotated);
	}

	/**
	 * @return the id
	 */
	public final String getId() {
		return id;
	}

	/**
	 * @param pId
	 *            the id to set
	 */
	public final void setId(String pId) {
		id = pId;
	}

	/**
	 * @return the gornIdx
	 */
	public final String getGornIdx() {
		return gornIdx;
	}

	/**
	 * @param pGornIdx
	 *            the gornIdx to set
	 */
	public final void setGornIdx(String pGornIdx) {
		gornIdx = pGornIdx;
	}

	/**
	 * @return the startTag
	 */
	public final StartElement getStartTag() {
		return startTag;
	}

	/**
	 * @param pStartTag
	 *            the startTag to set
	 */
	public final void setStartTag(StartElement pStartTag) {
		startTag = pStartTag;
	}

	/**
	 * @return the positionStart
	 */
	public final int getPositionStart() {
		return positionStart;
	}

	/**
	 * @param pPositionStart
	 *            the positionStart to set
	 */
	public final void setPositionStart(int pPositionStart) {
		positionStart = pPositionStart;
	}

	/**
	 * @return the positionEnd
	 */
	public final int getPositionEnd() {
		return positionEnd;
	}

	/**
	 * @param pPositionEnd
	 *            the positionEnd to set
	 */
	public final void setPositionEnd(int pPositionEnd) {
		positionEnd = pPositionEnd;
	}

	/**
	 * @return the isAnnotated
	 */
	public final boolean isAnnotated() {
		return isAnnotated;
	}

	/**
	 * @param pIsAnnotated
	 *            the isAnnotated to set
	 */
	public final void setAnnotated(boolean pIsAnnotated) {
		isAnnotated = pIsAnnotated;
	}

	/**
	 * Get the id value of the paragraph.
	 *
	 * @param pStartTag
	 *            The StartElement of the paragraph.
	 * @return the id value if found, null else.
	 */
	public String getIdFromAttributes() {
		final Attribute attr = startTag.getAttributeByName(paragraphIdQName);
		return attr == null ? null : attr.getValue();
	}

	/**
	 * {@inheritDoc} Used in Description to get the paragraph corresponding to
	 * the pointer.
	 */
	@Override
	public boolean equals(final Object pParagraph) {
		final int start = ((Paragraph) pParagraph).getPositionStart();
		final int end = ((Paragraph) pParagraph).getPositionEnd();
		if (descriptionPointer >= start && descriptionPointer <= end)
			return true;
		else
			return false;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public int hashCode() {
		return new HashCodeBuilder().append(id).toHashCode();
	}

}


text:
import path from 'path';
import fs from 'fs';

import { expect } from 'chai';
import sinon from 'sinon';

import * as fileUtils from '../../../src/utils/file-utils';

function wrapDirs(dirs: string[]) {
  return dirs.map((d) => {
    return {
      name: d,
      isDirectory: () => true,
    };
  });
}

describe('fileUtils', () => {
  let readdirStub: sinon.SinonStub;

  beforeEach(() => {
    sinon.stub(fs.promises, 'writeFile');
    sinon.stub(fs.promises, 'symlink');
    sinon.stub(fs.promises, 'mkdir');
    readdirStub = sinon.stub(fs.promises, 'readdir');
  });

  describe('symlinkJunction', () => {
    it('should call fs.symlink', async () => {
      await fileUtils.symlinkJunction('a', 'b');
      expect(fs.promises.symlink).calledWith('a', 'b', 'junction');
    });
    it("should create the dir if it doesn't exist", async () => {
      await fileUtils.symlinkJunction('a', path.resolve('b', 'c'));
      expect(fs.promises.mkdir).calledWith(path.resolve('b'), { recursive: true });
    });
  });

  describe('findNodeModulesList', () => {
    it('should return node_modules array located in `basePath`', async () => {
      const basePath = path.resolve('a', 'b', 'c');
      const expectedNodeModules = path.join('node_modules');
      readdirStub.resolves(wrapDirs(['node_modules']));
      const actual = await fileUtils.findNodeModulesList(basePath);
      expect(actual[0]).eq(expectedNodeModules);
    });

    it('should return node_modules array in subDirectory of `basePath`', async () => {
      const basePath = path.resolve('.');
      const expectedNodeModulesList = [path.join('a', 'b', 'node_modules'), path.join('a', 'b', 'c', 'node_modules')];
      readdirStub.withArgs(path.resolve(basePath)).resolves(wrapDirs(['a']));
      readdirStub.withArgs(path.resolve(basePath, 'a')).resolves(wrapDirs(['b']));
      readdirStub.withArgs(path.resolve(basePath, 'a', 'b')).resolves(wrapDirs(['c', 'node_modules']));
      readdirStub.withArgs(path.resolve(basePath, 'a', 'b', 'c')).resolves(wrapDirs(['node_modules']));
      const actual = await fileUtils.findNodeModulesList(basePath);
      expect(actual).deep.eq(expectedNodeModulesList);
    });

    it('should return empty array if no node_modules exist in basePath or parent directories', async () => {
      const basePath = path.resolve('a', 'b', 'c');
      readdirStub.resolves([]);
      const actual = await fileUtils.findNodeModulesList(basePath);
      expect(actual.length).eq(0);
    });
  });
});


text:
package client

import "testing"

var emptyLeaveGroupRequestBytes = []byte{0x00, 0x00, 0x00, 0x00}
var goodLeaveGroupRequestBytes = []byte{0x00, 0x05, 'g', 'r', 'o', 'u', 'p', 0x00, 0x06, 'm', 'e', 'm', 'b', 'e', 'r'}

var errorLeaveGroupResponseBytes = []byte{0x00, 15}
var goodLeaveGroupResponseBytes = []byte{0x00, 0x00}

func TestLeaveGroupRequest(t *testing.T) {
	emptyRequest := new(LeaveGroupRequest)
	testRequest(t, emptyRequest, emptyLeaveGroupRequestBytes)

	goodRequest := new(LeaveGroupRequest)
	goodRequest.GroupID = "group"
	goodRequest.MemberID = "member"
	testRequest(t, goodRequest, goodLeaveGroupRequestBytes)
}

func TestLeaveGroupResponse(t *testing.T) {
	errorLeaveGroupResponse := new(LeaveGroupResponse)
	decode(t, errorLeaveGroupResponse, errorLeaveGroupResponseBytes)
	assert(t, errorLeaveGroupResponse.Error, ErrConsumerCoordinatorNotAvailableCode)

	goodLeaveGroupResponse := new(LeaveGroupResponse)
	decode(t, goodLeaveGroupResponse, goodLeaveGroupResponseBytes)
	assert(t, goodLeaveGroupResponse.Error, ErrNoError)
}


text:
require 'fog/openstack/models/model'

module Fog
  module Identity
    class OpenStack
      class V3
        class Domain < Fog::OpenStack::Model
          identity :id

          attribute :description
          attribute :enabled
          attribute :name
          attribute :links

          class << self
            attr_accessor :cache
          end

          @cache = {}

          def to_s
            name
          end

          def destroy
            clear_cache
            requires :id
            service.delete_domain(id)
            true
          end

          def update(attr = nil)
            clear_cache
            requires :id, :name
            merge_attributes(
              service.update_domain(id, attr || attributes).body['domain']
            )
            self
          end

          def create
            clear_cache
            requires :name
            merge_attributes(
              service.create_domain(attributes).body['domain']
            )
            self
          end

          private

          def clear_cache
            self.class.cache = {}
          end
        end
      end
    end
  end
end


text:
"""This example updates a campaign by setting its status to PAUSED. To get
campaigns, run get_campaigns.py.

Tags: CampaignService.mutate
"""

__author__ = 'api.kwinter@gmail.com (Kevin Winter)'

import os
import sys
sys.path.insert(0, os.path.join('..', '..', '..', '..', '..'))

# Import appropriate classes from the client library.
from adspygoogle import AdWordsClient

campaign_id = 'INSERT_CAMPAIGN_ID_HERE'

def main(client, campaign_id):
  # Initialize appropriate service.
  campaign_service = client.GetCampaignService(version='v201306')

  # Construct operations and update campaign.
  operations = [{
      'operator': 'SET',
      'operand': {
          'id': campaign_id,
          'status': 'PAUSED'
      }
  }]
  campaigns = campaign_service.Mutate(operations)[0]

  # Display results.
  for campaign in campaigns['value']:
    print ('Campaign with name \'%s\' and id \'%s\' was updated.'
           % (campaign['name'], campaign['id']))

  print
  print ('Usage: %s units, %s operations' % (client.GetUnits(),
                                             client.GetOperations()))

if __name__ == '__main__':
  # Initialize client object.
  client = AdWordsClient(path=os.path.join('..', '..', '..', '..', '..'))

  main(client, campaign_id)