text:
package cogdebugger.ui.fieldvisualizations

import cogx.runtime.debugger.ProbedField
import libcog._
import cogdebugger.{ToolFactory, OneOfNProperty, RestorableState}
import cogdebugger.ui.components.{LoadingAnimationPanel, PanPane, ToolBar}
import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Failure, Success}
import scala.xml.Node
import scala.swing._
import scala.language.postfixOps

/** A high-level visualization container that lets a user choose switch between
  * available visualization options for a particular field.
  *
  * Besides a target field, this class also requires as arguments a list of
  * user-friendly visualization names and a factory that uses those names as
  * keys to produce an actual Viewer instance. The superpanel itself is
  * presented as a BorderPanel with a toolbar at the top and the visualization
  * in the center. The selectable viewer's names are presented to the user in a
  * ComboBox installed in the toolbar after any visualiztion specific controls
  * (which are installed if a given Viewer implements the ToolbarItems trait).
  * This combobox will only appear if there is more than one available
  * visualization.
  *
  * The first visualization named in the `options` argument is used as the
  * default and will be immediately installed in the superpanel as part of
  * initialization.
  *
  * While `viewerFactory` can be any map from Strings to Viewers, consider
  * making it some sort of lazy or memoized map, particularly if any of the
  * Viewer instances has substantial startup time. [[cogdebugger.Memoize#apply]]
  * [[cogdebugger.Memoize]]
  *
  * This class was designed with the expectation that we'll wish to implement
  * a subclass specific to each particualar type of field. A companion object
  * with a straightforward factory method can make the instantiation of the
  * subclass cleaner. E.g., for ColorFields (which currently only have one
  * visualization):
  *
  * {{{
  * class ColorFieldSuperPanel protected (target: ProbedField,
  *                                       options: List[String],
  *                                       factory: (String) => Viewer)
  *   extends ViewerSuperPanel2(target, options, factory)
  *
  * object ColorFieldSuperPanel {
  *
  *   val ColorPanelName = "Color Image"
  *   val viewerNames = List(ColorPanelName)
  *
  *   def apply(target: ProbedField) = {
  *     //require( // Check for ColorField //, "Not a ColorField")
  *     val fieldShape  = target.fieldType.fieldShape
  *     val tensorShape = target.fieldType.tensorShape
  *     val memoizer = Memoize[String, EventDrivenViewer] {
  *       case ColorPanelName => new ColorFieldMemoryView(target, fieldShape) with MouseDragZoom
  *     }
  *     new ColorFieldSuperPanel(target, viewerNames, memoizer)
  *   }
  * }
  * }}}
  *
  * Created by gonztobi on 4/10/2014.
  *
  * @param target ProbedField being visualized.
  * @param options User-presentable strings corresponding to the visualizations
  *                available for the `target` field.
  * @param viewerFactory A map from the Strings in `options` to their
  *                      respective visualization instances.
  */
class ViewerSuperPanel(target: ProbedField,
                        options: List[String],
                        viewerFactory: (String) => Viewer)
  extends BorderPanel
  with EventDrivenViewer
  with Zoomable
  with RestorableState
{

  /** Visualizations are created on demand; at any given point in time there
    * may be an available visualization that hasn't been instantiated yet.
    * This set helps us track which visualizations have actually been built so
    * that we can save their state to a file when the debugger closes or
    * restore from a file when they're recreated in a subsequent session. */
  private val instantiated = collection.mutable.Set.empty[Viewer]
  private val restored = collection.mutable.Set.empty[Viewer]

  // Default view is the first in the list.
  protected var currentView: Viewer = viewerFactory(options.head)
  instantiated += currentView

  protected var lastData: AbstractFieldMemory = null
  protected var lastTime: Long = 0L

  val selectedViewerProperty = new OneOfNProperty("viewselection", options.head, options)
  selectedViewerProperty.action = Action("Change Display") {
    changeDisplay(selectedViewerProperty.selection)
  }
  properties += selectedViewerProperty

  /** A toolbar that hosts common controls for the visualizations installed
    * as children in this SuperPanel, as well as the combo box that allows
    * switching between different visualizations. */
  val toolbar = new ToolBar("Field Visualization") {
    val zoomInButton  = Button("+")(zoomIn())
    val zoomOutButton = Button("-")(zoomOut())
    val displayBox = ToolFactory.comboBox(selectedViewerProperty)
    contents += zoomInButton
    contents += zoomOutButton
    contents += Swing.HGlue
    if (options.size > 1) contents += displayBox
    floatable = false
    border = Swing.EmptyBorder
  }

  /** Rebuild the toolbar, populating it with the standard controls (for
    * zooming and switching views) as well as any controls defined by the
    * current view. Used when switching views. */
  private def refreshToolbar() {
    toolbar.contents.clear()
    toolbar.contents += toolbar.zoomInButton
    toolbar.contents += toolbar.zoomOutButton
    currentView match {
      case hasItems: ToolbarItems =>
        val flattened = hasItems.toolbarComponents.foldLeft(Seq.empty[Component]) {
          (listSoFar, nextCompGroup) =>
            (listSoFar :+ Swing.HStrut(10)) ++ nextCompGroup.components.toSeq
        }
        toolbar.contents ++= flattened
      case _ =>
    }
    toolbar.contents += Swing.HGlue
    if (options.size > 1) toolbar.contents += toolbar.displayBox
    toolbar.revalidate()
  }

  private val scroller = new PanPane(currentView)
  scroller.border = Swing.EmptyBorder

  // Install toolbar and default visualization.
  layout(toolbar) = BorderPanel.Position.North
  layout(scroller) = BorderPanel.Position.Center
  refreshToolbar() // Make sure current view's toolbar items are installed

  /** Change the currently active display. Also adds/removes some controls
    * from the toolbar as appropriate (e.g. adds zoom buttons for Zoomable
    * views or removes them for views that cannot be zoomed).
    *
    * @param key Key into the `displayOptions` map for the desired view.
    */
  def changeDisplay(key: String) {
    // Building and updating the new view could take a while, so we do it off
    // the Event-Dispatch Thread with a future.
    // ---
    // It occurs to me that this introduces the possiblity of a race - we
    // changeDisplay rapidly, we'll spawn a bunch of futures, all of which
    // will on completion try to install the view they built. Whoever finishes
    // last wins. Is there a way to safely cancel a future if another
    // changeDisplay comes in the meantime? For now, I'm just going to disable
    // the combobox while switching views (I suspect I'll be asked to revert
    // this as soon as somebody switches to an expensive view, decides they'd
    // rather not wait, and wants to change back).
    toolbar.displayBox.enabled = false
    val progressBar = new LoadingAnimationPanel("Switching visualizations...")
    layout(progressBar) = BorderPanel.Position.Center
    revalidate(); repaint()
    val f = Future {
      val newView = viewerFactory(key)
      // We don't update hidden views in the background, so we probably have to
      // update/redraw the newly switched to view.
      if (lastData != null)
        newView.update(target, lastData, lastTime)
      newView
    }

    f.onComplete {
      case Success(newView) => Swing.onEDT {

        // If this is the first time we've switched to this particular
        // visualization, restore any state saved from a previous debugger
        // session.
        restoreIfNecessary(newView)
        instantiated += newView
        currentView = newView

        // Add/remove zoom buttons as necessary
        currentView match {
          case zoomable: Zoomable =>
            toolbar.zoomInButton.visible = true
            toolbar.zoomOutButton.visible = true
          case _ =>
            toolbar.zoomInButton.visible = false
            toolbar.zoomOutButton.visible = false
        }

        //        toolbar.subPanelTools.contents.clear()
        //        currentView match {
        //          case tbi: ToolbarItems =>
        //            println("Switched to viewer with toolbar items")
        //            val tools = tbi.toolbarComponents
        //            val flattened = tools.foldLeft(Seq.empty[Component]) {
        //              (listSoFar, nextGroup) =>
        //                (listSoFar :+ Swing.HStrut(10)) ++ nextGroup.components.toSeq
        //            }
        //            toolbar.subPanelTools.contents ++= flattened
        //          case _ =>
        //        }
        //        toolbar.revalidate()
        refreshToolbar()

        scroller.contents = currentView
        //layout(currentView) = BorderPanel.Position.Center
        layout(scroller) = BorderPanel.Position.Center
        revalidate(); repaint()
        toolbar.displayBox.enabled = true
      }

      case Failure(throwable) =>
        Console.err.println("Debugger error: Failed to build visualization "+key)
        Console.err.println("  "+throwable.getMessage)
        toolbar.displayBox.enabled = true
    }

  }

  /** Used for really lousy flow control. Basically, when it comes time to
    * update the current view, we create a new future with currentView's update
    * method as the body and save a reference to the future here. When that
    * future completes, it sets this reference to null. Thus, as long as this
    * reference is non-null, we know there's a currently running update op
    * in the background and we won't issue another. */
  @volatile
  private var currentUpdateOp: Future[Unit] = null

  def updateCurrentView(data: AbstractFieldMemory, step: Long) {
    if (currentView != null && currentUpdateOp == null) {
      //currentView.update(target, newData, step) // old impl, runs on EDT
      currentUpdateOp = scala.concurrent.Future(currentView.update(target, data, step))
      currentUpdateOp.onComplete {
        case Success(_) => currentUpdateOp = null
        case Failure(_) => currentUpdateOp = null
      }
    }
  }

  /** Updates the visualization based on the contents of `data`. */
  def update(newData: AbstractFieldMemory, step: Long) {
    updateCurrentView(newData, step)
    lastData = newData
    lastTime = step
  }

  def update(src: AnyRef, data: AbstractFieldMemory, simTime: Long) {
    update(data, simTime)
  }

  override def zoomIn() {
    currentView match {
      case z: Zoomable => z.zoomIn()
      case _ =>
    }
  }

  override def zoomOut() {
    currentView match {
      case z: Zoomable => z.zoomOut()
      case _ =>
    }
  }

  /** Encode the state of this panel into an XML tag. */
  def save =
  // TODO Copy old saved state, but overwrite with details of current session.
  // Copy saved state of viewers that didn't get instantiated in this
  // session, but did in the last.
    <ViewerSuperPanel>
      <SubPanels>{
        instantiated collect { case restorable: RestorableState => restorable.save }
        }</SubPanels>
    </ViewerSuperPanel>

  protected var savedState: Node = null
  def restore(tag: Node) {
    savedState = (tag \ "ViewerSuperPanel").head
    restoreIfNecessary(currentView)
  }

  /** Restores a viewer if `savedState` is not null and we haven't already
    * called this method for the viewer.
    * @param viewer Target viewer for the saved state restore attempt.
    */
  private def restoreIfNecessary(viewer: Viewer) {
    if (!restored.contains(viewer) && savedState != null) {
      viewer match {
        case restorable: RestorableState =>
          if (Cog.verboseDebugger)
            println("[ViewerSuperPanel] Restoring viewer: "+viewer+" ("+viewer.getClass.getSimpleName+")")
          restorable.restore(savedState \ "SubPanels" head)
        case _ =>
      }
    }
    restored += viewer
  }
}


text:
A little while ago I started putting up some of my math code onto Github which can be found here. Its a small simple math library that I use for my hobby projects (mostly games).

What Is It?

It's a header only math library, that handles most vector, and matrix math. It has other things in it as well. I've been porting it over in small bits as I write tests for those components. Also gives me a chance to add missing functions that should be in a math library but I've not had a need for.

How To Use It?

It's completely function based. And all functions start with the type name to make things like intellisence easier.

vector3 my_position = vector3_init(0,0,0);
vector3 my_velocity = vector3_init(1,0,0);

vector3 my_position = vector3_add(my_position, my_velocity);

Most of it works along those lines.

No SIMD

It's always been one of those things I've meant to add, but usually I find speed up's elsewhere so I use them. Combined with my projects being small scale. However its something I'd like to add after I've finished porting/testing the various components.

What Next

I need to finish Matrix support and I have some other basic geometry math I need to add for a project, I'll add that to the library when I come to that. And hopefully I can get SIMD done stuff at the end of summer.

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>manager</title>
        <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
        <link rel="stylesheet" href="/public/app.css">


text:
@class GenreDefinition;

@interface SFGenre : CollectionWithChildren <SFRootItem, SFDiscoverableItem>

+ (id)keyForGenreName:(NSString *)genreName;

- (id)initWithGenreDefinition:(GenreDefinition *)theGenreDefinition player:(SFNativeMediaPlayer *)thePlayer;

@property (nonatomic, readwrite, assign) CGFloat relativeSize;

- (NSArray *)pushTracksIntoArtistChildren;

@end


text:
local tmr = tmr
local assert = assert
local setmetatable = setmetatable
local TimerId = require('timer-id')

local Package = {}
setmetatable(Package, {__index = tmr})
setfenv(1,Package)

function Package:new(o)
  o = o or {}
  setmetatable(o, self)
  self.__index = self
  return o
end

function Package:alarm(interval, multiple)
  interval = interval or 1
  multiple = multiple or 0
  if self.id == nil then
    self.id = TimerId:pop()
  end
  tmr.alarm(self.id, interval, multiple, function()
    if multiple == 0 then
      self.id = TimerId:push(self.id)
    end
    self.callback(self)
  end)
  return self
end

function Package:stop()
  if self.id ~= nil then
    tmr.stop(self.id)
    self.id = TimerId:push(self.id)
  end
end

function callback()
  assert(false,'callback not defined')
end

return Package


text:
package test;

import javax.inject.Inject;

public class WithInjectedFieldExtended extends WithInjectedField {
    @Inject String field1;
}


text:
#include "mwtypes.h"
#include "windows.h"
#include "wintern.h"
#include "device.h"
#include "wx/msw/microwin.h"

void GdMoveCursor(MWCOORD x, MWCOORD y);
void MwSetCursor(HWND wp, PMWCURSOR pcursor);

BOOL SetCursorPos(int x, int y)
{
    GdMoveCursor(x, y);
    return TRUE;
}

HCURSOR SetCursor(HCURSOR hCursor)
{
    /* TODO */
    return 0;
}

int GetScrollPosWX (HWND hWnd, int iSBar)
{
    int pos = 0;
    if (GetScrollPos(hWnd, iSBar, & pos))
        return pos;
    else
        return 0;
}

BOOL ScrollWindow(HWND hWnd, int xAmount, int yAmount,
                  CONST RECT* lpRect, CONST RECT* lpClipRect)
{
    /* TODO */
    return FALSE;
}

HWND WindowFromPoint(POINT pt)
{
    /* TODO */
    return 0;
}

SHORT GetKeyState(int nVirtKey)
{
    /* TODO */
    return 0;
}

HWND SetParent(HWND hWndChild, HWND hWndNewParent)
{
    /* TODO */
    return 0;
}

VOID DragAcceptFiles(HWND hWnd, BOOL b)
{
    /* TODO */
}

BOOL IsDialogMessage(HWND hWnd, MSG* msg)
{
    /* TODO */
    return FALSE;
}

DWORD GetMessagePos(VOID)
{
    /* TODO */
    return 0;
}

BOOL IsIconic(HWND hWnd)
{
    /* TODO */
    return FALSE;
}

int SetMapMode(HDC hDC, wxMappingMode mode)
{
    return MM_TEXT;
}

wxMappingMode GetMapMode(HDC hDC)
{
    return MM_TEXT;
}

HCURSOR LoadCursor(HINSTANCE hInst, int cursor)
{
    /* TODO */
    return 0;
}

DWORD GetModuleFileName(HINSTANCE hInst, LPSTR name, DWORD sz)
{
    /* TODO */
    name[0] = 0;
    return 0;
}

VOID DestroyIcon(HICON hIcon)
{
    /* TODO */
}

COLORREF GetTextColor(HDC hdc)
{
    if (!hdc)
        return CLR_INVALID;
    return hdc->textcolor ;
}

COLORREF GetBkColor(HDC hdc)
{
    if (!hdc)
        return CLR_INVALID;
    return hdc->bkcolor ;
}

HPALETTE SelectPalette(HDC hdc, HPALETTE hPalette, BOOL b)
{
    /* TODO */
    return 0;
}

BOOL IntersectClipRect(HDC hdc, int x, int y,
                                int right, int bottom)
{
    /* TODO */
    HRGN rgn = CreateRectRgn(x, y, right, bottom);

    BOOL ret = (ExtSelectClipRgn(hdc, rgn, RGN_AND) != ERROR);
    DeleteObject(rgn);
    return ret;
}

BOOL GetClipBox(HDC hdc, RECT* rect)
{
    MWCLIPREGION* r;
    MWRECT mwrect;

    if (!hdc->region)
        return FALSE;

    r = ((MWRGNOBJ*) hdc->region)->rgn;
    GdGetRegionBox(r, & mwrect);
    rect->left = mwrect.left;
    rect->top = mwrect.top;
    rect->right = mwrect.right;
    rect->bottom = mwrect.bottom;

    return TRUE;
}

BOOL DrawIconEx(HDC hdc, int x, int y, HICON hIcon, int w, int h, UINT istepIfAniCur, HBRUSH hbrFlickerFreeDraw, UINT diFlags)
{
    /* TODO */
    return FALSE;
}

BOOL SetViewportExtEx(HDC hdc, int x, int y, LPSIZE lpSize)
{
    /* TODO */
    return FALSE;
}

BOOL SetViewportOrgEx(HDC hdc, int x, int y, LPPOINT lpPoint)
{
    /* TODO */
    return FALSE;
}

BOOL SetWindowExtEx(HDC hdc, int x, int y, LPSIZE lpSize)
{
    /* TODO */
    return FALSE;
}

BOOL SetWindowOrgEx(HDC hdc, int x, int y, LPPOINT lpSize)
{
    /* TODO */
    return FALSE;
}

BOOL ExtFloodFill(HDC hdc, int x, int y, COLORREF col, UINT flags)
{
    /* TODO */
    return FALSE;
}

int SetPolyFillMode(HDC hdc, int mode)
{
    /* TODO */
    return 0;
}

BOOL RoundRect(HDC hdc, int left, int top, int right, int bottom, int r1, int r2)
{
    /* TODO */
    return Rectangle(hdc, left, top, right, bottom);
}

BOOL MaskBlt(HDC hdc, int x, int y, int w, int h,
              HDC hDCSource, int xSrc, int ySrc, HBITMAP hBitmapMask, int xMask, int yMask, DWORD rop)
{
    /* TODO */
    return FALSE;
}

UINT RealizePalette(HDC hDC)
{
    /* TODO */
    return 0;
}

BOOL SetBrushOrgEx(HDC hdc, int xOrigin, int yOrigin, LPPOINT lpPoint)
{
    /* TODO */
    return FALSE;
}

int GetObject(HGDIOBJ hObj, int sz, LPVOID logObj)
{
    if (sz == sizeof(LOGFONT))
    {
        LOGFONT* logFont = (LOGFONT*) logObj;
        MWFONTINFO fi;
        HFONT hFont = (HFONT) hObj;

        GdGetFontInfo(((MWFONTOBJ*) hFont)->pfont, &fi);

        /* FIXME many items are guessed for the time being*/
        logFont->lfHeight = fi.height;

        /* reversed for kaffe port
           logFont->tmAscent = fi.height - fi.baseline;
           logFont->tmDescent= fi.baseline;
           */

        logFont->lfWidth = fi.widths['x'];
        logFont->lfWeight = FW_NORMAL;
        logFont->lfEscapement = 0;
        logFont->lfOrientation = 0;
        logFont->lfOutPrecision = OUT_OUTLINE_PRECIS;
        logFont->lfClipPrecision = CLIP_DEFAULT_PRECIS;
        logFont->lfQuality = DEFAULT_QUALITY;
        logFont->lfItalic = 0;
        logFont->lfUnderline = 0;
        logFont->lfStrikeOut = 0;
        /* note that win32 has the TMPF_FIXED_PITCH flags REVERSED...*/
        logFont->lfPitchAndFamily = fi.fixed?
            FF_DONTCARE: (FF_DONTCARE | TMPF_FIXED_PITCH);
        logFont->lfCharSet = OEM_CHARSET;
        /* TODO I don't know how to get the font name. May
         * test for different font classes.
         */
        logFont->lfFaceName[0] = 0;
#if 0
        strncpy(logFont->lfFaceName, ??, sizeof(logFont->lfFaceName));
#endif
        return sz;
    }
    else
    {
        return 0;
    }
}

/* Not in wingdi.c in earlier versions of MicroWindows */
#if 0
HBITMAP WINAPI
CreateCompatibleBitmap(HDC hdc, int nWidth, int nHeight)
{
    MWBITMAPOBJ *hbitmap;
    int size;
    int linelen;

    if(!hdc)
        return NULL;

    nWidth = MWMAX(nWidth, 1);
    nHeight = MWMAX(nHeight, 1);

    /* calc memory allocation size and linelen from width and height*/
    if(!GdCalcMemGCAlloc(hdc->psd, nWidth, nHeight, 0, 0, &size, &linelen))
        return NULL;

    /* allocate gdi object*/
    hbitmap = (MWBITMAPOBJ *)GdItemAlloc(sizeof(MWBITMAPOBJ)-1+size);
    if(!hbitmap)
        return NULL;
    hbitmap->hdr.type = OBJ_BITMAP;
    hbitmap->hdr.stockobj = FALSE;
    hbitmap->width = nWidth;
    hbitmap->height = nHeight;

    /* create compatible with hdc*/
    hbitmap->planes = hdc->psd->planes;
    hbitmap->bpp = hdc->psd->bpp;
    hbitmap->linelen = linelen;
    hbitmap->size = size;

    return (HBRUSH)hbitmap;
}
#endif

/* Attempt by JACS to create arbitrary bitmap
 * TODO: make use of lpData
 */

HBITMAP WINAPI
CreateBitmap( int nWidth, int nHeight, int nPlanes, int bPP, LPCVOID lpData)
{
    MWBITMAPOBJ *hbitmap;
    int size;
    int linelen;

    HDC hScreenDC;

    hScreenDC = GetDC(NULL);

    nWidth = MWMAX(nWidth, 1);
    nHeight = MWMAX(nHeight, 1);

    /* calc memory allocation size and linelen from width and height*/
    if(!GdCalcMemGCAlloc(hScreenDC->psd, nWidth, nHeight, nPlanes, bPP, &size, &linelen))
    {
        ReleaseDC(NULL, hScreenDC);
        return NULL;
    }
    ReleaseDC(NULL, hScreenDC);

    /* allocate gdi object*/
    hbitmap = (MWBITMAPOBJ *)GdItemAlloc(sizeof(MWBITMAPOBJ)-1+size);
    if(!hbitmap)
        return NULL;
    hbitmap->hdr.type = OBJ_BITMAP;
    hbitmap->hdr.stockobj = FALSE;
    hbitmap->width = nWidth;
    hbitmap->height = nHeight;

    /* create with specified parameters */
    hbitmap->planes = nPlanes;
    hbitmap->bpp = bPP;
    hbitmap->linelen = linelen;
    hbitmap->size = size;

    /* TODO: copy data */

    return (HBRUSH)hbitmap;
}


text:
Markitup::Rails::Engine.routes.draw do
  post "preview", to: "preview#preview", as: "preview"
end


text:
var APP = APP || {};

function extend(destination, source) {
    var toString = Object.prototype.toString,
        objTest = toString.call({});
    for (var property in source) {
        if (source[property] && objTest == toString.call(source[property])) {
            destination[property] = destination[property] || {};
            extend(destination[property], source[property]);
        } else {
            destination[property] = source[property];
        }
    }
    return destination;
};

extend(APP, {
  locationsMap:{
    init: function(){

      this.createMap();

    },

    createMap: function(){
      var position = {lat: $('#event-map').data('position-lat'), lng: $('#event-map').data('position-lng')};
      var map = new google.maps.Map(document.getElementById("event-map"), {
          zoom: 13,
          center: position
        });
      var markers = [];
      var markerBounds = new google.maps.LatLngBounds();
      var infoWindows = [];
      var infowindow = new google.maps.InfoWindow({
        content: 'contentString'
      });

      var marker = new google.maps.Marker({
       map: map,
       title: 'Uluru (Ayers Rock)',
       position: position
      });

        marker.addListener('click', function() {
          // infowindow.open(map, marker);
        });
     map.setCenter(marker.getPosition());

    }
  }
});

jQuery(document).ready(function($) {
	$(document).foundation();
	APP.locationsMap.init();
});


text:
package cmd

import (
	"testing"

	"github.com/Masterminds/cookoo"
)

var yamlFile = `
package: fake/testing
import:
  - package: github.com/kylelemons/go-gypsy
    subpackages: yaml
  - package: github.com/technosophos/structable
  # Intentionally left spaces at end of next line.
  - package: github.com/Masterminds/convert
    repo: git@github.com:Masterminds/convert.git
    ref: a9949121a2e2192ca92fa6dddfeaaa4a4412d955
    subpackages:
      - color
      - nautical
      - radial
    os: linux
    arch:
      - i386
      - arm

devimport:
  - package: github.com/kylelemons/go-gypsy
`

func TestFromYaml(t *testing.T) {
	reg, router, cxt := cookoo.Cookoo()

	reg.Route("t", "Testing").
		Does(ParseYamlString, "cfg").Using("yaml").WithDefault(yamlFile)

	if err := router.HandleRequest("t", cxt, false); err != nil {
		t.Errorf("Failed to parse YAML: %s", err)
	}

	cfg := cxt.Get("cfg", nil).(*Config)
	if cfg.Name != "fake/testing" {
		t.Errorf("Expected name to be 'fake/teting', not '%s'", cfg.Name)
	}

	if len(cfg.Imports) != 3 {
		t.Errorf("Expected 3 imports, got %d", len(cfg.Imports))
	}

	imp := cfg.Imports[2]
	if imp.Name != "github.com/Masterminds/convert" {
		t.Errorf("Expected the convert package, got %s", imp.Name)
	}

	if len(imp.Subpackages) != 3 {
		t.Errorf("Expected 3 subpackages. got %d", len(imp.Subpackages))
	}

	if imp.Subpackages[0] != "color" {
		t.Errorf("Expected first subpackage to be 'color', got '%s'", imp.Subpackages[0])
	}

	if len(imp.Os) != 1 {
		t.Errorf("Expected Os: SOMETHING")
	} else if imp.Os[0] != "linux" {
		t.Errorf("Expected Os: linux")
	}

	if len(imp.Arch) != 2 {
		t.Error("Expected two Archs.")
	} else if imp.Arch[0] != "i386" {
		t.Errorf("Expected arch 1 to be i386, got %s.", imp.Arch[0])
	} else if imp.Arch[1] != "arm" {
		t.Error("Expected arch 2 to be arm.")
	}

	if imp.Repository != "git@github.com:Masterminds/convert.git" {
		t.Errorf("Got wrong repo")
	}
	if imp.Reference != "a9949121a2e2192ca92fa6dddfeaaa4a4412d955" {
		t.Errorf("Got wrong reference.")
	}

	if len(cfg.DevImports) != 1 {
		t.Errorf("Expected one dev import.")
	}

}


text:
package me.yanaga.querydsl.args.core.single;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.core.types.dsl.TemporalExpression;

import java.time.format.DateTimeFormatter;
import java.util.function.BiFunction;

public abstract class AbstractTemporalArgument<T extends TemporalExpression<V>, V extends Comparable<?>>
        extends AbstractSingleArgument<T, V> {

    protected AbstractTemporalArgument(V value) {
        super(value);
    }

    @SafeVarargs
    @Override
    public final void append(BooleanBuilder builder, BiFunction<T, V, BooleanExpression> operation, T path, T... paths) {
        super.append(builder, operation, path, paths);
    }

    @SafeVarargs
    @Override
    public final void append(BooleanBuilder builder, T path, T... paths) {
        super.append(builder, path, paths);
    }

    public abstract String format(DateTimeFormatter formatter);

}


text:
'use strict';

import 'vs/css!./codelens';
import {TPromise} from 'vs/base/common/winjs.base';
import {format} from 'vs/base/common/strings';
import * as lifecycle from 'vs/base/common/lifecycle';
import * as schedulers from 'vs/base/common/async';
import Severity from 'vs/base/common/severity';
import * as dom from 'vs/base/browser/dom';
import * as errors from 'vs/base/common/errors';
import * as EditorBrowser from 'vs/editor/browser/editorBrowser';
import * as EditorCommon from 'vs/editor/common/editorCommon';
import * as Modes from 'vs/editor/common/modes';
import {EditorBrowserRegistry} from 'vs/editor/browser/editorBrowserExtensions';
import {IModelService} from 'vs/editor/common/services/modelService';
import {IConfigurationService} from 'vs/platform/configuration/common/configuration';
import {IKeybindingService} from 'vs/platform/keybinding/common/keybindingService';
import {IMessageService} from 'vs/platform/message/common/message';
import {Range} from 'vs/editor/common/core/range';
import {CodeLensRegistry, ICodeLensData, getCodeLensData} from '../common/codelens';

class CodeLensViewZone implements EditorBrowser.IViewZone {

	public afterLineNumber: number;
	public heightInLines: number;
	public suppressMouseDown: boolean;

	public domNode: HTMLElement;

	constructor(afterLineNumber: number) {

		this.afterLineNumber = afterLineNumber;
		this.heightInLines = 1;
		this.suppressMouseDown = true;

		this.domNode = document.createElement('div');
	}

	public setAfterLineNumber(afterLineNumber: number): void {
		this.afterLineNumber = afterLineNumber;
	}
}

class CodeLensContentWidget implements EditorBrowser.IContentWidget {

	private static ID: number = 0;

	private _id: string;

	private _domNode: HTMLElement;
	private _subscription: Function;
	private _symbolRange: EditorCommon.IEditorRange;
	private _widgetPosition: EditorBrowser.IContentWidgetPosition;
	private _editor: EditorBrowser.ICodeEditor;
	private _commands: { [id: string]: Modes.ICommand } = Object.create(null);

	public constructor(editor: EditorBrowser.ICodeEditor, symbolRange: EditorCommon.IEditorRange,
		keybindingService: IKeybindingService, messageService: IMessageService) {

		this._id = 'codeLensWidget' + (++CodeLensContentWidget.ID);
		this._editor = editor;

		this.setSymbolRange(symbolRange);

		this._domNode = document.createElement('span');
		this._domNode.style.height = `${editor.getConfiguration().lineHeight}px`;
		this._domNode.innerHTML = ' ';
		dom.addClass(this._domNode, 'codelens-decoration');
		dom.addClass(this._domNode, 'invisible-cl');
		this._subscription = dom.addListener(this._domNode, 'click', e => {
			let element = <HTMLElement>e.target;
			if (element.tagName === 'A' && element.id) {
				let command = this._commands[element.id];
				if (command) {
					editor.focus();
					keybindingService.executeCommand(command.id, command.arguments).done(undefined, err => {
						messageService.show(Severity.Error, err);
					});
				}
			}
		});

		this.updateVisibility();
	}

	public dispose(): void {
		this._subscription();
		this._symbolRange = null;
	}

	public updateVisibility(): void {
		if (this.isVisible()) {
			dom.removeClass(this._domNode, 'invisible-cl');
			dom.addClass(this._domNode, 'fadein');
		}
	}

	public withCommands(symbols: Modes.ICodeLensSymbol[]): void {
		this._commands = Object.create(null);
		if (!symbols || !symbols.length) {
			this._domNode.innerHTML = 'no commands';
			return;
		}

		let html: string[] = [];
		for (let i = 0; i < symbols.length; i++) {
			let command = symbols[i].command;
			let part: string;
			if (command.id) {
				part = format('{1}', i, command.title);
				this._commands[i] = command;
			} else {
				part = format('{0}', command.title);
			}
			html.push(part);
		}

		this._domNode.innerHTML = html.join(' | ');
		this._editor.layoutContentWidget(this);
	}

	public getId(): string {
		return this._id;
	}

	public getDomNode(): HTMLElement {
		return this._domNode;
	}

	public setSymbolRange(range: EditorCommon.IEditorRange): void {
		this._symbolRange = range;

		const lineNumber = range.startLineNumber;
		const column = this._editor.getModel().getLineFirstNonWhitespaceColumn(lineNumber);
		this._widgetPosition = {
			position: { lineNumber: lineNumber, column: column },
			preference: [EditorBrowser.ContentWidgetPositionPreference.ABOVE]
		};
	}

	public getPosition(): EditorBrowser.IContentWidgetPosition {
		return this._widgetPosition;
	}

	public isVisible(): boolean {
		return this._domNode.hasAttribute('monaco-visible-content-widget');
	}
}

function modelsVersionId(modelService: IModelService, modeId: string): number {
	let result = 1;
	let models = modelService.getModels()
		.filter(model => model.getMode().getId() === modeId)
		.map((model) => {
			return {
				url: model.getAssociatedResource().toString(),
				versionId: model.getVersionId()
			};
		})
		.sort((a, b) => {
			if (a.url  b.url) {
				return 1;
			}
			return 0;
		});

	for (let i = 0; i < models.length; i++) {
		result = (((31 * result) | 0) + models[i].versionId) | 0;
	}

	return result;
}

interface IDecorationIdCallback {
	(decorationId: string): void;
}

class CodeLensHelper {

	private _removeDecorations: string[];
	private _addDecorations: EditorCommon.IModelDeltaDecoration[];
	private _addDecorationsCallbacks: IDecorationIdCallback[];

	constructor() {
		this._removeDecorations = [];
		this._addDecorations = [];
		this._addDecorationsCallbacks = [];
	}

	public addDecoration(decoration: EditorCommon.IModelDeltaDecoration, callback: IDecorationIdCallback): void {
		this._addDecorations.push(decoration);
		this._addDecorationsCallbacks.push(callback);
	}

	public removeDecoration(decorationId: string): void {
		this._removeDecorations.push(decorationId);
	}

	public commit(changeAccessor: EditorCommon.IModelDecorationsChangeAccessor): void {
		var resultingDecorations = changeAccessor.deltaDecorations(this._removeDecorations, this._addDecorations);
		for (let i = 0, len = resultingDecorations.length; i < len; i++) {
			this._addDecorationsCallbacks[i](resultingDecorations[i]);
		}
	}

}

class CodeLens {

	private _viewZone: CodeLensViewZone;
	private _viewZoneId: number;
	private _contentWidget: CodeLensContentWidget;
	private _decorationIds: string[];
	private _data: ICodeLensData[];
	private _editor: EditorBrowser.ICodeEditor;
	private _lastUpdateModelsVersionId: number;

	public constructor(data: ICodeLensData[], editor: EditorBrowser.ICodeEditor,
		helper: CodeLensHelper,
		viewZoneChangeAccessor: EditorBrowser.IViewZoneChangeAccessor,
		keybindingService: IKeybindingService, messageService: IMessageService) {

		this._editor = editor;
		this._data = data;
		this._decorationIds = new Array<string>(this._data.length);

		let range: EditorCommon.IRange;
		this._data.forEach((codeLensData, i) => {

			helper.addDecoration({
				range: codeLensData.symbol.range,
				options: {}
			}, id => this._decorationIds[i] = id);

			// the range contain all lenses on this line
			for (let lensData of this._data) {
				if (!range) {
					range = lensData.symbol.range;
				} else {
					range = Range.plusRange(range, lensData.symbol.range);
				}
			}
		});

		this._viewZone = new CodeLensViewZone(range.startLineNumber - 1);
		this._contentWidget = new CodeLensContentWidget(editor, Range.lift(range), keybindingService, messageService);

		this._viewZoneId = viewZoneChangeAccessor.addZone(this._viewZone);
		this._editor.addContentWidget(this._contentWidget);

		this._lastUpdateModelsVersionId = -1;
	}

	public dispose(helper: CodeLensHelper, viewZoneChangeAccessor: EditorBrowser.IViewZoneChangeAccessor): void {
		while (this._decorationIds.length) {
			helper.removeDecoration(this._decorationIds.pop());
		}
		if (viewZoneChangeAccessor) {
			viewZoneChangeAccessor.removeZone(this._viewZoneId);
		}
		this._editor.removeContentWidget(this._contentWidget);

		this._contentWidget.dispose();
	}

	public isValid(): boolean {
		return this._decorationIds.some(id => {
			let range = this._editor.getModel().getDecorationRange(id);
			return range && !range.isEmpty();
		});
	}

	public updateCodeLensSymbols(data: ICodeLensData[]): void {
		this._data = data;
	}

	public computeIfNecessary(currentModelsVersionId: number, model: EditorCommon.IModel): ICodeLensData[] {
		this._contentWidget.updateVisibility(); // trigger the fade in
		if (!this._contentWidget.isVisible()) {
			return null;
		}

		if (this._lastUpdateModelsVersionId === currentModelsVersionId) {
			return null;
		}

		// Read editor current state
		for (let i = 0; i < this._decorationIds.length; i++) {
			this._data[i].symbol.range = model.getDecorationRange(this._decorationIds[i]);
		}
		return this._data;
	}

	public updateCommands(symbols: Modes.ICodeLensSymbol[], currentModelsVersionId: number): void {
		this._contentWidget.withCommands(symbols);
		this._lastUpdateModelsVersionId = currentModelsVersionId;
	}

	public getLineNumber(): number {
		const range = this._editor.getModel().getDecorationRange(this._decorationIds[0]);
		if (range) {
			return range.startLineNumber;
		}
		return -1;
	}

	public update(viewZoneChangeAccessor: EditorBrowser.IViewZoneChangeAccessor): void {
		if (this.isValid()) {
			const range = this._editor.getModel().getDecorationRange(this._decorationIds[0]);

			this._viewZone.setAfterLineNumber(range.startLineNumber - 1);
			viewZoneChangeAccessor.layoutZone(this._viewZoneId);

			this._contentWidget.setSymbolRange(range);
			this._editor.layoutContentWidget(this._contentWidget);
		}
	}
}

export class CodeLensContribution implements EditorCommon.IEditorContribution {

	public static ID: string = 'css.editor.codeLens';

	private static INSTANCE_COUNT: number = 0;

	private _instanceCount: number;
	private _editor: EditorBrowser.ICodeEditor;
	private _modelService: IModelService;

	private _globalToDispose: lifecycle.IDisposable[];

	private _localToDispose: lifecycle.IDisposable[];
	private _lenses: CodeLens[];
	private _currentFindCodeLensSymbolsPromise: TPromise<ICodeLensData[]>;
	private _modelChangeCounter: number;
	private _configurationService: IConfigurationService;
	private _keybindingService: IKeybindingService;
	private _messageService: IMessageService;
	private _codeLenseDisabledByMode: boolean;

	private _currentFindOccPromise: TPromise<any>;

	constructor(editor: EditorBrowser.ICodeEditor, @IModelService modelService: IModelService,
		@IConfigurationService configurationService: IConfigurationService,
		@IKeybindingService keybindingService: IKeybindingService,
		@IMessageService messageService: IMessageService) {

		this._instanceCount = (++CodeLensContribution.INSTANCE_COUNT);
		this._editor = editor;
		this._modelService = modelService;
		this._configurationService = configurationService;
		this._keybindingService = keybindingService;
		this._messageService = messageService;

		this._globalToDispose = [];
		this._localToDispose = [];
		this._lenses = [];
		this._currentFindCodeLensSymbolsPromise = null;
		this._modelChangeCounter = 0;
		this._codeLenseDisabledByMode = true;

		this._globalToDispose.push(this._editor.addListener2(EditorCommon.EventType.ModelChanged, () => this.onModelChange()));
		this._globalToDispose.push(this._editor.addListener2(EditorCommon.EventType.ModelModeChanged, () => this.onModelChange()));
		this._globalToDispose.push(this._editor.addListener2(EditorCommon.EventType.ModelModeSupportChanged, (e: EditorCommon.IModeSupportChangedEvent) => {
			if (e.codeLensSupport) {
				this.onModelChange();
			}
		}));
		this._globalToDispose.push(this._editor.addListener2(EditorCommon.EventType.ConfigurationChanged, (e: EditorCommon.IConfigurationChangedEvent) => {
			if (e.referenceInfos) {
				this.onModelChange();
			}
		}));
		this._globalToDispose.push(CodeLensRegistry.onDidChange(this.onModelChange, this));
		this.onModelChange();
	}

	public dispose(): void {
		this.localDispose();
		this._globalToDispose = lifecycle.disposeAll(this._globalToDispose);
	}

	private localDispose(): void {
		if (this._currentFindCodeLensSymbolsPromise) {
			this._currentFindCodeLensSymbolsPromise.cancel();
			this._currentFindCodeLensSymbolsPromise = null;
			this._modelChangeCounter++;
		}
		if (this._currentFindOccPromise) {
			this._currentFindOccPromise.cancel();
			this._currentFindOccPromise = null;
		}
		this._localToDispose = lifecycle.disposeAll(this._localToDispose);
	}

	public getId(): string {
		return CodeLensContribution.ID;
	}

	private onModelChange(): void {

		this.localDispose();

		const model = this._editor.getModel();
		if (!model) {
			return;
		}

		if (!this._editor.getConfiguration().referenceInfos) {
			return;
		}

		if (!CodeLensRegistry.has(model)) {
			return;
		}

		const detectVisible = new schedulers.RunOnceScheduler(() => {
			this._onViewportChanged(model.getMode().getId());
		}, 500);
		const scheduler = new schedulers.RunOnceScheduler(() => {
			if (this._currentFindCodeLensSymbolsPromise) {
				this._currentFindCodeLensSymbolsPromise.cancel();
			}

			this._currentFindCodeLensSymbolsPromise = getCodeLensData(model);

			const counterValue = ++this._modelChangeCounter;
			this._currentFindCodeLensSymbolsPromise.then((result) => {
				if (counterValue === this._modelChangeCounter) { // only the last one wins
					this.renderCodeLensSymbols(result);
					detectVisible.schedule();
				}
			}, (error) => {
				errors.onUnexpectedError(error);
			});
		}, 250);
		this._localToDispose.push(scheduler);
		this._localToDispose.push(detectVisible);
		this._localToDispose.push(model.addBulkListener2((events) => {
			let hadChange = false;
			for (let i = 0; i < events.length; i++) {
				const eventType = events[i].getType();
				if (eventType === EditorCommon.EventType.ModelContentChanged) {
					hadChange = true;
					break;
				}
			}
			if (hadChange) {
				this._editor.changeDecorations((changeAccessor) => {
					this._editor.changeViewZones((viewAccessor) => {
						const toDispose: CodeLens[] = [];
						this._lenses.forEach((lens) => {
							if (lens.isValid()) {
								lens.update(viewAccessor);
							} else {
								toDispose.push(lens);
							}
						});

						let helper = new CodeLensHelper();
						toDispose.forEach((l) => {
							l.dispose(helper, viewAccessor);
							this._lenses.splice(this._lenses.indexOf(l), 1);
						});
						helper.commit(changeAccessor);
					});
				});

				// Compute new `visible` code lenses
				detectVisible.schedule();
				// Ask for all references again
				scheduler.schedule();
			}
		}));
		this._localToDispose.push(this._editor.addListener2('scroll', (e) => {
			detectVisible.schedule();
		}));
		this._localToDispose.push({
			dispose: () => {
				if (this._editor.getModel()) {
					this._editor.changeDecorations((changeAccessor) => {
						this._editor.changeViewZones((accessor) => {
							this._disposeAllLenses(changeAccessor, accessor);
						});
					});
				} else {
					// No accessors available
					this._disposeAllLenses(null, null);
				}
			}
		});

		scheduler.schedule();
	}

	private _disposeAllLenses(decChangeAccessor: EditorCommon.IModelDecorationsChangeAccessor, viewZoneChangeAccessor: EditorBrowser.IViewZoneChangeAccessor): void {
		let helper = new CodeLensHelper();
		this._lenses.forEach((lens) => lens.dispose(helper, viewZoneChangeAccessor));
		if (decChangeAccessor) {
			helper.commit(decChangeAccessor);
		}
		this._lenses = [];
	}

	private renderCodeLensSymbols(symbols: ICodeLensData[]): void {
		if (!this._editor.getModel()) {
			return;
		}
		if (!symbols) {
			symbols = [];
		} else {
			symbols = symbols.sort((a, b) => Range.compareRangesUsingStarts(a.symbol.range, b.symbol.range));
		}

		let maxLineNumber = this._editor.getModel().getLineCount();
		let groups: ICodeLensData[][] = [];
		let lastGroup: ICodeLensData[];

		for (let symbol of symbols) {
			let line = symbol.symbol.range.startLineNumber;
			if (line < 1 || line >= maxLineNumber) {
				// invalid code lens
				continue;
			} else if (lastGroup && lastGroup[lastGroup.length - 1].symbol.range.startLineNumber === line) {
				// on same line as previous
				lastGroup.push(symbol);
			} else {
				// on later line as previous
				lastGroup = [symbol];
				groups.push(lastGroup);
			}
		}

		let centeredRange = this._editor.getCenteredRangeInViewport();
		let shouldRestoreCenteredRange = (groups.length !== this._lenses.length);
		this._editor.changeDecorations((changeAccessor) => {
			this._editor.changeViewZones((accessor) => {

				let codeLensIndex = 0, groupsIndex = 0, helper = new CodeLensHelper();

				while (groupsIndex < groups.length && codeLensIndex < this._lenses.length) {

					let symbolsLineNumber = groups[groupsIndex][0].symbol.range.startLineNumber;
					let codeLensLineNumber = this._lenses[codeLensIndex].getLineNumber();

					if (codeLensLineNumber < symbolsLineNumber) {
						this._lenses[codeLensIndex].dispose(helper, accessor);
						this._lenses.splice(codeLensIndex, 1);
					} else if (codeLensLineNumber === symbolsLineNumber) {
						this._lenses[codeLensIndex].updateCodeLensSymbols(groups[groupsIndex]);
						groupsIndex++;
						codeLensIndex++;
					} else {
						this._lenses.splice(codeLensIndex, 0, new CodeLens(groups[groupsIndex], this._editor, helper, accessor, this._keybindingService, this._messageService));
						codeLensIndex++;
						groupsIndex++;
					}
				}

				// Delete extra code lenses
				while (codeLensIndex < this._lenses.length) {
					this._lenses[codeLensIndex].dispose(helper, accessor);
					this._lenses.splice(codeLensIndex, 1);
				}

				// Create extra symbols
				while (groupsIndex < groups.length) {
					this._lenses.push(new CodeLens(groups[groupsIndex], this._editor, helper, accessor, this._keybindingService, this._messageService));
					groupsIndex++;
				}

				helper.commit(changeAccessor);
			});
		});
		if (shouldRestoreCenteredRange) {
			this._editor.revealRangeInCenter(centeredRange);
		}
	}

	private _onViewportChanged(modeId: string): void {
		if (this._currentFindOccPromise) {
			this._currentFindOccPromise.cancel();
			this._currentFindOccPromise = null;
		}

		const model = this._editor.getModel();
		if (!model) {
			return;
		}

		const currentModelsVersionId = modelsVersionId(this._modelService, modeId);

		const toResolve: ICodeLensData[][] = [];
		const lenses: CodeLens[] = [];
		this._lenses.forEach((lens) => {
			const request = lens.computeIfNecessary(currentModelsVersionId, model);
			if (request) {
				toResolve.push(request);
				lenses.push(lens);
			}
		});

		if (toResolve.length === 0) {
			return;
		}

		const resource = model.getAssociatedResource();
		const promises = toResolve.map((request, i) => {

			const resolvedSymbols = new Array<Modes.ICodeLensSymbol>(request.length);
			const promises = request.map((request, i) => {
				return request.support.resolveCodeLensSymbol(resource, request.symbol).then(symbol => {
					resolvedSymbols[i] = symbol;
				});
			});

			return TPromise.join(promises).then(() => {
				lenses[i].updateCommands(resolvedSymbols, currentModelsVersionId);
			})
		});

		this._currentFindOccPromise = TPromise.join(promises).then(() => {
			this._currentFindOccPromise = null;
		});
	}
}

EditorBrowserRegistry.registerEditorContribution(CodeLensContribution);


text:
package org.apache.rocketmq.test.listener;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.apache.rocketmq.client.consumer.listener.MessageListener;
import org.apache.rocketmq.test.clientinterface.MQCollector;
import org.apache.rocketmq.test.util.TestUtil;

public class AbstractListener extends MQCollector implements MessageListener {
    public static Logger logger = Logger.getLogger(AbstractListener.class);
    protected boolean isDebug = false;
    protected String listnerName = null;
    protected Collection<Object> allSendMsgs = null;

    public AbstractListener() {
        super();
    }

    public AbstractListener(String listnerName) {
        super();
        this.listnerName = listnerName;
    }

    public AbstractListener(String originMsgCollector, String msgBodyCollector) {
        super(originMsgCollector, msgBodyCollector);
    }

    public boolean isDebug() {
        return isDebug;
    }

    public void setDebug(boolean debug) {
        isDebug = debug;
    }

    public void waitForMessageConsume(int timeoutMills) {
        TestUtil.waitForMonment(timeoutMills);
    }

    public void stopRecv() {
        super.lockCollectors();
    }

    public Collection<Object> waitForMessageConsume(Collection<Object> allSendMsgs,
        int timeoutMills) {
        this.allSendMsgs = allSendMsgs;
        List<Object> sendMsgs = new ArrayList<Object>();
        sendMsgs.addAll(allSendMsgs);

        long curTime = System.currentTimeMillis();
        while (!sendMsgs.isEmpty()) {
            Iterator<Object> iter = sendMsgs.iterator();
            while (iter.hasNext()) {
                Object msg = iter.next();
                if (msgBodys.getAllData().contains(msg)) {
                    iter.remove();
                }
            }
            if (sendMsgs.isEmpty()) {
                break;
            } else {
                if (System.currentTimeMillis() - curTime >= timeoutMills) {
                    logger.error(String.format("timeout but  [%s]  not recv all send messages!",
                        listnerName));
                    break;
                } else {
                    logger.info(String.format("[%s] still [%s] msg not recv!", listnerName,
                        sendMsgs.size()));
                    TestUtil.waitForMonment(500);
                }
            }
        }

        return sendMsgs;
    }

    public void waitForMessageConsume(Map<Object, Object> sendMsgIndex, int timeoutMills) {
        Collection<Object> notRecvMsgs = waitForMessageConsume(sendMsgIndex.keySet(), timeoutMills);
        for (Object object : notRecvMsgs) {
            logger.info(sendMsgIndex.get(object));
        }
    }
}


text:
#include <cstdio>
#include <cmath>

#pragma GCC diagnostic ignored "-Wmissing-declarations"

// BOUNCING BALL

#if defined(_MSC_VER)
#define DLLEXPORT __declspec(dllexport)
#else
#define DLLEXPORT
#endif

const double m = 1; // ball mass
const double g = 9.8; // gravity
extern "C" DLLEXPORT void ballFExt(double time, unsigned int sizeOfq, double *fExt, unsigned int sizeZ, double* z)
{
  for (unsigned int i = 0; i < sizeOfq; i++)
    fExt[i] = 0.0;

  fExt[0] = -m * g;
}

// BALLBOWL

const double R = 0.5; // ball radius

extern "C" DLLEXPORT void groundFExt(double time, unsigned int sizeOfq, double *fExt, unsigned int sizeZ, double* z)
{
  for (unsigned int i = 0; i < sizeOfq; i++)
    fExt[i] = 0.0;
}

extern "C" DLLEXPORT void h0(unsigned int sizeOfq, double* q, unsigned int sizeOfY, double* y, unsigned int sizeZ, double* z)
{
  double R0 = 0.0;
  y[0] = q[0] + sqrt(R * R - q[1] * q[1]) - R0;
}

extern "C" DLLEXPORT void G0(unsigned int sizeOfq, double* q, unsigned int sizeOfY, double* G, unsigned int sizeZ, double* z)
{
  G[0] = 1.0;
  G[1] = -q[1] / (sqrt(R * R - q[1] * q[1]));
}


text:
#include "unicode/utypes.h"

#if !UCONFIG_NO_BREAK_ITERATION

#include "brkeng.h"
#include "dictbe.h"
#include "unicode/uniset.h"
#include "unicode/chariter.h"
#include "unicode/ubrk.h"
#include "uvector.h"
#include "triedict.h"

U_NAMESPACE_BEGIN

/*
 ******************************************************************
 */

/*DictionaryBreakEngine::DictionaryBreakEngine() {
    fTypes = 0;
}*/

DictionaryBreakEngine::DictionaryBreakEngine(uint32_t breakTypes) {
    fTypes = breakTypes;
}

DictionaryBreakEngine::~DictionaryBreakEngine() {
}

UBool
DictionaryBreakEngine::handles(UChar32 c, int32_t breakType) const {
    return (breakType >= 0 && breakType < 32 && (((uint32_t)1 << breakType) & fTypes)
            && fSet.contains(c));
}

int32_t
DictionaryBreakEngine::findBreaks( UText *text,
                                 int32_t startPos,
                                 int32_t endPos,
                                 UBool reverse,
                                 int32_t breakType,
                                 UStack &foundBreaks ) const {
    int32_t result = 0;

    // Find the span of characters included in the set.
    int32_t start = (int32_t)utext_getNativeIndex(text);
    int32_t current;
    int32_t rangeStart;
    int32_t rangeEnd;
    UChar32 c = utext_current32(text);
    if (reverse) {
        UBool   isDict = fSet.contains(c);
        while((current = (int32_t)utext_getNativeIndex(text)) > startPos && isDict) {
            c = utext_previous32(text);
            isDict = fSet.contains(c);
        }
        rangeStart = (current < startPos) ? startPos : current+(isDict ? 0 : 1);
        rangeEnd = start + 1;
    }
    else {
        while((current = (int32_t)utext_getNativeIndex(text)) < endPos && fSet.contains(c)) {
            utext_next32(text);         // TODO:  recast loop for postincrement
            c = utext_current32(text);
        }
        rangeStart = start;
        rangeEnd = current;
    }
    if (breakType >= 0 && breakType < 32 && (((uint32_t)1 << breakType) & fTypes)) {
        result = divideUpDictionaryRange(text, rangeStart, rangeEnd, foundBreaks);
        utext_setNativeIndex(text, current);
    }

    return result;
}

void
DictionaryBreakEngine::setCharacters( const UnicodeSet &set ) {
    fSet = set;
    // Compact for caching
    fSet.compact();
}

/*void
DictionaryBreakEngine::setBreakTypes( uint32_t breakTypes ) {
    fTypes = breakTypes;
}*/

/*
 ******************************************************************
 */

// Helper class for improving readability of the Thai word break
// algorithm. The implementation is completely inline.

// List size, limited by the maximum number of words in the dictionary
// that form a nested sequence.
#define POSSIBLE_WORD_LIST_MAX 20

class PossibleWord {
 private:
  // list of word candidate lengths, in increasing length order
  int32_t   lengths[POSSIBLE_WORD_LIST_MAX];
  int       count;      // Count of candidates
  int32_t   prefix;     // The longest match with a dictionary word
  int32_t   offset;     // Offset in the text of these candidates
  int       mark;       // The preferred candidate's offset
  int       current;    // The candidate we're currently looking at

 public:
  PossibleWord();
  ~PossibleWord();

  // Fill the list of candidates if needed, select the longest, and return the number found
  int       candidates( UText *text, const TrieWordDictionary *dict, int32_t rangeEnd );

  // Select the currently marked candidate, point after it in the text, and invalidate self
  int32_t   acceptMarked( UText *text );

  // Back up from the current candidate to the next shorter one; return TRUE if that exists
  // and point the text after it
  UBool     backUp( UText *text );

  // Return the longest prefix this candidate location shares with a dictionary word
  int32_t   longestPrefix();

  // Mark the current candidate as the one we like
  void      markCurrent();
};

inline
PossibleWord::PossibleWord() {
    offset = -1;
}

inline
PossibleWord::~PossibleWord() {
}

inline int
PossibleWord::candidates( UText *text, const TrieWordDictionary *dict, int32_t rangeEnd ) {
    // TODO: If getIndex is too slow, use offset < 0 and add discardAll()
    int32_t start = (int32_t)utext_getNativeIndex(text);
    if (start != offset) {
        offset = start;
        prefix = dict->matches(text, rangeEnd-start, lengths, count, sizeof(lengths)/sizeof(lengths[0]));
        // Dictionary leaves text after longest prefix, not longest word. Back up.
        if (count <= 0) {
            utext_setNativeIndex(text, start);
        }
    }
    if (count > 0) {
        utext_setNativeIndex(text, start+lengths[count-1]);
    }
    current = count-1;
    mark = current;
    return count;
}

inline int32_t
PossibleWord::acceptMarked( UText *text ) {
    utext_setNativeIndex(text, offset + lengths[mark]);
    return lengths[mark];
}

inline UBool
PossibleWord::backUp( UText *text ) {
    if (current > 0) {
        utext_setNativeIndex(text, offset + lengths[--current]);
        return TRUE;
    }
    return FALSE;
}

inline int32_t
PossibleWord::longestPrefix() {
    return prefix;
}

inline void
PossibleWord::markCurrent() {
    mark = current;
}

// How many words in a row are "good enough"?
#define THAI_LOOKAHEAD 3

// Will not combine a non-word with a preceding dictionary word longer than this
#define THAI_ROOT_COMBINE_THRESHOLD 3

// Will not combine a non-word that shares at least this much prefix with a
// dictionary word, with a preceding word
#define THAI_PREFIX_COMBINE_THRESHOLD 3

// Ellision character
#define THAI_PAIYANNOI 0x0E2F

// Repeat character
#define THAI_MAIYAMOK 0x0E46

// Minimum word size
#define THAI_MIN_WORD 2

// Minimum number of characters for two words
#define THAI_MIN_WORD_SPAN (THAI_MIN_WORD * 2)

ThaiBreakEngine::ThaiBreakEngine(const TrieWordDictionary *adoptDictionary, UErrorCode &status)
    : DictionaryBreakEngine((1<<UBRK_WORD) | (1<<UBRK_LINE)),
      fDictionary(adoptDictionary)
{
    fThaiWordSet.applyPattern(UNICODE_STRING_SIMPLE("[[:Thai:]&[:LineBreak=SA:]]"), status);
    if (U_SUCCESS(status)) {
        setCharacters(fThaiWordSet);
    }
    fMarkSet.applyPattern(UNICODE_STRING_SIMPLE("[[:Thai:]&[:LineBreak=SA:]&[:M:]]"), status);
    fMarkSet.add(0x0020);
    fEndWordSet = fThaiWordSet;
    fEndWordSet.remove(0x0E31);             // MAI HAN-AKAT
    fEndWordSet.remove(0x0E40, 0x0E44);     // SARA E through SARA AI MAIMALAI
    fBeginWordSet.add(0x0E01, 0x0E2E);      // KO KAI through HO NOKHUK
    fBeginWordSet.add(0x0E40, 0x0E44);      // SARA E through SARA AI MAIMALAI
    fSuffixSet.add(THAI_PAIYANNOI);
    fSuffixSet.add(THAI_MAIYAMOK);

    // Compact for caching.
    fMarkSet.compact();
    fEndWordSet.compact();
    fBeginWordSet.compact();
    fSuffixSet.compact();
}

ThaiBreakEngine::~ThaiBreakEngine() {
    delete fDictionary;
}

int32_t
ThaiBreakEngine::divideUpDictionaryRange( UText *text,
                                                int32_t rangeStart,
                                                int32_t rangeEnd,
                                                UStack &foundBreaks ) const {
    if ((rangeEnd - rangeStart) < THAI_MIN_WORD_SPAN) {
        return 0;       // Not enough characters for two words
    }

    uint32_t wordsFound = 0;
    int32_t wordLength;
    int32_t current;
    UErrorCode status = U_ZERO_ERROR;
    PossibleWord words[THAI_LOOKAHEAD];
    UChar32 uc;

    utext_setNativeIndex(text, rangeStart);

    while (U_SUCCESS(status) && (current = (int32_t)utext_getNativeIndex(text)) < rangeEnd) {
        wordLength = 0;

        // Look for candidate words at the current position
        int candidates = words[wordsFound%THAI_LOOKAHEAD].candidates(text, fDictionary, rangeEnd);

        // If we found exactly one, use that
        if (candidates == 1) {
            wordLength = words[wordsFound%THAI_LOOKAHEAD].acceptMarked(text);
            wordsFound += 1;
        }

        // If there was more than one, see which one can take us forward the most words
        else if (candidates > 1) {
            // If we're already at the end of the range, we're done
            if ((int32_t)utext_getNativeIndex(text) >= rangeEnd) {
                goto foundBest;
            }
            do {
                int wordsMatched = 1;
                if (words[(wordsFound+1)%THAI_LOOKAHEAD].candidates(text, fDictionary, rangeEnd) > 0) {
                    if (wordsMatched < 2) {
                        // Followed by another dictionary word; mark first word as a good candidate
                        words[wordsFound%THAI_LOOKAHEAD].markCurrent();
                        wordsMatched = 2;
                    }

                    // If we're already at the end of the range, we're done
                    if ((int32_t)utext_getNativeIndex(text) >= rangeEnd) {
                        goto foundBest;
                    }

                    // See if any of the possible second words is followed by a third word
                    do {
                        // If we find a third word, stop right away
                        if (words[(wordsFound+2)%THAI_LOOKAHEAD].candidates(text, fDictionary, rangeEnd)) {
                            words[wordsFound%THAI_LOOKAHEAD].markCurrent();
                            goto foundBest;
                        }
                    }
                    while (words[(wordsFound+1)%THAI_LOOKAHEAD].backUp(text));
                }
            }
            while (words[wordsFound%THAI_LOOKAHEAD].backUp(text));
foundBest:
            wordLength = words[wordsFound%THAI_LOOKAHEAD].acceptMarked(text);
            wordsFound += 1;
        }

        // We come here after having either found a word or not. We look ahead to the
        // next word. If it's not a dictionary word, we will combine it withe the word we
        // just found (if there is one), but only if the preceding word does not exceed
        // the threshold.
        // The text iterator should now be positioned at the end of the word we found.
        if ((int32_t)utext_getNativeIndex(text) < rangeEnd && wordLength < THAI_ROOT_COMBINE_THRESHOLD) {
            // if it is a dictionary word, do nothing. If it isn't, then if there is
            // no preceding word, or the non-word shares less than the minimum threshold
            // of characters with a dictionary word, then scan to resynchronize
            if (words[wordsFound%THAI_LOOKAHEAD].candidates(text, fDictionary, rangeEnd) <= 0
                  && (wordLength == 0
                      || words[wordsFound%THAI_LOOKAHEAD].longestPrefix() < THAI_PREFIX_COMBINE_THRESHOLD)) {
                // Look for a plausible word boundary
                //TODO: This section will need a rework for UText.
                int32_t remaining = rangeEnd - (current+wordLength);
                UChar32 pc = utext_current32(text);
                int32_t chars = 0;
                for (;;) {
                    utext_next32(text);
                    uc = utext_current32(text);
                    // TODO: Here we're counting on the fact that the SA languages are all
                    // in the BMP. This should get fixed with the UText rework.
                    chars += 1;
                    if (--remaining <= 0) {
                        break;
                    }
                    if (fEndWordSet.contains(pc) && fBeginWordSet.contains(uc)) {
                        // Maybe. See if it's in the dictionary.
                        // NOTE: In the original Apple code, checked that the next
                        // two characters after uc were not 0x0E4C THANTHAKHAT before
                        // checking the dictionary. That is just a performance filter,
                        // but it's not clear it's faster than checking the trie.
                        int candidates = words[(wordsFound+1)%THAI_LOOKAHEAD].candidates(text, fDictionary, rangeEnd);
                        utext_setNativeIndex(text, current+wordLength+chars);
                        if (candidates > 0) {
                            break;
                        }
                    }
                    pc = uc;
                }

                // Bump the word count if there wasn't already one
                if (wordLength <= 0) {
                    wordsFound += 1;
                }

                // Update the length with the passed-over characters
                wordLength += chars;
            }
            else {
                // Back up to where we were for next iteration
                utext_setNativeIndex(text, current+wordLength);
            }
        }

        // Never stop before a combining mark.
        int32_t currPos;
        while ((currPos = (int32_t)utext_getNativeIndex(text)) < rangeEnd && fMarkSet.contains(utext_current32(text))) {
            utext_next32(text);
            wordLength += (int32_t)utext_getNativeIndex(text) - currPos;
        }

        // Look ahead for possible suffixes if a dictionary word does not follow.
        // We do this in code rather than using a rule so that the heuristic
        // resynch continues to function. For example, one of the suffix characters
        // could be a typo in the middle of a word.
        if ((int32_t)utext_getNativeIndex(text) < rangeEnd && wordLength > 0) {
            if (words[wordsFound%THAI_LOOKAHEAD].candidates(text, fDictionary, rangeEnd) <= 0
                && fSuffixSet.contains(uc = utext_current32(text))) {
                if (uc == THAI_PAIYANNOI) {
                    if (!fSuffixSet.contains(utext_previous32(text))) {
                        // Skip over previous end and PAIYANNOI
                        utext_next32(text);
                        utext_next32(text);
                        wordLength += 1;            // Add PAIYANNOI to word
                        uc = utext_current32(text);     // Fetch next character
                    }
                    else {
                        // Restore prior position
                        utext_next32(text);
                    }
                }
                if (uc == THAI_MAIYAMOK) {
                    if (utext_previous32(text) != THAI_MAIYAMOK) {
                        // Skip over previous end and MAIYAMOK
                        utext_next32(text);
                        utext_next32(text);
                        wordLength += 1;            // Add MAIYAMOK to word
                    }
                    else {
                        // Restore prior position
                        utext_next32(text);
                    }
                }
            }
            else {
                utext_setNativeIndex(text, current+wordLength);
            }
        }

        // Did we find a word on this iteration? If so, push it on the break stack
        if (wordLength > 0) {
            foundBreaks.push((current+wordLength), status);
        }
    }

    // Don't return a break for the end of the dictionary range if there is one there.
    if (foundBreaks.peeki() >= rangeEnd) {
        (void) foundBreaks.popi();
        wordsFound -= 1;
    }

    return wordsFound;
}

U_NAMESPACE_END

#endif /* #if !UCONFIG_NO_BREAK_ITERATION */


text:
ACCEPTED

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

#### Published in
null

#### Original name
Haworthia venusta C.L.Scott

### Remarks
null


text:
var Nightmare = require('nightmare');
var Promise = require("bluebird");
let cheerio = require("cheerio");
let moment = require("moment");
var config = require('config');
var proxM = require('./getProxyIps')

let baseurl = 'http://www.anglia-live.com/products/batteries-accessories/batteries/ic-batteries-memory-backup';

// http://rightic.cn/search#/part=2222

module.exports.crawler = async function(q) {
    ////////////////////////////////////start module

    console.log('anglialist url =' + q.keyword);
    if (!(typeof q.keyword !== 'undefined' && q.keyword)) {
        console.log('q.keyword undefined...' + q.keyword);
        return undefined;
    }

    var data = await getByKeyword(q.keyword);
    //console.log('Final round ===crawler result =====' + JSON.stringify(data));
    return await data;
    ///////////////////////////////////before module
}

async function getPage( html) {

    let $ = await cheerio.load(html);

    let ipages = 0
    let pages = $('span#ucProductList_lblrecordcount').text();
    pages = pages.substr(pages.indexOf('of') + 2).trim().replace(/\s+/g, "").replace(/\r\n|\n/g, "");

    console.log("get final pages " + pages);
    if (pages == "") {
        pages = 0;
    } else {
        pages = Number.parseInt(pages);
    }
    if (isNaN(pages) || !isFinite(pages)) {
        console.log("pages is Nan or finite.")
        stockn = 0;
    }

    //computer pages number per page 20 default
    if (pages < 20) {
      pages = 0
    } else if (pages == 20) {
      pages = 1
    } else {
      if (pages %20 ==0) {
        pages = Number.parseInt(pages / 20)
      }else {
        pages = Number.parseInt(pages / 20 ) + 1
      }
    }

    return pages;
}

async function getByKeyword(keyword) {

    let result = { status: 1, keyword: keyword };
    //try{
    var startT = moment().unix();
    var durT = 0;
    console.log("Now start nightmare time is" + startT);

    var nightmare = {};
    //get proxy ip from daxiang.

    var proxyIp = await proxM.getProxyIps();

    if (!proxyIp.found) {
        console.log('get da xiang proxy ip error\n');
        proxyIp.proxyip = undefined;
    } else {
      console.log('get daxing proxy ip=' + proxyIp.proxyip.toString());
    }

    ///useing da xing proxy ip
    /*
    nightmare = Nightmare({
        switches: {
            // 'proxy-server': '10.8.11.240:8100' // set the proxy server here ...
            //'proxy-server': proxyIp // set the proxy server here ...
            'proxy-server': await proxyIp.proxyip // set the proxy server here ...
        },
        loadTimeout: 80000,
        webPreferences: {
            images: false,
            webSecurity: false
        },
        show: false
    });
    */

    //not using da xiang proxy ip
    console.log("Debug mode not undefinedneed proxy.")
    nightmare = Nightmare({waitTimeout: 8000, show: false });

    nightmare = Nightmare({
        switches: {
            // 'proxy-server': '10.8.11.240:8100' // set the proxy server here ...
            //'proxy-server': proxyIp // set the proxy server here ...
            // 'proxy-server': proxyIp.proxyip // set the proxy server here ...
            //'proxy-server': proxyIp.proxyip.toString() // set the proxy server here ...
        },
        webPreferences: {
            images: false
        },
        waitTimeout: 8000,
        show: false
    });

    var url = keyword;
    //anglia-live only crawler detail page use xvfb nightmare crawler all with different node adn proxy ip distrubte cluster
    // var url = baseurl ;

    await nightmare
        .useragent('Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36')
        .goto(url)
        .wait('#ucProductList_pnlResults table#ucProductList_tbltop ul.product-list.products-plain > li')
        //.wait(1000)
        .evaluate(function() {
            return document.querySelector('tr#ucProductList_trtoppages ').innerHTML;
        })
        .end()
        .then(async(html) => {
            //console.log('get html=============== html =' + html);
            durT = moment().unix() - startT;
            console.log("get rows spendxxx" + durT);

            await getPage(html)
                .then(data => {
                    durT = moment().unix() - startT;
                    console.log("nightmare request after parset Html Rows. spendxxx" + durT);
                    // console.log("FFFFFFFFFFFFinall after paserHtml content ===" + JSON.stringify(data));

                    //console.log("nightmare request spendxxx")
                    result.status = 0;
                    result.pages = data;
                    return result;
                });

        }).catch((e) => {
            console.error(e);
        });

    //   }catch(e) {
    //       console.error(e);
    //       return {status: 1, keyword: keyword, data: undefined};
    //   }

    // console.log("====================after await get result=" + JSON.stringify(result));

    durT = moment().unix() - startT;
    console.log("nightmare request spendxxx" + durT);
    return await result;

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class portfolio : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Master.pageTitle = "Portfolio";
        Master.bgImg = "portfolio-bg.jpg";
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="JavaScriptLibraryMappings">
    <file url="file://$PROJECT_DIR$" libraries="{kongtech node_modules}" />
    <includedPredefinedLibrary name="ECMAScript 6" />
  </component>
</project>


text:
#import "UICollectionViewTransitionLayout.h"

@class PUCollectionViewLayoutCache;

@interface PUStackedAlbumTransitionLayout : UICollectionViewTransitionLayout
{
    struct CGPoint _expandedStackDelta;
    _Bool _didPrepareLayout;
    PUCollectionViewLayoutCache *_currentLayoutCache;
    PUCollectionViewLayoutCache *_nextLayoutCache;
    _Bool _isExpanding;
    struct CGPoint _expandedStackFinalDelta;
    struct CGPoint _interactionOffset;
    struct CGPoint _initialCollapsedStackCenter;
    struct CGPoint _finalCollapsedStackCenter;
    struct CGPoint _currentCollapsedStackCenter;
}

@property(nonatomic) struct CGPoint currentCollapsedStackCenter; // @synthesize currentCollapsedStackCenter=_currentCollapsedStackCenter;
@property(nonatomic) struct CGPoint finalCollapsedStackCenter; // @synthesize finalCollapsedStackCenter=_finalCollapsedStackCenter;
@property(nonatomic) struct CGPoint initialCollapsedStackCenter; // @synthesize initialCollapsedStackCenter=_initialCollapsedStackCenter;
@property(nonatomic) struct CGPoint interactionOffset; // @synthesize interactionOffset=_interactionOffset;
@property(readonly, nonatomic) struct CGPoint expandedStackFinalDelta; // @synthesize expandedStackFinalDelta=_expandedStackFinalDelta;
@property(readonly, nonatomic) _Bool isExpanding; // @synthesize isExpanding=_isExpanding;
- (void).cxx_destruct;
- (id)layoutAttributesForDecorationViewOfKind:(id)arg1 atIndexPath:(id)arg2;
- (id)layoutAttributesForSupplementaryViewOfKind:(id)arg1 atIndexPath:(id)arg2;
- (id)layoutAttributesForItemAtIndexPath:(id)arg1;
- (id)layoutAttributesForElementsInRect:(struct CGRect)arg1;
- (void)prepareLayout;
- (struct CGPoint)_centerOfLayoutAttributes:(id)arg1;
- (struct CGPoint)_newCenterForLayoutAttributes:(id)arg1 transitionProgress:(double)arg2;
- (id)initWithCurrentLayout:(id)arg1 nextLayout:(id)arg2 isExpanding:(_Bool)arg3;

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
	<import resource="classpath:content-inspector-context.xml"/>
	<import resource="classpath:content-cache-context.xml"/>

	<bean id="contentProvider" class="org.contentment.content.provider.DiskContentProvider">
		<property name="metaDataReader" ref="metaDataReader"></property>
		<property name="cacheManager" ref="cacheManager"></property>
	</bean>

</beans>


text:
#ifndef TIME_HPP_
#define TIME_HPP_

#include <stdint.h>

#include <sys/time.h>

/**
 * This method returns the current timestamp in miniseconds.
 *
 * @returns Current timestamp in miniseconds.
 *
 */
inline uint64_t GetNow(void) {
    timeval now;

    gettimeofday(&now, NULL);
    return now.tv_sec * 1000 + now.tv_usec / 1000;
}

#endif // TIME_HPP_


text:
from lascaux import Controller

class Index(Controller):

    def get(self, p, place=None):
        # self.render('index', message=u"Hello World")
        # self.final('index', app_package=True)
        self.save("""
            <form method="post" enctype="multipart/form-data">
                <input type="text" />
                <input type="file" name="file" />
                <input type="submit" />
            </form>
        """)


text:
describe MiqAeClassCopy do
  before do
    @src_domain  = 'SPEC_DOMAIN'
    @dest_domain = 'FRED'
    @src_ns      = 'NS1'
    @dest_ns     = 'NS1'
    @src_class   = 'CLASS1'
    @dest_class  = 'CLASS1'
    @src_fqname  = "#{@src_domain}/#{@src_ns}/#{@src_class}"
    @yaml_file   = File.join(File.dirname(__FILE__), 'miq_ae_copy_data', 'class_copy1.yaml')
    MiqAeDatastore.reset
    EvmSpecHelper.import_yaml_model_from_file(@yaml_file, @src_domain)
  end

  context "clone the class to a new domain" do
    before do
      @ns1 = MiqAeNamespace.find_by_fqname("#{@src_domain}/#{@src_ns}", false)
    end

    it "after copy both classes in DB should be congruent" do
      class1 = MiqAeClass.find_by_namespace_id_and_name(@ns1.id, @src_class)
      class2 = MiqAeClassCopy.new(@src_fqname).to_domain(@dest_domain)
      class_check_status(class1, class2, MiqAeClassCompareFields::CONGRUENT_SCHEMA)
      @ns2 = MiqAeNamespace.find_by_fqname("#{@dest_domain}/#{@src_ns}", false)
      class2 = MiqAeClass.find_by_namespace_id_and_name(@ns2.id, @src_class)
      expect(class2).not_to be_nil
    end
  end

  context "clone the class to a new domain with a different namespace" do
    before do
      @ns1 = MiqAeNamespace.find_by_fqname("#{@src_domain}/#{@src_ns}", false)
    end

    it "after copy both classes in DB should be congruent" do
      class1 = MiqAeClass.find_by_namespace_id_and_name(@ns1.id, @src_class)
      new_ns   = "NS3/NS4"
      class2 = MiqAeClassCopy.new(@src_fqname).to_domain(@dest_domain, new_ns)
      class_check_status(class1, class2, MiqAeClassCompareFields::CONGRUENT_SCHEMA)
      @ns2 = MiqAeNamespace.find_by_fqname("#{@dest_domain}/#{new_ns}", false)
      class2 = MiqAeClass.find_by_namespace_id_and_name(@ns2.id, @src_class)
      expect(class2).not_to be_nil
    end
  end

  context "copy to a new classname in the same domain" do
    before do
      @ns1 = MiqAeNamespace.find_by_fqname("#{@src_domain}/#{@src_ns}", false)
    end

    it "after copy both classes in DB should be congruent" do
      new_name = "SAME_AS_#{@src_class}"
      class1 = MiqAeClass.find_by_namespace_id_and_name(@ns1.id, @src_class)
      class2 = MiqAeClassCopy.new(@src_fqname).as(new_name)
      class_check_status(class1, class2, MiqAeClassCompareFields::CONGRUENT_SCHEMA)
      class2 = MiqAeClass.find_by_namespace_id_and_name(@ns1.id, new_name)
      expect(class2).not_to be_nil
    end
  end

  context "copy to a existing class in the same domain" do
    before do
      @ns1 = MiqAeNamespace.find_by_fqname("#{@src_domain}/#{@src_ns}", false)
    end

    it "copy should fail with error" do
      expect { MiqAeClassCopy.new(@src_fqname).as(@src_class) }.to raise_error(RuntimeError)
    end
  end

  context "copy to a new class name in the same domain but different namespace" do
    before do
      @ns1 = MiqAeNamespace.find_by_fqname("#{@src_domain}/#{@src_ns}", false)
    end

    it "after copy both classes in DB should be congruent" do
      new_name = "SAME_AS_#{@src_class}"
      new_ns   = "NS3/NS4"
      class1 = MiqAeClass.find_by_namespace_id_and_name(@ns1.id, @src_class)
      class2 = MiqAeClassCopy.new(@src_fqname).as(new_name, new_ns)
      class_check_status(class1, class2, MiqAeClassCompareFields::CONGRUENT_SCHEMA)
      @ns2 = MiqAeNamespace.find_by_fqname("#{@src_domain}/#{new_ns}", false)
      class2 = MiqAeClass.find_by_namespace_id_and_name(@ns2.id, new_name)
      expect(class2).not_to be_nil
    end
  end

  context "copy class onto itself" do
    it "pass in same domain" do
      expect { MiqAeClassCopy.new(@src_fqname).to_domain(@src_domain, nil, true) }.to raise_error(RuntimeError)
    end

    it "pass in same classname" do
      expect { MiqAeClassCopy.new(@src_fqname).as(@src_class, nil, true) }.to raise_error(RuntimeError)
    end
  end

  context 'copy multiple' do
    it 'classes' do
      domain = 'Fred'
      fqname = 'test1'
      ids    = [1, 2, 3]
      miq_ae_class_copy = double(MiqAeClassCopy)
      miq_ae_class = double(MiqAeClass, :id => 1)
      new_ids = [miq_ae_class.id] * ids.length
      expect(miq_ae_class_copy).to receive(:to_domain).with(domain, nil, false).exactly(ids.length).times { miq_ae_class }
      expect(miq_ae_class).to receive(:fqname).with(no_args).exactly(ids.length).times { fqname }
      expect(MiqAeClass).to receive(:find).with(an_instance_of(Fixnum)).exactly(ids.length).times { miq_ae_class }
      expect(MiqAeClassCopy).to receive(:new).with(anything).exactly(ids.length).times { miq_ae_class_copy }
      expect(MiqAeClassCopy.copy_multiple(ids, domain)).to match_array(new_ids)
    end
  end

  def class_check_status(class1, class2, status)
    diff_obj = MiqAeClassCompareFields.new(class1, class2)
    diff_obj.compare
    expect(diff_obj.status).to equal(status)
  end
end


text:
using System.Collections.Specialized;
using System.Net;

namespace SelfishHttp.Params
{
    public interface IParamsParser
    {
        NameValueCollection ParseParams(HttpListenerRequest request);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:compileSdkVersion="28"
    android:compileSdkVersionCodename="9"
    package="org.andstatus.todoagenda.tests">

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="28" />

    <instrumentation
        android:label="Tests for DoTo Agenda"
        android:name="androidx.test.runner.AndroidJUnitRunner"
        android:targetPackage="org.andstatus.todoagenda"
        android:handleProfiling="false"
        android:functionalTest="false">
        <!-- See https://developer.android.com/reference/android/support/test/runner/AndroidJUnitRunner -->
        <meta-data
            android:name="listener"
            android:value="org.andstatus.todoagenda.TestRunListener" />
    </instrumentation>

    <application
        android:debuggable="true">
    </application>
</manifest>


text:
package it.unimi.di.law.bubing.util;

//RELEASE-STATUS: DIST

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet;

import java.io.IOException;
import java.io.StringReader;
import java.net.URI;
import java.util.Random;
import java.util.Set;

import org.apache.http.HttpHost;
import org.apache.http.client.HttpClient;
import org.apache.http.client.RedirectException;
import org.junit.After;
import org.junit.Test;

public class URLRespectsRobotsTest {

	SimpleFixedHttpProxy proxy;

	@After
	public void tearDownProxy() throws InterruptedException, IOException {
		if (proxy != null) proxy.stopService();
	}

	@Test
	public void testDisallowEverytingSync() throws Exception {
		proxy = new SimpleFixedHttpProxy();
		URI robotsURL = URI.create("http://foo.bar/robots.txt");
		proxy.add200(robotsURL, "",
				"# go away\n" +
						"User-agent: *\n" +
						"Disallow: /\n"
				);
		final URI disallowedUri1 = URI.create("http://foo.bar/goo/zoo.html"); // Disallowed
		final URI disallowedUri2 = URI.create("http://foo.bar/gaa.html"); // Disallowed
		final URI disallowedUri3 = URI.create("http://foo.bar/"); // Disallowed
		proxy.start();

		HttpClient httpClient = FetchDataTest.getHttpClient(new HttpHost("localhost", proxy.port()), false);

		FetchData fetchData = new FetchData(Helpers.getTestConfiguration(this));
		fetchData.fetch(robotsURL, httpClient, null, null, true);
		char[][] filter = URLRespectsRobots.parseRobotsResponse(fetchData, "any");
		assertFalse(URLRespectsRobots.apply(filter, disallowedUri1));
		assertFalse(URLRespectsRobots.apply(filter, disallowedUri2));
		assertFalse(URLRespectsRobots.apply(filter, disallowedUri3));
	}

	@Test
	public void testAllowDisallowSync() throws Exception {
		proxy = new SimpleFixedHttpProxy();
		URI robotsURL = URI.create("http://foo.bur/robots.txt");
		proxy.add200(robotsURL, "",
				"# goodguy can do anything\n" +
				"User-agent: goodguy\n" +
				"Disallow: \n\n" +
				"# badguy can do nothing\n" +
				"User-agent: badguy\n" +
				"Disallow: /\n"
		);

		final URI url = URI.create("http://foo.bur/goo/zoo.html"); // Disallowed

		proxy.start();

		HttpClient httpClient = FetchDataTest.getHttpClient(new HttpHost("localhost", proxy.port()), false);

		FetchData fetchData = new FetchData(Helpers.getTestConfiguration(this));
		fetchData.fetch(robotsURL, httpClient, null, null, true);

		assertTrue(URLRespectsRobots.apply(URLRespectsRobots.parseRobotsResponse(fetchData, "goodGuy"), url));
		assertTrue(URLRespectsRobots.apply(URLRespectsRobots.parseRobotsResponse(fetchData, "goodGuy foo"), url));
		assertFalse(URLRespectsRobots.apply(URLRespectsRobots.parseRobotsResponse(fetchData, "badGuy"), url));
		assertFalse(URLRespectsRobots.apply(URLRespectsRobots.parseRobotsResponse(fetchData, "badGuy foo"), url));
	}

	@Test
	public void testAllowOnlySync() throws Exception {
		proxy = new SimpleFixedHttpProxy();
		URI robotsURL = URI.create("http://foo.bor/robots.txt");
		proxy.add200(robotsURL, "",
				"# goodguy can do anything\n" +
				"User-agent: goodguy\n" +
				"Disallow:\n\n" +
				"# every other guy can do nothing\n" +
				"User-agent: *\n" +
				"Disallow: /\n"
		);
		final URI url = URI.create("http://foo.bor/goo/zoo.html"); // Disallowed
		proxy.start();

		HttpClient httpClient = FetchDataTest.getHttpClient(new HttpHost("localhost", proxy.port()), false);

		FetchData fetchData = new FetchData(Helpers.getTestConfiguration(this));
		fetchData.fetch(robotsURL, httpClient, null, null, true);
		assertTrue(URLRespectsRobots.apply(URLRespectsRobots.parseRobotsResponse(fetchData, "goodGuy"), url));
		assertTrue(URLRespectsRobots.apply(URLRespectsRobots.parseRobotsResponse(fetchData, "goodGuy foo"), url));
		assertFalse(URLRespectsRobots.apply(URLRespectsRobots.parseRobotsResponse(fetchData, "badGuy"), url));
		assertFalse(URLRespectsRobots.apply(URLRespectsRobots.parseRobotsResponse(fetchData, "badGuy foo"), url));
	}

	@Test
	public void test4xxSync() throws Exception {
		proxy = new SimpleFixedHttpProxy();
		URI robotsURL = URI.create("http://foo.bor/robots.txt");
		proxy.addNon200(robotsURL, "HTTP/1.1 404 Not Found\n",
				"# goodguy can do anything\n" +
				"User-agent: goodguy\n" +
				"Disallow:\n\n" +
				"# every other guy can do nothing\n" +
				"User-agent: *\n" +
				"Disallow: /\n"
		);
		proxy.start();

		HttpClient httpClient = FetchDataTest.getHttpClient(new HttpHost("localhost", proxy.port()), false);

		FetchData fetchData = new FetchData(Helpers.getTestConfiguration(this));
		fetchData.fetch(robotsURL, httpClient, null, null, true);
		assertEquals(0, URLRespectsRobots.parseRobotsResponse(fetchData, "goodGuy").length);
		assertEquals(0, URLRespectsRobots.parseRobotsResponse(fetchData, "goodGuy foo").length);
	}

	@Test
	public void testComplexSync() throws Exception {
		proxy = new SimpleFixedHttpProxy();
		URI robotsURL = URI.create("http://foo.bor/robots.txt");
		proxy.add200(robotsURL, "",
				"# every other guy can do nothing\n" +
				"User-agent: *\n" +
				"Disallow: /y\n" +
				"Disallow: /a\n" +
				"Disallow: /c/d\n" +
				"Disallow: /e\n"
		);
		proxy.start();

		HttpClient httpClient = FetchDataTest.getHttpClient(new HttpHost("localhost", proxy.port()), false);

		FetchData fetchData = new FetchData(Helpers.getTestConfiguration(this));
		fetchData.fetch(robotsURL, httpClient, null, null, true);
		final char[][] filter = URLRespectsRobots.parseRobotsResponse(fetchData, "goodGuy");
		assertTrue(URLRespectsRobots.apply(filter, URI.create("http://foo.bor/c")));
		assertTrue(URLRespectsRobots.apply(filter, URI.create("http://foo.bor/d")));
		assertFalse(URLRespectsRobots.apply(filter, URI.create("http://foo.bor/c/d")));
		assertTrue(URLRespectsRobots.apply(filter, URI.create("http://foo.bor/c/e")));
		assertTrue(URLRespectsRobots.apply(filter, URI.create("http://foo.bor/@")));
		assertTrue(URLRespectsRobots.apply(filter, URI.create("http://foo.bor/x")));
		assertTrue(URLRespectsRobots.apply(filter, URI.create("http://foo.bor/z")));
		assertFalse(URLRespectsRobots.apply(filter, URI.create("http://foo.bor/a")));
		assertFalse(URLRespectsRobots.apply(filter, URI.create("http://foo.bor/a/b")));
	}

	@Test
	public void testRedirectSync() throws Exception {
		proxy = new SimpleFixedHttpProxy();
		URI robotsURL0 = URI.create("http://foo.bar/robots.txt");
		URI robotsURL1 = URI.create("http://foo.bar/fubar/robots.txt");

		proxy.addNon200(robotsURL0, "HTTP/1.1 301 Moved Permanently\nLocation: " + robotsURL1 + "\n", "");
		proxy.add200(robotsURL1, "",
				"# goodguy can do anything\n" +
				"User-agent: goodguy\n" +
				"Disallow:\n\n" +
				"# every other guy can do nothing\n" +
				"User-agent: *\n" +
				"Disallow: /\n"
		);
		URI url = URI.create("http://foo.bar/goo/zoo.html"); // Disallowed
		proxy.add200(url, "", "Should not be crawled...");

		proxy.addNon200(URI.create("http://too.many/robots.txt"), "HTTP/1.1 301 Moved Permanently\nLocation: http://too.many/0\n", "");
		for(int i = 0; i < 5; i++) proxy.addNon200(URI.create("http://too.many/" + i), "HTTP/1.1 301 Moved Permanently\nLocation: http://too.many/" + (i + 1) + "\n", "");

		proxy.start();

		HttpClient httpClient = FetchDataTest.getHttpClient(new HttpHost("localhost", proxy.port()), true);

		FetchData fetchData = new FetchData(Helpers.getTestConfiguration(this));

		fetchData.fetch(URI.create(BURL.schemeAndAuthority(url) + "/robots.txt"), httpClient, null, null, true);
		char[][] filter = URLRespectsRobots.parseRobotsResponse(fetchData, "goodGuy");
		assertTrue(URLRespectsRobots.apply(filter, url));
		filter = URLRespectsRobots.parseRobotsResponse(fetchData, "badGuy");
		assertFalse(URLRespectsRobots.apply(filter, url));

		filter = URLRespectsRobots.parseRobotsResponse(fetchData, "goodGuy foo");
		assertTrue(URLRespectsRobots.apply(filter, url));
		filter = URLRespectsRobots.parseRobotsResponse(fetchData, "badGuy foo");
		assertFalse(URLRespectsRobots.apply(filter, url));

		fetchData = new FetchData(Helpers.getTestConfiguration(this));
		fetchData.fetch(URI.create("http://too.many/robots.txt"), httpClient, null, null, true);
		assertTrue(fetchData.exception instanceof RedirectException);

		fetchData.close();
	}

	public void testLiebert() throws IOException {
		char[][] robots;

		robots = URLRespectsRobots.parseRobotsReader(new StringReader("User-agent: *\nDisallow: /\n\nUser-agent: Googlebot\nDisallow: /action\n"), "BUbiNG");
		assertFalse(URLRespectsRobots.apply(robots, URI.create("http://online.liebertpub.com/doi/abs/10.1089/dna.2012.1756")));

		robots = URLRespectsRobots.parseRobotsReader(new StringReader("User-agent: *\nDisallow: /\nDisallow: /action\n"), "BUbiNG");
		assertFalse(URLRespectsRobots.apply(robots, URI.create("http://online.liebertpub.com/doi/abs/10.1089/dna.2012.1756")));
	}

	@Test
	public void testLiebert2() throws IOException {
		char[][] robots = URLRespectsRobots.parseRobotsReader(new StringReader("User-agent: *\nDisallow: /\n\nUser-agent: Googlebot\nDisallow: /action\n"), "BUbiNG");
		assertEquals(1, robots.length);
		assertEquals("/", new String(robots[0]));
	}

	@Test
	public void testPrefixes() throws IOException {
		char[][] robots;

		robots = URLRespectsRobots.parseRobotsReader(new StringReader("User-agent: *\nDisallow: /a\nDisallow: /a/a\nDisallow: /a/a\n"), "BUbiNG");
		assertTrue(URLRespectsRobots.apply(robots, URI.create("http://example.com/")));
		assertFalse(URLRespectsRobots.apply(robots, URI.create("http://example.com/a")));
		assertTrue(URLRespectsRobots.apply(robots, URI.create("http://example.com/b")));
		assertFalse(URLRespectsRobots.apply(robots, URI.create("http://example.com/a/b")));

		robots = URLRespectsRobots.parseRobotsReader(new StringReader("User-agent: *\nDisallow: /a/b\nDisallow: /a\nDisallow: /b/c\nDisallow: /b\n"), "BUbiNG");
		assertTrue(URLRespectsRobots.apply(robots, URI.create("http://example.com/c")));
		assertFalse(URLRespectsRobots.apply(robots, URI.create("http://example.com/a")));
		assertFalse(URLRespectsRobots.apply(robots, URI.create("http://example.com/b")));

		robots = URLRespectsRobots.parseRobotsReader(new StringReader("User-agent: *\nDisallow: /\nUser-agent: foo\nDisallow:\n"), "BUbiNG");
		assertArrayEquals(new char[][] { "/".toCharArray() }, robots);
		assertFalse(URLRespectsRobots.apply(robots, URI.create("http://example.com/")));
	}

	@Test
	public void testDisallowStar() throws IOException{
		char[][] robots;

		robots = URLRespectsRobots.parseRobotsReader(new StringReader("User-agent: *\nDisallow: /*buy_now*\n"), "BUbiNG");
		assertTrue(URLRespectsRobots.apply(robots, URI.create("http://example.com/hi")));
		assertTrue(URLRespectsRobots.apply(robots, URI.create("http://example.com/hi_buy_now")));
		assertTrue(URLRespectsRobots.apply(robots, URI.create("http://example.com/buy_now_hi")));
		assertTrue(URLRespectsRobots.apply(robots, URI.create("http://example.com/buy_now/page")));
		assertTrue(URLRespectsRobots.apply(robots, URI.create("http://example.com/page/buy_now")));
	}

	@Test
	public void testEmptyString() {
		char[][] robots = URLRespectsRobots.toSortedPrefixFreeCharArrays(new ObjectOpenHashSet<>(new String[] { "/", "" }));
		assertArrayEquals(new char[][] {{}}, robots);
		assertFalse(URLRespectsRobots.apply(robots, URI.create("http://example.com/")));
	}

	@Test
	public void testPrefixesDeep() {
		Set<String> inset = new ObjectOpenHashSet<>();
		Set<String> pfset = new ObjectOpenHashSet<>();
		Random rand = new Random(0);
		for (int i = 100; i < 999; i++) {
			if (rand.nextDouble() < 0.3) {
				String commonPref = String.valueOf(i);
				boolean putPrefix = rand.nextDouble() < 0.9;
				if (putPrefix) {
					pfset.add(commonPref);
					inset.add(commonPref);
				}
				for (int j = 100; j < 450; j++) {
					if (rand.nextDouble() < 0.3) {
						inset.add(commonPref + j);
						if (! putPrefix) pfset.add(commonPref + j);
					}
				}
			}
		}
		char[][] resultArray = URLRespectsRobots.toSortedPrefixFreeCharArrays(inset);
		Set<String> result = new ObjectOpenHashSet<>();
		for (char[] a: resultArray) result.add(new String(a));
		assertEquals(result, pfset);

	}

	@Test
	public void testDisallowEverytingWithUTFBOM() throws Exception {
		proxy = new SimpleFixedHttpProxy();
		URI robotsURL = URI.create("http://foo.bar/robots.txt");
		proxy.add200(robotsURL, "",
				"\ufeff"+
						"User-agent: *\n" +
						"Disallow: /\n\n"
				);
		final URI disallowedUri1 = URI.create("http://foo.bar/goo/zoo.html"); // Disallowed
		final URI disallowedUri2 = URI.create("http://foo.bar/gaa.html"); // Disallowed
		final URI disallowedUri3 = URI.create("http://foo.bar/"); // Disallowed
		proxy.start();

		HttpClient httpClient = FetchDataTest.getHttpClient(new HttpHost("localhost", proxy.port()), false);

		FetchData fetchData = new FetchData(Helpers.getTestConfiguration(this));
		fetchData.fetch(robotsURL, httpClient, null, null, true);
		char[][] filter = URLRespectsRobots.parseRobotsResponse(fetchData, "any");
		assertFalse(URLRespectsRobots.apply(filter, disallowedUri1));
		assertFalse(URLRespectsRobots.apply(filter, disallowedUri2));
		assertFalse(URLRespectsRobots.apply(filter, disallowedUri3));
	}

}