text:
package integration.api.json;

import static io.vertx.core.http.HttpHeaders.ACCEPT;
import static io.vertx.core.http.HttpHeaders.CONTENT_TYPE;
import integration.TestVerticle;
import integration.VertxNubesTestBase;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;

import java.util.List;
import java.util.Map;

import mock.domains.Dog;

import org.junit.Test;

public class JsonSyncApiTest extends VertxNubesTestBase {

	@Test
	public void noContentType(TestContext context) {
		Async async = context.async();
		client().getNow("/json/sync/dog", response -> {
			context.assertEquals(406, response.statusCode());
			async.complete();
		});
	}

	@Test
	public void wrongContentType(TestContext context) {
		Async async = context.async();
		client().get("/json/sync/dog", response -> {
			context.assertEquals(406, response.statusCode());
			response.bodyHandler(buff -> {
				context.assertEquals("Not acceptable", buff.toString("UTF-8"));
				async.complete();
			});
		}).putHeader(ACCEPT, "yourmum").end();
	}

	@Test
	public void getJsonObject(TestContext context) {
		Async async = context.async();
		getJSON("/json/sync/jsonobject", response -> {
			context.assertEquals(200, response.statusCode());
			context.assertEquals(response.getHeader(CONTENT_TYPE.toString()), "application/json");
			response.bodyHandler(buffer -> {
				JsonObject json = new JsonObject(buffer.toString("UTF-8"));
				context.assertNotNull(json);
				context.assertEquals(json.getString("Bill"), "Cocker");
				async.complete();
			});

		});
	}

	@Test
	public void getJsonArray(TestContext context) {
		Async async = context.async();
		getJSON("/json/sync/jsonarray", response -> {
			context.assertEquals(200, response.statusCode());
			context.assertEquals(response.getHeader(CONTENT_TYPE.toString()), "application/json");
			response.bodyHandler(buffer -> {
				JsonArray json = new JsonArray(buffer.toString("UTF-8"));
				context.assertNotNull(json);
				context.assertEquals(json.getJsonObject(0).getString("Bill"), "Cocker");
				async.complete();
			});

		});
	}

	@Test
	public void getMap(TestContext context) {
		Async async = context.async();
		getJSON("/json/sync/map", response -> {
			context.assertEquals(200, response.statusCode());
			context.assertEquals(response.getHeader(CONTENT_TYPE.toString()), "application/json");
			response.bodyHandler(buffer -> {
				JsonObject json = new JsonObject(buffer.toString("UTF-8"));
				context.assertNotNull(json);
				context.assertEquals(json.getString("Snoopy"), "Beagle");
				context.assertEquals(json.getString("Bill"), "Cocker");
				async.complete();
			});
		});
	}

	@Test
	@SuppressWarnings("rawtypes")
	public void getArray(TestContext context) {
		Async async = context.async();
		getJSON("/json/sync/array", response -> {
			context.assertEquals(200, response.statusCode());
			context.assertEquals(response.getHeader(CONTENT_TYPE.toString()), "application/json");
			response.bodyHandler(buffer -> {
				JsonArray json = new JsonArray(buffer.toString("UTF-8"));
				context.assertNotNull(json);
				List list = json.getList();
				context.assertEquals(list.get(0), "Snoopy");
				context.assertEquals(list.get(1), "Bill");
				async.complete();
			});
		});
	}

	@Test
	public void getDomainObject(TestContext context) {
		Async async = context.async();
		getJSON("/json/sync/dog", response -> {
			context.assertEquals(200, response.statusCode());
			context.assertEquals(response.getHeader(CONTENT_TYPE.toString()), "application/json");
			response.bodyHandler(buffer -> {
				JsonObject json = new JsonObject(buffer.toString("UTF-8"));
				context.assertNotNull(json);
				context.assertEquals(json.getString("name"), "Snoopy");
				context.assertEquals(json.getString("breed"), "Beagle");
				async.complete();
			});
		});
	}

	@Test
	@SuppressWarnings("rawtypes")
	public void getDomainObjects(TestContext context) {
		Async async = context.async();
		getJSON("/json/sync/dogs", response -> {
			context.assertEquals(200, response.statusCode());
			context.assertEquals("application/json", response.getHeader(CONTENT_TYPE.toString()));
			response.bodyHandler(buffer -> {
				JsonArray json = new JsonArray(buffer.toString("UTF-8"));
				context.assertNotNull(json);
				List list = json.getList();
				context.assertEquals(((Map) list.get(0)).get("name"), "Snoopy");
				context.assertEquals(((Map) list.get(0)).get("breed"), "Beagle");
				context.assertEquals(((Map) list.get(1)).get("name"), "Bill");
				context.assertEquals(((Map) list.get(1)).get("breed"), "Cocker");
				async.complete();
			});
		});
	}

	@Test
	public void postSomeStuff(TestContext context) {
		Dog dog = TestVerticle.dogService.someDog();
		JsonObject dogJson = new JsonObject();
		dogJson.put("name", dog.getName());
		dogJson.put("breed", dog.getBreed());
		Async async = context.async();
		sendJSON("/json/sync/postdog", dogJson, response -> {
			context.assertEquals(200, response.statusCode());
			context.assertEquals("application/json", response.getHeader(CONTENT_TYPE.toString()));
			response.bodyHandler(buffer -> {
				String json = buffer.toString("UTF-8");
				JsonObject receivedDog = new JsonObject(json);
				context.assertEquals(dog.getName(), receivedDog.getString("name"));
				context.assertEquals(dog.getBreed(), receivedDog.getString("breed"));
				async.complete();
			});
		});
	}

	@Test
	public void returnNothing(TestContext context) {
		Async async = context.async();
		getJSON("/json/sync/nothing", response -> {
			context.assertEquals(204, response.statusCode());
			async.complete();
		});
	}
}


text:
package fr.inria.jessy.partitioner;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import net.sourceforge.fractal.membership.Group;
import fr.inria.jessy.communication.JessyGroupManager;
import fr.inria.jessy.store.JessyEntity;
import fr.inria.jessy.store.ReadRequest;

public abstract class Partitioner {

	JessyGroupManager manager;

	public Partitioner(JessyGroupManager m) {
		manager = m;
	}

	public abstract <E extends JessyEntity> Set<Group> resolve(
			ReadRequest<E> readRequest);

	/**
	 * Returns one group that is replicating the given key.
	 * If the key is replicated in several groups, only one of them deterministically sould be returned.
	 *
	 * @param key
	 * @return
	 */
	public abstract Group resolve(String key);

	/**
	 * Returns the list of all groups replicating the given key.
	 * @param key
	 * @return
	 */
	public List<Group> resolveAll(String key) {
		List<Group> result=new ArrayList<Group>();
		result.add(resolve(key));
		return result;
	}

	public abstract boolean isLocal(String k);

	public abstract Set<String> resolveNames(Set<String> keys);

	public abstract Set<String> generateKeysInAllGroups();

	public abstract Set<String> generateLocalKey();
}

redpajama_set_name: RedPajamaGithub


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fpt.qa.mdnlib.mldm.method.gibbslda;

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

import fpt.qa.mdnlib.util.string.StrUtil;

/**
 *
 * @author hieupx
 */
public class NewData {
    public List<Document> docs; /* new data */
    public List<Document> idocs; /* for inference */
    public Map<Integer, Integer> iid2id; /* for inference */
    public Map<Integer, Integer> id2iid; /* for inference */

    public NewData() {
        docs = new ArrayList();
        idocs = new ArrayList();
        iid2id = new HashMap();
        id2iid = new HashMap();
    }

    public void reset() {
        docs.clear();
        idocs.clear();
        iid2id.clear();
        id2iid.clear();
    }

    public int size() {
        return docs.size();
    }

    public Map<Integer, Integer> getIId2IdMap() {
        return iid2id;
    }

    public Map<Integer, Integer> getId2IIdMap() {
        return id2iid;
    }

    public int dictSize() {
        return id2iid.size();
    }

    public boolean readNewData(List<String> documents, Dictionary dict) {
        if (docs.isEmpty()) {
            System.out.println("No documents provided!");
            return false;
        }

        reset(); /* reset variables for storing new data */

        for (int i = 0; i < docs.size(); i++) {
            List<String> tokens = StrUtil.tokenizeStr(documents.get(i));

            if (tokens.isEmpty()) {
                continue;
            }

            List<Integer> tempList1 = new ArrayList();
            List<Integer> tempList2 = new ArrayList();

            int len = tokens.size();
            for (int j = 0; j < len; j++) {
                Integer wordInt = dict.getId(tokens.get(j));

                if (wordInt != null) {
                    Integer iId = id2iid.get(wordInt);

                    if (iId == null) {
                        iId = id2iid.size();
                        id2iid.put(wordInt, iId);
                        iid2id.put(iId, wordInt);
                    }

                    tempList1.add(wordInt);
                    tempList2.add(iId);
                }
            }

            if (tempList1.isEmpty()) {
                continue;
            }

            Document doc = new Document(tempList1);
            Document idoc = new Document(tempList2);

            docs.add(doc);
            idocs.add(idoc);
        }

        return true;
    }

    public boolean readNewData(String dataFile, Dictionary dict) {
        List<String> documents = new ArrayList();
        BufferedReader fin;

        try {
            fin = new BufferedReader(
                    new InputStreamReader(
                    new FileInputStream(dataFile), "UTF8"));

            String line;

            /* read number of docs */
            line = fin.readLine();
            int nDocs = Integer.parseInt(line);

            if (nDocs <= 0) {
                System.out.println("You must specify the number of documents at the top of data file");
                fin.close();
                return false;
            }

            /* read new documents */
            while ((line = fin.readLine()) != null) {
                documents.add(line);
            }

            fin.close();

        } catch (UnsupportedEncodingException ex) {
            System.err.println(ex.toString());
            return false;
        } catch (IOException ex) {
            System.err.println(ex.toString());
            return false;
        }

        return readNewData(documents, dict);
    }
}


text:
#if !defined(Q3_PLAY_MODE_H)
/* ========================================================================
   $File: $
   $Date: $
   $Revision: $
   $Creator: Christopher LaBauve $
   $Notice: $
   ======================================================================== */

enum facing_direction
{
    FacingDirection_Right,
    FacingDirection_Up,
    FacingDirection_Left,
    FacingDirection_Down,
};

enum brain_type
{
    BrainType_None = 1<<0,
    BrainType_Player = 1<<1,
};

enum entity_render_type
{
    EntityRenderType_Thief,
    EntityRenderType_Knight,
    EntityRenderType_Magician,
    EntityRenderType_Demon,
    EntityRenderType_Guard,
    EntityRenderType_Captain,
    EntityRenderType_Terminator,
};

struct entity
{
    brain_type BrainType;
    entity_render_type RenderType;
    collider_type ColliderType;
    v2 P;
    r32 MoveTimer;
    facing_direction Facing;
    facing_direction LastFacing;
};

struct palette_cycle
{
    u32 Count;
    palette *Palettes;
};

struct particle
{
    v3 P;
    v3 dP;
    r32 Yaw;
    r32 dYaw;
    v2 A;
    v2 B;
    v2 C;
    r32 Timer;
    r32 Duration;
    v4 Color;
};

struct play_state
{
    b32 IsInitialized;

    u32 TestPaletteIndex;
    u32 TestColorIndex;

    physics_state PhysicsState;

    b32 Paused;
    s32 Lives;

    u32 EntityCount;
    entity Entities[256];

    u32 ParticleCount;
    particle Particles[256];
};

inline particle *
CreateParticle(play_state *State)
{
    particle *Result = State->Particles;
    if(State->ParticleCount < ArrayCount(State->Particles))
    {
        Result = State->Particles + State->ParticleCount++;
    }
    else
    {
        Assert(!"Created too many particles");
    }
    return(Result);
}

inline void
DestroyParticle(play_state *State, particle *Particle)
{
    *Particle = State->Particles[--State->ParticleCount];
}

inline entity *
CreateEntity(play_state *State)
{
    entity *Result = State->Entities;
    physics_state *PhysicsState = &State->PhysicsState;
    memory_arena *ShapeArena = &PhysicsState->ShapeArena;
    if(State->EntityCount < ArrayCount(State->Entities))
    {
#if 0
        if(HasRoomForArray(ShapeArena, ShapeCount, collision_shape))
        {
#endif
            Result = State->Entities + State->EntityCount++;
            *Result = {};
#if 0
            for(u32 ShapeIndex = 0;
                ShapeIndex < ShapeCount;
                ++ShapeIndex)
            {
                collision_shape *Shape = PhysicsState->FirstFreeShape;
                if(Shape)
                {
                    PhysicsState->FirstFreeShape = Shape->NextFree;
                }
                else
                {
                    Shape = PushStruct(ShapeArena, collision_shape);
                }
                *Shape = *(Shapes + ShapeIndex);
                Shape->Next = Result->CollisionShapes;
                Result->CollisionShapes = Shape;
                Result->CollisionShapeCount = ShapeCount;
            }
            Result->BoundingRadius = CalculateBoundingRadius(Result);
        }
        else
        {
            Assert(!"Created too many collision shapes.");
        }
#endif
    }
    else
    {
        Assert(!"Created too many entities.");
    }
    return(Result);
}

inline void
DestroyEntity(play_state *State, entity *Entity)
{
#if 0
    physics_state *PhysicsState = &State->PhysicsState;
    for(collision_shape *Shape = Entity->CollisionShapes;
        Shape;
        )
    {
        collision_shape *Next = Shape->Next;

        Shape->NextFree = PhysicsState->FirstFreeShape;
        PhysicsState->FirstFreeShape = Shape;

        Shape = Next;
    }
#endif
    *Entity = State->Entities[--State->EntityCount];
}

#if 0
inline b32
IsDestroyed(entity *Entity)
{
    b32 Result = Entity->DestroyedBy;
    return(Result);
}

inline void
SetNotDestroyed(entity *Entity)
{
    Entity->DestroyedBy = (collider_type)0;
}

inline b32
CanCollide(entity *Entity)
{
    b32 Result = !IsDestroyed(Entity) && (Entity->ColliderType != ColliderType_None);
    return(Result);
}

inline b32
CanCollide(play_state *State, entity *A, entity *B)
{
    b32 Result = !IsDestroyed(A) && !IsDestroyed(B) &&
        CanCollide(&State->PhysicsState, A->ColliderType, B->ColliderType);
    return(Result);
}
#endif

#define Q3_PLAY_MODE_H
#endif


text:
using Esri.ArcGISRuntime.Controls;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Layers;
using Esri.ArcGISRuntime.Tasks.Query;
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace ArcGISRuntime.Samples.Desktop
{
    /// <summary>
    /// This sample demonstrates using an QueryTask to Query an ArcGISImageServiceLayer to find the outlines of image tiles and display them in a GraphicOverlay. MapOverlay attribute information is displayed for selected tile graphics when they are clicked on the map.
    /// </summary>
    /// <title>Get Samples</title>
    /// <category>Tasks</category>
    /// <subcategory>Imagery</subcategory>
    public partial class GetSamples : UserControl
    {
		private GraphicsOverlay _graphicsOverlay;
		private FrameworkElement _mapTip;

        /// <summary>Construct Get Image Samples sample control</summary>
        public GetSamples()
        {
            InitializeComponent();
			_graphicsOverlay = MyMapView.GraphicsOverlays["graphicsOverlay"];
			_mapTip = MyMapView.Overlays.Items.First() as FrameworkElement;
            MyMapView.LayerLoaded += MyMapView_LayerLoaded;
        }

        // Zoom to the image service extent
        private async void MyMapView_LayerLoaded(object sender, LayerLoadedEventArgs e)
        {
            if (e.Layer is ArcGISImageServiceLayer)
            {
                if (e.Layer.FullExtent != null)
                    await MyMapView.SetViewAsync(e.Layer.FullExtent);
            }
        }

        // Start query process on user button click
        private async void GetSamplesButton_Click(object sender, RoutedEventArgs e)
        {
            _graphicsOverlay.Graphics.Clear();
			_mapTip.Visibility = System.Windows.Visibility.Collapsed;
			await QueryImageTiles();
        }

        // Query the image service for sample tiles
        private async Task QueryImageTiles()
        {
            try
            {
                var envelope = await MyMapView.Editor.RequestShapeAsync(DrawShape.Envelope) as Envelope;

                QueryTask queryTask = new QueryTask(
					new Uri("http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Portland/Aerial/ImageServer/"));

                Query query = new Query(envelope)
                {
                    OutFields = new OutFields(new string[] { "Name", "LowPS" }),
                    ReturnGeometry = true,
                    OutSpatialReference = MyMapView.SpatialReference,
                    Where = "Category = 1"
                };

                var result = await queryTask.ExecuteAsync(query);

				_graphicsOverlay.Graphics.AddRange(result.FeatureSet.Features.OfType<Graphic>());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Sample Error");
            }
        }

        // Hittest the graphics layer and show the map tip for the selected graphic
        private async void MyMapView_MapViewTapped(object sender, MapViewInputEventArgs e)
        {
            try
            {
				_graphicsOverlay.ClearSelection();

				var graphic = await _graphicsOverlay.HitTestAsync(MyMapView, e.Position);
                if (graphic != null)
                {
                    graphic.IsSelected = true;
					MapView.SetViewOverlayAnchor(mapTip, e.Location);
					_mapTip.DataContext = graphic;
					_mapTip.Visibility = System.Windows.Visibility.Visible;
                }
                else
					_mapTip.Visibility = System.Windows.Visibility.Collapsed;
            }
            catch
            {
				_mapTip.Visibility = System.Windows.Visibility.Collapsed;
            }
        }
    }
}


text:
package ops2015.holyspider.domain;

import java.util.Map;

import ops2015.holyspider.Domain;
import ops2015.holyspider.spi.impl.DefaultFetcher;

/**
 * 页面抓取
 *

 * 通过PageUrlGenerator产生的地址,获取页面的内容,然后使用PageParser解析页面内容生成所有的对象URL
 * 将生成的对象URL加入到Domain的targetUrls中,从而产生某个网站的所有需要获取的对象的地址列表
 *

 * PageFetcher可以多个异步执行,因为PageUrlGenerator总是保持同步的
 *
 * @author wangs
 *
 */
public class DomainPageFetcher extends DefaultFetcher {
	protected Map<String, ?> currentPageArguments = null;
	protected String lastPageUrl = null;

	public DomainPageFetcher(Domain domain) {
		super(domain);
	}

	@Override
	public void fetch() {
		// 获取域的PageUrlGenerator实例

		// 获取所能取到的下个地址
	}

	protected void fetchOne(String url) {
		// 获取地址的页面内容

		// 使用域的PageContentParser实例解析页面内容获得Target的Url列表

		// 将url放入到Domain的TargetUrls中
	}
}


text:
class InitProjectColumns

  def initialize current_user, project
    @project = project
    @current_user = current_user
  end

  attr_reader :project, :current_user
  delegate :columns, to: :project

  def init_columns
    Settings.column_types.each_with_index do |column_type, i|
      create_column(column_type, i).tap do |column|
        init_open_issues column if column.issues_start_here?
        init_closed_issues column if column.closed?
      end
    end
  end

  private

  def init_closed_issues column
    github_issues.select { |i| i[:state] == 'closed'}.each do |issue|
      column.issues.create!(
        project_id: project.id,
        number: issue[:number],
      )
    end
  end

  def init_open_issues column
    open_issues.each do |issue|
      issue_type = IssueTypes::SPEC
      issue_type = IssueTypes::BUG if issue[:labels].any? { |label| label[:name].downcase == 'bug' }
      issue_type = IssueTypes::QUESTION if issue[:labels].any? { |label| label[:name].downcase == 'question' }
      column.issues.create!(
        project_id: project.id,
        number: issue[:number],
        issue_type: issue_type,
      )
    end
  end

  def create_column column_type, ordinal
    columns.create! column_type.merge('ordinal' => ordinal)
  end

  def github_issues
    @github_issues ||= GithubApi.new(current_user.token)
      .get(project.issues_url)
  end

  def closed_issues
    issues_by_state 'closed'
  end

  def open_issues
    issues_by_state 'open'
  end

  def issues_by_state state
    github_issues.select { |i| i[:state] == state }
  end

end


text:
/**
 * @title WET-BOEW Data InView example
 * @overview Handles the Data InView view state change events and updates the status on the page.
 * @license wet-boew.github.io/wet-boew/License-en.html / wet-boew.github.io/wet-boew/Licence-fr.html
 * @author WET Community
 */
(function( $, wb ) {
"use strict";

wb.doc.on( "all.wb-inview partial.wb-inview none.wb-inview", function( event) {
	if ( event.namespace === "wb-inview" ) {
		$( event.target ).find( ".view-state-status" ).html( event.type );
	}
});

})( jQuery, wb );


text:
/*
	Slate by Pixelarity
	pixelarity.com @pixelarity
	License: pixelarity.com/license
*/

var settings = {

	banner: {

		// Indicators (= the clickable dots at the bottom).
			indicators: true,

		// Transition speed (in ms)
		// For timing purposes only. It *must* match the transition speed of "#banner > article".
			speed: 1500,

		// Transition delay (in ms)
			delay: 5000,

		// Parallax intensity (between 0 and 1; higher = more intense, lower = less intense; 0 = off)
			parallax: 0.25

	}

};

(function($) {

	skel.breakpoints({
		xlarge:	'(max-width: 1680px)',
		large:	'(max-width: 1280px)',
		medium:	'(max-width: 980px)',
		small:	'(max-width: 736px)',
		xsmall:	'(max-width: 480px)'
	});

	/**
	 * Applies parallax scrolling to an element's background image.
	 * @return {jQuery} jQuery object.
	 */
	$.fn._parallax = (skel.vars.browser == 'ie' || skel.vars.mobile) ? function() { return $(this) } : function(intensity) {

		var	$window = $(window),
			$this = $(this);

		if (this.length == 0 || intensity === 0)
			return $this;

		if (this.length > 1) {

			for (var i=0; i < this.length; i++)
				$(this[i])._parallax(intensity);

			return $this;

		}

		if (!intensity)
			intensity = 0.25;

		$this.each(function() {

			var $t = $(this),
				on, off;

			on = function() {

				$t.css('background-position', 'center 100%, center 100%, center 0px');

				$window
					.on('scroll._parallax', function() {

						var pos = parseInt($window.scrollTop()) - parseInt($t.position().top);

						$t.css('background-position', 'center ' + (pos * (-1 * intensity)) + 'px');

					});

			};

			off = function() {

				$t
					.css('background-position', '');

				$window
					.off('scroll._parallax');

			};

			skel.on('change', function() {

				if (skel.breakpoint('medium').active)
					(off)();
				else
					(on)();

			});

		});

		$window
			.off('load._parallax resize._parallax')
			.on('load._parallax resize._parallax', function() {
				$window.trigger('scroll');
			});

		return $(this);

	};

	/**
	 * Custom banner slider for Slate.
	 * @return {jQuery} jQuery object.
	 */
	$.fn._slider = function(options) {

		var	$window = $(window),
			$this = $(this);

		if (this.length == 0)
			return $this;

		if (this.length > 1) {

			for (var i=0; i < this.length; i++)
				$(this[i])._slider(options);

			return $this;

		}

		// Vars.
			var	current = 0, pos = 0, lastPos = 0,
				slides = [], indicators = [],
				$indicators,
				$slides = $this.children('article'),
				intervalId,
				isLocked = false,
				i = 0;

		// Turn off indicators if we only have one slide.
			if ($slides.length == 1)
				options.indicators = false;

		// Functions.
			$this._switchTo = function(x, stop) {

				if (isLocked || pos == x)
					return;

				isLocked = true;

				if (stop)
					window.clearInterval(intervalId);

				// Update positions.
					lastPos = pos;
					pos = x;

				// Hide last slide.
					slides[lastPos].removeClass('top');

					if (options.indicators)
						indicators[lastPos].removeClass('visible');

				// Show new slide.
					slides[pos].addClass('visible').addClass('top');

					if (options.indicators)
						indicators[pos].addClass('visible');

				// Finish hiding last slide after a short delay.
					window.setTimeout(function() {

						slides[lastPos].addClass('instant').removeClass('visible');

						window.setTimeout(function() {

							slides[lastPos].removeClass('instant');
							isLocked = false;

						}, 100);

					}, options.speed);

			};

		// Indicators.
			if (options.indicators)
				$indicators = $('

').appendTo($this);

		// Slides.
			$slides
				.each(function() {

					var $slide = $(this),
						$img = $slide.find('img');

					// Slide.
						$slide
							.css('background-image', 'url("' + $img.attr('src') + '")')
							.css('background-position', ($slide.data('position') ? $slide.data('position') : 'center'));

					// Add to slides.
						slides.push($slide);

					// Indicators.
						if (options.indicators) {

							var $indicator_li = $('
' + i + '
').appendTo($indicators);

							// Indicator.
								$indicator_li
									.data('index', i)
									.on('click', function() {
										$this._switchTo($(this).data('index'), true);
									});

							// Add to indicators.
								indicators.push($indicator_li);

						}

					i++;

				})
				._parallax(options.parallax);

		// Initial slide.
			slides[pos].addClass('visible').addClass('top');

			if (options.indicators)
				indicators[pos].addClass('visible');

		// Bail if we only have a single slide.
			if (slides.length == 1)
				return;

		// Main loop.
			intervalId = window.setInterval(function() {

				current++;

				if (current >= slides.length)
					current = 0;

				$this._switchTo(current);

			}, options.delay);

	};

	$(function() {

		var	$window = $(window),
			$body = $('body'),
			$header = $('#header'),
			$banner = $('#banner');

		// Disable animations/transitions until the page has loaded.
			$body.addClass('is-loading');

			$window.on('load', function() {
				window.setTimeout(function() {
					$body.removeClass('is-loading');
				}, 100);
			});

		// Mobile?
			if (skel.vars.mobile)
				$body.addClass('is-mobile');
			else
				skel
					.on('-medium !medium', function() {
						$body.removeClass('is-mobile');
					})
					.on('+medium', function() {
						$body.addClass('is-mobile');
					});

		// Fix: Placeholder polyfill.
			$('form').placeholder();

		// Fix: Post wrapping on IE<10.
			if (skel.vars.IEVersion < 10)
				$('.posts > .post:nth-child(3n + 1)')
					.addClass('first');

		// Prioritize "important" elements on medium.
			skel.on('+medium -medium', function() {
				$.prioritize(
					'.important\\28 medium\\29',
					skel.breakpoint('medium').active
				);
			});

		// Dropdowns.
			$('#nav > ul').dropotron({
				alignment: 'center',
				hideDelay: 400
			});

		// Header.
			if (skel.vars.IEVersion < 9)
				$header.removeClass('alt');

			if ($banner.length > 0
			&&	$header.hasClass('alt')) {

				$window.on('resize', function() { $window.trigger('scroll'); });

				$banner.scrollex({
					bottom:		$header.outerHeight(),
					terminate:	function() { $header.removeClass('alt'); },
					enter:		function() { $header.addClass('alt'); },
					leave:		function() { $header.removeClass('alt'); $header.addClass('reveal'); }
				});

			}

		// Banner.
			$banner._slider(settings.banner);

		// Off-Canvas Navigation.

			// Navigation Panel Toggle.
				$('')
					.appendTo($header);

			// Navigation Panel.
				$(
					'
' +
						'' +
							$('#nav').navList() +
						'' +
						'' +
					'
'
				)
					.appendTo($body)
					.panel({
						delay: 500,
						hideOnClick: true,
						hideOnSwipe: true,
						resetScroll: true,
						resetForms: true,
						side: 'right'
					});

			// Fix: Remove transitions on WP<10 (poor/buggy performance).
				if (skel.vars.os == 'wp' && skel.vars.osVersion < 10)
					$('#navPanel')
						.css('transition', 'none');

	});

})(jQuery);


text:
<?php

class CM_Usertext_Filter_ListReplace extends CM_Usertext_Filter_Abstract {

    /** @var Traversable */
    private $_phrases;

    /** @var string */
    private $_replacementPattern;

    /**
     * @param Traversable $phrases
     * @param string      $replacementPattern
     */
    public function __construct(Traversable $phrases, $replacementPattern) {
        $this->_phrases = $phrases;
        $this->_replacementPattern = (string) $replacementPattern;
    }

    /**
     * @param $text
     * @return string
     */
    public function replaceMatch($text) {
        $text = (string) $text;
        $regex = $this->_toRegex();
        $text = preg_replace($regex, $this->_replacementPattern, $text);

        return $text;
    }

    public function transform($text, CM_Frontend_Render $render) {
        return $this->replaceMatch((string) $text);
    }

    /**
     * @param string $userInput
     * @return string|false
     */
    public function getMatch($userInput) {
        if (!$this->isMatch($userInput)) {
            return false;
        }
        $userInput = (string) $userInput;
        foreach ($this->_phrases as $phrase) {
            $regexp = $this->_transformItemToRegex($phrase);
            if (preg_match('#' . $regexp . '#i', $userInput)) {
                return $this->_transformItemToHumanreadable($phrase);
            }
        }

        return false;
    }

    /**
     * @param string $userInput
     * @return boolean
     */
    public function isMatch($userInput) {
        return (boolean) preg_match($this->_toRegex(), (string) $userInput);
    }

    /**
     * @return string
     */
    private function _toRegex() {
        if (0 === iterator_count($this->_phrases)) {
            $phrasesRegex = '#\z.#';
        } else {
            $regexList = [];
            foreach ($this->_phrases as $phrase) {
                $regexList[] = $this->_transformItemToRegex($phrase);
            }
            $phrasesRegex = '#' . implode('|', $regexList) . '#i';
        }
        return $phrasesRegex;
    }

    /**
     * @param string $phrase
     * @return string
     */
    private function _transformItemToHumanreadable($phrase) {
        return str_replace(array('*', '|'), '', $phrase);
    }

    /**
     * @param string $phrase
     * @return string
     */
    protected function _transformItemToRegex($phrase) {
        $regexp = preg_quote($phrase, '#');
        $regexp = str_replace('\*', '[^A-Za-z]*', $regexp);
        $regexp = str_replace('\|', '\b', $regexp);
        $regexp = '\S*' . $regexp . '\S*';
        return $regexp;
    }
}


text:
extern bool ignore_qexec_packet;

typedef struct agg_t agg_t;
apr_status_t agg_create(agg_t** retagg, apr_int64_t generation, apr_pool_t* parent_pool, apr_hash_t* fsinfotab);
apr_status_t agg_dup(agg_t** agg, agg_t* oldagg, apr_pool_t* pool, apr_hash_t* fsinfotab);
void agg_destroy(agg_t* agg);
apr_status_t agg_put(agg_t* agg, const gp_smon_to_mmon_packet_t* pkt);
apr_status_t agg_dump(agg_t* agg);

#endif


text:
namespace JsonBuilder
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    public class JsonObject: IJsonData
    {
        private readonly List<IJsonData> values = new List<IJsonData>();

        public JsonObject(string elementName)
        {
            this.Name = elementName;
        }

        public JsonObject() { }

        public IEnumerable<IJsonData> Values => this.values;

        /// <summary>
        /// Adds the given object as child and returns reference of this instance.
        /// </summary>
        /// <param name="jsonObject">The json object which is part of this instance.</param>
        /// <returns>Reference of this object, not of the added child!</returns>
        public JsonObject ContainingObject(JsonObject jsonObject)
        {
            this.values.Add(jsonObject);
            return this;
        }

        public string Name { get; set; }

        /// <summary>
        /// Returns a string that represents the current object.
        /// </summary>
        /// <returns>
        /// A string that represents the current object.
        /// </returns>
        public override string ToString()
        {
            return this.ToJson();
        }

        public string ToJson()
        {
            if (!this.values.Any())
            {
                throw new InvalidOperationException($"No values provided for object {this.Name}!");
            }

            var elementName = JsonBuilder.GetFormatedElementName(this.Name);
            string content;

            if (this.values.Count == 1)
            {
                var value = this.values.First();
                content = value.ToJson();
            }
            else
            {
                content = JsonBuilder.ListObjects(this.values);
            }

            var formatedObject = elementName + JsonBuilder.WrapInBraces(content);
            return formatedObject;
        }

        public JsonObject WithValue(string name, object value)
        {
            var jsonValue = new JsonValue(name, value);
            this.values.Add(jsonValue);

            return this;
        }

        public JsonObject ContainingObject(string childName)
        {
            var jsonObject = new JsonObject(childName);
            this.values.Add(jsonObject);

            return jsonObject;
        }

        public JsonCollection WithCollection(string collectionName)
        {
            var collection = new JsonCollection(collectionName);

            this.values.Add(collection);

            return collection;
        }
    }
}


text:
package com.bison.app.ui.swipeback;

/**
 * Created by oeager on 2015/8/14 0014.
 * email: oeager@foxmail.com
 */
public interface SwipeController {
    void lock();
    void unlock();
}


text:
/**
 *
 */
package net.freecoder.restdemo.dao.impl;

import java.util.List;

import net.freecoder.restdemo.dao.ReplyAutoDao;
import net.freecoder.restdemo.model.WlsReplyAuto;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author JiTing
 */
@Repository
@Transactional
public class ReplyAutoDaoImpl extends CommonDaoImpl<WlsReplyAuto> implements
		ReplyAutoDao {

	/**
	 * User only can setup one auto reply, so this method will delete original
	 * one before save.
	 */
	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public String save(WlsReplyAuto entity) {
		// TODO:J validate entity data before read it's value. The same to other
		// daos.
		List<WlsReplyAuto> entities = getListByWxAccountId(WlsReplyAuto.class,
				entity.getWlsWxAccountId());
		for (WlsReplyAuto existEntity : entities) {
			currentSession().delete(existEntity);
		}
		currentSession().flush();
		this.createTime(entity);
		return currentSession().save(entity).toString();
	}
}


text:
package io.druid.server.http.security;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.inject.Injector;
import com.sun.jersey.spi.container.ResourceFilter;
import io.druid.server.BrokerQueryResource;
import io.druid.server.ClientInfoResource;
import io.druid.server.QueryResource;
import io.druid.server.StatusResource;
import io.druid.server.http.BrokerResource;
import io.druid.server.http.CoordinatorDynamicConfigsResource;
import io.druid.server.http.CoordinatorResource;
import io.druid.server.http.DatasourcesResource;
import io.druid.server.http.HistoricalResource;
import io.druid.server.http.IntervalsResource;
import io.druid.server.http.MetadataResource;
import io.druid.server.http.RulesResource;
import io.druid.server.http.ServersResource;
import io.druid.server.http.TiersResource;
import io.druid.server.security.ForbiddenException;
import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.Collection;

@RunWith(Parameterized.class)
public class SecurityResourceFilterTest extends ResourceFilterTestHelper
{
  @Parameterized.Parameters
  public static Collection<Object[]> data()
  {
    return ImmutableList.copyOf(
        Iterables.concat(
            getRequestPathsWithAuthorizer(CoordinatorResource.class),
            getRequestPathsWithAuthorizer(DatasourcesResource.class),
            getRequestPathsWithAuthorizer(BrokerResource.class),
            getRequestPathsWithAuthorizer(HistoricalResource.class),
            getRequestPathsWithAuthorizer(IntervalsResource.class),
            getRequestPathsWithAuthorizer(MetadataResource.class),
            getRequestPathsWithAuthorizer(RulesResource.class),
            getRequestPathsWithAuthorizer(ServersResource.class),
            getRequestPathsWithAuthorizer(TiersResource.class),
            getRequestPathsWithAuthorizer(ClientInfoResource.class),
            getRequestPathsWithAuthorizer(CoordinatorDynamicConfigsResource.class),
            getRequestPathsWithAuthorizer(QueryResource.class),
            getRequestPathsWithAuthorizer(StatusResource.class),
            getRequestPathsWithAuthorizer(BrokerQueryResource.class)
        )
    );
  }

  private final String requestPath;
  private final String requestMethod;
  private final ResourceFilter resourceFilter;
  private final Injector injector;

  public SecurityResourceFilterTest(
      String requestPath,
      String requestMethod,
      ResourceFilter resourceFilter,
      Injector injector
  )
  {
    this.requestPath = requestPath;
    this.requestMethod = requestMethod;
    this.resourceFilter = resourceFilter;
    this.injector = injector;
  }

  @Before
  public void setUp() throws Exception
  {
    setUp(resourceFilter);
  }

  @Test
  public void testResourcesFilteringAccess()
  {
    setUpMockExpectations(requestPath, true, requestMethod);
    EasyMock.replay(req, request, authorizerMapper);
    Assert.assertTrue(((AbstractResourceFilter) resourceFilter.getRequestFilter()).isApplicable(requestPath));
    resourceFilter.getRequestFilter().filter(request);
    EasyMock.verify(req, request, authorizerMapper);
  }

  @Test(expected = ForbiddenException.class)
  public void testResourcesFilteringNoAccess()
  {
    setUpMockExpectations(requestPath, false, requestMethod);
    EasyMock.replay(req, request, authorizerMapper);
    Assert.assertTrue(((AbstractResourceFilter) resourceFilter.getRequestFilter()).isApplicable(requestPath));
    try {
      resourceFilter.getRequestFilter().filter(request);
      Assert.fail();
    }
    catch (ForbiddenException e) {
      throw e;
    }
    EasyMock.verify(req, request, authorizerMapper);
  }

  @Test
  public void testResourcesFilteringBadPath()
  {
    EasyMock.replay(req, request, authorizerMapper);
    final String badRequestPath = requestPath.replaceAll("\\w+", "droid");
    Assert.assertFalse(((AbstractResourceFilter) resourceFilter.getRequestFilter()).isApplicable(badRequestPath));
    EasyMock.verify(req, request, authorizerMapper);
  }
}


text:
class CommandsController < ApplicationController
  protect_from_forgery except: :create

  def index
    puts "INDEX_PARAMS: #{params}"
    render text: "OK"
  end

  def create
    Rails.logger.debug "CREATE_PARAMS: #{params}"
    puts "CREATE_PARAMS: #{params}"

    @echo = setup_echo_device
    @intent = try_to_find_intent

    if @echo.authentication_id.blank?
      render json: say_registration_message(@intent) and return
    end

    if params[:session] && params[:session][:new]
      response = {
          version: '1',
          response: {
              outputSpeech: {
                  type: "PlainText", text: "Hi #{@echo.name}, welcome to your smart home."
              },
              shouldEndSession: false
          }
      }
      render json: response and return
    end

    if @intent == "LightsIntent"
      render json: reply_to_lights and return
    end

    if @intent == "PresenceIntent"
      render json: reply_to_presence and return
    end

    if @intent == "MusicIntent"
      render json: reply_to_music and return
    end

    if params[:session] && params[:request]
      response = {
          version: '1',
          response: {
              outputSpeech: {
                  type: "PlainText", text: "Ok - you asked me to run a command!"
              },
              shouldEndSession: false
          }
      }
      render json: response and return
    end

    render text: "OK"
  end

  private

  def setup_echo_device
    EchoUser.find_or_create_by(device_id: params[:session][:user][:userId])
  end

  def try_to_find_intent
    if params[:request] && params[:request][:intent] && params[:request][:intent][:name]
      params[:request][:intent][:name]
    end
  end

  def say_registration_message(intent)
    if intent == "ReadyForCodeIntent"
      response = {
          version: '1',
          response: {
              outputSpeech: {
                  type: "PlainText",
                  text: "Your code to enter into the site is #{@echo.registration_code.split("").join(", ")}. Tell me you have entered it once you are done."
              },
              shouldEndSession: false
          }
      }
    else
      response = {
          version: '1',
          response: {
              outputSpeech: {
                  type: "PlainText",
                  text: "Hi There, welcome to Smart Things. It looks like you have not registered yet. Open a web browser and go
  to echo hyphen command dot herokuapp dot com and sign in. It will want you to enter your registration code. Tell me when you are ready
  for that code."
              },
              shouldEndSession: false
          }
      }
    end
  end

  def reply_to_lights
    command = params[:command][:request][:intent][:slots][:Command][:value]
    s = Smartthingr.new(@echo.user)
    s.change_lights(command)
    response = {
        version: '1',
        response: {
            outputSpeech: {
                type: "PlainText",
                text: "Got it - I will turn #{command} the lights now."
            },
            shouldEndSession: false
        }
    }
  end

  def reply_to_music
    command = params[:command][:request][:intent][:slots][:Command][:value]
    switch = params[:command][:request][:intent][:slots][:Speaker][:value]
    command = command == "play" ? "on" : "off"

    s = Smartthingr.new(@echo.user)
    worked = s.change_single_switch(switch,command)
    response = {
        version: '1',
        response: {
            outputSpeech: {
                type: "PlainText",
                text: (worked ? "Got it, done." : "Sorry, I had trouble finding a device called #{switch}")
            },
            shouldEndSession: false
        }
    }
  end

  def reply_to_presence
    command = params[:command][:request][:intent][:slots][:Command][:value]
    response = {
        version: '1',
        response: {
            outputSpeech: {
                type: "PlainText",
                text: "Got it, you are #{command} - I will prepare the house for you."
            },
            shouldEndSession: false
        }
    }
  end

end


text:
<?php

namespace Dudulina\Saga;

use Dudulina\Event\EventDispatcher;
use Dudulina\Event\EventSubscriber;
use Dudulina\Event\EventWithMetaData;
use Dudulina\EventProcessing\ConcurentEventProcessingException;
use Psr\Log\LoggerInterface;

class SagasOnlyOnceEventDispatcher implements EventDispatcher
{

    /** @var EventSubscriber */
    private $eventSubscriber;
    /**
     * @var SagaEventTrackerRepository
     */
    private $trackerRepository;
    /**
     * @var LoggerInterface|null
     */
    private $logger;

    public function __construct(
        SagaEventTrackerRepository $trackerRepository,
        EventSubscriber $eventSubscriber,
        ?LoggerInterface $logger
    )
    {
        $this->eventSubscriber = $eventSubscriber;
        $this->trackerRepository = $trackerRepository;
        $this->logger = $logger;
    }

    public function dispatchEvent(EventWithMetaData $eventWithMetadata)
    {
        $listeners = $this->eventSubscriber->getListenersForEvent($eventWithMetadata->getEvent());

        foreach ($listeners as $listener) {
            $metaData = $eventWithMetadata->getMetaData();

            if (is_array($listener)) {
                $saga = $listener[0];

                $sagaId = get_class($saga);

                if (!$this->trackerRepository->isEventProcessingAlreadyStarted($sagaId, $metaData->getEventId())) {
                    try {
                        $this->trackerRepository->startProcessingEvent($sagaId, $metaData->getEventId());
                        call_user_func($listener, $eventWithMetadata->getEvent(), $metaData);
                        $this->trackerRepository->endProcessingEvent($sagaId, $metaData->getEventId());
                    } catch (ConcurentEventProcessingException $exception) {
                        continue;
                    } catch (\Throwable $exception) {
                        if ($this->logger) {
                            $this->logger->error($exception->getMessage(), [
                                'saga'  => get_class($saga),
                                'event' => [
                                    'class' => get_class($eventWithMetadata->getEvent()),
                                    'id'    => (string)$metaData->getEventId(),
                                ],
                                'file'  => $exception->getFile(),
                                'line'  => $exception->getLine(),
                            ]);
                        }
                    }
                }
            }
        }
    }
}


text:
load('jstests/libs/fts.js');

(function() {
    "use strict";
    var coll = db.fts_diacriticsensitive;

    coll.drop();

    assert.writeOK(coll.insert({
        _id: 0,
        a: "O próximo vôo à noite sobre o Atlântico, põe freqüentemente o único médico."
    }));

    assert.commandWorked(coll.ensureIndex({a: "text"}, {default_language: "portuguese"}));

    assert.throws(function() {
        queryIDS(coll, "hello", null, {$diacriticSensitive: "invalid"});
    });

    assert.eq([0], queryIDS(coll, "PRÓXIMO VÔO À", null, {$diacriticSensitive: true}));
    assert.eq([0], queryIDS(coll, "atlântico", null, {$diacriticSensitive: true}));
    assert.eq([0], queryIDS(coll, "\"próximo\"", null, {$diacriticSensitive: true}));
    assert.eq([0], queryIDS(coll, "\"põe\" atlântico", null, {$diacriticSensitive: true}));
    assert.eq(
        [0], queryIDS(coll, "\"próximo vôo\" \"único médico\"", null, {$diacriticSensitive: true}));
    assert.eq(
        [0],
        queryIDS(coll, "\"próximo vôo\" -\"unico médico\"", null, {$diacriticSensitive: true}));

    assert.eq([], queryIDS(coll, "à", null, {$diacriticSensitive: true}));
    assert.eq([], queryIDS(coll, "proximo", null, {$diacriticSensitive: true}));
    assert.eq([], queryIDS(coll, "proximo voo à", null, {$diacriticSensitive: true}));
    assert.eq([], queryIDS(coll, "à -PRÓXIMO -vôo", null, {$diacriticSensitive: true}));
    assert.eq([], queryIDS(coll, "à proximo -vôo", null, {$diacriticSensitive: true}));
    assert.eq([], queryIDS(coll, "mo vô", null, {$diacriticSensitive: true}));
    assert.eq([], queryIDS(coll, "\"unico medico\"", null, {$diacriticSensitive: true}));
    assert.eq(
        [], queryIDS(coll, "\"próximo vôo\" -\"único médico\"", null, {$diacriticSensitive: true}));

})();


text:
import unittest, time, sys, random
sys.path.extend(['.','..','../..','py'])
import h2o, h2o_cmd, h2o_browse as h2b, h2o_import as h2i

def write_syn_dataset(csvPathname, rowCount, headerData):
    dsf = open(csvPathname, "w+")

    # output is just 0 or 1 randomly
    dsf.write(headerData + "\n")
    # add random output. just 0 or 1
    for i in range(rowCount):
        rowData = rand_rowData()
        dsf.write(rowData + "," + str(random.randint(0,1)) + "\n")
    dsf.close()

def append_syn_dataset(csvPathname, num):
    with open(csvPathname, "a") as dsf:
        for i in range(num):
            rowData = rand_rowData()
            dsf.write(rowData + "\n")

def rand_rowData():
    # UPDATE: maybe because of byte buffer boundary issues, single byte
    # data is best? if we put all 0s or 1, then I guess it will be bits?
    rowData = str(random.uniform(0,7))
    for i in range(7):
        # randomize the sign, mantissa, exponent separately
        b = random.random()
        e = random.random() * 40
        s = random.randint(0,1)
        f = b * (10**e) * (s and -1 or 1)
        rowData = rowData + "," + str(f)
    return rowData

class Basic(unittest.TestCase):
    def tearDown(self):
        h2o.check_sandbox_for_errors()

    @classmethod
    def setUpClass(cls):
        global SEED
        # SEED = h2o.setup_random_seed()
        # force the seed that gets the assertion error
        SEED = h2o.setup_random_seed(seed=4548383660131500992)

        # java.lang.AssertionError: -2.9975397E38<NaN n=98
        # at hex.gbm.DTree$Split.split(DTree.java:224)
        h2o.init(2,java_heap_MB=1300,use_flatfile=True)
        ### h2b.browseTheCloud()

    @classmethod
    def tearDownClass(cls):
        h2o.tear_down_cloud(h2o.nodes)

    def test_rf_float_rand2_fvec(self):
        SYNDATASETS_DIR = h2o.make_syn_dir()
        csvFilename = "syn_prostate.csv"
        csvPathname = SYNDATASETS_DIR + '/' + csvFilename
        headerData = "ID,CAPSULE,AGE,RACE,DPROS,DCAPS,PSA,VOL,GLEASON"
        totalRows = 10000
        write_syn_dataset(csvPathname, totalRows, headerData)

        for trial in range (5):
            rowData = rand_rowData()
            num = random.randint(4096, 10096)
            append_syn_dataset(csvPathname, num)
            totalRows += num
            start = time.time()

            # make sure all key names are unique, when we re-put and re-parse (h2o caching issues)
            hex_key = csvFilename + "_" + str(trial) + ".hex"
            # On EC2 once we get to 30 trials or so, do we see polling hang? GC or spill of heap or ??
            kwargs = {'ntrees': 5, 'max_depth': 5}
            parseResult = h2i.import_parse(path=csvPathname, schema='put', hex_key=hex_key)
            h2o_cmd.runRF(parseResult=parseResult, timeoutSecs=60, pollTimeoutSecs=60, **kwargs)
            print "trial #", trial, "totalRows:", totalRows, "num:", num, "RF end on ", csvFilename, \
                'took', time.time() - start, 'seconds'
            ### h2o_cmd.runInspect(key=hex_key)
            ### h2b.browseJsonHistoryAsUrlLastMatch("Inspect")
            h2o.check_sandbox_for_errors()

if __name__ == '__main__':
    h2o.unit_main()


text:
package com.epam.ta.reportportal.entity.item.issue;

import com.epam.ta.reportportal.entity.enums.TestItemIssueGroup;
import org.hibernate.annotations.Type;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Objects;

/**
 * @author Pavel Bortnik
 */
@Entity
@Table(name = "issue_group", schema = "public")
public class IssueGroup implements Serializable {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "issue_group_id")
	private Integer id;

	@Column(name = "issue_group")
	@Enumerated(EnumType.STRING)
	@Type(type = "pqsql_enum")
	private TestItemIssueGroup testItemIssueGroup;

	public IssueGroup() {
	}

	public IssueGroup(TestItemIssueGroup testItemIssueGroup) {
		this.testItemIssueGroup = testItemIssueGroup;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public TestItemIssueGroup getTestItemIssueGroup() {
		return testItemIssueGroup;
	}

	public void setTestItemIssueGroup(TestItemIssueGroup testItemIssueGroup) {
		this.testItemIssueGroup = testItemIssueGroup;
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) {
			return true;
		}
		if (o == null || getClass() != o.getClass()) {
			return false;
		}
		IssueGroup that = (IssueGroup) o;
		return testItemIssueGroup == that.testItemIssueGroup;
	}

	@Override
	public int hashCode() {

		return Objects.hash(testItemIssueGroup);
	}
}


text:
__author__ = 'bcambl'

import logging
import shutil
import os

# Logging Setup - START ##
log = logging.getLogger("copylib")
log.setLevel(logging.DEBUG)
stream = logging.StreamHandler()
stream.setLevel(logging.DEBUG)
log.addHandler(stream)
handler = logging.FileHandler('copy-log.log')
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(message)s')
handler.setFormatter(formatter)
log.addHandler(handler)
# Logging Setup - END ##

def copy_files(source=None, destination=None):
    """ Copies all source directories and files recursively with logging
    :param source: source path
    :param destination: destination path
    """
    names = os.listdir(source)
    os.makedirs(destination)
    errors = []
    for name in names:
        srcname = os.path.join(source, name)
        destname = os.path.join(destination, name)
        try:
            if os.path.isdir(srcname):
                copy_files(srcname, destname)
                log.debug("Copied %s to %s" % (srcname, destname))
            else:
                shutil.copy2(srcname, destname)
                log.debug("Copied %s to %s" % (srcname, destname))
        except shutil.Error, err:
            errors.extend(err.args[0])
        except EnvironmentError, enverr:
            errors.append((srcname, destname, str(enverr)))
    try:
        shutil.copystat(source, destination)
    except OSError, oserr:
        errors.append((source, destination, str(oserr)))
    if errors:
        for error in errors:
            log.debug(error)

def main(task_dict):
    for task in copy_tasks.keys():
        source_path = task_dict[task]['source']
        destination_path = task_dict[task]['destination']
        copy_files(source=source_path, destination=destination_path)

if __name__ == '__main__':
    copy_tasks = {'fileset1':
                      {'source': '/tmp/fake_data/directory0',
                       'destination': '/tmp/test_destination0/'
                       },
                  'fileset2':
                      {'source': '/tmp/fake_data/directory1',
                       'destination': '/tmp/test_destination1/'
                       },
                  'fileset3':
                      {'source': '/tmp/fake_data/directory2',
                       'destination': '/tmp/test_destination2/'
                       },
                  'fileset4':
                      {'source': '/tmp/fake_data/directory3',
                       'destination': '/tmp/test_destination3/'
                       }
                  }
    main(copy_tasks)


text: <manifest package="cn.qqtheme.framework.GoodsSpec" />


text:
title: "mapper.kernel.tricube"
layout: function
desc: "Pushes onto the stack a mapper which applies a tricube kernel function on the sliding window."
category: miscellaneous
---

Pushes onto the stack a mapper which applies a tricube kernel function on the sliding window.

```
- mapper.kernel.tricube mapper
```


text:
/*
  Prototype JavaScript framework
  (c) 2005-2009 Sam Stephenson

  Prototype is freely distributable under the terms of an MIT-style license.
  For details, see the Prototype web site: http://www.prototypejs.org/

  stripped down to work with the AppliCast(tm) framework
  (c) 2009 Estanislau Trepat / ILERRED, S.L.
*/

var Prototype = {
	emptyFunction: function() { },
	K: function(x) { return x; }
};

var Abstract = { };

Object.extend = function(destination, source) {
  for (var property in source)
    destination[property] = source[property];
  return destination;
};

Object.extend(Object, {
  getClass: function(object) {
    return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];
  },

  keys: function(object) {
    var keys = [];
    for (var property in object)
      keys.push(property);
    return keys;
  },

  values: function(object) {
    var values = [];
    for (var property in object)
      values.push(object[property]);
    return values;
  },

	clone: function(object) {
		return Object.extend({ }, object);
	},

	// Applicast(tm) only
	isNode: function(object) {
	  return Object.getClass(object) === 'node';
	},

  isArray: function(object) {
    return object != null && typeof object == "object" && 'splice' in object && 'join' in object;
  },

  isFunction: function(object) {
    return typeof object === 'function';
  },

  isString: function(object) {
    return Object.getClass(object) === 'String';
  },

  isNumber: function(object) {
    return Object.getClass(object) === 'Number';
  },

  isUndefined: function(object) {
    return typeof object === 'undefined';
  }
});

Object.extend(Function.prototype, {
  argumentNames: function() {
    var names = this.toString().match(/^[\s\(]*function[^(]*\(([^\)]*)\)/)[1].replace(/\s+/g, '').split(',');
    return names.length == 1 && !names[0] ? [] : names;
  },

  bind: function(object) {
    var __method = this;
    return function() { return __method.apply(object, arguments); };
  },

  delay: function() {
    var __method = this, args = arguments, timeout = args.shift() * 1000;
    return setTimeout(function() {
      return __method.apply(__method, args);
    }, timeout);
  },

  wrap: function(wrapper) {
    var __method = this;
    return function() {
      return wrapper.apply(this, [__method.bind(this)].concat($A(arguments)));
    };
  }
});

/* Based on Alex Arnell's inheritance implementation. */
var Class = {
  create: function() {
    var parent = null, properties = $A(arguments);

    if ( Object.isFunction(properties[0]) )
      parent = properties.shift();

    function klass() {
      this.initialize.apply(this, arguments);
    }

    Object.extend(klass, Class.Methods);
    klass.superclass = parent;
    klass.subclasses = [];

    if (parent) {
      var subclass = function() { };
      subclass.prototype = parent.prototype;
      klass.prototype = new subclass;
      parent.subclasses.push(klass);
    }

    for (var i = 0; i < properties.length; i++)
      klass.addMethods(properties[i]);

    if ( !klass.prototype.initialize )
      klass.prototype.initialize = Prototype.emptyFunction;

    klass.prototype.constructor = klass;

    return klass;
  }
};

Class.Methods = {
  addMethods: function(source) {
    var ancestor   = this.superclass && this.superclass.prototype;
    var properties = Object.keys(source);

    if ( !Object.keys({ toString: true }).length )
      properties.push("toString", "valueOf");

    for (var i = 0, length = properties.length; i < length; i++) {
      var property = properties[i], value = source[property];
      if (ancestor && Object.isFunction(value) && value.argumentNames().first() == "$super") {
        var method = value;
        value = (function(m) { return function() { return ancestor[m].apply(this, arguments); }; })(property).wrap(method);

        value.valueOf = method.valueOf.bind(method);
        value.toString = method.toString.bind(method);
      }
      this.prototype[property] = value;
    }

    return this;
  }
};

Object.extend(String, {
  interpret: function(value) {
    return value == null ? '' : String(value);
  }
});

Object.extend(String.prototype, {
  strip: function() {
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
  },

  stripTags: function() {
    return this.replace(/<\/?[^>]+>/gi, '');
  },

  toArray: function() {
    return this.split('');
  },

  include: function(pattern) {
    return this.indexOf(pattern) > -1;
  },

  capitalize: function(){
    return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
  },

  startsWith: function(pattern) {
    return this.indexOf(pattern) === 0;
  },

  endsWith: function(pattern) {
    var d = this.length - pattern.length;
    return d >= 0 && this.lastIndexOf(pattern) === d;
  },

  empty: function() {
    return this == '';
  },

  blank: function() {
    return (/^\s*$/).test(this);
  },

  times: function(count) {
    return count < 1 ? '' : new Array(count + 1).join(this);
  }
});

Object.extend(Number.prototype, {
  toColorPart: function() {
    return this.toPaddedString(2, 16);
  },

  toPaddedString: function(length, radix) {
    var string = this.toString(radix || 10);
    return '0'.times(length - string.length) + string;
  },

  // convert degrees to radians
  toRad: function() {
    return this * Math.PI / 180;
  },

  // convert radians to degrees
  toDeg: function() {
    return this * 180 / Math.PI;
  }
});

Object.extend(Array.prototype, {
  each: function(f) {
    for(var i=0, m=this.length; i < m; ++i)
      f(this[i], i);
  },

  empty: function() {
    return this.length < 1 ? true : false;
  },

  clear: function() {
    this.length = 0;
    return this;
  },

  first: function() {
    return this[0];
  },

  last: function() {
    return this[this.length - 1];
  },

  size: function() {
    return this.length;
  },

  indexOf: function(object) {
    for (var i = 0, length = this.length; i < length; i++)
      if (this[i] == object) return i;
    return -1;
  },

  pluck: function(property) {
    var results = [];
    for(var i=0, m=this.length; i < m; ++i) {
      var value = this[i];
      if ( !Object.isUndefined(value[property]) )
        results.push(this[i][property]);
    }
    return results;
  }
});

function $A(iterable) {
  if ( !iterable ) return [];

  if ( iterable.toArray ) return iterable.toArray();

  var length = iterable.length || 0;
  var results = new Array(length);

  while ( length-- )
    results[length] = iterable[length];

  return results;
}

//////////////////////////////////////////////////////
// PeriodicalExecuter
//////////////////////////////////////////////////////

// Modified for AppliCast(tm)
// setInterval implementation under the AppliCast(tm) stack does not allow
// setting the timer with an anonymous function

var PeriodicalExecuter = Class.create({
  // remember!: callback should not be an anonymous function
  initialize: function(callback, frequency, precision) {
    this.callback = callback || Prototype.emptyFunction;
    this.frequency = frequency || 1;
    this.precision = precision || 1000;
    this.currentlyExecuting = false;

    this.timer = setInterval(this.callback, this.frequency * this.precision);
  },

  stop: function() {
    if ( !this.timer ) return;
    clearInterval(this.timer);
    this.timer = null;
  },

  restart: function() {
    if ( this.timer ) return;
    this.timer = setInterval(this.callback, this.frequency * this.precision);
  }
});

//////////////////////////////////////////////////////
// XMLHttpRequest / Ajax
//////////////////////////////////////////////////////
var Ajax = {
  activeRequestCount: 0,

  transport: null,

  getTransport: function() {
    // fix-wa: make transport a global object into Ajax.transport
    // Returning new transport object makes it unusable ¿? <- need to work on this
    // this prevents multiple requests at the same time but, in AppliCast(tm)
    // only three are allowed anyway.
    // be sure to call one "after" the other, then.
    Ajax.transport = new XMLHttpRequest();
    return Ajax.transport;
    // return new XMLHttpRequest();
  }
};

Ajax.Base = Class.create({
  initialize: function(options) {
    this.options = {
      method:       'post',
      asynchronous: true,
      parameters:   ''
    };
    Object.extend(this.options, options || { });

    // fix
    this.options.method = 'get';
    this.options.asynchronous = true;
  }
});

Ajax.Request = Class.create(Ajax.Base, {
  initialize: function($super, url, options) {
    $super(options);
    this.transport = Ajax.getTransport();
    this.request(url);
  },

  request: function(url) {
    this.url = url;
    this.method = this.options.method;
    this.headers = {
		  'X-Requested-Width': 'Applicast/XMLHttpRequest',
		  'Accept': 'text/html,application/xhtml+xml,application/xml,application/json',
		  'Accept-Charset': 'utf-8,ISO-8859-1',
      'Accept-Language': 'es-es,es,en-us,en',
      'Cache-Control': 'no-cache',
      'Pragma': 'no-cache'
    };

    if ( this.method == 'get' && this.options.parameters )
      this.url += (this.url.indexOf('?') > -1 ? '&' : '?') + this.options.parameters;

		for(var k in this.headers)
		  this.transport.setRequestHeader(k, this.headers[k]);

		this.transport.onreadystatechange = this.onStateChange.bind(this);
		this.transport.open(this.method.toUpperCase(), this.url);
  	this.transport.send(null);
  },

  onStateChange: function() {
    var readyState = this.transport.readyState;
    if ( readyState > 1 && !((readyState == 4) && this._complete) ) {
      var state = Ajax.Request.Events[readyState];
      if ( state == 'Complete' ) {
        try {
          this._complete = true;
          (this.options['on' + (this.success() ? 'Success' : 'Failure')] || Prototype.emptyFunction)(this.transport);
        } catch(e) {
          (this.options.onException || Prototype.emptyFunction)(e);
        }

        this.transport.onreadystatechange = Prototype.emptyFunction;
      }
    }
  },

	success: function() {
	  var status = this.getStatus();
  	return !status || (status >= 200 && status < 300);
	},

	getStatus: function() {
  	try {
    	return this.transport.status || 0;
  	} catch(e) {
    	return 0;
  	}
	}
});

Ajax.Request.Events = ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];


text:
function Invoke-WhiskeyPipeline
{
    <#
    .SYNOPSIS
    Invokes Whiskey pipelines.

    .DESCRIPTION
    The `Invoke-WhiskeyPipeline` function runs the tasks in a pipeline. Pipelines are properties in a `whiskey.yml` under which one or more tasks are defined. For example, this `whiskey.yml` file:

        Build:
        - TaskOne
        - TaskTwo
        Publish:
        - TaskOne
        - Task

    Defines two pipelines: `Build` and `Publish`.

    .EXAMPLE
    Invoke-WhiskeyPipeline -Context $context -Name 'Build'

    Demonstrates how to run the tasks in a `Build` pipeline. The `$context` object is created by calling `New-WhiskeyContext`.
    #>
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [object]
        # The current build context. Use the `New-WhiskeyContext` function to create a context object.
        $Context,

        [Parameter(Mandatory=$true)]
        [string]
        # The name of pipeline to run, e.g. `Build` would run all the tasks under a property named `Build`. Pipelines are properties in your `whiskey.yml` file that are lists of Whiskey tasks to run.
        $Name
    )

    Set-StrictMode -Version 'Latest'
    Use-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState

    $config = $Context.Configuration
    $Context.PipelineName = $Name

    if( -not $config.ContainsKey($Name) )
    {
        Stop-Whiskey -Context $Context -Message ('Pipeline ''{0}'' does not exist. Create a pipeline by defining a ''{0}'' property:

    {0}:
    - TASK_ONE
    - TASK_TWO

' -f $Name)
        return
    }

    $taskIdx = -1
    if( -not $config[$Name] )
    {
        Write-Warning -Message ('It looks like pipeline ''{0}'' doesn''t have any tasks.' -f $Context.ConfigurationPath)
        $config[$Name] = @()
    }

    foreach( $taskItem in $config[$Name] )
    {
        $taskIdx++

        $taskName,$taskParameter = ConvertTo-WhiskeyTask -InputObject $taskItem -ErrorAction Stop
        if( -not $taskName )
        {
            continue
        }

        $Context.TaskIndex = $taskIdx

        Invoke-WhiskeyTask -TaskContext $Context -Name $taskName -Parameter $taskParameter
    }
}


text:
(function ($) {
    $.fn.readingStats = function (options, callback) {
        var defaultOptions = {
                readingSpeed: 200, // in words per minute
                format: function (seconds) {
                    // default formatter returns a string like 2 min 45 sec
                    // in 15 seconds increments
                    var mins = Math.floor(seconds / 60),
                        sec15 = 15 * Math.floor((seconds - 60 * mins) / 15),
                        result = '';

                    result = (mins > 0) ? mins.toString() + ' min ' : '';
                    if (sec15 > 0) {
                        result += sec15.toString() + ' sec';
                    }
                    return result;
                }
            },
            options = $.extend(defaultOptions, options || {});

        var wordCount = $.grep( $(this).text().split(' '),
                function (el) {return (el.replace(/^\s*/, '') == "") ? false : true;}
            ).length,
            secondsToRead = Math.ceil(wordCount / options.readingSpeed * 60),
            result = {
                wordCount: wordCount,
                secondsToRead: secondsToRead,

                format: function (secs) {
                    return options.format(secs || this.secondsToRead);
                }

            };

        if (callback === undefined) {
            return result;
        } else {
            callback(result);
            return this
        }
    }
})(jQuery);


text:
'use strict';
L.Control.Measure = L.Control.extend({
  // Posible units : nm, ft, yd, mi, km
  options: {
    position: 'topleft',
    measureUnit: 'km',
    measureButtonHidden: false,
    precision: 2
  },

  onAdd: function () {
    var className = 'leaflet-control-zoom leaflet-bar leaflet-control',
        container = L.DomUtil.create('div', className);

    this.options = L.Util.extend(this.options, this._map.options.measureOptions);

    if(!this.options.measureButtonHidden)
      this._createButton('⇢', 'Measure', 'leaflet-control-measure leaflet-bar-part leaflet-bar-part-top-and-bottom', container, this._toggleMeasure, this);

    var self = this;
    this._map.on('measure:start', function() {
      self._measuring = true;
      self._changeState(true);
    });
    this._map.on('measure:stop', function() {
      self._measuring = false;
      self._changeState(true);
    });
    this._map.on('measure:toggle', function() {
      self._toggleMeasure(true);
    });

    return container;
  },

  _createButton: function (html, title, className, container, fn, context) {
    var link = L.DomUtil.create('a', className, container);
    link.innerHTML = html;
    link.href = '#';
    link.title = title;

    L.DomEvent
      .on(link, 'click', L.DomEvent.stopPropagation)
      .on(link, 'click', L.DomEvent.preventDefault)
      .on(link, 'click', fn, context)
      .on(link, 'dblclick', L.DomEvent.stopPropagation);

    return link;
  },

  _toggleMeasure: function (inEvent) {
    this._measuring = !this._measuring;

    this._changeState(inEvent);
  },

  _changeState: function(inEvent) {
    if(this._measuring) {
      L.DomUtil.addClass(this._container, 'leaflet-control-measure-on');
      this._startMeasuring(inEvent);
    } else {
      L.DomUtil.removeClass(this._container, 'leaflet-control-measure-on');
      this._stopMeasuring(inEvent);
    }
  },

  _startMeasuring: function(inEvent) {
    this._oldCursor = this._map._container.style.cursor;
    this._map._container.style.cursor = 'crosshair';

    this._doubleClickZoom = this._map.doubleClickZoom.enabled();
    this._map.doubleClickZoom.disable();

    L.DomEvent
      .on(this._map, 'mousemove', this._mouseMove, this)
      .on(this._map, 'click', this._mouseClick, this)
      .on(this._map, 'measure:click', this._mouseClick, this)
      .on(this._map, 'dblclick', this._finishPath, this)
      .on(document, 'keydown', this._onKeyDown, this);

    if(!inEvent)
      this._map.fire('measure:measurestart', { layerType: this.type });

    if(!this._layerPaint) {
      this._layerPaint = L.layerGroup().addTo(this._map);
    }

    if(!this._points) {
      this._points = [];
    }
  },

  _stopMeasuring: function(inEvent) {
    this._map._container.style.cursor = this._oldCursor;

    L.DomEvent
      .off(document, 'keydown', this._onKeyDown, this)
      .off(this._map, 'mousemove', this._mouseMove, this)
      .off(this._map, 'click', this._mouseClick, this)
      .off(this._map, 'dblclick', this._mouseClick, this);

    if(!inEvent)
      this._map.fire('measure:measurestop', { layerType: this.type });

    if(this._doubleClickZoom) {
      this._map.doubleClickZoom.enable();
    }

    if(this._layerPaint) {
      this._layerPaint.clearLayers();
    }

    this._restartPath();
  },

  _mouseMove: function(e) {
    if(!e.latlng || !this._lastPoint) {
      return;
    }

    if(!this._layerPaintPathTemp) {
      this._layerPaintPathTemp = L.polyline([this._lastPoint, e.latlng], {
        color: 'black',
        weight: 1.5,
        clickable: false,
        dashArray: '6,3'
      }).addTo(this._layerPaint);
    } else {
      this._layerPaintPathTemp.spliceLatLngs(0, 2, this._lastPoint, e.latlng);
    }

    if(this._tooltip) {
      if(!this._distance) {
        this._distance = 0;
      }

      this._updateTooltipPosition(e.latlng);

      var distance = e.latlng.distanceTo(this._lastPoint);
      this._updateTooltipDistance(this._distance + distance, distance);
    }
  },

  _mouseClick: function(e) {
    if(!this._measuring)
      return;
    // Skip if no coordinates
    if(!e.latlng) {
      return;
    }

    // If we have a tooltip, update the distance and create a new tooltip, leaving the old one exactly where it is (i.e. where the user has clicked)
    if(this._lastPoint && this._tooltip) {
      if(!this._distance) {
        this._distance = 0;
      }

      this._updateTooltipPosition(e.latlng);

      var distance = e.latlng.distanceTo(this._lastPoint);
      this._updateTooltipDistance(this._distance + distance, distance);

      this._distance += distance;
    }
    this._createTooltip(e.latlng);

    // If this is already the second click, add the location to the fix path (create one first if we don't have one)
    if(this._lastPoint && !this._layerPaintPath) {
      this._layerPaintPath = L.polyline([this._lastPoint], {
        color: 'black',
        weight: 2,
        clickable: false
      }).addTo(this._layerPaint);
    }

    if(this._layerPaintPath) {
      this._layerPaintPath.addLatLng(e.latlng);
    }

    // Upate the end marker to the current location
    if(this._lastCircle) {
      this._layerPaint.removeLayer(this._lastCircle);
    }

    this._lastCircle = new L.CircleMarker(e.latlng, {
      color: 'black',
      opacity: 1,
      weight: 1,
      fill: true,
      fillOpacity: 1,
      radius:2,
      clickable: this._lastCircle ? true : false
    }).addTo(this._layerPaint);

    this._lastCircle.on('click', function() { this._finishPath(); }, this);

    // Save current location as last location
    this._lastPoint = e.latlng;
  },

  _finishPath: function() {
    // Remove the last end marker as well as the last (moving tooltip)
    if(this._lastCircle) {
      this._layerPaint.removeLayer(this._lastCircle);
    }
    if(this._tooltip) {
      this._layerPaint.removeLayer(this._tooltip);
    }
    if(this._layerPaint && this._layerPaintPathTemp) {
      this._layerPaint.removeLayer(this._layerPaintPathTemp);
    }

    // Reset everything
    this._restartPath();
  },

  _restartPath: function() {
    this._distance = 0;
    this._tooltip = undefined;
    this._lastCircle = undefined;
    this._lastPoint = undefined;
    this._layerPaintPath = undefined;
    this._layerPaintPathTemp = undefined;
  },

  _createTooltip: function(position) {
    var icon = L.divIcon({
      className: 'leaflet-measure-tooltip',
      iconAnchor: [-5, -5]
    });
    this._tooltip = L.marker(position, {
      icon: icon,
      clickable: false
    }).addTo(this._layerPaint);
  },

  _updateTooltipPosition: function(position) {
    this._tooltip.setLatLng(position);
  },

  _updateTooltipDistance: function(total, difference) {
    var totalRound = total;
    var differenceRound = difference;
    var measureUnit = this.options.measureUnit;

    //extensible option for multiple units
    switch(measureUnit){
      case 'nm':
        totalRound *= 0.00053996;
        differenceRound	*= 0.00053996;
        break;
      case 'ft':
        totalRound *= 3.2808;
        differenceRound	*= 3.2808;
        break;
      case 'yd':
        totalRound *= 1.0936;
        differenceRound	*= 1.0936;
        break;
      case 'mi':
        totalRound *= 0.00062137;
        differenceRound	*= 0.00062137;
        break;
      case 'km':
        totalRound /= 1000;
        differenceRound	/= 1000;
        break;
    }

    var text = '
' + totalRound.toFixed(this.options.precision) + measureUnit + '
';
    if (differenceRound > 0 && totalRound !== differenceRound) {
      text += '
(+' + differenceRound.toFixed(this.options.precision) + measureUnit + ')
';
    }

    this._tooltip._icon.innerHTML = text;
  },

  _onKeyDown: function (e) {
    if(e.keyCode === 27) {
      // If not in path exit measuring mode, else just finish path
      if(!this._lastPoint) {
        this._toggleMeasure();
      } else {
        this._finishPath();
      }
    }
  }
});

L.Map.mergeOptions({
  measureControl: false
});

L.Map.addInitHook(function () {
  if (this.options.measureOptions.control) {
    this.measureControl = new L.Control.Measure();
    this.addControl(this.measureControl);
  }
});

L.control.measure = function (options) {
  return new L.Control.Measure(options);
};


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.monitor.query.implementation.logs.models;

import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

/** Contains details when the response code indicates an error. */
@Fluent
public final class ErrorResponse {
    /*
     * The error details.
     */
    @JsonProperty(value = "error", required = true)
    private ErrorInfo error;

    /**
     * Creates an instance of ErrorResponse class.
     *
     * @param error the error value to set.
     */
    @JsonCreator
    public ErrorResponse(@JsonProperty(value = "error", required = true) ErrorInfo error) {
        this.error = error;
    }

    /**
     * Get the error property: The error details.
     *
     * @return the error value.
     */
    public ErrorInfo getError() {
        return this.error;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (getError() == null) {
            throw new IllegalArgumentException("Missing required property error in model ErrorResponse");
        } else {
            getError().validate();
        }
    }
}


text:
namespace Empires.Core
{
    using System;
    using System.Collections.Generic;

    using Contracts;
    using Enums;

    public class EmpiresData : IEmpiresData
    {
        private readonly ICollection<IBuilding> buildings
            = new List<IBuilding>();

        public EmpiresData()
        {
            this.Units = new Dictionary<string, int>();
            this.Resources = new Dictionary<ResourceType, int>();
            this.InitResources();
        }

        public IEnumerable<IBuilding> Buildings => this.buildings;

        public void AddBuilding(IBuilding building)
        {
            if (building == null)
            {
                throw new ArgumentNullException(nameof(building));
            }

            this.buildings.Add(building);
        }

        public IDictionary<string, int> Units { get; }

        public void AddUnit(IUnit unit)
        {
            if (unit == null)
            {
                throw new ArgumentNullException(nameof(unit));
            }

            var unitType = unit.GetType().Name;

            if (!this.Units.ContainsKey(unitType))
            {
                this.Units.Add(unitType, 0);
            }

            this.Units[unitType]++;
        }

        public IDictionary<ResourceType, int> Resources { get; }

        private void InitResources()
        {
            var resourceTypes = Enum.GetValues(typeof(ResourceType));

            foreach (ResourceType resourceType in resourceTypes)
            {
                this.Resources.Add(resourceType, 0);
            }
        }
    }
}


text:
import os
import unittest
from __main__ import vtk, qt, ctk, slicer
from slicer.ScriptedLoadableModule import *
import logging
import SimpleITK as sitk
import sitkUtils

#
# ComputeTempRelativeR2s
#

class ComputeTempRelativeR2s(ScriptedLoadableModule):
  """Uses ScriptedLoadableModule base class, available at:
  https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
  """

  def __init__(self, parent):
    ScriptedLoadableModule.__init__(self, parent)
    self.parent.title = "ComputeTempRelativeR2s" # TODO make this more human readable by adding spaces
    self.parent.categories = ["IGT"]
    self.parent.dependencies = []
    self.parent.contributors = ["Junichi Tokuda (Brigham and Women's Hospital)"] # replace with "Firstname Lastname (Organization)"
    self.parent.helpText = """
    This is an example of scripted loadable module bundled in an extension.
    It performs a simple thresholding on the input volume and optionally captures a screenshot.
    """
    self.parent.acknowledgementText = """
    This module was developed based on a template created by Jean-Christophe Fillion-Robin, Kitware Inc.
    and Steve Pieper, Isomics, Inc. and was partially funded by NIH grant 3P41RR013218-12S1.
""" # replace with organization, grant and thanks.

#
# ComputeTempRelativeR2sWidget
#

class ComputeTempRelativeR2sWidget(ScriptedLoadableModuleWidget):
  """Uses ScriptedLoadableModuleWidget base class, available at:
  https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
  """

  def setup(self):

    ScriptedLoadableModuleWidget.setup(self)

    #--------------------------------------------------
    # For debugging
    #
    # Reload and Test area
    reloadCollapsibleButton = ctk.ctkCollapsibleButton()
    reloadCollapsibleButton.text = "Reload && Test"
    self.layout.addWidget(reloadCollapsibleButton)
    reloadFormLayout = qt.QFormLayout(reloadCollapsibleButton)

    reloadCollapsibleButton.collapsed = True

    # reload button
    # (use this during development, but remove it when delivering
    #  your module to users)
    self.reloadButton = qt.QPushButton("Reload")
    self.reloadButton.toolTip = "Reload this module."
    self.reloadButton.name = "ComputeTempRelativeR2s Reload"
    reloadFormLayout.addWidget(self.reloadButton)
    self.reloadButton.connect('clicked()', self.onReload)
    #
    #--------------------------------------------------

    # Instantiate and connect widgets ...

    #
    # Parameters Area
    #
    parametersCollapsibleButton = ctk.ctkCollapsibleButton()
    parametersCollapsibleButton.text = "Parameters"
    self.layout.addWidget(parametersCollapsibleButton)

    # Layout within the dummy collapsible button
    parametersFormLayout = qt.QFormLayout(parametersCollapsibleButton)

    #
    # input volume selector
    #
    self.baselineR2StarSelector = slicer.qMRMLNodeComboBox()
    self.baselineR2StarSelector.nodeTypes = ( ("vtkMRMLScalarVolumeNode"), "" )
    self.baselineR2StarSelector.selectNodeUponCreation = True
    self.baselineR2StarSelector.addEnabled = False
    self.baselineR2StarSelector.removeEnabled = False
    self.baselineR2StarSelector.noneEnabled = False
    self.baselineR2StarSelector.showHidden = False
    self.baselineR2StarSelector.showChildNodeTypes = False
    self.baselineR2StarSelector.setMRMLScene( slicer.mrmlScene )
    self.baselineR2StarSelector.setToolTip( "Pick the baseline R2* map" )
    parametersFormLayout.addRow("Baseline R2*: ", self.baselineR2StarSelector)

    #
    # input volume selector
    #
    self.referenceR2StarSelector = slicer.qMRMLNodeComboBox()
    self.referenceR2StarSelector.nodeTypes = ( ("vtkMRMLScalarVolumeNode"), "" )
    self.referenceR2StarSelector.selectNodeUponCreation = True
    self.referenceR2StarSelector.addEnabled = False
    self.referenceR2StarSelector.removeEnabled = False
    self.referenceR2StarSelector.noneEnabled = False
    self.referenceR2StarSelector.showHidden = False
    self.referenceR2StarSelector.showChildNodeTypes = False
    self.referenceR2StarSelector.setMRMLScene( slicer.mrmlScene )
    self.referenceR2StarSelector.setToolTip( "Pick the reference R2* map" )
    parametersFormLayout.addRow("Reference R2*: ", self.referenceR2StarSelector)

    #
    # tempMap volume selector
    #
    self.tempMapSelector = slicer.qMRMLNodeComboBox()
    self.tempMapSelector.nodeTypes = ( ("vtkMRMLScalarVolumeNode"), "" )
    self.tempMapSelector.selectNodeUponCreation = True
    self.tempMapSelector.addEnabled = True
    self.tempMapSelector.removeEnabled = True
    self.tempMapSelector.noneEnabled = True
    self.tempMapSelector.renameEnabled = True
    self.tempMapSelector.showHidden = False
    self.tempMapSelector.showChildNodeTypes = False
    self.tempMapSelector.setMRMLScene( slicer.mrmlScene )
    self.tempMapSelector.setToolTip( "Pick the output temperature map." )
    parametersFormLayout.addRow("Temp. Map: ", self.tempMapSelector)

    #
    # Parameter A (Temp = A * R2Star + B)
    #
    self.paramASpinBox = qt.QDoubleSpinBox()
    self.paramASpinBox.objectName = 'paramASpinBox'
    self.paramASpinBox.setMaximum(100.0)
    self.paramASpinBox.setMinimum(-100.0)
    self.paramASpinBox.setDecimals(8)
    #self.paramASpinBox.setValue(0.0735)
    self.paramASpinBox.setValue(-0.1282)
    self.paramASpinBox.setToolTip("TE for Input Volume 1")
    parametersFormLayout.addRow("Param A: ", self.paramASpinBox)

    #
    # Parameter B (Temp = A * R2Star + B)
    #
    self.paramBSpinBox = qt.QDoubleSpinBox()
    self.paramBSpinBox.objectName = 'paramBSpinBox'
    self.paramBSpinBox.setMaximum(100.0)
    self.paramBSpinBox.setMinimum(-100.0)
    self.paramBSpinBox.setDecimals(8)
    #self.paramBSpinBox.setValue(-4.0588)
    self.paramBSpinBox.setValue(43.8461)
    self.paramBSpinBox.setToolTip("TE for Input Volume 2")
    parametersFormLayout.addRow("Param B: ", self.paramBSpinBox)

    #
    # Use input threshold
    #
    self.useInputThresholdFlagCheckBox = qt.QCheckBox()
    self.useInputThresholdFlagCheckBox.checked = 1
    self.useInputThresholdFlagCheckBox.setToolTip("If checked, apply the threshold to limit the pixel value ranges.")
    parametersFormLayout.addRow("Use InputThreshold", self.useInputThresholdFlagCheckBox)

    #
    # Upper threshold - We set threshold value to limit the range of intensity
    #
    self.upperInputThresholdSpinBox = qt.QDoubleSpinBox()
    self.upperInputThresholdSpinBox.objectName = 'upperInputThresholdSpinBox'
    self.upperInputThresholdSpinBox.setMaximum(1000000.0)
    self.upperInputThresholdSpinBox.setMinimum(-1000000.0)
    self.upperInputThresholdSpinBox.setDecimals(6)
    self.upperInputThresholdSpinBox.setValue(800.0)
    self.upperInputThresholdSpinBox.setToolTip("Upper threshold for the output")
    parametersFormLayout.addRow("Upper InputThreshold (ms): ", self.upperInputThresholdSpinBox)

    #
    # Use output threshold
    #
    self.useOutputThresholdFlagCheckBox = qt.QCheckBox()
    self.useOutputThresholdFlagCheckBox.checked = 1
    self.useOutputThresholdFlagCheckBox.setToolTip("If checked, apply the threshold to limit the pixel value ranges.")
    parametersFormLayout.addRow("Use OutputThreshold", self.useOutputThresholdFlagCheckBox)

    #
    # Upper threshold - We set threshold value to limit the range of intensity
    #
    self.upperOutputThresholdSpinBox = qt.QDoubleSpinBox()
    self.upperOutputThresholdSpinBox.objectName = 'upperOutputThresholdSpinBox'
    self.upperOutputThresholdSpinBox.setMaximum(1000000.0)
    self.upperOutputThresholdSpinBox.setMinimum(-1000000.0)
    self.upperOutputThresholdSpinBox.setDecimals(6)
    self.upperOutputThresholdSpinBox.setValue(1000000.0)
    self.upperOutputThresholdSpinBox.setToolTip("Upper threshold for the output")
    parametersFormLayout.addRow("Upper OutputThreshold (deg): ", self.upperOutputThresholdSpinBox)

    #
    # Lower threshold - We set threshold value to limit the range of intensity
    #
    self.lowerOutputThresholdSpinBox = qt.QDoubleSpinBox()
    self.lowerOutputThresholdSpinBox.objectName = 'lowerOutputThresholdSpinBox'
    self.lowerOutputThresholdSpinBox.setMaximum(1000000.0)
    self.lowerOutputThresholdSpinBox.setMinimum(-1000000.0)
    self.lowerOutputThresholdSpinBox.setDecimals(6)
    self.lowerOutputThresholdSpinBox.setValue(-1000000.0)
    self.lowerOutputThresholdSpinBox.setToolTip("Lower threshold for the output")
    parametersFormLayout.addRow("Lower OutputThreshold (deg): ", self.lowerOutputThresholdSpinBox)

    #
    # Apply Button
    #
    self.applyButton = qt.QPushButton("Apply")
    self.applyButton.toolTip = "Run the algorithm."
    self.applyButton.enabled = False
    parametersFormLayout.addRow(self.applyButton)

    # connections
    self.applyButton.connect('clicked(bool)', self.onApplyButton)
    self.baselineR2StarSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.onSelect)
    self.referenceR2StarSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.onSelect)
    self.tempMapSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.onSelect)
    self.useOutputThresholdFlagCheckBox.connect('toggled(bool)', self.onUseOutputThreshold)

    # Add vertical spacer
    self.layout.addStretch(1)

    # Refresh Apply button state
    self.onSelect()

  def cleanup(self):
    pass

  def onSelect(self):
    self.applyButton.enabled = self.baselineR2StarSelector.currentNode() and self.baselineR2StarSelector.currentNode() and self.tempMapSelector.currentNode()

  def onUseOutputThreshold(self):
    if self.useOutputThresholdFlagCheckBox.checked == True:
      self.lowerOutputThresholdSpinBox.enabled = True;
      self.upperOutputThresholdSpinBox.enabled = True;
    else:
      self.lowerOutputThresholdSpinBox.enabled = False;
      self.upperOutputThresholdSpinBox.enabled = False;

  def onApplyButton(self):
    logic = ComputeTempRelativeR2sLogic()
    #enableScreenshotsFlag = self.enableScreenshotsFlagCheckBox.checked
    #imageOutputThreshold = self.imageOutputThresholdSliderWidget.value

    tempMapName = ''

    if self.tempMapSelector.currentNode():
      tempMapName = self.tempMapSelector.currentNode().GetName()

    inputThreshold = None
    if self.useInputThresholdFlagCheckBox.checked == True:
      inputThreshold = [0, self.upperInputThresholdSpinBox.value]

    outputThreshold = None
    if self.useOutputThresholdFlagCheckBox.checked == True:
      outputThreshold = [self.lowerOutputThresholdSpinBox.value, self.upperOutputThresholdSpinBox.value]

    logic.run(self.baselineR2StarSelector.currentNode(), self.referenceR2StarSelector.currentNode(),
              self.tempMapSelector.currentNode(), self.paramASpinBox.value, self.paramBSpinBox.value,
              outputThreshold, inputThreshold)

    tempMapNode = slicer.util.getNode(tempMapName)
    self.tempMapSelector.setCurrentNode(tempMapNode)

  def onReload(self, moduleName="ComputeTempRelativeR2s"):
    # Generic reload method for any scripted module.
    # ModuleWizard will subsitute correct default moduleName.

    globals()[moduleName] = slicer.util.reloadScriptedModule(moduleName)

#
# ComputeTempRelativeR2sLogic
#

class ComputeTempRelativeR2sLogic(ScriptedLoadableModuleLogic):

  def isValidInputOutputData(self, baselineR2StarVolumeNode, referenceR2StarVolumeNode):
    """Validates if the output is not the same as input
    """
    if not baselineR2StarVolumeNode:
      logging.debug('isValidInputOutputData failed: no input volume node for ParamA image defined')
      return False
    if not referenceR2StarVolumeNode:
      logging.debug('isValidInputOutputData failed: no input volume node for ParamB image defined')
      return False
    return True

  def run(self, baselineR2StarVolumeNode, referenceR2StarVolumeNode, tempMapVolumeNode, paramA, paramB, outputThreshold, inputThreshold):
    """
    Run the actual algorithm
    """

    if not self.isValidInputOutputData(baselineR2StarVolumeNode, referenceR2StarVolumeNode):
      slicer.util.errorDisplay('Input volume is the same as output volume. Choose a different output volume.')
      return False

    logging.info('Processing started')

    imageBaseline  = sitk.Cast(sitkUtils.PullFromSlicer(baselineR2StarVolumeNode.GetID()), sitk.sitkFloat64)
    imageReference = sitk.Cast(sitkUtils.PullFromSlicer(referenceR2StarVolumeNode.GetID()), sitk.sitkFloat64)

    if tempMapVolumeNode:
      imageTemp = paramA * (imageReference - imageBaseline) + paramB

      if inputThreshold != None:
        mask1 = sitk.BinaryThreshold(imageBaseline, 0.0, inputThreshold[1] - 10e-10, 1, 0)
        mask2 = sitk.BinaryThreshold(imageReference, 0.0, inputThreshold[1] - 10e-10, 1, 0)
        mask = sitk.And(mask1, mask2)
        imageTemp = sitk.Mask(imageTemp, mask)
        imask = sitk.Not(mask)
        imaskFloat = sitk.Cast(imask, sitk.sitkFloat64)
        imaskFillTemp = imaskFloat * (-40.0)
        imageTemp = imageTemp + imaskFillTemp ## TODO: The lower temperature limit

      if outputThreshold != None:
        lowerOutputThreshold = outputThreshold[0]
        upperOutputThreshold = outputThreshold[1]
        imageTempOutputThreshold = sitk.Threshold(imageTemp, lowerOutputThreshold, upperOutputThreshold, 0.0)
        sitkUtils.PushToSlicer(imageTempOutputThreshold, tempMapVolumeNode.GetName(), 0, True)
      else:
        sitkUtils.PushToSlicer(imageTemp, tempMapVolumeNode.GetName(), 0, True)

    logging.info('Processing completed')

    return True

class ComputeTempRelativeR2sTest(ScriptedLoadableModuleTest):
  """
  This is the test case for your scripted module.
  Uses ScriptedLoadableModuleTest base class, available at:
  https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
  """

  def setUp(self):
    """ Do whatever is needed to reset the state - typically a scene clear will be enough.
    """
    slicer.mrmlScene.Clear(0)

  def runTest(self):
    """Run as few or as many tests as needed here.
    """
    self.setUp()
    self.test_ComputeTempRelativeR2s1()

  def test_ComputeTempRelativeR2s1(self):
    """ Ideally you should have several levels of tests.  At the lowest level
    tests should exercise the functionality of the logic with different inputs
    (both valid and invalid).  At higher levels your tests should emulate the
    way the user would interact with your code and confirm that it still works
    the way you intended.
    One of the most important features of the tests is that it should alert other
    developers when their changes will have an impact on the behavior of your
    module.  For example, if a developer removes a feature that you depend on,
    your test should break so they know that the feature is needed.
    """

    pass

    #self.delayDisplay("Starting the test")
    ##
    ## first, get some data
    ##
    #import urllib
    #downloads = (
    #    ('http://slicer.kitware.com/midas3/download?items=5767', 'FA.nrrd', slicer.util.loadVolume),
    #    )
    #
    #for url,name,loader in downloads:
    #  filePath = slicer.app.temporaryPath + '/' + name
    #  if not os.path.exists(filePath) or os.stat(filePath).st_size == 0:
    #    logging.info('Requesting download %s from %s...\n' % (name, url))
    #    urllib.urlretrieve(url, filePath)
    #  if loader:
    #    logging.info('Loading %s...' % (name,))
    #    loader(filePath)
    #self.delayDisplay('Finished with download and loading')
    #
    #volumeNode = slicer.util.getNode(pattern="FA")
    #logic = ComputeTempRelativeR2sLogic()
    #self.assertTrue( logic.hasImageData(volumeNode) )
    #self.delayDisplay('Test passed!')


text:
// This file is automatically generated.

package adila.db;

/*
 * Samsung Galaxy S6
 *
 * DEVICE: zerofltektt
 * MODEL: SM-G920K
 */
final class zerofltektt {
    public static final String DATA = "Samsung|Galaxy S6|Galaxy S";
}