text:
/* $NetBSD: machdep.c,v 1.4 2002/03/17 11:37:55 simonb Exp $ */

/*
 * Copyright 2000, 2001
 * Broadcom Corporation. All rights reserved.
 *
 * This software is furnished under license and may be used and copied only
 * in accordance with the following terms and conditions.  Subject to these
 * conditions, you may download, copy, install, use, modify and distribute
 * modified or unmodified copies of this software in source and/or binary
 * form. No title or ownership is transferred hereby.
 *
 * 1) Any source code used, modified or distributed must reproduce and
 *    retain this copyright notice and list of conditions as they appear in
 *    the source file.
 *
 * 2) No right is granted to use any trade name, trademark, or logo of
 *    Broadcom Corporation. Neither the "Broadcom Corporation" name nor any
 *    trademark or logo of Broadcom Corporation may be used to endorse or
 *    promote products derived from this software without the prior written
 *    permission of Broadcom Corporation.
 *
 * 3) THIS SOFTWARE IS PROVIDED "AS-IS" AND ANY EXPRESS OR IMPLIED
 *    WARRANTIES, INCLUDING BUT NOT LIMITED TO, ANY IMPLIED WARRANTIES OF
 *    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
 *    NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL BROADCOM BE LIABLE
 *    FOR ANY DAMAGES WHATSOEVER, AND IN PARTICULAR, BROADCOM SHALL NOT BE
 *    LIABLE FOR DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 *    CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 *    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
 *    BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 *    WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 *    OR OTHERWISE), EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * Copyright (c) 2000 Soren S. Jorvang.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions, and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include "opt_ddb.h"
#include "opt_execfmt.h"

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/map.h>
#include <sys/proc.h>
#include <sys/buf.h>
#include <sys/reboot.h>
#include <sys/conf.h>
#include <sys/file.h>
#include <sys/malloc.h>
#include <sys/mbuf.h>
#include <sys/msgbuf.h>
#include <sys/device.h>
#include <sys/user.h>
#include <sys/exec.h>
#include <sys/sysctl.h>
#include <sys/mount.h>
#include <sys/syscallargs.h>
#include <sys/kcore.h>

#include <uvm/uvm_extern.h>

#include <machine/cpu.h>
#include <machine/reg.h>
#include <machine/psl.h>
#include <machine/pte.h>
#include <machine/autoconf.h>
#include <machine/intr.h>
#include <machine/swarm.h>
#include <mips/locore.h>

#include <mips/cfe/cfe_xiocb.h>
#include <mips/cfe/cfe_api.h>

#if 0 /* XXXCGD */
#include <machine/nvram.h>
#endif /* XXXCGD */
#include <machine/leds.h>

#ifdef DDB
#include <machine/db_machdep.h>
#include <ddb/db_access.h>
#include <ddb/db_sym.h>
#include <ddb/db_extern.h>
#ifndef DB_ELFSIZE
#error Must define DB_ELFSIZE!
#endif
#define	ELFSIZE		DB_ELFSIZE
#include <sys/exec_elf.h>
#endif

#include <dev/cons.h>

#ifdef IKOS
#include <sbmips/ikos/ikosvar.h>
#endif

/* For sysctl. */
char machine[] = MACHINE;
char machine_arch[] = MACHINE_ARCH;
char cpu_model[] = "sb1250";

/* Our exported CPU info.  Only one for now */
struct cpu_info cpu_info_store;

/* Maps for VM objects. */
struct vm_map *exec_map = NULL;
struct vm_map *mb_map = NULL;
struct vm_map *phys_map = NULL;

int	physmem;		/* Total physical memory */

char	bootstring[512];	/* Boot command */
int	netboot;		/* Are we netbooting? */
int	cfe_present;

struct bootinfo_v1 bootinfo;

phys_ram_seg_t mem_clusters[VM_PHYSSEG_MAX];
int mem_cluster_cnt;

void	configure(void);
void	mach_init(long,long,long,long);

/*
 * safepri is a safe priority for sleep to set for a spin-wait during
 * autoconfiguration or after a panic.  Used as an argument to splx().
 */
int	safepri = MIPS_INT_MASK | MIPS_SR_INT_IE;

extern caddr_t esym;
extern struct user *proc0paddr;

/*
 * Do all the stuff that locore normally does before calling main().
 */
void
mach_init(fwhandle,magic,bootdata,reserved)
	long fwhandle;
	long magic;
	long bootdata;
	long reserved;
{
	caddr_t kernend, v, p0;
	u_long first, last;
	vsize_t size;
	extern char edata[], end[];
	int i;
	u_int memsize;
	uint32_t config;

	/* XXX this code must run on the target cpu */
	config = mips3_cp0_config_read();
	config &= ~MIPS3_CONFIG_K0_MASK;
	config |= 0x05;				/* XXX.  cacheable coherent */
	mips3_cp0_config_write(config);

	/* XXXCGD */
#ifdef SBMIPS_MEM_SIZE
	memsize = SBMIPS_MEM_SIZE;
#else
	memsize = 32 * 1024 * 1024;
#endif
	memsize += MIPS_KSEG0_START;

	/*
	 * Clear the BSS segment.
	 */
#ifdef DDB
	if (memcmp(((Elf_Ehdr *)end)->e_ident, ELFMAG, SELFMAG) == 0 &&
	    ((Elf_Ehdr *)end)->e_ident[EI_CLASS] == ELFCLASS) {
		esym = end;
		esym += ((Elf_Ehdr *)end)->e_entry;
		kernend = (caddr_t)mips_round_page(esym);
		bzero(edata, end - edata);
	} else
#endif
	{
		kernend = (caddr_t)mips_round_page(end);
		memset(edata, 0, kernend - edata);
	}

	/*
	 * Copy the bootinfo structure from the boot loader.
	 * this has to be done before mips_vector_init is
	 * called because we may need CFE's TLB handler
	 */

	cfe_present = 0;
	if (magic == BOOTINFO_MAGIC)
		bcopy((struct bootinfo_v1 *)bootdata, &bootinfo,
		    sizeof bootinfo);
	else if (reserved == CFE_EPTSEAL) {
		magic = BOOTINFO_MAGIC;
		bzero(&bootinfo, sizeof bootinfo);
		bootinfo.version = BOOTINFO_VERSION;
		bootinfo.fwhandle = fwhandle;
		bootinfo.fwentry = bootdata;
	}

#ifdef IKOS
	ikoscons_output_bufsize = IKOSCONS_OUTPUT_BUFSIZE;
	memsize -= ikoscons_output_bufsize;
	ikoscons_output_buf =
	    (void *)MIPS_PHYS_TO_KSEG1(MIPS_KSEG0_TO_PHYS(memsize));
	memset(ikoscons_output_buf, 0, ikoscons_output_bufsize);
#endif

	/*
	 * physmem is measured in pages
	 * XXX does this need to be set for 'consinit', 'uvm_setpagesize',
	 * XXX or 'mips_vector_init'?  not that I can tell right now...
	 * XXX if CFE is present, this will be recalculated.
	 * XXX
	 * XXX Does 'physmem' want to be the total amount of RAM in the
	 * XXX system, or the amount that is available to us?
	 */
	physmem = btoc(memsize - MIPS_KSEG0_START);

	consinit();

	uvm_setpagesize();

	/*
	 * Copy exception-dispatch code down to exception vector.
	 * Initialize locore-function vector.
	 * Clear out the I and D caches.
	 */
	mips_vector_init();

#if 0
*(unsigned long long *)0xb0020440 = 3;
#endif

	printf("fwhandle=%08X magic=%08X bootdata=%08X reserved=%08X\n",
	    (u_int) fwhandle,(u_int) magic,(u_int) bootdata,(u_int) reserved);

	if (magic == BOOTINFO_MAGIC) {
		int idx;
		int added;
		cfe_xuint_t start,len,type;

		cfe_init(fwhandle);
		cfe_present = 1;

		idx = 0;
		physmem = 0;
		mem_cluster_cnt = 0;
		while (cfe_getmeminfo(idx,&start,&len,&type) == 0) {
			added = 0;
			printf("Memory Block #%d start %08llX len %08llX: %s: ",
			    idx, start, len, (type == CFE_MI_AVAILABLE) ?
			    "Available" : "Reserved");
			if ((type == CFE_MI_AVAILABLE) &&
			    (mem_cluster_cnt < VM_PHYSSEG_MAX)) {
				/*
				 * XXX Ignore memory above 256MB for now, it
				 * XXX needs special handling.
				 */
				if (start < (256*1024*1024)) {
				    physmem += btoc(((int) len));
				    mem_clusters[mem_cluster_cnt].start =
					(long) start;
				    mem_clusters[mem_cluster_cnt].size =
					(long) len;
				    mem_cluster_cnt++;
				    added = 1;
				}
			}
			if (added)
				printf("added to map\n");
			else
				printf("not added to map\n");
			idx++;
		}

	} else {
		/*
		 * Handle the case of not being called from the firmware.
		 */
		mem_clusters[0].start = 0;
		mem_clusters[0].size = ctob(physmem);
		mem_cluster_cnt = 1;
	}

	for (i = 0; i < sizeof(bootinfo.boot_flags); i++) {
		switch (bootinfo.boot_flags[i]) {
		case '\0':
			break;
		case ' ':
			continue;
		case '-':
			while (bootinfo.boot_flags[i] != ' ' &&
			    bootinfo.boot_flags[i] != '\0') {
				switch (bootinfo.boot_flags[i]) {
				case 'a':
					boothowto |= RB_ASKNAME;
					break;
				case 'd':
					boothowto |= RB_KDB;
					break;
				case 's':
					boothowto |= RB_SINGLE;
					break;
				}
				i++;
			}
		}
		if (memcmp("single", &bootinfo.boot_flags[i], 5) == 0)
			boothowto |= RB_SINGLE;
		if (memcmp("nfsroot=", &bootinfo.boot_flags[i], 8) == 0)
			netboot = 1;
		/*
		 * XXX Select root device from 'root=/dev/hd[abcd][1234]' too.
		 */
	}

	/*
	 * Load the rest of the available pages into the VM system.
	 * The first chunk is tricky because we have to avoid the
	 * kernel, but the rest are easy.
	 */
	first = round_page(MIPS_KSEG0_TO_PHYS(kernend));
	last = mem_clusters[0].start + mem_clusters[0].size;
	uvm_page_physload(atop(first), atop(last), atop(first), atop(last),
		VM_FREELIST_DEFAULT);

	for (i = 1; i < mem_cluster_cnt; i++) {
		first = round_page(mem_clusters[i].start);
		last = mem_clusters[i].start + mem_clusters[i].size;
		uvm_page_physload(atop(first), atop(last), atop(first),
		    atop(last), VM_FREELIST_DEFAULT);
	}

	/*
	 * Initialize error message buffer (at end of core).
	 */
	mips_init_msgbuf();

	/*
	 * Allocate space for proc0's USPACE
	 */
	p0 = (caddr_t)pmap_steal_memory(USPACE, NULL, NULL);
	proc0.p_addr = proc0paddr = (struct user *)p0;
	proc0.p_md.md_regs = (struct frame *)(p0 + USPACE) - 1;
	curpcb = &proc0.p_addr->u_pcb;
	curpcb->pcb_context[11] = MIPS_INT_MASK | MIPS_SR_INT_IE; /* SR */

	/*
	 * Allocate space for system data structures.  These data structures
	 * are allocated here instead of cpu_startup() because physical
	 * memory is directly addressable.  We don't have to map these into
	 * virtual address space.
	 */
	size = (vsize_t)allocsys(NULL, NULL);
	v = (caddr_t)pmap_steal_memory(size, NULL, NULL);
	if ((allocsys(v, NULL) - v) != size)
		panic("mach_init: table size inconsistency");

	pmap_bootstrap();

	/*
	 * Initialize debuggers, and break into them, if appropriate.
	 */
#if defined(DDB)
	ddb_init(0, 0, 0);
#endif

	if (boothowto & RB_KDB) {
#if defined(DDB)
		Debugger();
#endif
	}
}

/*
 * Allocate memory for variable-sized tables,
 */
void
cpu_startup()
{
	unsigned i;
	int base, residual;
	vaddr_t minaddr, maxaddr;
	vsize_t size;
	char pbuf[9];

	/*
	 * Good {morning,afternoon,evening,night}.
	 */
	printf(version);
	format_bytes(pbuf, sizeof(pbuf), ctob(physmem));
	printf("%s memory", pbuf);

	/*
	 * Allocate virtual address space for file I/O buffers.
	 * Note they are different than the array of headers, 'buf',
	 * and usually occupy more virtual memory than physical.
	 */
	size = MAXBSIZE * nbuf;
	if (uvm_map(kernel_map, (vaddr_t *)&buffers, round_page(size),
		    NULL, UVM_UNKNOWN_OFFSET, 0,
		    UVM_MAPFLAG(UVM_PROT_NONE, UVM_PROT_NONE, UVM_INH_NONE,
		    UVM_ADV_NORMAL, 0)) != 0)
		panic("startup: cannot allocate VM for buffers");
	minaddr = (vaddr_t)buffers;
	base = bufpages / nbuf;
	residual = bufpages % nbuf;
	for (i = 0; i < nbuf; i++) {
		vsize_t curbufsize;
		vaddr_t curbuf;
		struct vm_page *pg;

		/*
		 * Each buffer has MAXBSIZE bytes of VM space allocated.  Of
		 * that MAXBSIZE space, we allocate and map (base+1) pages
		 * for the first "residual" buffers, and then we allocate
		 * "base" pages for the rest.
		 */
		curbuf = (vaddr_t) buffers + (i * MAXBSIZE);
		curbufsize = NBPG * ((i < residual) ? (base + 1) : base);

		while (curbufsize) {
			pg = uvm_pagealloc(NULL, 0, NULL, 0);
			if (pg == NULL)
				panic("cpu_startup: not enough memory for "
					"buffer cache");
			pmap_kenter_pa(curbuf, VM_PAGE_TO_PHYS(pg),
			    VM_PROT_READ|VM_PROT_WRITE);
			curbuf += PAGE_SIZE;
			curbufsize -= PAGE_SIZE;
		}
	}

	/*
	 * Allocate a submap for exec arguments.  This map effectively
	 * limits the number of processes exec'ing at any time.
	 */
	exec_map = uvm_km_suballoc(kernel_map, &minaddr, &maxaddr, 16 * NCARGS,
	    VM_MAP_PAGEABLE, FALSE, NULL);
	/*
	 * Allocate a submap for physio.
	 */
	phys_map = uvm_km_suballoc(kernel_map, &minaddr, &maxaddr, VM_PHYS_SIZE,
	    0, FALSE, NULL);

	/*
	 * (No need to allocate an mbuf cluster submap.  Mbuf clusters
	 * are allocated via the pool allocator, and we use KSEG to
	 * map those pages.)
	 */

	format_bytes(pbuf, sizeof(pbuf), ptoa(uvmexp.free));
	printf(", %s free", pbuf);
	format_bytes(pbuf, sizeof(pbuf), bufpages * NBPG);
	printf(", %s in %d buffers\n", pbuf, nbuf);

	/*
	 * Set up buffers, so they can be used to read disk labels.
	 */
	bufinit();
}

int
cpu_sysctl(name, namelen, oldp, oldlenp, newp, newlen, p)
	int *name;
	u_int namelen;
	void *oldp;
	size_t *oldlenp;
	void *newp;
	size_t newlen;
	struct proc *p;
{
	/* All sysctl names at this level are terminal. */
	if (namelen != 1)
		return ENOTDIR;

	switch (name[0]) {
	default:
		return EOPNOTSUPP;
	}
}

int	waittime = -1;

void
cpu_reboot(howto, bootstr)
	int howto;
	char *bootstr;
{
	/* Take a snapshot before clobbering any registers. */
	if (curproc)
		savectx((struct user *)curpcb);

	if (cold) {
		howto |= RB_HALT;
		goto haltsys;
	}

	/* If "always halt" was specified as a boot flag, obey. */
	if (boothowto & RB_HALT)
		howto |= RB_HALT;

	boothowto = howto;
	if ((howto & RB_NOSYNC) == 0 && (waittime < 0)) {
		waittime = 0;
		vfs_shutdown();

		/*
		 * If we've been adjusting the clock, the todr
		 * will be out of synch; adjust it now.
		 */
		resettodr();
	}

	splhigh();

	if (howto & RB_DUMP)
		dumpsys();

haltsys:
	doshutdownhooks();

	if (howto & RB_HALT) {
		printf("\n");
		printf("The operating system has halted.\n");
		printf("Please press any key to reboot.\n\n");
		cnpollc(1);	/* For proper keyboard command handling */
		cngetc();
		cnpollc(0);
	}

	printf("rebooting...\n\n");

	if (cfe_present) {
		cfe_exit(1, (howto & RB_DUMP) ? 1 : 0);
		printf("cfe_exit didn't!\n");
	}

	delay(500000);

#if defined(IKOS) && defined(REALLY_IKOS)
	*(volatile char *)MIPS_PHYS_TO_KSEG1(0x408000) = 0;
#else
    {
	static int broken;

	if (!broken) {
		broken = 1;
		__asm__ ( "move $4, %0 ; break 0x3ff" : : "r"(howto) );
	}
    }
#endif

	printf("WARNING: reboot failed!\n");

	for (;;);
}

static void
cswarm_setled(u_int index, char c)
{
	volatile u_char *led_ptr =
	    (void *)MIPS_PHYS_TO_KSEG1(SWARM_LEDS_PHYS);

	if (index < 4)
		led_ptr[0x20 + ((3 - index) << 3)] = c;
}

void
cswarm_setleds(const char *str)
{
	int i;

	for (i = 0; i < 4 && str[i]; i++)
		cswarm_setled(i, str[i]);
	for (; i < 4; i++)
		cswarm_setled(' ', str[i]);
}

int
sbmips_cca_for_pa(paddr_t pa)
{
	int rv;

	/* Check each DRAM region. */
	if ((pa >= 0x0000000000 && pa <= 0x000fffffff) ||	/* DRAM 0 */
	    (pa >= 0x0080000000 && pa <= 0x008fffffff) ||	/* DRAM 1 */
	    (pa >= 0x0090000000 && pa <= 0x009fffffff) ||	/* DRAM 2 */
	    (pa >= 0x00c0000000 && pa <= 0x00cfffffff) ||	/* DRAM 3 */
#ifdef _MIPS_PADDR_T_64BIT
	    (pa >= 0x0100000000 && pa <= 0x07ffffffff) ||	/* DRAM exp */
#endif
	   0) {
		rv = 5;		/* Cacheable coherent. */
		goto done;
	}

	rv = 2;			/* Uncached. */
done:
	return (rv);
}


text:
using System;
using System.Collections.Generic;

namespace EZOper.NetSiteUtilities.AliyunAcsCore
{
    public interface IClientProfile
    {

        ISigner GetSigner();

        String GetRegionId();

        FormatType GetFormat();

        Credential GetCredential();

        List<Endpoint> GetEndpoints();

        List<Endpoint> GetEndpoints(String regionId, String product, Credential credential, String locationProduct);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package face;

import gui.ChatPane;
import gui.GUIMain;
import lib.scalr.Scalr;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.image.BufferedImage;
import java.net.URL;

/**
 * A class which specifies special chat icons, or 'badges'.
 * This allows for easier creation of custom icons, and
 * should be easily adaptable to create custom donation
 * levels.
 *
 * @author Joseph Blackman
 * @version 4/10/2015
 */

public class Icons {

    /**
     * For a specified icon, returns the file containing the
     * image, resized to fit into the chat window.
     *
     * @param i the type of icon to get
     * @return the icon along with what type it is
     */

    public static BotnakIcon getIcon(IconEnum i, String channel) {
        ImageIcon icon = null;
        switch (i) {
            case MOD:
                icon = sizeIcon(GUIMain.currentSettings.modIcon);
                break;
            case BROADCASTER:
                icon = sizeIcon(GUIMain.currentSettings.broadIcon);
                break;
            case ADMIN:
                icon = sizeIcon(GUIMain.currentSettings.adminIcon);
                break;
            case STAFF:
                icon = sizeIcon(GUIMain.currentSettings.staffIcon);
                break;
            case TURBO:
                icon = sizeIcon(GUIMain.currentSettings.turboIcon);
                break;
            case SUBSCRIBER:
                URL subIcon = FaceManager.getSubIcon(channel);
                if (subIcon != null) {
                    icon = sizeIcon(subIcon);
                }
                break;
            case DONOR_BASIC:
                icon = sizeIcon(ChatPane.class.getResource("/image/green.png"));
                break;
            case DONOR_LOW:
                icon = sizeIcon(ChatPane.class.getResource("/image/bronze.png"));
                break;
            case DONOR_MEDIUM:
                icon = sizeIcon(ChatPane.class.getResource("/image/silver.png"));
                break;
            case DONOR_HIGH:
                icon = sizeIcon(ChatPane.class.getResource("/image/gold.png"));
                break;
            case DONOR_INSANE:
                icon = sizeIcon(ChatPane.class.getResource("/image/diamond.png"));
                break;
            case GLOBALMOD:
                icon = sizeIcon(ChatPane.class.getResource("/image/globalmod.png"));
                break;
            case NONE:
                break;
            default:
                break;
        }
        return new BotnakIcon(i, icon);
    }

    /**
     * Resize an icon to match the chat font size. This has the
     * effect of allowing users to submit images of any size.
     *
     * @param image the image URL
     * @return ImageIcon the resized image
     */

    private static ImageIcon sizeIcon(URL image) {
        ImageIcon icon;
        try {
            BufferedImage img = ImageIO.read(image);
            int size = GUIMain.currentSettings.font.getSize();
            img = Scalr.resize(img, Scalr.Method.ULTRA_QUALITY, size, size);
            icon = new ImageIcon(img);
            icon.getImage().flush();
            return icon;
        } catch (Exception e) {
            icon = new ImageIcon(image);
        }
        return icon;
    }

    //Wrapper class for logging purposes
    public static class BotnakIcon {
        public final IconEnum t;
        public final ImageIcon ii;

        public IconEnum getType() {
            return t;
        }

        public ImageIcon getImage() {
            return ii;
        }

        public BotnakIcon(IconEnum type, ImageIcon icon) {
            t = type;
            ii = icon;
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <stroke
        android:width="1dp"
        android:color="#66ffff00"
        android:dashGap="2dp"
        android:dashWidth="5dp" />
    <solid android:color="#00000000" />
</shape>


text:
@interface PostListTableViewController : UITableViewController <SlideNavigationControllerDelegate>

@end


text:
function [ distance ] = calc_distance_route( route )
%CALCAIRDISTANCE Summary of this function goes here
%   Detailed explanation goes here
    %Haversine formula
    %http://en.wikipedia.org/wiki/Haversine_formula
    %http://andrew.hedges.name/experiments/haversine/
%   Convert degree to radians
distance = 0.0;

for ii=1:(size(route,2)-1)
   distance = distance + calc_air_distance_byPoint(route(:,ii),route(:,ii+1));
end

end


text:
package algoritmos�os_algoritmos;
public class ExamenClas {
static MiNuevaClase mnc;

	public static void main(String[] args) {
		mnc = new MiNuevaClase();
		mnc.Suma_a_i(10);
      System.out.print(mnc.i);
	}

}


text:
var assert = require('chai').assert,
  moment = require('moment'),
  nock = require('nock'),
  realtime = require('gtfs-realtime-bindings')

var util = require('./util.js')

var BASE_URL_PATH = '/service/publicXMLFeed',
  NOCK_HOST = 'http://webservices.nextbus.com',
  FIXTURES_FOLDER = './test/fixtures'

var testTranslator = util.getTranslator()

describe('vehicle positions', function() {

  it('should dl nextbus vehicle locations and return vehicle positions protobuf', function(done) {

    var nockScope = nock(NOCK_HOST)
      .get(BASE_URL_PATH)
      .query(util.makeQueryParams('vehicleLocations', { t: 0, r: '' }))
      .replyWithFile(200, FIXTURES_FOLDER + '/vehicleLocations.xml')

    testTranslator.processVehiclePositions(function(err, feedMessage) {

      nockScope.done()

      try {

        assert.isNotOk(err)

        var entities = util.assertIsFeedMessageWithExactEntityLength(feedMessage, 8)

        util.assertAllEntitiesAreSameType('vehicle', entities)

        var vehicle = util.findEntity('vehicle', entities, '404')

        // id
        assert.deepPropertyVal(vehicle, 'vehicle.id', '404')

        // position
        assert.deepPropertyVal(vehicle, 'position.latitude', 47.599205)
        assert.deepPropertyVal(vehicle, 'position.longitude', -122.325349)
        assert.deepPropertyVal(vehicle, 'position.bearing', 88)
        assert.deepProperty(vehicle, 'position.speed')
        assert.approximately(vehicle.position.speed, 7.777777777, 0.00001)

        // timestamp
        assert.isBelow(util.getUInt64(vehicle.timestamp), moment().subtract(8, 'seconds').unix())

      } catch(e) {
        return done(e)
      }

      done()

    })
  })
})


text:
using Esfa.Vacancy.Register.Api;
using NUnit.Framework;

namespace Esfa.Vacancy.UnitTests.Shared.Api
{
    [TestFixture]
    public class AutoMapperConfigTest
    {
        [Test]
        public void ShouldHaveValidAutoMapperConfig()
        {
            var config = AutoMapperConfig.Configure();

            config.AssertConfigurationIsValid();
        }
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Flora, Jena 65(no. 21): 330 (1882)

#### Original name
Patellaria chloritis var. nigrata Müll. Arg.

### Remarks
null


text:
Simple calculator application that uses:

  * Xamarin.Android
  * Xamarin.iOS
  * Xamarin.Forms
  * Xamarin.UITest

Source code is MIT licensed.

## Source

Two solutions - One for Xamarin.Forms and one for both Xamarin.Android and Xamarin.iOS

 * Calculator.sln
 * Calculator.Form.sln

### Android and iOS Projects

 * Calculator.Core - PCL project that contains calculator logic.
 * Calculator.Core.Tests - Unit test project for the calculator logic.
 * Calculator.Droid - Xamarin.Android calculator project.
 * Calculator.iOS - Xamarin.iOS calculator project.
 * Calculator.UITests - Xamarin.UITest project for iOS and Android projects.

### Forms Projects

 * Calculator.Core - PCL project that contains calculator logic. Shared with both solutions.
 * Calculator.Forms - PCL project for Xamarin.Forms.
 * Calculator.Forms.Droid - Android calculator project.
 * Calculator.Forms.iOS - iOS calculator project.
 * Calculator.Forms.UITests - Xamarin.UITest project for Forms iOS and Android projects.


text:
package org.wildfly.camel.test.ejb;

import javax.naming.InitialContext;

import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.ServiceStatus;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.wildfly.camel.test.ejb.subA.HelloBean;
import org.wildfly.extension.camel.CamelAware;
import org.wildfly.extension.camel.CamelContextRegistry;

@CamelAware
@RunWith(Arquillian.class)
public class EjbEarSubWarSpringIntegrationTest {

    static final String SIMPLE_WAR = "camel-ejb-sub-deployment.war";
    static final String SIMPLE_EAR = "camel-ejb-ear.ear";

    @ArquillianResource
    CamelContextRegistry contextRegistry;

    @Deployment
    public static JavaArchive createDeployment() {
        return ShrinkWrap.create(JavaArchive.class, "camel-ejb-ear-tests");
    }

    @Test
    public void testEjbEarDeployment() throws Exception {
        CamelContext camelctx = contextRegistry.getCamelContext("ejb-ear-context");
        Assert.assertEquals(ServiceStatus.Started, camelctx.getStatus());
        assertContextAccess(camelctx);
    }

    @Test
    public void testEjbEarContextLookup() throws Exception {
        InitialContext inicxt = new InitialContext();
        CamelContext camelctx = (CamelContext) inicxt.lookup("java:jboss/camel/context/ejb-ear-context");
        Assert.assertEquals(ServiceStatus.Started, camelctx.getStatus());
        assertContextAccess(camelctx);
    }

    private void assertContextAccess(CamelContext camelctx) {
        ProducerTemplate producer = camelctx.createProducerTemplate();
        String result = producer.requestBody("direct:start", "Kermit", String.class);
        Assert.assertEquals("Hello Kermit", result);
    }

    @Deployment(name = SIMPLE_EAR, managed = true, testable = false)
    public static EnterpriseArchive createEarDeployment() {
        return ShrinkWrap.create(EnterpriseArchive.class, SIMPLE_EAR)
            .addAsModule(getEjbModule("ejb/ejb-ear-camel-context.xml"));
    }

    private static WebArchive getEjbModule(String descriptorName) {
        return ShrinkWrap.create(WebArchive.class, SIMPLE_WAR)
            .addAsWebInfResource(descriptorName, "ejb-camel-context.xml")
            .addClasses(HelloBean.class);
    }
}


text:
package re.agiledesign.mp2.internal.expressions;

import re.agiledesign.mp2.internal.Scope;
import re.agiledesign.mp2.lexer.Token;

public class ConstantExpression extends Expression {
	private final Object mConstant;

	public ConstantExpression(final Object aObject) {
		mConstant = aObject;
	}

	public ConstantExpression(final Token aToken) {
		mConstant = aToken.getValue();
	}

	public Object execute(Scope aScope) {
		return mConstant;
	}
}


text:
package Homework4;

import Homework4.Gate;

public class Gym {
    final Gate[] gates; // array of gates
    final int capacity; // capacity of the gym

    // initialize with number of gates set to 3 and capacity set to 1000
    public Gym() {
        this(3);
    }
    // initialize with specified number of gates and capacity set to 1000
    public Gym(int numOfGates) {
        this(numOfGates, 1000);
    }
    // initialize with specified number of gates and with specified capacity
    public Gym(int numOfGates, int capacity) {
        assert(numOfGates > 1);
        assert(capacity > 0);
        this.gates = new Gate[numOfGates];
        for (int idx = 0; idx < this.gates.length; idx++) {
            this.gates[idx] = new Gate("gate_" + Integer.toString(idx));
        }
        this.capacity = capacity;
    }

    // lock all gates
    public void lockDown() {
        for (Gate g : this.gates) {
            g.close();
        }
    }

    // open (roughly) half of the gates for in and the other half for out
    public void open() {
        this.open(this.gates.length / 2);
    }

    // open specific number of gate for in and leave the rest for out
    // if numOfInGate >= gates.length, then open (gates.length-1) gates for in and 1 for out
    // if numOfInGate <= 0, then open 1 gate for in and rest for out
    public void open(int numOfInGate) {
        this.lockDown();
        if (numOfInGate >= this.gates.length) {
            numOfInGate = this.gates.length - 1;
        } else if (numOfInGate < 1) {
            numOfInGate = 1;
        }
        for (int idx = 0; idx < this.gates.length; idx++) {
            State state = (idx+1 > numOfInGate) ? State.OUT : State.IN;
            this.gates[idx].open(state);
        }
    }

    // enters 1 person at gates[gateNumber] if the persons inside do not exceed capacity
    public void getIn(int gateNumber) {
        if (!this.validGateNumber(gateNumber)) {
            return;
        }
        if (this.canGoIn()) {
            this.gates[gateNumber].getIn(1);
        }
    }

    // exits 1 person at gates[gateNumber] if there is at least 1 person inside
    public void getOut(int gateNumber) {
        if (!this.validGateNumber(gateNumber)) {
            return;
        }
        Gate gate = this.gates[gateNumber];
        if (this.canGoOut()) {
            gate.getOut(1);
        }
    }
    // returns true if and only if capacity is not reached
    public boolean canGoIn() {
        return this.personsInside() < this.capacity;
    }
    // returns true if and only if it is not empty
    public boolean canGoOut() {
        return this.personsInside() > 0;
    }
    // return the number of persons inside the gym
    public int personsInside() {
        int n = 0;
        for (Gate g : this.gates) {
            n += g.numPersonGoneInside();
        }
        return n;
    }

    private boolean validGateNumber(int gateNumber) {
        return gateNumber >= 0 && gateNumber < this.gates.length;
    }

    // print each gate of the gym
    @Override
    public String toString() {
        // Initialize an array of strings to String.join()
        // The +1 is for the extra newline.
        String[] gateStrings = new String[this.gates.length+1];
        for (int idx = 0; idx < this.gates.length; idx++) {
            gateStrings[idx] = this.gates[idx].toString();
        }
        // Set the last string to "" so String.join() adds another newline at the end.
        gateStrings[this.gates.length] = ""; // Hack
        return String.join("\n", gateStrings);
    }
}


text:
<?php

namespace Prooph\ProcessingTest\Mock;

use Prooph\Processing\Environment\Environment;
use Prooph\Processing\Environment\Plugin;

/**
 * Class SimpleEnvPlugin
 *
 * @package Prooph\ProcessingTest\Mock
 * @author Alexander Miertsch <kontakt@codeliner.ws>
 */
class SimpleEnvPlugin implements Plugin
{
    /**
     * @var bool
     */
    private $registered = false;

    /**
     * Return the name of the plugin
     *
     * @return string
     */
    public function getName()
    {
        return get_class($this);
    }

    /**
     * Register the plugin on the workflow environment
     *
     * @param Environment $workflowEnv
     * @return void
     */
    public function registerOn(Environment $workflowEnv)
    {
        $this->registered = true;
    }

    /**
     * @return bool
     */
    public function isRegistered()
    {
        return $this->registered;
    }

    /**
     * @return string
     */
    public function getSupportedTypesComposerPackage()
    {
        return "";
    }

    /**
     * @return array
     */
    public function getSupportedMessagesByTypeMap()
    {
        return [];
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;

namespace ModernForms.Controls
{
    public class ModernMenuStrip : MenuStrip
    {
        Color hotTrackColor;
        public Color HotTrackColor
        {
            get { return hotTrackColor; }
            set { hotTrackColor = value; }
        }

        Color selectedColor;
        public Color SelectedColor
        {
            get { return selectedColor; }
            set { selectedColor = value; }
        }

        public ModernMenuStrip()
        {
            this.Renderer = new ModernToolStripRenderer();
            this.Dock = DockStyle.None;
            this.AutoSize = false;
            this.Padding = new Padding(1);
            this.Size = new Size(100, 30);
        }

        protected override void OnItemAdded(ToolStripItemEventArgs e)
        {
            int width = 1;

            for (int i = 0; i < this.Items.Count; i++)
            {
                width += this.Items[i].Width;
            }

            width += 1;

            this.Size = new Size(width, 30);

            base.OnItemAdded(e);
        }

        protected override void OnItemRemoved(ToolStripItemEventArgs e)
        {
            int width = 1;

            for (int i = 0; i < this.Items.Count; i++)
            {
                width += this.Items[i].Width;
            }

            width += 1;

            this.Size = new Size(width, 30);

            base.OnItemRemoved(e);
        }
    }
}


text:
'use strict';

var path = require('path');
var EE = require('events').EventEmitter;
var util = require('util');
var spawn = require('child_process').spawn;

module.exports = function(grunt) {

  var livereload = require('./livereload')(grunt);

  // Create a TaskRun on a target
  function TaskRun(target) {
    this.name = target.name || 0;
    this.files = target.files || [];
    this._getConfig = target._getConfig;
    this.options = target.options;
    this.startedAt = false;
    this.spawned = null;
    this.changedFiles = Object.create(null);
    this.spawnTaskFailure = false;
    this.livereloadOnError = true;
    if (typeof this.options.livereloadOnError !== 'undefined') {
      this.livereloadOnError = this.options.livereloadOnError;
    }
  }

  var getErrorCount = function() {
    if (typeof grunt.fail.forever_warncount !== 'undefined') {
      return grunt.fail.forever_warncount + grunt.fail.forever_errorcount;
    } else {
      return grunt.fail.warncount + grunt.fail.errorcount;
    }
  };

  // Run it
  TaskRun.prototype.run = function(done) {
    var self = this;

    // Dont run if already running
    if (self.startedAt !== false) { return; }

    // Start this task run
    self.startedAt = Date.now();

    // reset before each run
    self.spawnTaskFailure = false;
    self.errorsAndWarningsCount = getErrorCount();

    // pull the tasks here in case they were changed by a watch event listener
    self.tasks = self._getConfig('tasks') || [];
    if (typeof self.tasks === 'string') {
      self.tasks = [self.tasks];
    }

    // If no tasks just call done to trigger potential livereload
    if (self.tasks.length < 1) { return done(); }

    if (self.options.spawn === false || self.options.nospawn === true) {
      grunt.task.run(self.tasks);
      done();
    } else {
      var cmd = process.execPath;
      var args = process.execArgv.concat(process.argv[1]);
      args = args.concat(self.tasks.concat(self.options.cliArgs || []));
      var child = self.spawned = spawn(cmd, args, {
        cwd: self.options.cwd.spawn,
        stdio: 'inherit'
      });
      child.on('close', function(code, signal) {
        self.spawnTaskFailure = (code !== 0);
        if (self.options.interrupt !== true || (code !== 130 && code !== 1 && signal !== 'SIGINT')) {
          // Spawn is done
          self.spawned = null;
          done();
        }
      });
    }
  };

  // When the task run has completed
  TaskRun.prototype.complete = function() {
    var time = Date.now() - this.startedAt;
    this.startedAt = false;
    if (this.spawned) {
      this.spawned.kill('SIGINT');
      this.spawned = null;
    }

    var taskFailed = this.spawnTaskFailure || (getErrorCount() > this.errorsAndWarningsCount);
    this.errorsAndWarningsCount = getErrorCount();

    // Trigger livereload if necessary
    if (this.livereload && (this.livereloadOnError || !taskFailed)) {
      this.livereload.trigger(Object.keys(this.changedFiles));
      this.changedFiles = Object.create(null);
    }
    return time;
  };

  return TaskRun;
};


text:
require 'forwardable'

module Extras

  # A class that provides a queue-like (first-in, first-out)
  #  structure to clients
  class Fifo
    extend Forwardable

    def_delegators :@store, :length

    def initialize
      @store = Array.new
    end

    # Puts an object into the queue
    #
    # @param [Object] obj
    # @return [Fifo] The queue itself.
    def put!(obj)
      @store.push(obj)
      self
    end

    # Takes the least recently added element.
    #
    # @return [Object] whatever was stored in this queue.
    def take!
      @store.shift
    end
  end

end


text:
function smallestNumber(array){
  var smallest = array[0];
    for (var i = 0; i < array.length; i++){
      if(smallest > array[i]){
        smallest = array[i];
      }
    }

console.log(smallest)
}

 smallestNumber([10, 9, 2, 8, 6, 4])
// -------------------------------------------------------
// take sentence, split into array, iterate through and choose smallest word

function smallestWord(sentence) {
  var wordsArray = sentence.split(" ");
  var smallest = wordsArray[0];

  for (var i=0; i < wordsArray.length; i++) {
    if (smallest.length > wordsArray[i].length) {
      smallest = wordsArray[i];
    }
  }
  console.log(smallest);
}

// smallestWord("this is a sentence")
// -------------------------------------------------------
// take array of words, return the third greatest number in the array
// (two versions: one with sort, one without)

// version 1 -- not sorting the array first
function unsortedThirdGreatest(array) {
  var first = 0;
  var second = 0;
  var third = 0;

  for (var i=0; i < array.length; i++) {

    if (array[i] > first) {
      first = array[i];
    }
    else if (array[i] > second) {
      second = array[i];
    }
    else if (array[i] > third) {
      third = array[i];
    }
  }
  console.log(third)
}

// unsortedThirdGreatest([5, 11, 10, 8, 2, 6])

//version 2 -- sorting the array first

function sortedThirdGreatest(array) {
  array.sort(function(a, b) {
    return a - b;
  }).reverse();
  var thirdGreatest = array[2]
  console.log(thirdGreatest);
}

// sortedThirdGreatest([5, 11, 10, 8, 2, 6])
// -------------------------------------------------------
// method that returns the most common letter in a string

function mostCommonLetter(string) {
  var mostCommon = "";
  var highestCount = 0;
  var stringArray = string.split("");

  for (var i=0; i < stringArray.length; i++) {
    var current = stringArray[i];
    var currentCount = stringArray.map( function(element) {
      if (element === current) {
        return element;
      }
    }).filter(Boolean).length

    if (currentCount > highestCount) {
      highestCount = currentCount;
      mostCommon = current;
    }
  }
  console.log(mostCommon);
}

// mostCommonLetter("ttttrggr")
// ------------------------------------------------------
// add commas into a number to look like a standard number

function injectCommas(number) {
  var backwardsArray = number.toString().split("").reverse();
  var splitSets = new Array;

  while (backwardsArray.length) {
    var set = backwardsArray.splice(0, 3);
    splitSets.push(set.reverse().join(""));
  }
  console.log(splitSets.reverse().join(","));
}

// injectCommas(23451);
// injectCommas(8468247468450);
// -------------------------------------------------------
// write a method that returns the factorial of a given number

function recursiveFactorial(num){
  if (num == 1) {
    return 1;
  }
  else if (num == 0) {
    return 1;
  }
  else {
    return num * recursiveFactorial(num - 1);
  }
}

// var result = recursiveFactorial(3);
// console.log(result);
// -------------------------------------------------------
// write a method that takes an array of numbers and returns true if any
// number in the array, added up to its index, equals 10.

function addToTen(array) {
  var numsPlusIndex = new Array;

  for (var i=0; i < array.length; i++) {
    numsPlusIndex.push(array[i] + i);
  }

  for (var i=0; i < numsPlusIndex.length; i++) {
    if (numsPlusIndex[i] === 10) {
      return true;
    }
  }
  return false;
}

// console.log(addToTen([2, 9, 3, 4]));
// -------------------------------------------------------
// write method that prints out factors for each number from 1 to a given max.

function getFactors(num) {
  var range = new Array;
  for (var i=1; i <= num; i++) {
    range.push(i);
  }

  var factors = new Array;
  for (var i=0; i < range.length; i++) {
    if (num % range[i] === 0) {
      factors.push(range[i]);
    }
  }
  console.log(factors);
}

// getFactors(8);
// -------------------------------------------------------
// method that takes an array of numbers, and returns a new array with all the numbers doubled

function doubler(array) {
  var doubledNums = array.map( function(elem) {
    return elem * 2;
  });
  console.log(doubledNums);
}

// doubler([1, 2, 3, 4, 5]);
// -------------------------------------------------------
// Write a function oddball_sum(numbers), which takes in an array of
// integers and returns the sum of all the odd elements.

function oddballSum(array) {
  var sumArray = new Array;

  for (var i=0; i < array.length; i++) {
    if (!(array[i] % 2 === 0)) {
      sumArray.push(array[i]);
    }
    else if (array[i] === 1) {
      sumArray.push(array[i]);
    }
  }

  var sum = 0;
  for (var i=0; i < sumArray.length; i++) {
    sum = sum + sumArray[i];
  }

  console.log(sum);
}

// oddballSum([1, 4, 5, 3, 1])
// -------------------------------------------------------
// method that takes two numbers and returns the greatest common factor
function euclidGreatestCommonFactor(numOne, numTwo){
  if (numOne > numTwo) {
    var larger = numOne;
    var smaller = numTwo;
  }
  else {
    var larger = numTwo;
    var smaller = numOne;
  }

  var remainder = larger % smaller;

  if (!(remainder === 0)) {
    console.log(remainder);
    return euclidGreatestCommonFactor(smaller, remainder);
  }
}

// euclidGreatestCommonFactor(30, 12);
// euclidGreatestCommonFactor(45, 330);
// euclidGreatestCommonFactor(345, 230);
// -------------------------------------------------------
// Write a function disemvowel(string), which takes in a string,
// and returns that string will all the vowels removed.

function disemvowel(string) {
  var noVowels = new Array;
  var vowels = [ "a", "e", "i", "o", "u" ];
  var letters = string.split("");
  for (var i=0; i < letters.length; i++) {
    var current = letters[i];
    var tester = false;
    for (var j=0; j < vowels.length; j++) {
      if (current === vowels[j]) {
        tester = true;
      }
    }
    if (!tester) {
      noVowels.push(current);
    }
  }
  console.log(noVowels.join(""));
}

// disemvowel("this sentence might still be readable");
// -------------------------------------------------------
// method that takes a number and returns true/false depending on if it is prime

function primeTester(num) {
  var range = new Array;
  for (var i=1; i <= num; i++) {
    range.push(i);
  }

  var factors = new Array;
  for (var i=0; i < range.length; i++) {
    var current = range[i];
    if (num % current === 0) {
      factors.push(current);
    }
  }

  if (factors.length === 2) {
    return true;
  }
  return false;
}

// console.log(primeTester(37));
// console.log(primeTester(22));
// -------------------------------------------------------
// adding up items in an array

function sumUpArray(array) {
  var sum = 0;
  for (var i=0; i < array.length; i++) {
    sum = sum + array[i];
  }
  console.log(sum);
}

// sumUpArray([1, 2, 3, 4, 5, 6]);
// -------------------------------------------------------
// sum of integers from 1 to given num

function sumToMax(max) {
  var sum = 0;
  for (var i=1; i <= max; i++) {
    sum = sum + i;
  }
  console.log(sum);
}

// sumToMax(6);
// -------------------------------------------------------
// reverse a string || reverse an array

function reverseString(string) {
  var chars = string.split("").reverse();
  console.log(chars.join(""));
}

// reverseString("string");

function reverseArray(array) {
  console.log(array.reverse());
}

// reverseArray([1, 2, 3, 4, 5]);
// -------------------------------------------------------
// find the mode in a given array

function findMode(array) {
  var hashOfValues = {
  };
  for (var i=0; i < array.length; i++) {
    var count = 0;
    var current = array[i];
    for (var j=0; j < array.length; j++) {
      var secondCurrent = array[j];
      if (secondCurrent === current) {
        count += 1;
      }
    }
    hashOfValues[count] = current;
  }
  var highestCount = 0;
  for (var elem in hashOfValues) {
    if (elem > highestCount) {
      highestCount = elem;
    }
  }
  console.log(hashOfValues[highestCount]);
}
// findMode([1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4]);
// -------------------------------------------------------
// count vowels in a string

function countVowels(string) {
  var totalCount = 0;

  var vowels = [ "a", "e", "i", "o", "u" ];
  var letters = string.split("");

  for (var i=0; i < letters.length; i++) {
    var current = letters[i];
    for (var j=0; j < vowels.length; j++) {
      if (current === vowels[j]) {
        totalCount = totalCount + 1;
      }
    }

  }
  console.log(totalCount);
}

// countVowels("talekijohu");
// -------------------------------------------------------
// recursive palindrome

function recursivePalindrome(word) {
  if (word.length === 1) {
    return true;
  }
  else if (word.length === 2) {
    if (word[0] === word[1]) {
      return true;
    }
    else {
      return false;
    }
  }
  else {
    var newWord = word.slice(1, -1);
    return recursivePalindrome(newWord);
  }
}

// console.log(recursivePalindrome("radar"));
// console.log(recursivePalindrome("tart"));
// -------------------------------------------------------
// method that takes a book title and capitalizes appropriately

function capitalizeBookTitles(titleString) {
  var wordsArray = titleString.split(" ");
  var noCapitalize = [ "a", "the", "of", "an", "to", "for", "if" ];
  var titlizedArray = [];

  for (var i=0; i < wordsArray.length; i++) {
    var word = wordsArray[i];
    var inNoCapitalize = false;
    for (var j=0; j < noCapitalize.length; j++) {
      if (noCapitalize[j] == word) {
        inNoCapitalize = true;
      }
    }

    if (i === 0) {
      var newWord = word.charAt(0).toUpperCase() + word.slice(1);
      titlizedArray.push(newWord);
    }
    else if (!(inNoCapitalize)) {
      var newWord = word.charAt(0).toUpperCase() + word.slice(1);
      titlizedArray.push(newWord);
    }
    else {
      titlizedArray.push(word);
    }

  }
  console.log(titlizedArray.join(" "));
}

// capitalizeBookTitles("the life changing magic of tidying up");
// -------------------------------------------------------
// 'nearby az': Write a method that takes a string in and returns true if the letter
// "z" appears within three letters **after** an "a". You may assume
// that the string contains only lowercase letters.

// -------------------------------------------------------
// Write a method that takes an array of numbers. If a pair of numbers
// in the array sums to zero, return true. If no pair of numbers sums to zero,
// return false.

function twoSum(array) {
  var toZero = false;
  for (var i=0; i < array.length; i++) {
    var current = array[i];
    for (var j=0; j < array.length; j++) {
      var comparator = array[j];
      if (!(current === comparator)) {
        if (current + comparator === 0) {
          toZero = true;
        }
      }
    }
  }
  console.log(toZero);
}

// twoSum([1, 2, 3, 3, -2, 4, 5]);

// -------------------------------------------------------
// method that takes an array of words ["grasping", "turning", "running", "fighting"]
// and selects a word that contains "turn"

function wordInArray(array, wordToFind) {
  var word = "";
  for (var i=0; i < array.length; i++) {
    var current = array[i];
    if (current.indexOf(wordToFind) > -1) {
      word = current;
    }
  }
  console.log(word);
}

// wordInArray(["turning", "running", "hanging", "instruct"], "tru")
// wordInArray(["turning", "running", "hanging", "instructing"], "run")

// -------------------------------------------------------
// fahrenheit to celsius conversion & celsius to fahrenheit

function temperatureConversion(temp, toNewType) {
  if ((toNewType[0] === "c") || (toNewType[0] === "C")) {
    // convert to celsius
    console.log((temp - 32) * (5/9))
  }
  else {
    // convert to fahrenheit
    console.log((temp * 9/5) + 32)
  }
}

// temperatureConversion(36, "Fahrenheit") // 98.8
// temperatureConversion(98, "Celsius") // 36.66...7

// -------------------------------------------------------
// method that returns true if num passed to it is a power of 2, otherwise return false
// my method: It repeatedly divides x, the 32-bit unsigned integer being tested, by 2.
// It divides until either the quotient becomes 1, in which case x is a power of two,
// or the quotient becomes odd before reaching 1, in which case x is not a power of two.
function checkIfPowerOfTwo(num) {
  while ((num % 2 === 0) && (num > 1)) {
    num = num / 2
  }
  console.log(num === 1);
}

// checkIfPowerOfTwo(2 * 2 * 2 * 2);
// checkIfPowerOfTwo(2 * 2 * 3);
// -------------------------------------------------------
// method that finds perfect squares in a given array

// -------------------------------------------------------
// Write a method that takes in a string and an array of indices in the
// string. Produce a new string, which contains letters from the input
// string in the order specified by the indices of the array of indices.

// -------------------------------------------------------
// Write a method that takes in a string and returns the number of
// letters that appear more than once in the string. You may assume
// the string contains only lowercase letters. Count the number of
// letters that repeat, not the number of times they repeat in the string.

// -------------------------------------------------------
// Write a function lucky_sevens?(numbers), which takes in an array of integers
// and returns true if any three consecutive elements sum to 7.

// -------------------------------------------------------
// given a word, return true if that word's vowels are in alphabetical order.

// -------------------------------------------------------
// bubble sort an array

// -------------------------------------------------------
//In Ruby, Array has a `uniq` method that removes duplicates from an array. It
// returns the unique elements in the order in which they first appeared:
//
// [1, 2, 1, 3, 3].uniq # => [1, 2, 3]
//
// Write your own `uniq` method, called `my_uniq`; it should take in an
// Array and return a new array. It should not call `uniq`.

//   Implement a Rock, Paper, Scissors game. The method `rps` should take
//   a string (either "Rock", "Paper" or "Scissors") as a parameter and
//   return the computer's choice, and the outcome of the match. Example:
//
// rps("Rock") # => "Paper, Lose"
// rps("Scissors") # => "Scissors, Draw"
// rps("Scissors") # => "Paper, Win"

// -------------------------------------------------------
//   Implement a Swingers game. The method `swingers` should take an
//   array of couple arrays and return the same type of data structure,
//   with the couples mixed up. Assume that the first item in the couple
//   array is a man, and the second item is a woman. Don't pair a person
//   with someone of their own gender (sorry to ruin your fun). An
//   example run of the program:
//
// swingers([
//   ["Clyde", "Bonnie"],
//   ["Paris", "Helen"],
//   ["Romeo", "Juliet"]
// ])

// -------------------------------------------------------
// Write a method `substrings` that will take a `String` and return an
// array containing each of its substrings.
// Example output: substrings("cat") => ["c", "ca", "cat", "a", "at", "t"]

// -------------------------------------------------------
// To represent a *matrix*, or two-dimensional grid of numbers, we can
// write an array containing arrays which represent rows:
//
// rows = [
//     [0, 1, 2],
//     [3, 4, 5],
//     [6, 7, 8]
//   ]
//
// row1 = rows[0]
// row2 = rows[1]
// row3 = rows[2]
//
// We could equivalently have stored the matrix as an array of
// columns:
//
// cols = [
//     [0, 3, 6],
//     [1, 4, 7],
//     [2, 5, 8]
//   ]
// Write a method, `my_transpose`, which will convert between the
// row-oriented and column-oriented representations.

// -------------------------------------------------------
// Martha has created a hash with letter symbols as keys to represent items that start
// with their keys. However, she realized everything is off by one letter.
//
// wrong_hash = { :a => "banana", :b => "cabbage", :c => "dental_floss", :d => "eel_sushi" }
//
// Write a program `hash_correct` that takes this wrong hash and returns the correct one.


text:
require 'spec_helper'

describe RailsBestPractices::Reviews::SimplifyRenderInViewsReview do
  let(:runner) { RailsBestPractices::Core::Runner.new(:reviews => RailsBestPractices::Reviews::SimplifyRenderInViewsReview.new) }

  it "should simplify render simple partial" do
    content =<<-EOF
    <%= render :partial => 'sidebar' %>
    EOF
    runner.review('app/views/posts/index.html.erb', content)
    runner.should have(1).errors
    runner.errors[0].to_s.should == "app/views/posts/index.html.erb:1 - simplify render in views"
  end

  it "should simplify render partial with object" do
    content =<<-EOF
    <%= render :partial => 'post', :object => @post %>
    EOF
    runner.review('app/views/posts/index.html.erb', content)
    runner.should have(1).errors
    runner.errors[0].to_s.should == "app/views/posts/index.html.erb:1 - simplify render in views"
  end

  it "should simplify render partial with collection" do
    content =<<-EOF
    <%= render :partial => 'posts', :collection => @posts %>
    EOF
    runner.review('app/views/posts/index.html.erb', content)
    runner.should have(1).errors
    runner.errors[0].to_s.should == "app/views/posts/index.html.erb:1 - simplify render in views"
  end

  it "should simplify render partial with local variables" do
    content =<<-EOF
    <%= render :partial => 'comment', :locals => { :parent => post } %>
    EOF
    runner.review('app/views/posts/index.html.erb', content)
    runner.should have(1).errors
    runner.errors[0].to_s.should == "app/views/posts/index.html.erb:1 - simplify render in views"
  end

  it "should not simplify render simple partial" do
    content =<<-EOF
    <%= render 'sidebar' %>
    <%= render 'shared/sidebar' %>
    EOF
    runner.review('app/views/posts/index.html.erb', content)
    runner.should have(0).errors
  end

  it "should not simplify render partial with object" do
    content =<<-EOF
    <%= render @post %>
    EOF
    runner.review('app/views/posts/index.html.erb', content)
    runner.should have(0).errors
  end

  it "should not simplify render partial with collection" do
    content =<<-EOF
    <%= render @posts %>
    EOF
    runner.review('app/views/posts/index.html.erb', content)
    runner.should have(0).errors
  end

  it "should not simplify render partial with local variables" do
    content =<<-EOF
    <%= render 'comment', :parent => post %>
    EOF
    runner.review('app/views/posts/index.html.erb', content)
    runner.should have(0).errors
  end

  it "should not simplify render partial with complex partial" do
    content =<<-EOF
    <%= render :partial => 'shared/post', :object => @post %>
    EOF
    runner.review('app/views/posts/index.html.erb', content)
    runner.should have(0).errors
  end
end


text:
<?php defined('SYSPATH') OR die('No direct script access.');

class Task_Asset_Generate extends Minion_Task {

	protected $_options = array(
		'view' => FALSE,
	);

	public function build_validation(Validation $validation)
	{
		return parent::build_validation($validation)
			->rule('view', 'not_empty')
			->rule('view', 'Kohana::find_file', array('views', ':value'));
	}

	protected function _execute(array $options)
	{
		$view = View::factory($options['view']);
		$view->render();

		Minion_CLI::write('View rendered, assets should be generated');
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<PRONOM-Report xmlns="http://pronom.nationalarchives.gov.uk">
  <report_format_detail>
    <FileFormat>
      <FormatID>1107</FormatID>
      <FormatName>pulse EKKO data file</FormatName>
      <FormatVersion>
      </FormatVersion>
      <FormatAliases>
      </FormatAliases>
      <FormatFamilies>
      </FormatFamilies>
      <FormatTypes>
      </FormatTypes>
      <FormatDisclosure>
      </FormatDisclosure>
      <FormatDescription>This is an outline record only, and requires further details, research or authentication to provide information that will enable users to further understand the format and to assess digital preservation risks associated with it if appropriate. If you are able to help by supplying any additional information concerning this entry, please return to the main PRONOM page and select 'Add an Entry'.</FormatDescription>
      <BinaryFileFormat>
      </BinaryFileFormat>
      <ByteOrders>
      </ByteOrders>
      <ReleaseDate>
      </ReleaseDate>
      <WithdrawnDate>
      </WithdrawnDate>
      <ProvenanceSourceID>170</ProvenanceSourceID>
      <ProvenanceName>Archaeology Data Service / Archaeology Data Service</ProvenanceName>
      <ProvenanceSourceDate>18 Aug 2011</ProvenanceSourceDate>
      <ProvenanceDescription>Submitted by Archaeology Data Service</ProvenanceDescription>
      <LastUpdatedDate>18 Aug 2011</LastUpdatedDate>
      <FormatNote>
      </FormatNote>
      <FormatRisk>
      </FormatRisk>
      <TechnicalEnvironment>
      </TechnicalEnvironment>
      <FileFormatIdentifier>
        <Identifier>fmt/360</Identifier>
        <IdentifierType>PUID</IdentifierType>
      </FileFormatIdentifier>
      <Developers>
        <DeveloperID>171</DeveloperID>
        <DeveloperName>Sensors and Software Inc.</DeveloperName>
        <OrganisationName>Sensors and Software Inc.</OrganisationName>
        <DeveloperCompoundName>Sensors and Software Inc. / Sensors and Software Inc.</DeveloperCompoundName>
      </Developers>
      <ExternalSignature>
        <ExternalSignatureID>1129</ExternalSignatureID>
        <Signature>dt1</Signature>
        <SignatureType>File extension</SignatureType>
      </ExternalSignature>
      <InternalSignature>
        <SignatureID>529</SignatureID>
        <SignatureName>pulse EKKO data file</SignatureName>
        <SignatureNote>A binary data file which contains a record for every trace. Each record consists of a 128-byte header section and a data section. Header section starts: 00 00 80 3F</SignatureNote>
        <ByteSequence>
          <ByteSequenceID>654</ByteSequenceID>
          <PositionType>Absolute from BOF</PositionType>
          <Offset>0</Offset>
          <MaxOffset>
          </MaxOffset>
          <IndirectOffsetLocation>
          </IndirectOffsetLocation>
          <IndirectOffsetLength>
          </IndirectOffsetLength>
          <Endianness>
          </Endianness>
          <ByteSequenceValue>0000803F{12}00000000{4}0000{2}0000{1}[41:42]{8}0000000000000000000000000000000000000000{28}00000000{3}[40:49]</ByteSequenceValue>
        </ByteSequence>
      </InternalSignature>
    </FileFormat>
    <SearchCriteria>Criteria</SearchCriteria>
  </report_format_detail>
</PRONOM-Report>


text:
<?php

ini_set('display_errors',1);
error_reporting(E_ALL);

// Load configurations
$CONFIGS = parse_ini_file('config.ini', true);

// Include database class
require 'class/database.php';

// Create a pointer to $database
$database = new database();

// Resident code
$intCodSur = filter_input(INPUT_POST, 'intCodSur', FILTER_SANITIZE_NUMBER_INT);
// Resident name
$strNomSur = filter_input(INPUT_POST, 'strNomSur', FILTER_SANITIZE_STRING);
// Resident address
$strEndSur = filter_input(INPUT_POST, 'strEndSur', FILTER_SANITIZE_STRING);
// Resident gender
$strSexSur = filter_input(INPUT_POST, 'strSexSur', FILTER_SANITIZE_STRING);
// City code
$intCodCid = filter_input(INPUT_POST, 'intCodCid', FILTER_SANITIZE_NUMBER_INT);
// Locality code
$intCodBai = filter_input(INPUT_POST, 'intCodBai', FILTER_SANITIZE_NUMBER_INT);
// Resident telephone
$strTelSur = filter_input(INPUT_POST, 'strTelSur', FILTER_SANITIZE_STRING);
// Resident email
$strEmaSur = filter_input(INPUT_POST, 'strEmaSur', FILTER_SANITIZE_STRING);
// Resident obs
$strObsSur = filter_input(INPUT_POST, 'strObsSur', FILTER_SANITIZE_STRING);
// Latitude
$dblLatPosSur = filter_input(INPUT_POST, 'dblLatPosSur', FILTER_VALIDATE_FLOAT);
// Longitude
$dblLonPosSur = filter_input(INPUT_POST, 'dblLonPosSur', FILTER_VALIDATE_FLOAT);
// Color Marker
$strCorMarSur = filter_input(INPUT_POST, 'strCorMarSur', FILTER_SANITIZE_STRING);
// Campaign code
$intCodCam = filter_input(INPUT_POST, 'intCodCam', FILTER_SANITIZE_STRING);
// Campaign year
$intAnoCam = filter_input(INPUT_POST, 'intAnoCam', FILTER_SANITIZE_NUMBER_INT);
// Resident map zoom
$intZooSur = filter_input(INPUT_POST, 'intZooSur', FILTER_SANITIZE_NUMBER_INT);

$where = '';
if ($intCodSur) {
    $operation = 'update';
    $where = ' where codsur = :surdo';
}
else {
    $result = $database->select('select max(CODSUR) FROM SURDO')->fetch();
    $intCodSur = $result[0]+1;

    $operation = 'insert into';
}

$strDesCid = '';
$strNomBai = '';
if ($intCodCid) {
    $result = $database->select('select DESCID, SIGEST FROM CIDADE WHERE CODCID = ' . $intCodCid)->fetch();
    $strDesCid = $result['DESCID'];
    $strSigEst = $result['SIGEST'];
}
if ($intCodBai) {
    $result = $database->select('select NOMBAI FROM BAIRRO WHERE CODCID = ' . $intCodCid . ' AND CODBAI = ' . $intCodBai)->fetch();
    $strNomBai = $result['NOMBAI'];
}

if (!$dblLatPosSur || !$dblLonPosSur) {
    $src = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=" . urlencode($strEndSur . ($strNomBai ? ', ' . $strNomBai : '') . ($strDesCid ? ', ' . $strDesCid : '') . ($strSigEst ? ', ' . $strSigEst : '')) . "&sensor=false", 10);
    $google = json_decode($src);

    $dblLatPosSur = number_format($google->results[0]->geometry->location->lat, 7, '.', '');
    $dblLonPosSur = number_format($google->results[0]->geometry->location->lng, 7, '.', '');

    if ($google->status == 'ZERO_RESULTS') {
        echo $strEndSur . '\n Falha na atualização do endereço.';
        exit;
    }
}

$strSexSur = (in_array($strSexSur, array('F', 'M')) ? $strSexSur : null);

if ($operation && $strNomSur && $dblLatPosSur && $dblLonPosSur) {
    $stm = $database->execute($operation . ' surdo set ' . ($operation == 'insert into' ? 'data_criacao = curdate(),' : '') . ' codsur = :surdo, codcid = :cidade, codbai = :bairro, nomsur = :nome, sexsur = :sexo, endsur = :endereco, telsur = :telefone, emasur = :email, obssur = :obs, LATPOSSUR = :lat, LONPOSSUR = :lon, CORMARSUR = :cor, ZOOSUR = :zoom ' . $where, array(':cidade' => $intCodCid, ':bairro' => (int)$intCodBai, ':surdo' => $intCodSur, ':nome' => $strNomSur, ':endereco' => $strEndSur, ':sexo' => $strSexSur, ':telefone' => $strTelSur, ':email' => $strEmaSur, ':obs' => $strObsSur, ':lat' => $dblLatPosSur, ':lon' => $dblLonPosSur, ':cor' => $strCorMarSur, ':zoom' => $intZooSur ));
    if ($stm->errorCode()) {
        $info = $stm->errorInfo();
        echo $info[2];
    }
}

if ($intCodCam && $intCodSur && $intAnoCam) {
    foreach (explode(',', $intCodCam) as $intCodCamAux) {
        $smt = $database->execute('INSERT INTO CAMPANHAESPECIALSURDO SET CODCAM = :campanha, ANOCAM = :ano, CODSUR = :surdo',
                array(':campanha' => $intCodCamAux, ':ano' => $intAnoCam, ':surdo' => $intCodSur));
    }
}


text:
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;

namespace FluidDbClient.Sql.Test
{
    public class DataContext : DbContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

            modelBuilder.AddAllTypeConfigurations();

            base.OnModelCreating(modelBuilder);
        }
    }
}


text:
import test
import warnings
from test import env
from test.asyncio_tests import AsyncIOTestCase, asyncio_test

import bson

from motor.motor_asyncio import AsyncIOMotorClientSession, AsyncIOMotorGridFSBucket

class TestAsyncIOAwait(AsyncIOTestCase):
    @asyncio_test
    async def test_to_list(self):
        collection = self.collection
        await collection.delete_many({})

        results = await collection.find().sort("_id").to_list(length=None)
        self.assertEqual([], results)

        docs = [{"_id": 1}, {"_id": 2}]
        await collection.insert_many(docs)
        cursor = collection.find().sort("_id")
        results = await cursor.to_list(length=None)
        self.assertEqual(docs, results)
        results = await cursor.to_list(length=None)
        self.assertEqual([], results)

    @asyncio_test
    async def test_iter_cursor(self):
        collection = self.collection
        await collection.delete_many({})

        for n_docs in 0, 1, 2, 10:
            if n_docs:
                docs = [{"_id": i} for i in range(n_docs)]
                await collection.insert_many(docs)

            # Force extra batches to test iteration.
            j = 0
            async for doc in collection.find().sort("_id").batch_size(3):
                self.assertEqual(j, doc["_id"])
                j += 1

            self.assertEqual(j, n_docs)

            j = 0
            raw_cursor = collection.find_raw_batches().sort("_id").batch_size(3)
            async for batch in raw_cursor:
                j += len(bson.decode_all(batch))

            await collection.delete_many({})

    @asyncio_test
    async def test_iter_aggregate(self):
        collection = self.collection
        await collection.delete_many({})
        pipeline = [{"$sort": {"_id": 1}}]

        # Empty iterator.
        async for _ in collection.aggregate(pipeline):
            self.fail()

        for n_docs in 1, 2, 10:
            if n_docs:
                docs = [{"_id": i} for i in range(n_docs)]
                await collection.insert_many(docs)

            # Force extra batches to test iteration.
            j = 0
            cursor = collection.aggregate(pipeline).batch_size(3)
            async for doc in cursor:
                self.assertEqual(j, doc["_id"])
                j += 1

            self.assertEqual(j, n_docs)

            j = 0
            raw = collection.aggregate_raw_batches(pipeline).batch_size(3)
            async for batch in raw:
                j += len(bson.decode_all(batch))

            self.assertEqual(j, n_docs)
            await collection.delete_many({})

    @asyncio_test
    async def test_iter_gridfs(self):
        gfs = AsyncIOMotorGridFSBucket(self.db)

        async def cleanup():
            await self.db.fs.files.delete_many({})
            await self.db.fs.chunks.delete_many({})

        await cleanup()

        # Empty iterator.
        async for _ in gfs.find({"_id": 1}):
            self.fail()

        data = b"data"

        for n_files in 1, 2, 10:
            for _ in range(n_files):
                async with gfs.open_upload_stream(filename="filename") as f:
                    await f.write(data)

            # Force extra batches to test iteration.
            j = 0
            async for _ in gfs.find({"filename": "filename"}).batch_size(3):
                j += 1

            self.assertEqual(j, n_files)
            await cleanup()

        await gfs.upload_from_stream_with_id(1, "filename", source=data, chunk_size_bytes=1)
        cursor = gfs.find({"_id": 1})
        await cursor.fetch_next
        gout = cursor.next_object()
        chunks = []
        async for chunk in gout:
            chunks.append(chunk)

        self.assertEqual(len(chunks), len(data))
        self.assertEqual(b"".join(chunks), data)

    @asyncio_test
    async def test_stream_to_handler(self):
        # Sort of Tornado-specific, but it does work with asyncio.
        fs = AsyncIOMotorGridFSBucket(self.db)
        content_length = 1000
        await fs.delete(1)
        await fs.upload_from_stream_with_id(1, "filename", source=b"a" * content_length)
        gridout = await fs.open_download_stream(1)
        handler = test.MockRequestHandler()
        await gridout.stream_to_handler(handler)
        self.assertEqual(content_length, handler.n_written)
        await fs.delete(1)

    @asyncio_test
    async def test_cursor_iter(self):
        # Have we handled the async iterator change in Python 3.5.2?:
        # python.org/dev/peps/pep-0492/#api-design-and-implementation-revisions
        with warnings.catch_warnings(record=True) as w:
            async for _ in self.collection.find():
                pass

        if w:
            self.fail(w[0].message)

    @asyncio_test
    async def test_list_indexes(self):
        await self.collection.drop()
        await self.collection.create_index([("x", 1)])
        await self.collection.create_index([("y", -1)])
        keys = set()
        async for info in self.collection.list_indexes():
            keys.add(info["name"])

        self.assertEqual(keys, {"_id_", "x_1", "y_-1"})

    @env.require_version_min(3, 6)
    @env.require_replica_set
    @asyncio_test
    async def test_session(self):
        s = await self.cx.start_session()
        self.assertIsInstance(s, AsyncIOMotorClientSession)
        self.assertIs(s.client, self.cx)
        self.assertFalse(s.has_ended)
        await s.end_session()
        self.assertTrue(s.has_ended)

        # Raises a helpful error if used in a regular with-statement.
        with self.assertRaises(AttributeError) as ctx:
            with await self.cx.start_session():
                pass

        self.assertIn("async with await", str(ctx.exception))

        async with await self.cx.start_session() as s:
            self.assertIsInstance(s, AsyncIOMotorClientSession)
            self.assertFalse(s.has_ended)
            await s.end_session()
            self.assertTrue(s.has_ended)

        self.assertTrue(s.has_ended)

    @env.require_version_min(3, 7)
    @env.require_replica_set
    @asyncio_test
    async def test_transaction(self):
        async with await self.cx.start_session() as s:
            s.start_transaction()
            self.assertTrue(s.in_transaction)
            self.assertFalse(s.has_ended)
            await s.end_session()
            self.assertFalse(s.in_transaction)
            self.assertTrue(s.has_ended)

        async with await self.cx.start_session() as s:
            # Use start_transaction in "async with", not "async with await".
            with self.assertRaises(TypeError):
                async with await s.start_transaction():
                    pass

            await s.abort_transaction()

            async with s.start_transaction():
                self.assertTrue(s.in_transaction)
                self.assertFalse(s.has_ended)
            self.assertFalse(s.in_transaction)
            self.assertFalse(s.has_ended)

        self.assertTrue(s.has_ended)


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

Description: RSS1 Version works
Expect: result.version == 'atom'
-->
<feed xmlns="http://www.w3.org/2005/Atom">

</feed>


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
es5id: 15.2.3.12-2-a-5
description: >
    Object.isFrozen - 'P' is own accessor property that overrides an
    inherited data property
---*/

        var proto = {};

        Object.defineProperty(proto, "foo", {
            value: 12,
            configurable: false
        });

        var Con = function () { };
        Con.prototype = proto;
        var child = new Con();

        Object.defineProperty(child, "foo", {
            get: function () {
                return 9;
            },
            configurable: true
        });

        Object.preventExtensions(child);

assert.sameValue(Object.isFrozen(child), false, 'Object.isFrozen(child)');


text:
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
const _excluded = ["externalLabel"];

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

import React, { useState } from 'react';
import { ExtendComponentsThemeProvider } from '@looker/components-providers';
import { defaultArgTypes as argTypes } from '@looker/storybook';
import { Button } from '../../../Button';
import { Popover, PopoverContent } from '../../../Popover';
import { DateFormat } from '../../Inputs/DateFormat';
import { FieldDate } from './FieldDate';
export default {
  argTypes,
  component: FieldDate,
  title: 'FieldDate'
};

const Template = _ref => {
  let {
    externalLabel = true
  } = _ref,
      args = _objectWithoutProperties(_ref, _excluded);

  return React.createElement(ExtendComponentsThemeProvider, {
    themeCustomizations: {
      defaults: {
        externalLabel
      }
    }
  }, React.createElement(FieldDate, args));
};

export const Basic = Template.bind({});
Basic.args = {
  defaultValue: new Date('July 25, 2020'),
  label: 'Example'
};
export const Disabled = Template.bind({});
Disabled.args = _objectSpread(_objectSpread({}, Basic.args), {}, {
  disabled: true
});
export const Required = Template.bind({});
Required.args = _objectSpread(_objectSpread({}, Basic.args), {}, {
  required: true
});
export const Error = Template.bind({});
Error.args = _objectSpread(_objectSpread({}, Basic.args), {}, {
  validationMessage: {
    message: 'Error Message',
    type: 'error'
  }
});
export const Controlled = () => {
  const [controlledDate, setControlledDate] = useState();

  function handleNextWeekClick() {
    setControlledDate(new Date('03/09/2020'));
  }

  return React.createElement(Popover, {
    content: React.createElement(PopoverContent, null, React.createElement(Button, {
      onClick: handleNextWeekClick
    }, "Next Week"), React.createElement(FieldDate, {
      value: controlledDate,
      onChange: setControlledDate
    }))
  }, React.createElement(Button, null, controlledDate ? React.createElement(React.Fragment, null, React.createElement(DateFormat, null, controlledDate)) : 'Select Dates'));
};
Controlled.parameters = {
  storyshots: {
    disable: true
  }
};
export const ControlledFloatingLabelNoValue = () => {
  const [today, setToday] = useState();

  const onClickSelectToday = () => setToday(new Date());

  return React.createElement(ExtendComponentsThemeProvider, {
    themeCustomizations: {
      defaults: {
        externalLabel: false
      }
    }
  }, React.createElement(Button, {
    onClick: onClickSelectToday
  }, "Today"), React.createElement(FieldDate, {
    externalLabel: false,
    label: "Controlled",
    value: today,
    onChange: setToday
  }));
};
ControlledFloatingLabelNoValue.parameters = {
  storyshots: {
    disable: true
  }
};
export const ControlledFloatingLabel = () => {
  const [today, setToday] = useState(new Date('04/07/1776'));

  const onClickSelectToday = () => setToday(new Date());

  return React.createElement(ExtendComponentsThemeProvider, {
    themeCustomizations: {
      defaults: {
        externalLabel: false
      }
    }
  }, React.createElement(Button, {
    onClick: onClickSelectToday
  }, "Today"), React.createElement(FieldDate, {
    externalLabel: false,
    label: "Controlled",
    value: today,
    onChange: setToday
  }));
};
ControlledFloatingLabel.parameters = {
  storyshots: {
    disable: true
  }
};
export const FloatingLabel = Template.bind({});
FloatingLabel.args = _objectSpread(_objectSpread({}, Basic.args), {}, {
  externalLabel: false
});
export const FloatingLabelNoDefaultValue = Template.bind({});
FloatingLabelNoDefaultValue.args = {
  externalLabel: false,
  label: 'Example'
};
FloatingLabelNoDefaultValue.parameters = {
  storyshots: {
    disable: true
  }
};
//# sourceMappingURL=FieldDate.stories.js.map


text:
"use strict";
var di_1 = require('angular2/src/core/di');
var lang_1 = require('angular2/src/facade/lang');
/**
 * A DI Token representing a unique string id assigned to the application by Angular and used
 * primarily for prefixing application attributes and CSS styles when
 * {@link ViewEncapsulation#Emulated} is being used.
 *
 * If you need to avoid randomly generated value to be used as an application id, you can provide
 * a custom value via a DI provider <!-- TODO: provider --> configuring the root {@link Injector}
 * using this token.
 */
exports.APP_ID = lang_1.CONST_EXPR(new di_1.OpaqueToken('AppId'));
function _appIdRandomProviderFactory() {
    return "" + _randomChar() + _randomChar() + _randomChar();
}
/**
 * Providers that will generate a random APP_ID_TOKEN.
 */
exports.APP_ID_RANDOM_PROVIDER = lang_1.CONST_EXPR(new di_1.Provider(exports.APP_ID, { useFactory: _appIdRandomProviderFactory, deps: [] }));
function _randomChar() {
    return lang_1.StringWrapper.fromCharCode(97 + lang_1.Math.floor(lang_1.Math.random() * 25));
}
/**
 * A function that will be executed when a platform is initialized.
 */
exports.PLATFORM_INITIALIZER = lang_1.CONST_EXPR(new di_1.OpaqueToken("Platform Initializer"));
/**
 * A function that will be executed when an application is initialized.
 */
exports.APP_INITIALIZER = lang_1.CONST_EXPR(new di_1.OpaqueToken("Application Initializer"));
/**
 * A token which indicates the root directory of the application
 */
exports.PACKAGE_ROOT_URL = lang_1.CONST_EXPR(new di_1.OpaqueToken("Application Packages Root URL"));
//# sourceMappingURL=application_tokens.js.map


text:
using blink::testing::runPendingTasks;

namespace blink {

class TextFinderTest : public ::testing::Test {
protected:
    TextFinderTest()
    {
        m_webViewHelper.initialize();
        WebLocalFrameImpl& frameImpl = *m_webViewHelper.webViewImpl()->mainFrameImpl();
        frameImpl.viewImpl()->resize(WebSize(640, 480));
        frameImpl.viewImpl()->updateAllLifecyclePhases();
        m_document = PassRefPtrWillBeRawPtr<Document>(frameImpl.document());
        m_textFinder = &frameImpl.ensureTextFinder();
    }

    Document& document() const;
    TextFinder& textFinder() const;

    static WebFloatRect findInPageRect(Node* startContainer, int startOffset, Node* endContainer, int endOffset);

private:
    FrameTestHelpers::WebViewHelper m_webViewHelper;
    RefPtrWillBePersistent<Document> m_document;
    RawPtrWillBePersistent<TextFinder> m_textFinder;
};

Document& TextFinderTest::document() const
{
    return *m_document;
}

TextFinder& TextFinderTest::textFinder() const
{
    return *m_textFinder;
}

WebFloatRect TextFinderTest::findInPageRect(Node* startContainer, int startOffset, Node* endContainer, int endOffset)
{
    RefPtrWillBeRawPtr<Range> range = Range::create(startContainer->document(), startContainer, startOffset, endContainer, endOffset);
    return WebFloatRect(findInPageRectFromRange(range.get()));
}

TEST_F(TextFinderTest, FindTextSimple)
{
    document().body()->setInnerHTML("XXXXFindMeYYYYfindmeZZZZ", ASSERT_NO_EXCEPTION);
    Node* textNode = document().body()->firstChild();

    int identifier = 0;
    WebString searchText(String("FindMe"));
    WebFindOptions findOptions; // Default.
    bool wrapWithinFrame = true;
    WebRect* selectionRect = nullptr;

    ASSERT_TRUE(textFinder().find(identifier, searchText, findOptions, wrapWithinFrame, selectionRect));
    Range* activeMatch = textFinder().activeMatch();
    ASSERT_TRUE(activeMatch);
    EXPECT_EQ(textNode, activeMatch->startContainer());
    EXPECT_EQ(4, activeMatch->startOffset());
    EXPECT_EQ(textNode, activeMatch->endContainer());
    EXPECT_EQ(10, activeMatch->endOffset());

    findOptions.findNext = true;
    ASSERT_TRUE(textFinder().find(identifier, searchText, findOptions, wrapWithinFrame, selectionRect));
    activeMatch = textFinder().activeMatch();
    ASSERT_TRUE(activeMatch);
    EXPECT_EQ(textNode, activeMatch->startContainer());
    EXPECT_EQ(14, activeMatch->startOffset());
    EXPECT_EQ(textNode, activeMatch->endContainer());
    EXPECT_EQ(20, activeMatch->endOffset());

    // Should wrap to the first match.
    ASSERT_TRUE(textFinder().find(identifier, searchText, findOptions, wrapWithinFrame, selectionRect));
    activeMatch = textFinder().activeMatch();
    ASSERT_TRUE(activeMatch);
    EXPECT_EQ(textNode, activeMatch->startContainer());
    EXPECT_EQ(4, activeMatch->startOffset());
    EXPECT_EQ(textNode, activeMatch->endContainer());
    EXPECT_EQ(10, activeMatch->endOffset());

    // Search in the reverse order.
    identifier = 1;
    findOptions = WebFindOptions();
    findOptions.forward = false;

    ASSERT_TRUE(textFinder().find(identifier, searchText, findOptions, wrapWithinFrame, selectionRect));
    activeMatch = textFinder().activeMatch();
    ASSERT_TRUE(activeMatch);
    EXPECT_EQ(textNode, activeMatch->startContainer());
    EXPECT_EQ(14, activeMatch->startOffset());
    EXPECT_EQ(textNode, activeMatch->endContainer());
    EXPECT_EQ(20, activeMatch->endOffset());

    findOptions.findNext = true;
    ASSERT_TRUE(textFinder().find(identifier, searchText, findOptions, wrapWithinFrame, selectionRect));
    activeMatch = textFinder().activeMatch();
    ASSERT_TRUE(activeMatch);
    EXPECT_EQ(textNode, activeMatch->startContainer());
    EXPECT_EQ(4, activeMatch->startOffset());
    EXPECT_EQ(textNode, activeMatch->endContainer());
    EXPECT_EQ(10, activeMatch->endOffset());

    // Wrap to the first match (last occurence in the document).
    ASSERT_TRUE(textFinder().find(identifier, searchText, findOptions, wrapWithinFrame, selectionRect));
    activeMatch = textFinder().activeMatch();
    ASSERT_TRUE(activeMatch);
    EXPECT_EQ(textNode, activeMatch->startContainer());
    EXPECT_EQ(14, activeMatch->startOffset());
    EXPECT_EQ(textNode, activeMatch->endContainer());
    EXPECT_EQ(20, activeMatch->endOffset());
}

TEST_F(TextFinderTest, FindTextAutosizing)
{
    document().body()->setInnerHTML("XXXXFindMeYYYYfindmeZZZZ", ASSERT_NO_EXCEPTION);

    int identifier = 0;
    WebString searchText(String("FindMe"));
    WebFindOptions findOptions; // Default.
    bool wrapWithinFrame = true;
    WebRect* selectionRect = nullptr;

    // Set viewport scale to 20 in order to simulate zoom-in
    VisualViewport& visualViewport = document().page()->frameHost().visualViewport();
    visualViewport.setScale(20);

    // Enforce autosizing
    document().settings()->setTextAutosizingEnabled(true);
    document().settings()->setTextAutosizingWindowSizeOverride(IntSize(20, 20));
    document().textAutosizer()->updatePageInfo();

    // In case of autosizing, scale _should_ change
    ASSERT_TRUE(textFinder().find(identifier, searchText, findOptions, wrapWithinFrame, selectionRect));
    ASSERT_TRUE(textFinder().activeMatch());
    ASSERT_EQ(1, visualViewport.scale()); // in this case to 1

    // Disable autosizing and reset scale to 20
    visualViewport.setScale(20);
    document().settings()->setTextAutosizingEnabled(false);
    document().textAutosizer()->updatePageInfo();

    ASSERT_TRUE(textFinder().find(identifier, searchText, findOptions, wrapWithinFrame, selectionRect));
    ASSERT_TRUE(textFinder().activeMatch());
    ASSERT_EQ(20, visualViewport.scale());
}

TEST_F(TextFinderTest, FindTextNotFound)
{
    document().body()->setInnerHTML("XXXXFindMeYYYYfindmeZZZZ", ASSERT_NO_EXCEPTION);

    int identifier = 0;
    WebString searchText(String("Boo"));
    WebFindOptions findOptions; // Default.
    bool wrapWithinFrame = true;
    WebRect* selectionRect = nullptr;

    EXPECT_FALSE(textFinder().find(identifier, searchText, findOptions, wrapWithinFrame, selectionRect));
    EXPECT_FALSE(textFinder().activeMatch());
}

TEST_F(TextFinderTest, FindTextInShadowDOM)
{
    document().body()->setInnerHTML("FOOfoo", ASSERT_NO_EXCEPTION);
    RefPtrWillBeRawPtr<ShadowRoot> shadowRoot = document().body()->createShadowRootInternal(ShadowRootType::V0, ASSERT_NO_EXCEPTION);
    shadowRoot->setInnerHTML("<content select=\"i\"></content>Foo<content></content>", ASSERT_NO_EXCEPTION);
    Node* textInBElement = document().body()->firstChild()->firstChild();
    Node* textInIElement = document().body()->lastChild()->firstChild();
    Node* textInUElement = shadowRoot->childNodes()->item(1)->firstChild();

    int identifier = 0;
    WebString searchText(String("foo"));
    WebFindOptions findOptions; // Default.
    bool wrapWithinFrame = true;
    WebRect* selectionRect = nullptr;

    // TextIterator currently returns the matches in the composed treeorder, so
    // in this case the matches will be returned in the order of
    //  ->  -> .
    ASSERT_TRUE(textFinder().find(identifier, searchText, findOptions, wrapWithinFrame, selectionRect));
    Range* activeMatch = textFinder().activeMatch();
    ASSERT_TRUE(activeMatch);
    EXPECT_EQ(textInIElement, activeMatch->startContainer());
    EXPECT_EQ(0, activeMatch->startOffset());
    EXPECT_EQ(textInIElement, activeMatch->endContainer());
    EXPECT_EQ(3, activeMatch->endOffset());

    findOptions.findNext = true;
    ASSERT_TRUE(textFinder().find(identifier, searchText, findOptions, wrapWithinFrame, selectionRect));
    activeMatch = textFinder().activeMatch();
    ASSERT_TRUE(activeMatch);
    EXPECT_EQ(textInUElement, activeMatch->startContainer());
    EXPECT_EQ(0, activeMatch->startOffset());
    EXPECT_EQ(textInUElement, activeMatch->endContainer());
    EXPECT_EQ(3, activeMatch->endOffset());

    ASSERT_TRUE(textFinder().find(identifier, searchText, findOptions, wrapWithinFrame, selectionRect));
    activeMatch = textFinder().activeMatch();
    ASSERT_TRUE(activeMatch);
    EXPECT_EQ(textInBElement, activeMatch->startContainer());
    EXPECT_EQ(0, activeMatch->startOffset());
    EXPECT_EQ(textInBElement, activeMatch->endContainer());
    EXPECT_EQ(3, activeMatch->endOffset());

    // Should wrap to the first match.
    ASSERT_TRUE(textFinder().find(identifier, searchText, findOptions, wrapWithinFrame, selectionRect));
    activeMatch = textFinder().activeMatch();
    ASSERT_TRUE(activeMatch);
    EXPECT_EQ(textInIElement, activeMatch->startContainer());
    EXPECT_EQ(0, activeMatch->startOffset());
    EXPECT_EQ(textInIElement, activeMatch->endContainer());
    EXPECT_EQ(3, activeMatch->endOffset());

    // Fresh search in the reverse order.
    identifier = 1;
    findOptions = WebFindOptions();
    findOptions.forward = false;

    ASSERT_TRUE(textFinder().find(identifier, searchText, findOptions, wrapWithinFrame, selectionRect));
    activeMatch = textFinder().activeMatch();
    ASSERT_TRUE(activeMatch);
    EXPECT_EQ(textInBElement, activeMatch->startContainer());
    EXPECT_EQ(0, activeMatch->startOffset());
    EXPECT_EQ(textInBElement, activeMatch->endContainer());
    EXPECT_EQ(3, activeMatch->endOffset());

    findOptions.findNext = true;
    ASSERT_TRUE(textFinder().find(identifier, searchText, findOptions, wrapWithinFrame, selectionRect));
    activeMatch = textFinder().activeMatch();
    ASSERT_TRUE(activeMatch);
    EXPECT_EQ(textInUElement, activeMatch->startContainer());
    EXPECT_EQ(0, activeMatch->startOffset());
    EXPECT_EQ(textInUElement, activeMatch->endContainer());
    EXPECT_EQ(3, activeMatch->endOffset());

    ASSERT_TRUE(textFinder().find(identifier, searchText, findOptions, wrapWithinFrame, selectionRect));
    activeMatch = textFinder().activeMatch();
    ASSERT_TRUE(activeMatch);
    EXPECT_EQ(textInIElement, activeMatch->startContainer());
    EXPECT_EQ(0, activeMatch->startOffset());
    EXPECT_EQ(textInIElement, activeMatch->endContainer());
    EXPECT_EQ(3, activeMatch->endOffset());

    // And wrap.
    ASSERT_TRUE(textFinder().find(identifier, searchText, findOptions, wrapWithinFrame, selectionRect));
    activeMatch = textFinder().activeMatch();
    ASSERT_TRUE(activeMatch);
    EXPECT_EQ(textInBElement, activeMatch->startContainer());
    EXPECT_EQ(0, activeMatch->startOffset());
    EXPECT_EQ(textInBElement, activeMatch->endContainer());
    EXPECT_EQ(3, activeMatch->endOffset());
}

TEST_F(TextFinderTest, ScopeTextMatchesSimple)
{
    document().body()->setInnerHTML("XXXXFindMeYYYYfindmeZZZZ", ASSERT_NO_EXCEPTION);
    Node* textNode = document().body()->firstChild();

    int identifier = 0;
    WebString searchText(String("FindMe"));
    WebFindOptions findOptions; // Default.

    textFinder().resetMatchCount();
    textFinder().scopeStringMatches(identifier, searchText, findOptions, true);
    while (textFinder().scopingInProgress())
        runPendingTasks();

    EXPECT_EQ(2, textFinder().totalMatchCount());
    WebVector<WebFloatRect> matchRects;
    textFinder().findMatchRects(matchRects);
    ASSERT_EQ(2u, matchRects.size());
    EXPECT_EQ(findInPageRect(textNode, 4, textNode, 10), matchRects[0]);
    EXPECT_EQ(findInPageRect(textNode, 14, textNode, 20), matchRects[1]);
}

TEST_F(TextFinderTest, ScopeTextMatchesWithShadowDOM)
{
    document().body()->setInnerHTML("FOOfoo", ASSERT_NO_EXCEPTION);
    RefPtrWillBeRawPtr<ShadowRoot> shadowRoot = document().body()->createShadowRootInternal(ShadowRootType::V0, ASSERT_NO_EXCEPTION);
    shadowRoot->setInnerHTML("<content select=\"i\"></content>Foo<content></content>", ASSERT_NO_EXCEPTION);
    Node* textInBElement = document().body()->firstChild()->firstChild();
    Node* textInIElement = document().body()->lastChild()->firstChild();
    Node* textInUElement = shadowRoot->childNodes()->item(1)->firstChild();

    int identifier = 0;
    WebString searchText(String("fOO"));
    WebFindOptions findOptions; // Default.

    textFinder().resetMatchCount();
    textFinder().scopeStringMatches(identifier, searchText, findOptions, true);
    while (textFinder().scopingInProgress())
        runPendingTasks();

    // TextIterator currently returns the matches in the composed tree order,
    // so in this case the matches will be returned in the order of
    //  ->  -> .
    EXPECT_EQ(3, textFinder().totalMatchCount());
    WebVector<WebFloatRect> matchRects;
    textFinder().findMatchRects(matchRects);
    ASSERT_EQ(3u, matchRects.size());
    EXPECT_EQ(findInPageRect(textInIElement, 0, textInIElement, 3), matchRects[0]);
    EXPECT_EQ(findInPageRect(textInUElement, 0, textInUElement, 3), matchRects[1]);
    EXPECT_EQ(findInPageRect(textInBElement, 0, textInBElement, 3), matchRects[2]);
}

TEST_F(TextFinderTest, ScopeRepeatPatternTextMatches)
{
    document().body()->setInnerHTML("ab ab ab ab ab", ASSERT_NO_EXCEPTION);
    Node* textNode = document().body()->firstChild();

    int identifier = 0;
    WebString searchText(String("ab ab"));
    WebFindOptions findOptions; // Default.

    textFinder().resetMatchCount();
    textFinder().scopeStringMatches(identifier, searchText, findOptions, true);
    while (textFinder().scopingInProgress())
        runPendingTasks();

    EXPECT_EQ(2, textFinder().totalMatchCount());
    WebVector<WebFloatRect> matchRects;
    textFinder().findMatchRects(matchRects);
    ASSERT_EQ(2u, matchRects.size());
    EXPECT_EQ(findInPageRect(textNode, 0, textNode, 5), matchRects[0]);
    EXPECT_EQ(findInPageRect(textNode, 6, textNode, 11), matchRects[1]);
}

TEST_F(TextFinderTest, OverlappingMatches)
{
    document().body()->setInnerHTML("aababaa", ASSERT_NO_EXCEPTION);
    Node* textNode = document().body()->firstChild();

    int identifier = 0;
    WebString searchText(String("aba"));
    WebFindOptions findOptions; // Default.

    textFinder().resetMatchCount();
    textFinder().scopeStringMatches(identifier, searchText, findOptions, true);
    while (textFinder().scopingInProgress())
        runPendingTasks();

    // We shouldn't find overlapped matches.
    EXPECT_EQ(1, textFinder().totalMatchCount());
    WebVector<WebFloatRect> matchRects;
    textFinder().findMatchRects(matchRects);
    ASSERT_EQ(1u, matchRects.size());
    EXPECT_EQ(findInPageRect(textNode, 1, textNode, 4), matchRects[0]);
}

TEST_F(TextFinderTest, SequentialMatches)
{
    document().body()->setInnerHTML("ababab", ASSERT_NO_EXCEPTION);
    Node* textNode = document().body()->firstChild();

    int identifier = 0;
    WebString searchText(String("ab"));
    WebFindOptions findOptions; // Default.

    textFinder().resetMatchCount();
    textFinder().scopeStringMatches(identifier, searchText, findOptions, true);
    while (textFinder().scopingInProgress())
        runPendingTasks();

    EXPECT_EQ(3, textFinder().totalMatchCount());
    WebVector<WebFloatRect> matchRects;
    textFinder().findMatchRects(matchRects);
    ASSERT_EQ(3u, matchRects.size());
    EXPECT_EQ(findInPageRect(textNode, 0, textNode, 2), matchRects[0]);
    EXPECT_EQ(findInPageRect(textNode, 2, textNode, 4), matchRects[1]);
    EXPECT_EQ(findInPageRect(textNode, 4, textNode, 6), matchRects[2]);
}

class TextFinderFakeTimerTest : public TextFinderTest {
protected:
    // A simple platform that mocks out the clock.
    class TimeProxyPlatform : public TestingPlatformSupport {
    public:
        TimeProxyPlatform()
            : m_timeCounter(m_oldPlatform->currentTimeSeconds())
        {
        }

    private:
        Platform& ensureFallback()
        {
            ASSERT(m_oldPlatform);
            return *m_oldPlatform;
        }

        // From blink::Platform:
        double currentTimeSeconds() override
        {
            return ++m_timeCounter;
        }

        // These two methods allow timers to work correctly.
        double monotonicallyIncreasingTimeSeconds() override
        {
            return ensureFallback().monotonicallyIncreasingTimeSeconds();
        }

        WebUnitTestSupport* unitTestSupport() override { return ensureFallback().unitTestSupport(); }
        WebString defaultLocale() override { return ensureFallback().defaultLocale(); }
        WebCompositorSupport* compositorSupport() override { return ensureFallback().compositorSupport(); }

        double m_timeCounter;
    };

    TimeProxyPlatform m_proxyTimePlatform;
};

TEST_F(TextFinderFakeTimerTest, ScopeWithTimeouts)
{
    // Make a long string.
    String text(Vector<UChar>(100));
    text.fill('a');
    String searchPattern("abc");
    // Make 4 substrings "abc" in text.
    text.insert(searchPattern, 1);
    text.insert(searchPattern, 10);
    text.insert(searchPattern, 50);
    text.insert(searchPattern, 90);

    document().body()->setInnerHTML(text, ASSERT_NO_EXCEPTION);

    int identifier = 0;
    WebFindOptions findOptions; // Default.

    textFinder().resetMatchCount();

    // There will be only one iteration before timeout, because increment
    // of the TimeProxyPlatform timer is greater than timeout threshold.
    textFinder().scopeStringMatches(identifier, searchPattern, findOptions, true);
    while (textFinder().scopingInProgress())
        runPendingTasks();

    EXPECT_EQ(4, textFinder().totalMatchCount());
}

} // namespace blink


text:
@interface MainTableView : UITableViewController

@end


text:
import SecretHandshake from './secret-handshake';

describe('Secret Handshake', () => {
  test('binary 1 (hexadecimal 0x01) is a wink', () => {
    const handshake = new SecretHandshake(0x01);
    expect(handshake.commands()).toEqual(['wink']);
  });

  xtest('binary 10 (hexadecimal 0x02) is a double blink', () => {
    const handshake = new SecretHandshake(0x02);
    expect(handshake.commands()).toEqual(['double blink']);
  });

  xtest('binary 100 (hexadecimal 0x04) is close your eyes', () => {
    const handshake = new SecretHandshake(0x04);
    expect(handshake.commands()).toEqual(['close your eyes']);
  });

  xtest('binary 1000 (hexadecimal 0x08) is jump', () => {
    const handshake = new SecretHandshake(0x08);
    expect(handshake.commands()).toEqual(['jump']);
  });

  xtest('binary 11 (hexadecimal 0x03) is wink and double blink', () => {
    const handshake = new SecretHandshake(0x03);
    expect(handshake.commands()).toEqual(['wink', 'double blink']);
  });

  xtest('binary 10011 (hexadecimal 0x13) is double blink and wink', () => {
    const handshake = new SecretHandshake(0x13);
    expect(handshake.commands()).toEqual(['double blink', 'wink']);
  });

  xtest('binary 11111 (hexadecimal 0x1F) is jump, close your eyes, double blink, and wink', () => {
    const handshake = new SecretHandshake(0x1F);
    expect(handshake.commands()).toEqual(['jump', 'close your eyes', 'double blink', 'wink']);
  });

  xtest('text is an invalid secret handshake', () => {
    expect(() => new SecretHandshake('piggies'))
      .toThrow(new Error('Handshake must be a number'));
  });
});


text:
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import { Router } from 'express';
import { Order } from '../models';

const router = new Router();

// List of orders for current session
router.get('/orders', (req, res) => {
  const sessionId = res.locals.session.id;
  const orders = Order.find({
    query: { user: sessionId },
  });

  res.render('index.ejs', {
    store: {},
    session: res.locals.session,
    markup: ReactDOMServer.renderToString(<Orders store={orders}/>),
  });
});

export default router;