text:
.class Lcom/android/server/content/SyncManager$PrintTable;
.super Ljava/lang/Object;
.source "SyncManager.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/content/SyncManager;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = "PrintTable"
.end annotation

# instance fields
.field private final mCols:I

.field private mTable:Ljava/util/ArrayList;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/ArrayList",
            "<[",
            "Ljava/lang/Object;",
            ">;"
        }
    .end annotation
.end field

# direct methods
.method constructor <init>(I)V
    .locals 1
    .param p1, "cols"    # I

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

    .line 3552
    invoke-static {}, Lcom/google/android/collect/Lists;->newArrayList()Ljava/util/ArrayList;

    move-result-object v0

    iput-object v0, p0, Lcom/android/server/content/SyncManager$PrintTable;->mTable:Ljava/util/ArrayList;

    .line 3556
    iput p1, p0, Lcom/android/server/content/SyncManager$PrintTable;->mCols:I

    .line 3557
    return-void
.end method

.method private printRow(Ljava/io/PrintWriter;[Ljava/lang/String;[Ljava/lang/Object;)V
    .locals 6
    .param p1, "out"    # Ljava/io/PrintWriter;
    .param p2, "formats"    # [Ljava/lang/String;
    .param p3, "row"    # [Ljava/lang/Object;

    .prologue
    const/4 v5, 0x0

    .line 3602
    const/4 v0, 0x0

    .local v0, "j":I
    array-length v1, p3

    .local v1, "rowLength":I
    :goto_0
    if-ge v0, v1, :cond_0

    .line 3603
    aget-object v2, p2, v0

    const/4 v3, 0x1

    new-array v3, v3, [Ljava/lang/Object;

    aget-object v4, p3, v0

    invoke-virtual {v4}, Ljava/lang/Object;->toString()Ljava/lang/String;

    move-result-object v4

    aput-object v4, v3, v5

    invoke-static {v2, v3}, Ljava/lang/String;->format(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;

    move-result-object v2

    new-array v3, v5, [Ljava/lang/Object;

    invoke-virtual {p1, v2, v3}, Ljava/io/PrintWriter;->printf(Ljava/lang/String;[Ljava/lang/Object;)Ljava/io/PrintWriter;

    .line 3604
    const-string v2, "  "

    invoke-virtual {p1, v2}, Ljava/io/PrintWriter;->print(Ljava/lang/String;)V

    .line 3602
    add-int/lit8 v0, v0, 0x1

    goto :goto_0

    .line 3606
    :cond_0
    invoke-virtual {p1}, Ljava/io/PrintWriter;->println()V

    .line 3607
    return-void
.end method

# virtual methods
.method public getNumRows()I
    .locals 1

    .prologue
    .line 3610
    iget-object v0, p0, Lcom/android/server/content/SyncManager$PrintTable;->mTable:Ljava/util/ArrayList;

    invoke-virtual {v0}, Ljava/util/ArrayList;->size()I

    move-result v0

    return v0
.end method

.method varargs set(II[Ljava/lang/Object;)V
    .locals 6
    .param p1, "row"    # I
    .param p2, "col"    # I
    .param p3, "values"    # [Ljava/lang/Object;

    .prologue
    .line 3560
    array-length v3, p3

    add-int/2addr v3, p2

    iget v4, p0, Lcom/android/server/content/SyncManager$PrintTable;->mCols:I

    if-le v3, v4, :cond_0

    .line 3561
    new-instance v3, Ljava/lang/IndexOutOfBoundsException;

    new-instance v4, Ljava/lang/StringBuilder;

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

    const-string v5, "Table only has "

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    iget v5, p0, Lcom/android/server/content/SyncManager$PrintTable;->mCols:I

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v4

    const-string v5, " columns. can\'t set "

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    array-length v5, p3

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v4

    const-string v5, " at column "

    invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4, p2}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v4

    invoke-virtual {v4}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v4

    invoke-direct {v3, v4}, Ljava/lang/IndexOutOfBoundsException;-><init>(Ljava/lang/String;)V

    throw v3

    .line 3564
    :cond_0
    iget-object v3, p0, Lcom/android/server/content/SyncManager$PrintTable;->mTable:Ljava/util/ArrayList;

    invoke-virtual {v3}, Ljava/util/ArrayList;->size()I

    move-result v0

    .local v0, "i":I
    :goto_0
    if-gt v0, p1, :cond_2

    .line 3565
    iget v3, p0, Lcom/android/server/content/SyncManager$PrintTable;->mCols:I

    new-array v2, v3, [Ljava/lang/Object;

    .line 3566
    .local v2, "list":[Ljava/lang/Object;
    iget-object v3, p0, Lcom/android/server/content/SyncManager$PrintTable;->mTable:Ljava/util/ArrayList;

    invoke-virtual {v3, v2}, Ljava/util/ArrayList;->add(Ljava/lang/Object;)Z

    .line 3567
    const/4 v1, 0x0

    .local v1, "j":I
    :goto_1
    iget v3, p0, Lcom/android/server/content/SyncManager$PrintTable;->mCols:I

    if-ge v1, v3, :cond_1

    .line 3568
    const-string v3, ""

    aput-object v3, v2, v1

    .line 3567
    add-int/lit8 v1, v1, 0x1

    goto :goto_1

    .line 3564
    :cond_1
    add-int/lit8 v0, v0, 0x1

    goto :goto_0

    .line 3571
    .end local v1    # "j":I
    .end local v2    # "list":[Ljava/lang/Object;
    :cond_2
    const/4 v3, 0x0

    iget-object v4, p0, Lcom/android/server/content/SyncManager$PrintTable;->mTable:Ljava/util/ArrayList;

    invoke-virtual {v4, p1}, Ljava/util/ArrayList;->get(I)Ljava/lang/Object;

    move-result-object v4

    array-length v5, p3

    invoke-static {p3, v3, v4, p2, v5}, Ljava/lang/System;->arraycopy(Ljava/lang/Object;ILjava/lang/Object;II)V

    .line 3572
    return-void
.end method

.method writeTo(Ljava/io/PrintWriter;)V
    .locals 13
    .param p1, "out"    # Ljava/io/PrintWriter;

    .prologue
    const/4 v12, 0x0

    .line 3575
    iget v9, p0, Lcom/android/server/content/SyncManager$PrintTable;->mCols:I

    new-array v1, v9, [Ljava/lang/String;

    .line 3576
    .local v1, "formats":[Ljava/lang/String;
    const/4 v8, 0x0

    .line 3577
    .local v8, "totalLength":I
    const/4 v0, 0x0

    .local v0, "col":I
    :goto_0
    iget v9, p0, Lcom/android/server/content/SyncManager$PrintTable;->mCols:I

    if-ge v0, v9, :cond_2

    .line 3578
    const/4 v6, 0x0

    .line 3579
    .local v6, "maxLength":I
    iget-object v9, p0, Lcom/android/server/content/SyncManager$PrintTable;->mTable:Ljava/util/ArrayList;

    invoke-virtual {v9}, Ljava/util/ArrayList;->iterator()Ljava/util/Iterator;

    move-result-object v3

    .local v3, "i$":Ljava/util/Iterator;
    :cond_0
    :goto_1
    invoke-interface {v3}, Ljava/util/Iterator;->hasNext()Z

    move-result v9

    if-eqz v9, :cond_1

    invoke-interface {v3}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v7

    check-cast v7, [Ljava/lang/Object;

    .line 3580
    .local v7, "row":[Ljava/lang/Object;
    aget-object v9, v7, v0

    invoke-virtual {v9}, Ljava/lang/Object;->toString()Ljava/lang/String;

    move-result-object v9

    invoke-virtual {v9}, Ljava/lang/String;->length()I

    move-result v4

    .line 3581
    .local v4, "length":I
    if-le v4, v6, :cond_0

    .line 3582
    move v6, v4

    goto :goto_1

    .line 3585
    .end local v4    # "length":I
    .end local v7    # "row":[Ljava/lang/Object;
    :cond_1
    add-int/2addr v8, v6

    .line 3586
    const-string v9, "%%-%ds"

    const/4 v10, 0x1

    new-array v10, v10, [Ljava/lang/Object;

    invoke-static {v6}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;

    move-result-object v11

    aput-object v11, v10, v12

    invoke-static {v9, v10}, Ljava/lang/String;->format(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;

    move-result-object v9

    aput-object v9, v1, v0

    .line 3577
    add-int/lit8 v0, v0, 0x1

    goto :goto_0

    .line 3588
    .end local v3    # "i$":Ljava/util/Iterator;
    .end local v6    # "maxLength":I
    :cond_2
    iget v9, p0, Lcom/android/server/content/SyncManager$PrintTable;->mCols:I

    add-int/lit8 v9, v9, -0x1

    const-string v10, "%s"

    aput-object v10, v1, v9

    .line 3589
    iget-object v9, p0, Lcom/android/server/content/SyncManager$PrintTable;->mTable:Ljava/util/ArrayList;

    invoke-virtual {v9, v12}, Ljava/util/ArrayList;->get(I)Ljava/lang/Object;

    move-result-object v9

    check-cast v9, [Ljava/lang/Object;

    invoke-direct {p0, p1, v1, v9}, Lcom/android/server/content/SyncManager$PrintTable;->printRow(Ljava/io/PrintWriter;[Ljava/lang/String;[Ljava/lang/Object;)V

    .line 3590
    iget v9, p0, Lcom/android/server/content/SyncManager$PrintTable;->mCols:I

    add-int/lit8 v9, v9, -0x1

    mul-int/lit8 v9, v9, 0x2

    add-int/2addr v8, v9

    .line 3591
    const/4 v2, 0x0

    .local v2, "i":I
    :goto_2
    if-ge v2, v8, :cond_3

    .line 3592
    const-string v9, "-"

    invoke-virtual {p1, v9}, Ljava/io/PrintWriter;->print(Ljava/lang/String;)V

    .line 3591
    add-int/lit8 v2, v2, 0x1

    goto :goto_2

    .line 3594
    :cond_3
    invoke-virtual {p1}, Ljava/io/PrintWriter;->println()V

    .line 3595
    const/4 v2, 0x1

    iget-object v9, p0, Lcom/android/server/content/SyncManager$PrintTable;->mTable:Ljava/util/ArrayList;

    invoke-virtual {v9}, Ljava/util/ArrayList;->size()I

    move-result v5

    .local v5, "mTableSize":I
    :goto_3
    if-ge v2, v5, :cond_4

    .line 3596
    iget-object v9, p0, Lcom/android/server/content/SyncManager$PrintTable;->mTable:Ljava/util/ArrayList;

    invoke-virtual {v9, v2}, Ljava/util/ArrayList;->get(I)Ljava/lang/Object;

    move-result-object v7

    check-cast v7, [Ljava/lang/Object;

    .line 3597
    .restart local v7    # "row":[Ljava/lang/Object;
    invoke-direct {p0, p1, v1, v7}, Lcom/android/server/content/SyncManager$PrintTable;->printRow(Ljava/io/PrintWriter;[Ljava/lang/String;[Ljava/lang/Object;)V

    .line 3595
    add-int/lit8 v2, v2, 0x1

    goto :goto_3

    .line 3599
    .end local v7    # "row":[Ljava/lang/Object;
    :cond_4
    return-void
.end method


text:
'use strict'

const EventManager = require('../eventManager')
const helper = require('../helpers/traceHelper')

/**
  * allow to manage breakpoint
  *
  * Trigger events: breakpointHit, breakpointAdded, breakpointRemoved
  */
class BreakpointManager {
  /**
    * constructor
    *
    * @param {Object} _debugger - type of EthDebugger
    * @return {Function} _locationToRowConverter - function implemented by editor which return a column/line position for a char source location
    */
  constructor (_debugger, _locationToRowConverter, _jumpToCallback) {
    this.event = new EventManager()
    this.debugger = _debugger
    this.breakpoints = {}
    this.locationToRowConverter = _locationToRowConverter
    this.previousLine
    this.jumpToCallback = _jumpToCallback || (() => {})
  }

  /**
    * start looking for the next breakpoint
    * @param {Bool} defaultToLimit - if true jump to the end of the trace if no more breakpoint found
    *
    */
  async jumpNextBreakpoint (fromStep, defaultToLimit) {
    this.jump(fromStep || 0, 1, defaultToLimit)
  }

  /**
    * start looking for the previous breakpoint
    * @param {Bool} defaultToLimit - if true jump to the start of the trace if no more breakpoint found
    *
    */
  async jumpPreviousBreakpoint (fromStep, defaultToLimit) {
    this.jump(fromStep || 0, -1, defaultToLimit)
  }

   /**
    * start looking for the previous or next breakpoint
    * @param {Int} direction - 1 or -1 direction of the search
    * @param {Bool} defaultToLimit - if true jump to the limit (end if direction is 1, beginning if direction is -1) of the trace if no more breakpoint found
    *
    */
  async jump (fromStep, direction, defaultToLimit) {
    if (!this.locationToRowConverter) {
      console.log('row converter not provided')
      return
    }

    function depthChange (step, trace) {
      return trace[step].depth !== trace[step - 1].depth
    }

    function hitLine (currentStep, sourceLocation, previousSourceLocation, self) {
      // isJumpDestInstruction -> returning from a internal function call
      // depthChange -> returning from an external call
      // sourceLocation.start <= previousSourceLocation.start && ... -> previous src is contained in the current one
      if ((helper.isJumpDestInstruction(self.debugger.traceManager.trace[currentStep]) && previousSourceLocation.jump === 'o') ||
        depthChange(currentStep, self.debugger.traceManager.trace) ||
        (sourceLocation.start <= previousSourceLocation.start &&
        sourceLocation.start + sourceLocation.length >= previousSourceLocation.start + previousSourceLocation.length)) {
        return false
      } else {
        self.jumpToCallback(currentStep)
        self.event.trigger('breakpointHit', [sourceLocation, currentStep])
        return true
      }
    }

    let sourceLocation
    let previousSourceLocation
    let currentStep = fromStep + direction
    let lineHadBreakpoint = false
    while (currentStep > 0 && currentStep < this.debugger.traceManager.trace.length) {
      try {
        previousSourceLocation = sourceLocation
        sourceLocation = await this.debugger.callTree.extractSourceLocation(currentStep)
      } catch (e) {
        console.log('cannot jump to breakpoint ' + e)
        return
      }
      let lineColumn = await this.locationToRowConverter(sourceLocation)
      if (this.previousLine !== lineColumn.start.line) {
        if (direction === -1 && lineHadBreakpoint) { // TODO : improve this when we will build the correct structure before hand
          lineHadBreakpoint = false
          if (hitLine(currentStep + 1, previousSourceLocation, sourceLocation, this)) {
            return
          }
        }
        this.previousLine = lineColumn.start.line
        if (this.hasBreakpointAtLine(sourceLocation.file, lineColumn.start.line)) {
          lineHadBreakpoint = true
          if (direction === 1) {
            if (hitLine(currentStep, sourceLocation, previousSourceLocation, this)) {
              return
            }
          }
        }
      }
      currentStep += direction
    }
    this.event.trigger('NoBreakpointHit', [])
    if (defaultToLimit) {
      if (direction === -1) {
        this.jumpToCallback(0)
      } else if (direction === 1) {
        this.jumpToCallback(this.debugger.traceManager.trace.length - 1)
      }
    }
  }

  /**
    * check the given pair fileIndex/line against registered breakpoints
    *
    * @param {Int} fileIndex - index of the file content (from the compilation result)
    * @param {Int} line - line number where looking for breakpoint
    * @return {Bool} return true if the given @arg fileIndex @arg line refers to a breakpoint
    */
  hasBreakpointAtLine (fileIndex, line) {
    const filename = this.debugger.solidityProxy.fileNameFromIndex(fileIndex)
    if (filename && this.breakpoints[filename]) {
      const sources = this.breakpoints[filename]
      for (let k in sources) {
        const source = sources[k]
        if (line === source.row) {
          return true
        }
      }
    }
    return false
  }

  /**
    * return true if current manager has breakpoint
    *
    * @return {Bool} true if breapoint registered
    */
  hasBreakpoint () {
    for (let k in this.breakpoints) {
      if (this.breakpoints[k].length) {
        return true
      }
    }
    return false
  }

  /**
    * add a new breakpoint to the manager
    *
    * @param {Object} sourceLocation - position of the breakpoint { file: '<file index>', row: '<line number' }
    */
  add (sourceLocation) {
    if (!this.breakpoints[sourceLocation.fileName]) {
      this.breakpoints[sourceLocation.fileName] = []
    }
    this.breakpoints[sourceLocation.fileName].push(sourceLocation)
    this.event.trigger('breakpointAdded', [sourceLocation])
  }

  /**
    * remove a breakpoint from the manager
    *
    * @param {Object} sourceLocation - position of the breakpoint { file: '<file index>', row: '<line number' }
    */
  remove (sourceLocation) {
    if (this.breakpoints[sourceLocation.fileName]) {
      var sources = this.breakpoints[sourceLocation.fileName]
      for (let k in sources) {
        const source = sources[k]
        if (sourceLocation.row === source.row) {
          sources.splice(k, 1)
          this.event.trigger('breakpointRemoved', [sourceLocation])
          break
        }
      }
    }
  }
}

module.exports = BreakpointManager

redpajama_set_name: RedPajamaGithub


text:
<resources>

    <!--
         Customize dimensions originally defined in res/values/dimens.xml (such as
         screen margins) for sw600dp devices (e.g. 7" tablets) here.

    -->
    <dimen name="slidingmenu_offset">300dp</dimen>

    <!-- KitKat Navigation Bar Margins -->
    <dimen name="kitkat_nav_bar_margin">0dp</dimen>
    <dimen name="kitkat_nav_bar_margin_large">30dp</dimen>

</resources>


text:
namespace CanvasExport
{
	// Globals
	extern ofstream outFile;
	extern bool debug;

	/// Represents the resources for a document
	class DocumentResources
	{
	private:

	public:

		DocumentResources();
		~DocumentResources();

		ImageCollection		images;
		PatternCollection	patterns;
		std::string			folderPath;					// Path to output folder

	};
}

#endif


text:
package com.google.common.collect;

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

import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.collect.Multiset.Entry;
import com.google.common.primitives.Ints;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;

import javax.annotation.Nullable;

/**
 * An immutable hash-based multiset. Does not permit null elements.
 *
 *
Its iterator orders elements according to the first appearance of the
 * element among the items passed to the factory method or builder. When the
 * multiset contains multiple instances of an element, those instances are
 * consecutive in the iteration order.
 *
 *
See the Guava User Guide article on
 * immutable collections.
 *
 * @author Jared Levy
 * @author Louis Wasserman
 * @since 2.0 (imported from Google Collections Library)
 */
@GwtCompatible(serializable = true, emulated = true)
@SuppressWarnings("serial") // we're overriding default serialization
// TODO(user): write an efficient asList() implementation
public abstract class ImmutableMultiset<E> extends ImmutableCollection<E>
    implements Multiset<E> {

  private static final ImmutableMultiset<Object> EMPTY =
      new RegularImmutableMultiset<Object>(ImmutableMap.<Object, Integer>of(), 0);

  /**
   * Returns the empty immutable multiset.
   */
  @SuppressWarnings("unchecked") // all supported methods are covariant
  public static <E> ImmutableMultiset<E> of() {
    return (ImmutableMultiset<E>) EMPTY;
  }

  /**
   * Returns an immutable multiset containing a single element.
   *
   * @throws NullPointerException if {@code element} is null
   * @since 6.0 (source-compatible since 2.0)
   */
  @SuppressWarnings("unchecked") // generic array created but never written
  public static <E> ImmutableMultiset<E> of(E element) {
    return copyOfInternal(element);
  }

  /**
   * Returns an immutable multiset containing the given elements, in order.
   *
   * @throws NullPointerException if any element is null
   * @since 6.0 (source-compatible since 2.0)
   */
  @SuppressWarnings("unchecked") //
  public static <E> ImmutableMultiset<E> of(E e1, E e2) {
    return copyOfInternal(e1, e2);
  }

  /**
   * Returns an immutable multiset containing the given elements, in order.
   *
   * @throws NullPointerException if any element is null
   * @since 6.0 (source-compatible since 2.0)
   */
  @SuppressWarnings("unchecked") //
  public static <E> ImmutableMultiset<E> of(E e1, E e2, E e3) {
    return copyOfInternal(e1, e2, e3);
  }

  /**
   * Returns an immutable multiset containing the given elements, in order.
   *
   * @throws NullPointerException if any element is null
   * @since 6.0 (source-compatible since 2.0)
   */
  @SuppressWarnings("unchecked") //
  public static <E> ImmutableMultiset<E> of(E e1, E e2, E e3, E e4) {
    return copyOfInternal(e1, e2, e3, e4);
  }

  /**
   * Returns an immutable multiset containing the given elements, in order.
   *
   * @throws NullPointerException if any element is null
   * @since 6.0 (source-compatible since 2.0)
   */
  @SuppressWarnings("unchecked") //
  public static <E> ImmutableMultiset<E> of(E e1, E e2, E e3, E e4, E e5) {
    return copyOfInternal(e1, e2, e3, e4, e5);
  }

  /**
   * Returns an immutable multiset containing the given elements, in order.
   *
   * @throws NullPointerException if any element is null
   * @since 6.0 (source-compatible since 2.0)
   */
  @SuppressWarnings("unchecked") //
  public static <E> ImmutableMultiset<E> of(
      E e1, E e2, E e3, E e4, E e5, E e6, E... others) {
    return new Builder<E>()
        .add(e1)
        .add(e2)
        .add(e3)
        .add(e4)
        .add(e5)
        .add(e6)
        .add(others)
        .build();
  }

  /**
   * Returns an immutable multiset containing the given elements.
   *
   *
The multiset is ordered by the first occurrence of each element. For
   * example, {@code ImmutableMultiset.copyOf([2, 3, 1, 3])} yields a multiset
   * with elements in the order {@code 2, 3, 3, 1}.
   *
   * @throws NullPointerException if any of {@code elements} is null
   * @since 6.0
   */
  public static <E> ImmutableMultiset<E> copyOf(E[] elements) {
    return copyOf(Arrays.asList(elements));
  }

  /**
   * Returns an immutable multiset containing the given elements.
   *
   *
The multiset is ordered by the first occurrence of each element. For
   * example, {@code ImmutableMultiset.copyOf(Arrays.asList(2, 3, 1, 3))} yields
   * a multiset with elements in the order {@code 2, 3, 3, 1}.
   *
   *
Despite the method name, this method attempts to avoid actually copying
   * the data when it is safe to do so. The exact circumstances under which a
   * copy will or will not be performed are undocumented and subject to change.
   *
   *
Note: Despite what the method name suggests, if {@code elements}
   * is an {@code ImmutableMultiset}, no copy will actually be performed, and
   * the given multiset itself will be returned.
   *
   * @throws NullPointerException if any of {@code elements} is null
   */
  public static <E> ImmutableMultiset<E> copyOf(
      Iterable<? extends E> elements) {
    if (elements instanceof ImmutableMultiset) {
      @SuppressWarnings("unchecked") // all supported methods are covariant
      ImmutableMultiset<E> result = (ImmutableMultiset<E>) elements;
      if (!result.isPartialView()) {
        return result;
      }
    }

    Multiset<? extends E> multiset = (elements instanceof Multiset)
        ? Multisets.cast(elements)
        : LinkedHashMultiset.create(elements);

    return copyOfInternal(multiset);
  }

  private static <E> ImmutableMultiset<E> copyOfInternal(E... elements) {
    return copyOf(Arrays.asList(elements));
  }

  private static <E> ImmutableMultiset<E> copyOfInternal(
      Multiset<? extends E> multiset) {
    return copyFromEntries(multiset.entrySet());
  }

  static <E> ImmutableMultiset<E> copyFromEntries(
      Collection<? extends Entry<? extends E>> entries) {
    long size = 0;
    ImmutableMap.Builder<E, Integer> builder =
        new ImmutableMap.Builder<E, Integer>(entries.size());
    for (Entry<? extends E> entry : entries) {
      int count = entry.getCount();
      if (count > 0) {
        // Since ImmutableMap.Builder throws an NPE if an element is null, no
        // other null checks are needed.
        builder.put(entry.getElement(), count);
        size += count;
      }
    }

    if (size == 0) {
      return of();
    }
    return new RegularImmutableMultiset<E>(
        builder.build(), Ints.saturatedCast(size));
  }

  /**
   * Returns an immutable multiset containing the given elements.
   *
   *
The multiset is ordered by the first occurrence of each element. For
   * example,
   * {@code ImmutableMultiset.copyOf(Arrays.asList(2, 3, 1, 3).iterator())}
   * yields a multiset with elements in the order {@code 2, 3, 3, 1}.
   *
   * @throws NullPointerException if any of {@code elements} is null
   */
  public static <E> ImmutableMultiset<E> copyOf(
      Iterator<? extends E> elements) {
    Multiset<E> multiset = LinkedHashMultiset.create();
    Iterators.addAll(multiset, elements);
    return copyOfInternal(multiset);
  }

  ImmutableMultiset() {}

  @Override public UnmodifiableIterator<E> iterator() {
    final Iterator<Entry<E>> entryIterator = entrySet().iterator();
    return new UnmodifiableIterator<E>() {
      int remaining;
      E element;

      @Override
      public boolean hasNext() {
        return (remaining > 0) || entryIterator.hasNext();
      }

      @Override
      public E next() {
        if (remaining <= 0) {
          Entry<E> entry = entryIterator.next();
          element = entry.getElement();
          remaining = entry.getCount();
        }
        remaining--;
        return element;
      }
    };
  }

  @Override
  public boolean contains(@Nullable Object object) {
    return count(object) > 0;
  }

  @Override
  public boolean containsAll(Collection<?> targets) {
    return elementSet().containsAll(targets);
  }

  /**
   * Guaranteed to throw an exception and leave the collection unmodified.
   *
   * @throws UnsupportedOperationException always
   * @deprecated Unsupported operation.
   */
  @Deprecated
  @Override
  public final int add(E element, int occurrences) {
    throw new UnsupportedOperationException();
  }

  /**
   * Guaranteed to throw an exception and leave the collection unmodified.
   *
   * @throws UnsupportedOperationException always
   * @deprecated Unsupported operation.
   */
  @Deprecated
  @Override
  public final int remove(Object element, int occurrences) {
    throw new UnsupportedOperationException();
  }

  /**
   * Guaranteed to throw an exception and leave the collection unmodified.
   *
   * @throws UnsupportedOperationException always
   * @deprecated Unsupported operation.
   */
  @Deprecated
  @Override
  public final int setCount(E element, int count) {
    throw new UnsupportedOperationException();
  }

  /**
   * Guaranteed to throw an exception and leave the collection unmodified.
   *
   * @throws UnsupportedOperationException always
   * @deprecated Unsupported operation.
   */
  @Deprecated
  @Override
  public final boolean setCount(E element, int oldCount, int newCount) {
    throw new UnsupportedOperationException();
  }

  @GwtIncompatible("not present in emulated superclass")
  @Override
  int copyIntoArray(Object[] dst, int offset) {
    for (Multiset.Entry<E> entry : entrySet()) {
      Arrays.fill(dst, offset, offset + entry.getCount(), entry.getElement());
      offset += entry.getCount();
    }
    return offset;
  }

  @Override public boolean equals(@Nullable Object object) {
    return Multisets.equalsImpl(this, object);
  }

  @Override public int hashCode() {
    return Sets.hashCodeImpl(entrySet());
  }

  @Override public String toString() {
    return entrySet().toString();
  }

  private transient ImmutableSet<Entry<E>> entrySet;

  @Override
  public ImmutableSet<Entry<E>> entrySet() {
    ImmutableSet<Entry<E>> es = entrySet;
    return (es == null) ? (entrySet = createEntrySet()) : es;
  }

  private final ImmutableSet<Entry<E>> createEntrySet() {
    return isEmpty() ? ImmutableSet.<Entry<E>>of() : new EntrySet();
  }

  abstract Entry<E> getEntry(int index);

  private final class EntrySet extends ImmutableSet<Entry<E>> {
    @Override
    boolean isPartialView() {
      return ImmutableMultiset.this.isPartialView();
    }

    @Override
    public UnmodifiableIterator<Entry<E>> iterator() {
      return asList().iterator();
    }

    @Override
    ImmutableList<Entry<E>> createAsList() {
      return new ImmutableAsList<Entry<E>>() {
        @Override
        public Entry<E> get(int index) {
          return getEntry(index);
        }

        @Override
        ImmutableCollection<Entry<E>> delegateCollection() {
          return EntrySet.this;
        }
      };
    }

    @Override
    public int size() {
      return elementSet().size();
    }

    @Override
    public boolean contains(Object o) {
      if (o instanceof Entry) {
        Entry<?> entry = (Entry<?>) o;
        if (entry.getCount() <= 0) {
          return false;
        }
        int count = count(entry.getElement());
        return count == entry.getCount();
      }
      return false;
    }

    @Override
    public int hashCode() {
      return ImmutableMultiset.this.hashCode();
    }

    // We can't label this with @Override, because it doesn't override anything
    // in the GWT emulated version.
    // TODO(cpovirk): try making all copies of this method @GwtIncompatible instead
    Object writeReplace() {
      return new EntrySetSerializedForm<E>(ImmutableMultiset.this);
    }

    private static final long serialVersionUID = 0;
  }

  static class EntrySetSerializedForm<E> implements Serializable {
    final ImmutableMultiset<E> multiset;

    EntrySetSerializedForm(ImmutableMultiset<E> multiset) {
      this.multiset = multiset;
    }

    Object readResolve() {
      return multiset.entrySet();
    }
  }

  private static class SerializedForm implements Serializable {
    final Object[] elements;
    final int[] counts;

    SerializedForm(Multiset<?> multiset) {
      int distinct = multiset.entrySet().size();
      elements = new Object[distinct];
      counts = new int[distinct];
      int i = 0;
      for (Entry<?> entry : multiset.entrySet()) {
        elements[i] = entry.getElement();
        counts[i] = entry.getCount();
        i++;
      }
    }

    Object readResolve() {
      LinkedHashMultiset<Object> multiset =
          LinkedHashMultiset.create(elements.length);
      for (int i = 0; i < elements.length; i++) {
        multiset.add(elements[i], counts[i]);
      }
      return ImmutableMultiset.copyOf(multiset);
    }

    private static final long serialVersionUID = 0;
  }

  // We can't label this with @Override, because it doesn't override anything
  // in the GWT emulated version.
  Object writeReplace() {
    return new SerializedForm(this);
  }

  /**
   * Returns a new builder. The generated builder is equivalent to the builder
   * created by the {@link Builder} constructor.
   */
  public static <E> Builder<E> builder() {
    return new Builder<E>();
  }

  /**
   * A builder for creating immutable multiset instances, especially {@code
   * public static final} multisets ("constant multisets"). Example:
   *
 {@code
   *
   *   public static final ImmutableMultiset<Bean> BEANS =
   *       new ImmutableMultiset.Builder<Bean>()
   *           .addCopies(Bean.COCOA, 4)
   *           .addCopies(Bean.GARDEN, 6)
   *           .addCopies(Bean.RED, 8)
   *           .addCopies(Bean.BLACK_EYED, 10)
   *           .build();}

   *
   *
Builder instances can be reused; it is safe to call {@link #build} multiple
   * times to build multiple multisets in series.
   *
   * @since 2.0 (imported from Google Collections Library)
   */
  public static class Builder<E> extends ImmutableCollection.Builder<E> {
    final Multiset<E> contents;

    /**
     * Creates a new builder. The returned builder is equivalent to the builder
     * generated by {@link ImmutableMultiset#builder}.
     */
    public Builder() {
      this(LinkedHashMultiset.<E>create());
    }

    Builder(Multiset<E> contents) {
      this.contents = contents;
    }

    /**
     * Adds {@code element} to the {@code ImmutableMultiset}.
     *
     * @param element the element to add
     * @return this {@code Builder} object
     * @throws NullPointerException if {@code element} is null
     */
    @Override public Builder<E> add(E element) {
      contents.add(checkNotNull(element));
      return this;
    }

    /**
     * Adds a number of occurrences of an element to this {@code
     * ImmutableMultiset}.
     *
     * @param element the element to add
     * @param occurrences the number of occurrences of the element to add. May
     *     be zero, in which case no change will be made.
     * @return this {@code Builder} object
     * @throws NullPointerException if {@code element} is null
     * @throws IllegalArgumentException if {@code occurrences} is negative, or
     *     if this operation would result in more than {@link Integer#MAX_VALUE}
     *     occurrences of the element
     */
    public Builder<E> addCopies(E element, int occurrences) {
      contents.add(checkNotNull(element), occurrences);
      return this;
    }

    /**
     * Adds or removes the necessary occurrences of an element such that the
     * element attains the desired count.
     *
     * @param element the element to add or remove occurrences of
     * @param count the desired count of the element in this multiset
     * @return this {@code Builder} object
     * @throws NullPointerException if {@code element} is null
     * @throws IllegalArgumentException if {@code count} is negative
     */
    public Builder<E> setCount(E element, int count) {
      contents.setCount(checkNotNull(element), count);
      return this;
    }

    /**
     * Adds each element of {@code elements} to the {@code ImmutableMultiset}.
     *
     * @param elements the elements to add
     * @return this {@code Builder} object
     * @throws NullPointerException if {@code elements} is null or contains a
     *     null element
     */
    @Override public Builder<E> add(E... elements) {
      super.add(elements);
      return this;
    }

    /**
     * Adds each element of {@code elements} to the {@code ImmutableMultiset}.
     *
     * @param elements the {@code Iterable} to add to the {@code
     *     ImmutableMultiset}
     * @return this {@code Builder} object
     * @throws NullPointerException if {@code elements} is null or contains a
     *     null element
     */
    @Override public Builder<E> addAll(Iterable<? extends E> elements) {
      if (elements instanceof Multiset) {
        Multiset<? extends E> multiset = Multisets.cast(elements);
        for (Entry<? extends E> entry : multiset.entrySet()) {
          addCopies(entry.getElement(), entry.getCount());
        }
      } else {
        super.addAll(elements);
      }
      return this;
    }

    /**
     * Adds each element of {@code elements} to the {@code ImmutableMultiset}.
     *
     * @param elements the elements to add to the {@code ImmutableMultiset}
     * @return this {@code Builder} object
     * @throws NullPointerException if {@code elements} is null or contains a
     *     null element
     */
    @Override public Builder<E> addAll(Iterator<? extends E> elements) {
      super.addAll(elements);
      return this;
    }

    /**
     * Returns a newly-created {@code ImmutableMultiset} based on the contents
     * of the {@code Builder}.
     */
    @Override public ImmutableMultiset<E> build() {
      return copyOf(contents);
    }
  }
}


text:
<!doctype html>

    <meta charset="utf-8">

    <title>Full Stack Robotics - FullStack 2014</title>

    <meta name="description" content="A framework for easily creating beautiful presentations using HTML">
    <meta name="author" content="Hakim El Hattab">

    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

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

    <link rel="stylesheet" href="css/reveal.min.css">
    <link rel="stylesheet" href="css/theme/default.css" id="theme">

    <link rel="stylesheet" href="lib/css/tomorrow.css">

    <link rel="stylesheet" href="css/hybrid.css">

Full Stack Robotics

hybridgroup.com

Good Afternoon

This is #fullstackcon

I am @deadprogram

Ringleader

@hybrid_group

The other guy is @adzankich

Serious Programming Guy

@hybrid_group

hybridgroup.com

kidsruby.com

Full Stack Robotics

Starring

What Is 'Full Stack Robotics'?

Arduino

var Cylon = require('cylon');

Cylon.robot({
  connection: {
    name: 'arduino',
    adaptor: 'firmata',
    port: '/dev/ttyACM0'
  },

  device: {
    name: 'led',
    driver: 'led',
    pin: 13
  },

  work: function(my) {
    every((1).second(), function(){ my.led.toggle() });
  }
}).start();

Spark

var Cylon = require('cylon');

Cylon.robot({
  connection: {
    name: 'spark',
    adaptor: 'spark',
    accessToken: 'XXXYYYZZZ',
    deviceId: '1234XXX7890'
  },

  device: {
    name: 'led',
    driver: 'led',
    pin: 'D7'
  },

  work: function(my) {
    every((1).second(), my.led.toggle);
  }
}).start();

Intel Edison

var Cylon = require('cylon');

Cylon.robot({
  connection: {
    name: 'edison',
    adaptor: 'intel-iot'
  },

  device: {
    name: 'led',
    driver: 'led',
    pin: 4
  },

  work: function(my) {
    every((1).second(), my.led.toggle);
  }
}).start();

Choose Your Own Hardware Adventure!

To win a Sphero, tweet

@gosphero and @cylonjs

To win a Spark Core, tweet

@spark_io and @cylonjs

It All Starts With A Customer...

Brewforce

var Cylon = require('cylon');

Cylon.config({
  api: {
    host: '0.0.0.0', port: '8080', ssl:  false
  }
})

Cylon.api();

Cylon.robot({
  name: 'brewforce',
  connections: [
    { name: 'pebble', adaptor: 'pebble' },
    { name: 'edison', adaptor: 'intel-iot' },
    {
      name: 'sfcon',
      adaptor: 'force',
      sfuser: process.env.SF_USERNAME,
      sfpass: process.env.SF_SECURITY_TOKEN
    }
  ],
  devices: [
    { name: 'pump', driver: 'direct-pin', pin: 6, connection: 'edison' },
    { name: 'tap', driver: 'button', pin: 4, connection: 'edison' },
    { name: 'fault', driver: 'button', pin: 2, connection: 'edison' },
    { name: 'pebble', driver: 'pebble', connection: 'pebble' },
    { name: 'salesforce', driver: 'force', connection: 'sfcon' }
  ],
  work: function() {
    this.tap.on('press', function() {
      if (!this.pumping) {
        this.activatePump();
      }
    }.bind(this));

    this.fault.on('press', function() {
      this.reportFault();
    }.bind(this));
  },

  served: 0,
  pumping: false,
  dispenserId: 5,
  droneId: 4,

  activatePump: function() {
    this.pumping = true;
    this.pump.digitalWrite(1);
    this.served += 1;
    var date = new Date(),
        dateStr = date.toISOString(),
        toSend = {
          dispenserId: this.dispenserId,
          drinkId: this.served,
          event: 'online',
          eventTimestamp: dateStr,
          details: 'dispenser'
        };

    this.salesforce.post('/Drink/', toSend, function(err, data) {
      console.log('Err:', err);
      console.log('Data:', data);
    });

    setTimeout(function() {
      this.pump.digitalWrite(0);
      this.pumping = false;
    }.bind(this), 2000);

    console.log("Total customers served: " + toSend.drinkId);
    this.pebble.send_notification("Total customers served: " + toSend.drinkId);
  },

  reportFault: function() {
    console.log("Pushing fault to SF.....");
    var date = new Date(),
        dateStr = date.toISOString(),
        toSend = { dispenserId: this.dispenserId,
                   drinkId: this.served,
                   event: 'error',
                   eventTimestamp: dateStr,
                   details: 'dispenser'
        };

    this.salesforce.post('/Drink/', toSend, function(err, data) {
      console.log('Err:', err);
      console.log('Data:', data);
    });

    this.pebble.send_notification("there was an error");
  },

  airDrop: function() {
    var date = new Date();
    var dateStr = date.toISOString();
    var toSend = {
      dispenserId: this.droneId,
      drinkId: this.served,
      event: 'en route',
      eventTimestamp: dateStr,
      details: 'drone'
    };

    this.salesforce.post('/Drink/', toSend, function(err, data) {
      console.log('airDrop Err:', err);
      console.log('airDrop Data:', data);
    });

    this.pebble.send_notification("delivery sent by drone");
  },

  delivered: function() {
    var date = new Date();
    var dateStr = date.toISOString();
    var toSend = {
      dispenserId: this.droneId,
      drinkId: this.served,
      event: 'delivery complete',
      eventTimestamp: dateStr,
      details: 'drone'
    };

    this.salesforce.post('/Drink/', toSend, function(err, data) {
      console.log('delivered Err:', err);
      console.log('delivered Data:', data);
    });

    this.pebble.send_notification("delivery sent by drone");
  },

  commands: function() {
    return {
      air_drop: this.airDrop,
      delivered: this.delivered,
      report_fault: this.reportFault,
      activate_pump: this.activatePump
    };
  }
}).start();

Connected Devices

Drink Dispenser

Intel Edison + Salesforce

  activatePump: function() {
    this.pumping = true;
    this.pump.digitalWrite(1);
    this.served += 1;
    var date = new Date(),
        dateStr = date.toISOString(),
        toSend = {
          dispenserId: this.dispenserId,
          drinkId: this.served,
          event: 'online',
          eventTimestamp: dateStr,
          details: 'dispenser'
        };

    this.salesforce.post('/Drink/', toSend, function(err, data) {
      console.log('Err:', err);
      console.log('Data:', data);
    });

    setTimeout(function() {
      this.pump.digitalWrite(0);
      this.pumping = false;
    }.bind(this), 2000);

    console.log("Total customers served: " + toSend.drinkId);
    this.pebble.send_notification("Total customers served: " + toSend.drinkId);
  },

Wearables

Wearable Demo

Intel Edison + Pebble + Salesforce

  reportFault: function() {
    console.log("Pushing fault to SF.....");
    var date = new Date(),
        dateStr = date.toISOString(),
        toSend = { dispenserId: this.dispenserId,
                   drinkId: this.served,
                   event: 'error',
                   eventTimestamp: dateStr,
                   details: 'dispenser'
        };

    this.salesforce.post('/Drink/', toSend, function(err, data) {
      console.log('Err:', err);
      console.log('Data:', data);
    });

    this.pebble.send_notification("there was an error");
  },

Mobile

Mobile Demo

Intel Edison + Pebble + Commander + Salesforce

Cylon.config({
  api: {
    host: '0.0.0.0', port: '8080', ssl:  false
  }
})

Cylon.api();

  commands: function() {
    return {
      air_drop: this.airDrop,
      delivered: this.delivered,
      report_fault: this.reportFault,
      activate_pump: this.activatePump
    };
  }

Robots

Drone Demo

Intel Edison + Salesforce + ARDrone + Commander + Pebble (Featuring Cylon.js)

DigiSpark (Featuring Gobot)

  airDrop: function() {
    var date = new Date();
    var dateStr = date.toISOString();
    var toSend = {
      dispenserId: this.droneId,
      drinkId: this.served,
      event: 'en route',
      eventTimestamp: dateStr,
      details: 'drone'
    };

    this.salesforce.post('/Drink/', toSend, function(err, data) {
      console.log('airDrop Err:', err);
      console.log('airDrop Data:', data);
    });

    this.pebble.send_notification("delivery sent by drone");
  },

var cylon = require('cylon');
var restler = require('restler');

cylon.robot({
  connections: [
    {name: 'dualshock3', adaptor: 'joystick'},
    {name: 'ardrone', adaptor: 'ardrone', port: '192.168.1.1'}
  ],
  devices: [
    {name: 'controller', driver: 'dualshock-3', connection: 'dualshock3'},
    {name: 'drone', driver: 'ardrone', connection: 'ardrone'}
  ]
})
  .on("ready", function(bot) {
    var offset = 32767.0;
    var rightStick = {
      x: 0.0,
      y: 0.0
    };
    var leftStick = {
      x: 0.0,
      y: 0.0
    };
    bot.controller.on("circle:press", function() {
      restler.get('http://192.168.1.1:3000/commands/drop_package')
        .on('complete', function(result) {
          console.log("response from drone: " + JSON.stringify(result));
        });
    });
    bot.controller.on("square:press", function() {
      bot.drone.takeoff();
    });
    bot.controller.on("triangle:press", function() {
      bot.drone.hover();
    });
    bot.controller.on("x:press", function() {
      bot.drone.land();
    });
    bot.controller.on("right_x:move", function(data) {
      rightStick.x = data;
    });
    bot.controller.on("right_y:move", function(data) {
      rightStick.y = data;
    });
    bot.controller.on("left_x:move", function(data) {
      leftStick.x = data;
    });
    bot.controller.on("left_y:move", function(data) {
      leftStick.y = data;
    });

    setInterval(function() {
      var pair = leftStick;
      if (pair.y < 5) {
        bot.drone.front(validatePitch(pair.y, offset));
      } else if (pair.y > 5) {
        bot.drone.back(validatePitch(pair.y, offset));
      }
      if (pair.x > 5) {
        bot.drone.right(validatePitch(pair.x, offset));
      } else if (pair.x < 5) {
        bot.drone.left(validatePitch(pair.x, offset));
      }
    }, 0);

    setInterval(function() {
      var pair = rightStick;
      if (pair.y < 5) {
        bot.drone.up(validatePitch(pair.y, offset));
      } else if (pair.y > 5) {
        bot.drone.down(validatePitch(pair.y, offset));
      }
      if (pair.x > 20) {
        bot.drone.clockwise(validatePitch(pair.x, offset));
      } else if (pair.x < 20) {
        bot.drone.counterClockwise(validatePitch(pair.x, offset));
      }
    }, 0);

    setInterval(function() {
      bot.drone.hover();
    }, 10);
  })
  .on('error', function(err) {
    console.log(err);
  })
  .start();

function validatePitch(data, offset) {
  var value = Math.abs(data) / offset;
  if (value >= 0.1) {
    if (value <= 1.0) {
      return Math.round(value * 100.0) / 100.0;
    } else {
      return 1.0;
    }
  } else {
    return 0.0;
  }
}

Was that fun?

Join the Robot Evolution!

cylonjs.com

@cylonjs

Thank you!

@deadprogram

@adzankich


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <artifactId>textio</artifactId>
    <version>3.8-SNAPSHOT</version>
    <name>text I/O</name>
    <description>Input and output of plain text files</description>

    <parent>
        <groupId>edu.mayo.mprc</groupId>
        <artifactId>lib</artifactId>
        <version>3.8-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <dependencies>
        <dependency>
            <groupId>edu.mayo.mprc</groupId>
            <artifactId>util</artifactId>
            <version>3.8-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <classifier>jdk15</classifier>
        </dependency>
    </dependencies>
</project>


text:
#ifndef cascades_docklayout_h
#define cascades_docklayout_h
#include "gmock/gmock.h"
#include <bb/cascades/bbcascades_global.h>
#include <bb/cascades/layouts/layout.h>
namespace bb {
    namespace cascades {
    class DockLayoutPrivate;
    class DockLayout : public Layout {
public:
        DockLayout() { }
        virtual ~DockLayout() { }
public:
        typedef DockLayout ThisClass;
        typedef Layout BaseClass;
        template <typename BuilderType, typename BuiltType>
        class TBuilder : public BaseClass::TBuilder<BuilderType, BuiltType> {
        protected:
            TBuilder(BuiltType* node) : BaseClass::TBuilder<BuilderType, BuiltType>(node) {
            }
        public:
        };
        class Builder : public TBuilder<Builder, DockLayout>
        {
        public:
            Builder() : TBuilder<Builder, DockLayout>(new DockLayout()) {
            }
        };
        static Builder create() {
            return Builder();
        }
    };
}
}
#endif


text:
title:  When Perceptions Lie to Us
date:  02/04/2022
---

#### inTro

**Read This Week's Passage: James 1:9–18**

**When Perceptions Lie to Us**

There is an interesting phenomenon in couples, in which the same pattern of slight disagreements seems to arise. The wife will be telling a story and mention that they left a restaurant at 5:00 p.m. No, the husband will argue, it was at least 5:15; she disagrees, certain that it was 5:00. To the listeners, this detail is unimportant, but it becomes vital to those telling the story because they're both certain that their perception of the situation was correct. When the stakes are higher—for example, when two people disagree on what the other said out of anger—the tension intensifies. If someone can't trust their own perception of what happened, whose can they trust?

Humanity defaults to trusting self from an early age. Born with a natural inclination to selfishness and self-reliance, we can stop this trend only by Divine intervention and dependence. Despite our noble intentions for honesty, integrity, and clear vision, it's easy for us to be confused by the false narratives shared by media, peers, and our selfish nature. It's hard to distrust our own (learned or natural) perception of reality and trust God's instead. The irony is that humanity's natural perception of reality is wrong, in more ways than one. While we are learning self-distrust, it is essential to learn God-trust. Only then can we see clearly.

#### inScribe

Write out James 1:9–18 from the translation of your choice. If you're pressed for time, write out James 1:12–16. You may also rewrite the passage in your own words, or outline or mind-map it.

` `


text:
import os
import sys
import random
from copy import deepcopy
import multiprocessing
import jsonpickle

import numpy
import Image, ImageDraw

#-------------------------------------------------------------------------------------------------
#Knobs and Dials
#-------------------------------------------------------------------------------------------------
POP_PER_GENERATION = 50
MUTATION_CHANCE = 0.01
ADD_GENE_CHANCE = 0.3
REM_GENE_CHANCE = 0.2
INITIAL_GENES = 50

#How often to output images and save files
GENERATIONS_PER_IMAGE = 100
GENERATIONS_PER_SAVE = 100

try:
    globalTarget = Image.open("reference.png")
except IOError:
    print "File reference.png must be located in the same directory as poly_artist.py."
    exit()

#-------------------------------------------------------------------------------------------------
#Helper Classes
#-------------------------------------------------------------------------------------------------
class Point:
    """
    A 2D point. You can add them together if you want.
    """
    def __init__(self,x,y):
        self.x = x
        self.y = y

    def __add__(self,o):
        return Point(self.x+o.x,self.y+o.y)

class Color:
    """
    A color. You can shift it by a given value.
    """
    def __init__(self,r,g,b):
        self.r = r
        self.g = g
        self.b = b

    def shift(self,r,g,b):
        self.r = max(0,min(255,self.r+r))
        self.g = max(0,min(255,self.g+g))
        self.b = max(0,min(255,self.b+b))

    def __str__(self):
        return "({},{},{})".format(self.r,self.g,self.b)

#-------------------------------------------------------------------------------------------------
#Genetic Classes
#-------------------------------------------------------------------------------------------------
class Gene:
    """
    A gene is the object that can be mutated. Genetic algorithms work by randomly mutating genes
    and then using some function to determine how "ideal" the resulting organism is.

    This one is basically a circle, with a size, color, and position on the canvas.
    """
    def __init__(self,size):
        self.size = size #The canvas size so we know the maximum position value

        self.diameter = random.randint(5,15)
        self.pos = Point(random.randint(0,size[0]),random.randint(0,size[1]))
        self.color = Color(random.randint(0,255),random.randint(0,255),random.randint(0,255))
        self.params = ["diameter","pos","color"]

    def mutate(self):
        #Decide how big the mutation will be
        mutation_size = max(1,int(round(random.gauss(15,4))))/100

        #Decide what will be mutated
        mutation_type = random.choice(self.params)

        #Mutate the thing
        if mutation_type == "diameter":
            self.diameter = max(1,random.randint(int(self.diameter*(1-mutation_size)),int(self.diameter*(1+mutation_size))))

        elif mutation_type == "pos":
            x = max(0,random.randint(int(self.pos.x*(1-mutation_size)),int(self.pos.x*(1+mutation_size))))
            y = max(0,random.randint(int(self.pos.y*(1-mutation_size)),int(self.pos.y*(1+mutation_size))))
            self.pos = Point(min(x,self.size[0]),min(y,self.size[1]))

        elif mutation_type == "color":
            r = min(max(0,random.randint(int(self.color.r*(1-mutation_size)),int(self.color.r*(1+mutation_size)))),255)
            g = min(max(0,random.randint(int(self.color.g*(1-mutation_size)),int(self.color.g*(1+mutation_size)))),255)
            b = min(max(0,random.randint(int(self.color.b*(1-mutation_size)),int(self.color.b*(1+mutation_size)))),255)
            self.color = Color(r,g,b)

    def getSave(self):
        """
        Allows us to save an individual gene in case the program is stopped.
        """
        so = {}
        so["size"] = self.size
        so["diameter"] = self.diameter
        so["pos"] = (self.pos.x,self.pos.y)
        so["color"] = (self.color.r,self.color.g,self.color.b)
        return so

    def loadSave(self,so):
        """
        Allows us to load an individual gene in case the program is stopped.
        """
        self.size = so["size"]
        self.diameter = so["diameter"]
        self.pos = Point(so["pos"][0],so["pos"][1])
        self.color = Color(so["color"][0],so["color"][1],so["color"][2])

class Organism:
    """
    The organism consists of a variety of genes that work together for some sort of effect. The main
    effect of the genetic algorithm takes place here, as each step involves mutating some of the
    organisms genes to produce offspring, and the best performing of those offspring carries on.

    This organism contains a bunch of genes that draw circles, working together to draw a picture.
    """
    def __init__(self,size,num):
        self.size = size

        #Create random genes up to the number given
        self.genes = [Gene(size) for _ in xrange (num)]

    def mutate(self):
        #For small numbers of genes, each one has a random chance of mutating
        if len(self.genes) < 200:
            for g in self.genes:
                if MUTATION_CHANCE < random.random():
                    g.mutate()

        #For large numbers of genes, pick a random sample, this is statistically equivalent and faster
        else:
            for g in random.sample(self.genes,int(len(self.genes)*MUTATION_CHANCE)):
                g.mutate()

        #We also have a chance to add or remove a gene
        if ADD_GENE_CHANCE < random.random():
            self.genes.append(Gene(self.size))
        if len(self.genes) > 0 and REM_GENE_CHANCE < random.random():
            self.genes.remove(random.choice(self.genes))

    def drawImage(self):
        """
        Using the Image module, use the genes to draw the image.
        """
        image = Image.new("RGB",self.size,(255,255,255))
        canvas = ImageDraw.Draw(image)

        for g in self.genes:
            color = (g.color.r,g.color.g,g.color.b)
            canvas.ellipse([g.pos.x-g.diameter,g.pos.y-g.diameter,g.pos.x+g.diameter,g.pos.y+g.diameter],outline=color,fill=color)

        return image

    def getSave(self,generation):
        """
        Allows us to save an individual organism in case the program is stopped.
        """
        so = [generation]
        return so + [g.getSave() for g in self.genes]

    def loadSave(self,so):
        """
        Allows us to load an individual organism in case the program is stopped.
        """
        self.genes = []
        gen = so[0]
        so = so[1:]
        for g in so:
            newGene = Gene(self.size)
            newGene.loadSave(g)
            self.genes.append(newGene)
        return gen

def fitness(im1,im2):
    """
    The fitness function is used by the genetic algorithm to determine how successful a given organism
    is. Usually a genetic algorithm is trying to either minimize or maximize this function.

    This one uses numpy to quickly compute the sum of the differences between the pixels.
    """
    #Convert Image types to numpy arrays
    i1 = numpy.array(im1,numpy.int16)
    i2 = numpy.array(im2,numpy.int16)
    dif = numpy.sum(numpy.abs(i1-i2))
    return (dif / 255.0 * 100) / i1.size

#-------------------------------------------------------------------------------------------------
#Functions to Make Stuff Run
#-------------------------------------------------------------------------------------------------
def run(cores,so=None):
    """
    Contains the loop that creates and tests new generations.
    """
    #Create storage directory in current directory
    if not os.path.exists("results"):
        os.mkdir("results")

    #Create output log file
    f = file(os.path.join("results","log.txt"),'a')

    target = globalTarget

    #Create the parent organism (with random genes)
    generation = 1
    parent = Organism(target.size,INITIAL_GENES)

    #Load the save if one is given
    if so != None:
        gen = parent.loadSave(jsonpickle.decode(so))
        generation = int(gen)
    prevScore = 101
    score = fitness(parent.drawImage(),target)
    #Setup the multiprocessing pool
    p = multiprocessing.Pool(cores)
    #Infinite loop (until the process is interrupted)
    while True:
        #Print the current score and write it to the log file
        print "Generation {} - {}".format(generation,score)
        f.write("Generation {} - {}\n".format(generation,score))

        #Save an image of the current best organism to the results directory
        if (generation) % GENERATIONS_PER_IMAGE == 0:
            parent.drawImage().save(os.path.join("results","{}.png".format(generation)))
        generation += 1

        prevScore = score

        #Spawn children
        children = []
        scores = []

        #Keep the best from before in case all mutations are bad
        children.append(parent)
        scores.append(score)

        #Perform the mutations and add to the parent
        try:
            results = groupMutate(parent,POP_PER_GENERATION-1,p)
        except KeyboardInterrupt:
            print 'Bye!'
            p.close()
            return

        newScores,newChildren = zip(*results)

        children.extend(newChildren)
        scores.extend(newScores)
        #Find the winner

        winners = sorted(zip(children,scores),key=lambda x: x[1])

        parent,score = winners[0]

        #Store a backup to resume running if the program is interrupted
        if generation % 100 == 0:
            sf = file(os.path.join("results","{}.txt".format(generation)),'w')
            sf.write(jsonpickle.encode(parent.getSave(generation)))
            sf.close()

def mutateAndTest(o):
    """
    Given an organism, perform a random mutation on it, and then use the fitness function to
    determine how accurate of a result the mutated offspring draws.
    """
    try:
        c = deepcopy(o)
        c.mutate()
        i1 = c.drawImage()
        i2 = globalTarget
        return (fitness(i1,i2),c)
    except KeyboardInterrupt, e:
        pass

def groupMutate(o,number,p):
    """
    Mutates and tests a number of organisms using the multiprocessing module.
    """
    results = p.map(mutateAndTest,[o]*int(number))
#    results = [mutateAndTest(i) for i in [o]*int(number)]
    return results

#-------------------------------------------------------------------------------------------------
#Main Function
#-------------------------------------------------------------------------------------------------
if __name__ == "__main__":
    #Set defaults
    cores = max(1,multiprocessing.cpu_count()-1)
    so = None

	#Check the arguments, options are currents -t (number of threads) and -s (save file)
    if len(sys.argv) > 1:
        args = sys.argv[1:]

        for i,a in enumerate(args):
            if a == "-t":
                cores = int(args[i+1])
            elif a == "-s":
                with open(args[i+1],'r') as save:
                    so = save.read()

    run(cores,so)


text:
package org.jetbrains.jps.model.java;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.model.JpsDummyElement;
import org.jetbrains.jps.model.JpsElementFactory;
import org.jetbrains.jps.model.JpsElementTypeWithDefaultProperties;
import org.jetbrains.jps.model.module.JpsModuleType;

/**
 * @author nik
 */
public class JpsJavaModuleType extends JpsModuleType<JpsDummyElement> implements JpsElementTypeWithDefaultProperties<JpsDummyElement> {
  public static final JpsJavaModuleType INSTANCE = new JpsJavaModuleType();

  @NotNull
  @Override
  public JpsDummyElement createDefaultProperties() {
    return JpsElementFactory.getInstance().createDummyElement();
  }
}


text:
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

import isPlainObject from 'lodash-es/isPlainObject';

export default function isStatePlainEnough(a) {
  // isPlainObject + duck type not immutable
  if (!a) return false;
  if ((typeof a === 'undefined' ? 'undefined' : _typeof(a)) !== 'object') return false;
  if (typeof a.asMutable === 'function') return false;
  if (!isPlainObject(a)) return false;
  return true;
}


text:
define(function (require) {
  'use strict';

  var modules = require('modules');
  var angular = require('angular');

  require('scripts/common/services/suggestion_services');

  modules.get('a4c-common', []).directive('a4cTags', function () {
    return {
      restrict: 'E',
      templateUrl: 'views/_ref/common/tags.html',
      controller: 'TagsCtrl',
      scope: {
        // Base url of the tags management controller
        baseUrl: '@',
        // Resource key and id
        resourceKey: '@',
        resourceId: '=',
        manager: '=',
        // Tags array
        tags: '='
      }
    };
  });

  const alienInternalTags = ['icon'];

  modules.get('a4c-common', []).controller('TagsCtrl', ['$scope', '$alresource', 'suggestionServices',
    function ($scope, $alresource, suggestionServices) {
      var tagService = $alresource($scope.baseUrl+'/:tagId');

      /* Restrict tags visibility */
      $scope.isInternalTag = function(tag) {
        var internalTag = false;
        for (var i = 0; i < alienInternalTags.length; i++) {
          if (alienInternalTags[i] === tag) {
            return true;
          }
        }
        return internalTag;
      };

      /* Update / Delete application tags */
      $scope.updateTag = function(tagName, tagValue) {
        var pathParams = {};
        pathParams[$scope.resourceKey] = $scope.resourceId;
        $scope.tagUpdateResult = tagService.create(pathParams, angular.toJson({
          tagKey: tagName,
          tagValue: tagValue
        }));
      };

      $scope.deleteTag = function(tag) {
        var index = $scope.tags.indexOf(tag);
        if (index >= 0) {
          var pathParams = {
            tagId: tag.name
          };
          pathParams[$scope.resourceKey] = $scope.resourceId;
          $scope.tagDeleteResult = tagService.remove(pathParams);
          // Remove the selected tag
          $scope.tags.splice(index, 1);
        }
      };

      /* Add new tags */
      var removeTagIfExists = function(tagName) {
        for (var i in $scope.tags) {
          if ($scope.tags.hasOwnProperty(i)) {
            var tag = $scope.tags[i];
            if (tag.name === tagName) {
              $scope.tags.splice(i, 1);
              return;
            }
          }
        }
      };

      var resetTagForm = function(newTag) {
        newTag.key = '';
        newTag.val = '';
      };

      $scope.addTag = function(newTag) {
        $scope.updateTag(newTag.key, newTag.val);
        removeTagIfExists(newTag.key);
        $scope.tags.push({
          name: newTag.key,
          value: newTag.val
        });
        resetTagForm(newTag);
      };

      /**
       * TAG SUGGESTION
       */
      var getTagNameSuggestions = function(keyword) {
        return suggestionServices.tagNameSuggestions(keyword);
      };

      $scope.tagSuggestion = {
        get: getTagNameSuggestions,
        waitBeforeRequest: 0,
        minLength: 2
      };
    }]);
});


text:
  <link rel="stylesheet" href="../bower_components/mocha/mocha.css"/>

This is a test page. Mocha tests should run below.


text:
This package gives you an easy way to generate automatically all language fields on database, using Laravel 5 command.  If you have on database fields like `body_en` and you want to create new like `body_it` you can use this package to create it.

## Installing

First, pull in the package through Composer.

```
composer require makth/laravel-db-language
```

or

```php
"require":{
    "makth/laravel-db-language": "2.0"
}
```

Next, open `config/app.php`, and include service provider.

```php
'providers' => [
    Makth\DbLanguage\DbLanguageServiceProvider::class,
];
```

And, for convenience, add a facade alias to the same file at the bottom:

```php
'aliases' => [
    'Lang' => Makth\DbLanguage\Facade\Lang::class,
];
```

## Usage

### Add a language
```
php artisan language:add German
```

### Remove a language
```
php artisan language:remove German
```

#### Default language
You can set your default language using option `--default`. For example:
```
php artisan language:add German --default="English"
```
If you want to have more than one languages, you set your main (already installed) language as default, and you add the other languages.

### Config
You can publish config file `lang.php`, and set your default language there.
```
php artisan vendor:publish --tag=config
```

### Language Field
You can have form fields with multiple languages.

#### Step 1
Export css files to public folder.
```
php artisan vendor:publish --tag=flags
```

#### Step 2
Add in your blade file, on head tag:
```
@include('lang::style')
```
And at the bottom of the body:
```
@include('lang::script')
```

And now you can get the form field with all installed languages like this:
```blade
{{ Lang::fields(
    'table_name',
    'field_name',
    ['first_language_value', 'second_language_value'],
    null,
    ['placeholder' => 'Name', 'required' => 'required']
    )
}}
```
- `table_name` : the name of the db table.
- `field_name` : the name of table field, without language extension.
- the third parameter is an array with languages values.
- the fourth parameter used to sets manual the default language.
- the fifth parameter is an array with extra attributes for the fields.

For form fields used twitter bootstrap, and for the flags [this](https://github.com/lipis/flag-icon-css) package.

## Authors

* **Makis Thomas**

## License

This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details.


text:
<!DOCTYPE html>
	<head>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<title>Rebel Chat</title>
		<meta name="description" content="">
		<meta name="viewport" content="width=device-width, initial-scale=1">

		<link rel="stylesheet" href="vendor/bootstrap.min.css">
		<link rel="stylesheet" href="vendor/bootstrap-theme.min.css">
		<link rel="stylesheet" href="css/main.css">

		<script src="vendor/modernizr-2.6.2-respond-1.1.0.min.js"></script>
		<script src="vendor/knockout-3.2.0.min.js"></script>
		<script src="vendor/falcon.min.js"></script>
		<script src="vendor/falcon.jquery_adapter.min.js"></script>
		<script src="vendor/jquery-1.11.1.min.js"></script>
		<script src="vendor/bootstrap.min.js"></script>
		<script src="vendor/moment.min.js"></script>
		<script src="vendor/markdown.min.js"></script>

		<script src="js/rebelChat.js"></script>
		<script src="js/models/chatroom.js"></script>
		<script src="js/models/chatmessage.js"></script>
		<script src="js/views/home.js"></script>
		<script src="js/views/callsign.js"></script>
		<script src="js/views/createChatroom.js"></script>
		<script src="js/views/chatroom.js"></script>
		<script src="js/views/chatroomsList.js"></script>
		<script src="js/views/layout.js"></script>
		<script src="js/main.js"></script>
	</head>
	<body></body>
</html>


text:
#pragma strict

///All this script is responsible for is deciding wether or not the background elemts load. This can NOT go on the very last backgrounds, only BG 1 and 2.
function Start () {
	if(Random.Range(0,3)==1){
		transform.renderer.enabled = false;
	}
}


text:
package manifold.internal.javac;

import com.sun.source.util.JavacTask;
import com.sun.source.util.Plugin;
import manifold.util.NecessaryEvilUtil;

/**
 * The {@link JavacPlugin} can't be used directly with Java 16+ because stricter accessibility changes were added to
 * internal modules (JEP 396: Strongly Encapsulate JDK Internals by Default). For instance, {@code jdk.compiler} exports
 * fewer packages. This means we must make the necessary module changes via bypassJava9Security() <i>before</i> {@code
 * JavacPlugin} is constructed, which is the purpose of this bootstrap plugin; it makes dynamic module changes before
 * constructing and delegating to {@code JavacPlugin}.
 */
public class JavacPluginBootstrap implements Plugin
{
  private final Plugin _delegate;

  public JavacPluginBootstrap()
  {
    NecessaryEvilUtil.bypassJava9Security();
    _delegate = new JavacPlugin();
  }

  @Override
  public String getName()
  {
    return "Manifold";
  }

  @Override
  public void init( JavacTask task, String... args )
  {
    _delegate.init( task, args );
  }
}


text:
import sys
import subprocess
import os
from math import floor, ceil

import numpy
import h5py

import hifive
import heatmap

def main():
    datafname, modelprefix, outfname, fivecfname, regions = sys.argv[1:6]
    regions = regions.split(',')
    fivec = hifive.FiveC(fivecfname, 'r')
    data = h5py.File(datafname, 'r')
    # get fend range from data file
    data_path = os.path.dirname(datafname).split('/')
    fendfilename = data['/'].attrs['fendfilename']
    if fendfilename.count('../') > 0:
        data_path = data_path[:-fendfilename.count('../')]
    fendfilename = '/'.join(data_path + fendfilename.split('/')[-1:])
    fends = h5py.File(fendfilename, 'r')
    output = h5py.File(outfname, 'w')
    for region in regions:
        region = int(region)
        # get region bounds
        index, start_frag, stop_frag, chrom, start, stop = fivec.frags['regions'][region]
        bounds = numpy.zeros((stop_frag - start_frag, 2), dtype=numpy.int32)
        bounds[:, 0] = fivec.frags['fragments']['start'][start_frag:stop_frag]
        bounds[:, 1] = fivec.frags['fragments']['stop'][start_frag:stop_frag] + 1
        chr_indices = fends['chr_indices'][...]
        chromosomes = fends['chromosomes'][...]
        chr2int = {}
        mids = fends['fends']['mid'][...]
        for i in range(chromosomes.shape[0]):
            chr2int[chromosomes[i]] = i
        chrint = chr2int[chrom]
        start_fend = chr_indices[chrint]
        stop_fend = chr_indices[chrint + 1]
        while start_fend < stop_fend and mids[start_fend] < bounds[0, 0]:
            start_fend += 1
        while stop_fend > start_fend and mids[stop_fend - 1] > bounds[-1, 1]:
            stop_fend -= 1
        num_fends = stop_fend - start_fend
        # get data and indices
        start_index = data['cis_indices'][start_fend]
        stop_index = data['cis_indices'][stop_fend]
        cis_data = data['cis_data'][start_index:stop_index, :]
        cis_indices = data['cis_indices'][start_fend:(stop_fend + 1)]
        cis_indices -= cis_indices[0]
        print >> sys.stderr, ("Creating binned heatmap..."),
        # load model parameters
        gc_matrix = load_matrix("%s_frag_gc_bin.f" % modelprefix)
        len_matrix = load_matrix("%s_frag_len_bin.f" % modelprefix)
        map_matrix = load_matrix("%s_map_bin.f" % modelprefix)
        fend_bins = load_fend_bins("%s.binned" % modelprefix, mids.shape[0])
        # allocate results arrays
        num_bins = bounds.shape[0]
        observed = numpy.zeros(num_bins * (num_bins - 1) / 2, dtype=numpy.int32)
        expected = numpy.zeros(num_bins * (num_bins - 1) / 2, dtype=numpy.float32)
        unbinned_observed = numpy.zeros(num_fends * (num_fends - 1) / 2, dtype=numpy.int32)
        unbinned_expected = numpy.zeros(num_fends * (num_fends - 1) / 2, dtype=numpy.float32)
        # determine bins for fends
        mids =  fends['fends']['mid'][start_fend:stop_fend]
        start_indices = numpy.searchsorted(bounds[:, 1], mids, side='right')
        stop_indices = numpy.searchsorted(bounds[:, 0], mids, side='right')
        where = numpy.where(start_indices < stop_indices)[0]
        bins = numpy.zeros(mids.shape[0], dtype=numpy.int32) - 1
        bins[where] = start_indices[where]
        # Find cis heatmap
        heatmap.bin_bounds_cis(cis_data, cis_indices, bins, fend_bins, map_matrix, gc_matrix, len_matrix,
                                observed, expected, start_fend, stop_fend, bounds.shape[0])
        heatmap.bin_bounds_cis(cis_data, cis_indices, numpy.arange(num_fends).astype(numpy.int32), fend_bins, map_matrix, gc_matrix, len_matrix,
                                unbinned_observed, unbinned_expected, start_fend, stop_fend, num_fends)
        print >> sys.stderr, ("Done\n"),
        # Write results to file
        print >> sys.stderr, ("Writing to file..."),
        output.create_dataset(name='%i.counts' % region, data=observed)
        output.create_dataset(name='%i.expected' % region, data=expected)
        output.create_dataset(name='%i.unbinned_counts' % region, data=unbinned_observed)
        output.create_dataset(name='%i.unbinned_expected' % region, data=unbinned_expected)
        output.create_dataset(name='%i.bounds' % region, data=bounds)
        output.create_dataset(name='%i.mids' % region, data=mids)
        output.attrs['%i.chromosome' % region] = chrom
    output.close()
    print >> sys.stderr, ("Done\n"),
    return None

def load_matrix(fname):
    input = open(fname, 'r')
    data = []
    for line in input:
        data.append(line.strip('\n').split('\t'))
    input.close()
    data = data[1:]
    for i in range(len(data)):
        for j in range(len(data[i])):
            data[i][j] = float(data[i][j])
    data = numpy.array(data, dtype=numpy.float32)
    num_bins = int(numpy.amax(data[:,0]))
    matrix = numpy.zeros((num_bins, num_bins), dtype=numpy.float32)
    for i in range(data.shape[0]):
        matrix[int(data[i, 0]) - 1, int(data[i, 1]) - 1] = data[i, 2]
    matrix += matrix.T
    matrix[numpy.arange(num_bins), numpy.arange(num_bins)] /= 2.0
    return matrix

def load_fend_bins(fname, num_fends):
    input = open(fname, 'r')
    bins = numpy.zeros((num_fends, 4), dtype=numpy.int32)
    for line in input:
        temp = line.strip('\n').split('\t')
        if temp[0] == 'fend':
            continue
        fend = int(temp[0]) - 1
        map_bin = int(temp[8]) - 1
        gc_bin = int(temp[9]) - 1
        len_bin = int(temp[10]) - 1
        bins[fend, 0] = 1
        bins[fend, 1] = map_bin
        bins[fend, 2] = gc_bin
        bins[fend, 3] = len_bin
    input.close()
    return bins

if __name__ == "__main__":
    main()


text:
#ifndef __R_THINGS__
#define __R_THINGS__

#ifdef __GNUG__
#pragma interface
#endif

#define MAXVISSPRITES  	128

extern vissprite_t	vissprites[MAXVISSPRITES];
extern vissprite_t*	vissprite_p;
extern vissprite_t	vsprsortedhead;

// Constant arrays used for psprite clipping
//  and initializing clipping.
extern short		negonearray[SCREENWIDTH];
extern short		screenheightarray[SCREENWIDTH];

// vars for R_DrawMaskedColumn
extern short*		mfloorclip;
extern short*		mceilingclip;
extern fixed_t		spryscale;
extern fixed_t		sprtopscreen;

extern fixed_t		pspritescale;
extern fixed_t		pspriteiscale;

void R_DrawMaskedColumn (postColumn_t* column);

void R_SortVisSprites (void);

void R_AddSprites (sector_t* sec);
void R_AddPSprites (void);
void R_DrawSprites (void);
void R_InitSprites (const char* const* namelist);
void R_ClearSprites (void);
void R_DrawMasked (void);

void
R_ClipVisSprite
( vissprite_t*		vis,
  int			xl,
  int			xh );

#endif


text:
<?php
/**
 * UNIT TEST: Parser
 *
 * @group App
 * @group Import
 * @group Parser
 */

namespace Import;
\Module::load('import');

class Test_Parser extends \Fuel\Core\TestCase
{

	public function test_ConvertStringToSpecedArray()
	{

		$string_to_convert = '111222222222Test Person         6015551234';
		$array_spec = array( 'company_id' => 3, 'ssn' => 9, 'name' => 20, 'phone' => 10, );
		$expected = array( 'company_id' => '111', 'ssn' => '222222222', 'name' => 'Test Person         ', 'phone' => '6015551234', );

		$spec_provider = $this->getMock('\Import\Provider_Spec');
		$spec_provider->expects( $this->any() )
			->method('get_spec')
			->will($this->returnValue( $array_spec ));

		$filter_provider = $this->getMock('\Import\Provider_Filter');

		$parser = $this->getMock(
			'\Import\Parser' ,
			array(
				'parse_string_subrecords' ,
				'prune_empty_elements' ,
				'apply_filter_to_all_elements' ,
				'break_out_subarrays' ,
			)
		);

		$parser->expects($this->once())
		       ->method('parse_string_subrecords')
		       ->will($this->returnArgument(0));
		$parser::staticExpects($this->once())
		       ->method('prune_empty_elements')
		       ->will($this->returnArgument(0));
		$parser::staticExpects($this->once())
		       ->method('apply_filter_to_all_elements')
		       ->with( $this->anything() , $this->equalTo('trim_whitespace') , $filter_provider )
		       ->will($this->returnArgument(0));
		$parser::staticExpects($this->once())
		       ->method('break_out_subarrays')
		       ->will($this->returnArgument(0));

		$actual = $parser->convert_string_to_specified_array( $string_to_convert , 'teststring' , $spec_provider , $filter_provider );
		$this->assertEquals( $expected , $actual );

	}

	public function test_ParseStringSubrecords()
	{
		$original = array('foo'=>'bar','two'=>'threefour');
		$expected = array('foo'=>'bar','two'=>array('twofoo'=>'three','twobar'=>'four'));
		$subarray = array('twofoo'=>'three','twobar'=>'four');

		$spec_provider = $this->getMock('\Import\Provider_Spec');
		$spec_provider->expects($this->at(1))
		              ->method('get_spec')
		              ->will( $this->returnValue( TRUE ) );

		$parser = $this->getMock('\Import\Parser',array('convert_string_to_specified_array'));
		$parser->expects($this->once())
		       ->method('convert_string_to_specified_array')
		       ->with( 'threefour' , 'two' , $spec_provider )
		       ->will( $this->returnValue($subarray) );

		$actual = $parser->parse_string_subrecords( $original , $spec_provider );
		$this->assertEquals( $expected , $actual );
	}

	public function providerFor_test_FilterValueAccordingToColumnName()
	{
		return array(
			array( 'unfiltered' , 'foo' , 'foo' ),
			array( 'filtered' , 'bar' , 'baz' ),
		);
	}

	/**
	 * @dataProvider providerFor_test_FilterValueAccordingToColumnName
	 */
	public function test_FilterValueAccordingToColumnName( $start_column , $start_value , $expected_value )
	{

		$filter_spec = array(
			'^filtered$' => 'currency_from_post_signed',
		);

		// we need to test whether the correct method is invoked or not.
		$invoked_count = $start_column=='filtered' ? $this->once() : $this->any();

		// this mock filter provider object will allow us to test only our particular unit
		$filter_object = $this->getMock('\Import\Provider_Filter');
		$filter_object->expects( $invoked_count )->method('currency_from_post_signed')->will($this->returnValue('baz'));
		$filter_object->expects( $this->any() )->method('trim_whitespace')->will($this->returnArgument(0));

		$parser = new Parser();
		$this->assertEquals(
			$expected_value ,
			$parser::filter_value_with_filter_spec( $start_value , $start_column , $filter_spec , $filter_object )
		);

	}

	function test_BreakOutSubarrays()
	{

		$start = array(
			'one' => 'one',
			'two.one' => 'two.one',
			'two.two' => 'two.two',
			'three.one.one' => 'three.one.one',
			'three.one.two' => 'three.one.two',
			'three.two.one' => 'three.two.one',
			'three.two.two' => 'three.two.two',
		);

		$expected = array(
			'one' => 'one',
			'two' => array(
				'one' => 'two.one',
				'two' => 'two.two',
			),
			'three' => array(
				'one' => array(
					'one' => 'three.one.one',
					'two' => 'three.one.two',
				),
				'two' => array(
					'one' => 'three.two.one',
					'two' => 'three.two.two',
				),
			),
		);

		$parser = new Parser();
		$actual = $parser->break_out_subarrays($start);
		$this->assertEquals( $expected , $actual );

	}

	function test_FlattenSubarrays()
	{
		$start = array(
			'one' => 'val one',
			'two' => array(
				'one' => 'val twoone',
				'two' => 'val twotwo',
				'three' => 'val twothree',
			),
			'three' => array(
				'one' => 'val threeone',
				'two' => array(
					'one' => 'val threetwoone',
					'two' => 'val threetwotwo',
					'three' => 'val threetwothree',
				),
			),
		);

		$expected = array(
			'one' => 'val one',
			'two.one' => 'val twoone',
			'two.two' => 'val twotwo',
			'two.three' => 'val twothree',
			'three.one' => 'val threeone',
			'three.two.one' => 'val threetwoone',
			'three.two.two' => 'val threetwotwo',
			'three.two.three' => 'val threetwothree',
		);

		$actual = Parser::flatten_subarrays($start);
		$this->assertEquals( $expected , $actual );

	}

	function test_ApplyFilterToAllElements()
	{

		$original = array( 'fake'=>'array' , 'for'=>'test' );
		$expected = array( 'fake'=>'filter' , 'for'=>'filtered' );
		$parser = new Parser();

		$filter_name = 'trim_whitespace';
		$filter_provider = $this->getMock('\Import\Provider_Filter');
		$filter_provider->expects( $this->any() )
		                ->method( $filter_name )
		                ->will( $this->onConsecutiveCalls('filter','filtered') );

		$actual = $parser->apply_filter_to_all_elements( $original , $filter_name , $filter_provider );
		$this->assertEquals( $expected , $actual );

	}

	/**
	 * @expectedException \Import\FilterDoesNotExistException
	 */
	function test_ApplyFilterToAllElements_ThrowsExceptionForBadFilter()
	{
		$original = array( 'fake'=>'array' , 'for'=>'test' );
		$parser = new Parser();
		$parser->apply_filter_to_all_elements( $original , 'totally_fake_filter_name_that_does_not_exist' );
	}

	public function test_PruneEmptyElements()
	{
		$start = array(
			'one' => 'one',
			'two' => '',
			'three' => 'three',
		);

		$expected = array(
			'one' => 'one',
			'three' => 'three',
		);

		$parser = new Parser();
		$this->assertEquals( $expected , $parser->prune_empty_elements($start) );
	}

}


text:
var win = Ti.UI.currentWindow;
var textArea = Ti.UI.createTextArea(
    {
        height: 150,
        width: 300,
        top: 10,
        font: {fontSize:20},
        borderWidth: 2,
        borderColor: '#bbb',
        borderRadius: 5
    }
);
win.add(textArea);
var postButton = Ti.UI.createButton(
    {
        top: 170,
        right: 10,
        width: 100,
        height: 44,
        title: 'POST'
    }
);

Ti.include('lib/twitter_api.js');

Ti.App.twitterApi = new TwitterApi({
    consumerKey: 'consumerKey',
    consumerSecret: 'consumerSecret'
});
var twitterApi = Ti.App.twitterApi;
twitterApi.init();

var latitude;
var longitude;
function tweet(message) {
    var params = {status: message};
    if (latitude && longitude) {
        params['lat'] = latitude;
        params['long'] = longitude;
    }
    twitterApi.statuses_update(
        {
            onSuccess: function(response) {
                alert('tweet success');
                Ti.API.info(response);
            },
            onError: function(error) {
                Ti.API.error(error);
            },
            parameters: params
        }
    );
}

postButton.addEventListener(
    'click',
    function() {
        if (textArea.value) {
            tweet(textArea.value);
            win.close();
        }
    }
);
win.add(postButton);

var mapView = Titanium.Map.createView(
    {
        width: 320,
        height: 240,
        top: 220,
        mapType: Titanium.Map.STANDARD_TYPE,
        region: {latitude:40.0, longitude:130, latitudeDelta:30, longitudeDelta:30},
        animate:true,
        regionFit: true
    }
);
mapView.hide();
win.add(mapView);

Titanium.Geolocation.purpose = 'Twitter投稿のため';
function setCurrentPosition() {
    Titanium.Geolocation.getCurrentPosition(
        function(e) {
            textArea.blur();
            if (!e.success || e.error) {
                alert('位置情報を取得できませんでした。');
                return;
            }

            latitude = e.coords.latitude; //現在地(緯度)
            longitude = e.coords.longitude; //現在地(経度)

            //地図に表示するピン(現在地)を作成
            var currentPos = Titanium.Map.createAnnotation(
                {
                    latitude: latitude,
                    longitude: longitude,
                    title: "現在地",
                    pincolor: Titanium.Map.ANNOTATION_GREEN,
                    animate: true
                }
            );
            //地図にピンを追加
            mapView.addAnnotation(currentPos);
            //地図を表示
            mapView.show();
            //地図の中心を現在地へ移動
            mapView.setLocation(
                {
                    latitude: latitude,
                    longitude: longitude,
                    latitudeDelta: 0.01,
                    longitudeDelta: 0.01
                }
            );
        }
    );
}

var locationButton = Ti.UI.createButton(
    {
        top: 170,
        left: 10,
        width: 100,
        height: 44,
        title: 'Location'
    }
);
locationButton.addEventListener(
    'click',
    setCurrentPosition
);
win.add(locationButton);

var imageView = Titanium.UI.createImageView(
    {
        width: 'auto',
        height: 240,
        top: 220
    }
);
imageView.hide();
win.add(imageView);

function uploadToTwitPic(image) {
    var xhr = Ti.Network.createHTTPClient();

    var verifyURL = 'https://api.twitter.com/1/account/verify_credentials.json';
    var params = {
        url: verifyURL,
        method: 'GET'
    };
    var header = twitterApi.oAuthAdapter.createOAuthHeader(params);
    Ti.API.debug(header);

    xhr.onload = function() {
        var res = JSON.parse(this.responseText);
        textArea.value = ( textArea.value || '' ) + ' ' + res.url;
    };
    //xhr.onerror = function(){};

    xhr.open('POST', 'https://api.twitpic.com/2/upload.json');
    xhr.setRequestHeader('X-Verify-Credentials-Authorization', header);
    xhr.setRequestHeader('X-Auth-Service-Provider', verifyURL);

    xhr.send(
        {
            key: 'TWITPIC_API_KEY',
            message: textArea.value,
            media: image
        }
    );
}

function startCamera() {
    Titanium.Media.showCamera(
        {
            success: function(e) {
                var image = e.media;
                imageView.image = image;
                imageView.show();
                uploadToTwitPic(image);
            },
            //cancel: function(){},
            error: function(error) {
                if (error.code == Titanium.Media.NO_CAMERA) {
                    alert('カメラがありません');
                }
            },
            saveToPhotoGallery: true,
            allowEditting: true,
            mediaTypes: [Ti.Media.MEDIA_TYPE_PHOTO] //MEDIA_TYPE_PHOTO を指定することにより静止画限定になる。指定しなければ動画が来る可能性あり
        }
    );
}

function selectFromPhotoGallery() {
    Ti.Media.openPhotoGallery(
        {
            success: function(e) {
                var image = e.media;
                imageView.image = image;
                imageView.show();
                uploadToTwitPic(image);
            },
            //error: function(error){},
            //cancel: function(){},
            allowEditting: true,
            mediaTypes: [Ti.Media.MEDIA_TYPE_PHOTO] //MEDIA_TYPE_PHOTO を指定することにより静止画限定になる。指定しなければ動画が来る可能性あり
        }
    );
}

var sourceSelect = Titanium.UI.createOptionDialog(
    {
        options: ['撮影する', 'アルバムから選ぶ', 'キャンセル'],
        cancel: 2,
        title: '写真を添付'
    }
);
sourceSelect.addEventListener(
    'click',
    function(e) {
        switch(e.index) {
            case 0:
                startCamera();
                break;
            case 1:
                selectFromPhotoGallery();
                break;
        }
    }
);

var photoButton = Ti.UI.createButton(
    {
        top: 170,
        left: 120,
        width: 80,
        height: 44,
        title: 'Photo'
    }
);

photoButton.addEventListener(
    'click',
    function() {
        sourceSelect.show();
    }
);
win.add(photoButton);

Titanium.Gesture.addEventListener(
    'shake',
    function(){
        var alertDialog = Titanium.UI.createAlertDialog(
            {
                title: '入力をキャンセルしますか?',
                buttonNames: ['入力をキャンセル', '編集を続行'],
            }
        );
        alertDialog.addEventListener(
            'click',
            function(e) {
                if (e.index == 0) {
                    win.close();
                }
            }
        );
        alertDialog.show();
    }
);

function postByAccelerometer(e) {
    if ( Math.abs(e.z) > 1.1 ) {
        accEnabled = false;
        Ti.Accelerometer.removeEventListener('update',postByAccelerometer);
        tweet('iPhoneに触られた!');
    }
}

var accEnabled = false;
var accButton = Ti.UI.createButton(
    {
        top: 160,
        left: 190,
        width: 44,
        height: 44,
        title: 'Acc'
    }
);
accButton.addEventListener(
    'click',
    function () {
        if (accEnabled) {
            alert('無効にします');
            accEnabled = false;
            Ti.Accelerometer.removeEventListener('update',postByAccelerometer);
        } else {
            alert('有効にします');
            accEnabled = true;
            Ti.Accelerometer.addEventListener('update',postByAccelerometer);
        }
    }
);
win.add(accButton);


text:
using System;
using System.Runtime.Serialization;

namespace System.Threading
{
    [Serializable]
    [System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
    public class SemaphoreFullException : SystemException
    {
        public SemaphoreFullException() : base(SR.Threading_SemaphoreFullException)
        {
        }

        public SemaphoreFullException(string message) : base(message)
        {
        }

        public SemaphoreFullException(string message, Exception innerException) : base(message, innerException)
        {
        }

        protected SemaphoreFullException(SerializationInfo info, StreamingContext context) : base(info, context)
        {
        }
    }
}


text:
require 'net/http'

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  def get_map_metadata(map_id)
    url = URI(Map.find(map_id).cartodb_sql_url)

    data = Hash.new
    Map::SECTORS.each do |sector|
      query_string = Map::COUNT_DATA_PER_SECTOR % sector
      data[sector] = make_request(url, query_string)[0]
    end

    return data
  end

  def make_request(url, query_string)
    query = URI.encode_www_form({q: query_string})
    url = URI("#{url}#{query}")

    response = Net::HTTP.start(url.host, url.port, use_ssl: url.scheme == 'https') do |http|
      request = Net::HTTP::Get.new url
      response = http.request(request)
    end
    return JSON.parse(response.body)['rows']
  end
end


text:
#include "base/os.h"
#include "test/test_setup.h"
#include "ksync/ksync_sock_user.h"
#include "cmn/agent_cmn.h"

#include <boost/program_options.hpp>

using boost::optional;
namespace opt = boost::program_options;

char setup_file[1024];
char config_file[1024];

void RouterIdDepInit(Agent *agent) {
}

namespace {
class AclFlowTest : public ::testing::Test {
protected:
};

static void TxIpPacket(int ifindex, const char *sip, const char *dip,
              int proto, int hash_id) {
    PktGen *pkt = new PktGen();
    pkt->AddEthHdr("00:00:00:00:00:01", "00:00:00:00:00:02", 0x800);
    pkt->AddAgentHdr(ifindex, AgentHdr::TRAP_FLOW_MISS, hash_id);
    pkt->AddEthHdr("00:00:00:00:00:01", "00:00:00:00:00:02", 0x800);
    pkt->AddIpHdr(sip, dip, proto);

    uint8_t *ptr(new uint8_t[pkt->GetBuffLen()]);
    memcpy(ptr, pkt->GetBuff(), pkt->GetBuffLen());
    client->agent_init()->pkt0()->ProcessFlowPacket(ptr, pkt->GetBuffLen(),
                                                    pkt->GetBuffLen());
    delete pkt;
}

bool TrafficActionCheck(TrafficAction::Action act,
                       int32_t vr_flow_action) {
    switch (act) {
        case TrafficAction::DENY:
            return ((vr_flow_action & 0x1) == VR_FLOW_ACTION_DROP) ? true : false;
        case TrafficAction::PASS:
            return (vr_flow_action & VR_FLOW_ACTION_FORWARD) ? true : false;
        default:
            return false;
    }
    return false;
}

void ProcessExceptionPackets() {
    std::vector<ExceptionPacket>::iterator it;
    int hash_id = 10;
    for (it = excep_p_l.begin(); it != excep_p_l.end(); ++it) {
         ExceptionPacket ep = *it;
     Vn *vn = FindVn(ep.vn);
     if (vn == NULL) {
         LOG(ERROR, "Vn doesn't exist");
         return;
     }
     Vm *vm = FindVm(*vn, ep.vm);
     if (vm == NULL) {
         LOG(ERROR, "Vm:" << ep.vm << " doesn't exist in the Vn:" << vn->name);
         return;
     }

     VmInterface *intf = VmInterfaceGet(vm->pinfo.intf_id);
     if (intf == NULL) {
       LOG(ERROR, "Interface is not found");
       return;
     }
     LOG(DEBUG, "Interface ID:" << intf->id());
     TxIpPacket(intf->id(), ep.sip.c_str(), ep.dip.c_str(),
                strtoul((ep.proto).c_str(), NULL, 0), hash_id);
         client->WaitForIdle();
         AclTable *table = Agent::GetInstance()->acl_table();
         KSyncSockTypeMap *sock = KSyncSockTypeMap::GetKSyncSockTypeMap();
         KSyncSockTypeMap::ksync_map_flow::iterator ksit;
         EXPECT_TRUE((ksit = sock->flow_map.find(hash_id)) != sock->flow_map.end());
         vr_flow_req vr_flow = ksit->second;
         TrafficAction::Action act = table->ConvertActionString(ep.act);
         EXPECT_TRUE(TrafficActionCheck(act, vr_flow.get_fr_action()));
         EXPECT_TRUE((vr_flow.get_fr_flags() & VR_FLOW_FLAG_ACTIVE) == VR_FLOW_FLAG_ACTIVE);
         EXPECT_EQ(hash_id, vr_flow.get_fr_index());
         hash_id++;
    }
}

void CreateNodeNetwork(Vn &vn, bool del_op) {
    Acl *acl = FindAcl(vn.acl_id);
    EXPECT_TRUE(acl != NULL);
    client->Reset();
    if (del_op) {
        DelVn(vn.name.c_str());
        DelVrf(vn.vrf.c_str());
        DelLink("virtual-network", vn.name.c_str(), "routing-instance", vn.vrf.c_str());
        DelLink("virtual-network", vn.name.c_str(), "access-control-list", acl->name.c_str());
    } else {
        AddVn(vn.name.c_str(), vn.id);
        AddVrf(vn.vrf.c_str());
        AddLink("virtual-network", vn.name.c_str(), "routing-instance", vn.vrf.c_str());
        AddLink("virtual-network", vn.name.c_str(), "access-control-list", acl->name.c_str());
    }

    std::vector<Vm>::iterator iter;
    for (iter = vn.vm_l.begin(); iter != vn.vm_l.end();
     ++iter) {
         Vm vm = *iter;
         if (del_op) {
             DelVm(vm.name.c_str());
             DeleteVmportEnv(&(vm.pinfo), 1, 0);
         } else {
             AddVm(vm.name.c_str(), vm.id);
             CreateVmportEnv(&(vm.pinfo), 1);
         }
    }
    client->WaitForIdle();
    if (del_op) {
        return;
    }
    for (iter = vn.vm_l.begin(); iter != vn.vm_l.end();
     ++iter) {
         Vm vm = *iter;
         EXPECT_TRUE(VmPortActive(&(vm.pinfo), 0));
         EXPECT_TRUE(VmPortPolicyEnable(&(vm.pinfo), 0));
         Ip4Address ip = Ip4Address::from_string(vm.pinfo.addr);
         EXPECT_TRUE(RouteFind(vn.vrf, ip, 32));
    }
}

void CreateNodeNetworks(bool del_op) {
    std::vector<Vn>::iterator iter;
    for (iter = vn_l.begin(); iter !=vn_l.end(); ++iter) {
         Vn vn = *iter;
     CreateNodeNetwork(vn, del_op);
    }
}

void LoadAcl() {
    pugi::xml_document xdoc;
    xdoc.load_file("data.xml");
    Agent::GetInstance()->ifmap_parser()->ConfigParse(xdoc.first_child(), 0);
}

TEST_F(AclFlowTest, Setup) {
    string str;
    if (setup_file[0] == '\0') {
        ReadSetupFile(NULL);
    } else {
        ReadSetupFile(setup_file);
    }
    ConstructAclXmlDoc();
    LoadAcl();
    client->Reset();
    CreateNodeNetworks(false);
    ProcessExceptionPackets();
    client->WaitForIdle();
    CreateNodeNetworks(true);
}

} //namespace

int main (int argc, char **argv) {
    setup_file[0] = '\0';
    config_file[0] = '\0';
    opt::options_description desc("Command line options");
    desc.add_options()
            ("help", "help message")
            ("setup-file", opt::value<string>(), "Test setup file")
            ("config-file", opt::value<string>(), "Config file");
    opt::variables_map var_map;
    opt::store(opt::parse_command_line(argc, argv, desc), var_map);
    opt::notify(var_map);

    if (var_map.count("help")) {
        cout << desc << endl;
        exit(0);
    }
    if (var_map.count("setup-file")) {
       snprintf(setup_file, sizeof(setup_file), "%s",
                var_map["setup-file"].as<string>().c_str());
    }
    LOG(DEBUG, "Setup File:" << setup_file);
    if (var_map.count("config-file")) {
       snprintf(config_file, sizeof(config_file), "%s",
                var_map["config-file"].as<string>().c_str());
    } else {
        strcpy(config_file, DEFAULT_VNSW_CONFIG_FILE);
    }
    LOG(DEBUG, "Config File:" << config_file);

    client = TestInit(config_file, false, true, false, true);
    Agent::GetInstance()->set_router_id(Ip4Address::from_string("10.1.1.1"));

    ::testing::InitGoogleTest(&argc, argv);
    int ret = RUN_ALL_TESTS();
    client->WaitForIdle();
    TestShutdown();
    delete client;
    return ret;
}