text:
require 'canvas-api'

module CanvasAPI
  def self.set_org(org)
    @insecure = !!org.settings['insecure']
  end

  def self.api_call(path, user_config, all_pages=false)
    protocol = 'https'
    host = "#{protocol}://#{user_config.host}"
    canvas = Canvas::API.new(:host => host, :token => user_config.access_token, :insecure => @insecure)
    begin
      result = canvas.get(path)
      if result.is_a?(Array) && all_pages
        while result.more?
          result.next_page!
        end
      end
      return result
    rescue Canvas::ApiError => e
      return false
    end
  end
end

module OAuthConfig
  def self.oauth_config(org, domain)
    if org && org.settings['oss_oauth']
      oauth_config ||= ExternalConfig.first(:config_type => 'canvas_oss_oauth', :organization_id => org.id, :domain => domain)
      oauth_config ||= ExternalConfig.first(:config_type => 'canvas_oss_oauth', :organization_id => org.id, :domain => nil)
    else
      oauth_config ||= ExternalConfig.first(:config_type => 'canvas_oauth', :domain => domain)
      oauth_config ||= ExternalConfig.first(:config_type => 'canvas_oauth', :domain => nil)
    end

    raise "Missing oauth config" unless oauth_config
    oauth_config
  end
end

module Stats
  def self.general(org)
    OrgStats.check(org)
  end

  def self.badge_earnings(bc)
    weeks = Badge.all(:badge_config_id => bc.id, :state => 'awarded').group_by{|b| (b.issued.year * 100) + b.issued.cweek }.map{|wk, badges| [wk, badges.length] }
    hash = {}
    weeks = weeks.sort_by{|wk, cnt| wk }
    weeks.each{|wk, cnt| hash[wk] = cnt }
    if weeks.length > 0
      hash['start'] = weeks[0][0]
      hash['end'] = weeks[-1][0]
    end
    hash
  end

end

require 'dm-migrations/migration_runner'
require 'dm-types'
# I can never find good documentation on migrations for datamapper, don't judge
module  FixupMigration
  def self.enlarge_columns
    migration 1, :enlarge_small_columns do
      up do
        # user config
        modify_table :user_configs do
          add_column :temp_access_token, String, :length => 512
        end
        adapter.execute("UPDATE user_configs SET temp_access_token=access_token")
        modify_table :user_configs do
          drop_column :access_token
          rename_column :temp_access_token, :access_token
        end

        # badges
        modify_table :badges do
          add_column :temp_badge_url, DataMapper::Property::Text
          add_column :temp_salt, String, :length => 512
        end
        adapter.execute("UPDATE badges SET temp_badge_url=badge_url, temp_salt=salt")
        modify_table :badges do
          drop_column :badge_url
          drop_column :salt
          rename_column :temp_badge_url, :badge_url
          rename_column :temp_salt, :salt
        end
      end
    end
    migrate_up!
  end
end


text: No Copyright!

redpajama_set_name: RedPajamaGithub


text:
if Rails.env.development? || Rails.env.test?
  require 'dotenv'
  Dotenv.load
end


text:
package org.apache.ivy.util.url;

import java.io.File;
import java.net.URL;

import org.apache.ivy.util.FileUtil;
import org.apache.ivy.util.url.URLHandler.URLInfo;

import junit.framework.TestCase;

/**
 * Test HttpClientHandler
 */
public class HttpclientURLHandlerTest extends TestCase {
    // remote.test
    private File testDir;
    private HttpClientHandler handler;

    protected void setUp() throws Exception {
        testDir = new File("build/HttpclientURLHandlerTest");
        testDir.mkdirs();

        handler = new HttpClientHandler();
    }

    protected void tearDown() throws Exception {
        FileUtil.forceDelete(testDir);
    }

    public void testIsReachable() throws Exception {
        assertTrue(handler.isReachable(new URL("http://www.google.fr/")));
        assertFalse(handler.isReachable(new URL("http://www.google.fr/unknownpage.html")));
    }

    public void testGetURLInfo() throws Exception {
        // IVY-390
        URLHandler handler = new HttpClientHandler();
        URLInfo info = handler
                .getURLInfo(new URL(
                        "https://repo1.maven.org/maven2/commons-lang/commons-lang/[1.0,3.0[/commons-lang-[1.0,3.0[.pom"));

        assertEquals(URLHandler.UNAVAILABLE, info);
    }

    public void testContentEncoding() throws Exception {
        assertDownloadOK(new URL("http://carsten.codimi.de/gzip.yaws/daniels.html"), new File(testDir, "gzip.txt"));
        assertDownloadOK(new URL("http://carsten.codimi.de/gzip.yaws/daniels.html?deflate=on&zlib=on"), new File(testDir, "deflate-zlib.txt"));
        assertDownloadOK(new URL("http://carsten.codimi.de/gzip.yaws/daniels.html?deflate=on"), new File(testDir, "deflate.txt"));
        assertDownloadOK(new URL("http://carsten.codimi.de/gzip.yaws/a5.ps"), new File(testDir, "a5-gzip.ps"));
        assertDownloadOK(new URL("http://carsten.codimi.de/gzip.yaws/a5.ps?deflate=on"), new File(testDir, "a5-deflate.ps"));
        assertDownloadOK(new URL("http://carsten.codimi.de/gzip.yaws/nh80.pdf"), new File(testDir, "nh80-gzip.pdf"));
        assertDownloadOK(new URL("http://carsten.codimi.de/gzip.yaws/nh80.pdf?deflate=on"), new File(testDir, "nh80-deflate.pdf"));
    }

    private void assertDownloadOK(URL url, File file) throws Exception {
        handler.download(url, file, null);
        assertTrue(file.exists());
    }
}


text:
from django.db import models

# Create your models here.

class Alloy(models.Model):
    name = models.CharField("Alloy's name", max_length = 30)
    alloy_size = (
        ('d', 'Double'),
        ('d', 'Ternary')
    )
    def __str__(self):
        return self.name

class Parameter(models.Model):
    alloy = models.ForeignKey(Alloy, verbose_name="The related alloy")
    a0 = models.FloatField("Lattice parameter")
    ac = models.FloatField("Conductions's hydrostatic deformation potential")
    av = models.FloatField("Valence's hydrostatic deformation potential")
    b = models.FloatField("Deformation potential for tetragonal distorion")
    c11 = models.FloatField("Elastic constant")
    c12 = models.FloatField("Elastic constant")
    me = models.FloatField("Electron effective mass")
    mhh = models.FloatField("Heavy-hole effective mass", null = True)
    mlh = models.FloatField("Light-hole effective mass", null = True)
    eg2 = models.FloatField("Gap energy at 2 K")
    eg77 = models.FloatField("Gap energy at 77 K")
    eg300 = models.FloatField("Gap energy at 300 K")
    def __str__(self):
        return self.alloy.name + "'s parameters"

class Interpolation(models.Model):
    alloy = models.ForeignKey(Alloy, verbose_name="The related alloy")
    a0 = models.CharField("Lattice parameter", max_length = 200)
    ac = models.CharField("Conductions's hydrostatic deformation potential", max_length = 200)
    av = models.CharField("Valence's hydrostatic deformation potential", max_length = 200)
    b = models.CharField("Deformation potential for tetragonal distorion", max_length = 200)
    c11 = models.CharField("Elastic constant", max_length = 200)
    c12 = models.CharField("Elastic constant", max_length = 200)
    me = models.CharField("Electron effective mass", max_length = 200)
    mhh = models.CharField("Heavy-hole effective mass", max_length = 200, null = True)
    mlh = models.CharField("Light-hole effective mass", max_length = 200, null = True)
    eg2 = models.CharField("Gap energy at 2 K", max_length = 200)
    eg77 = models.CharField("Gap energy at 77 K", max_length = 200)
    eg300 = models.CharField("Gap energy at 300 K", max_length = 200)
    def __str__(self):
        return self.alloy.name + "'s interpolations"


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Aecidium peyritschianum Magnus

### Remarks
null


text:
/*	$NetBSD: if_le_pci.c,v 1.52 2014/03/29 19:28:24 christos Exp $	*/

/*-
 * Copyright (c) 1997, 1998 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Charles M. Hannum and by Jason R. Thorpe of the Numerical Aerospace
 * Simulation Facility, NASA Ames Research Center.
 *
 * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
 */

/*-
 * Copyright (c) 1992, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * This code is derived from software contributed to Berkeley by
 * Ralph Campbell and Rick Macklem.
 *
 * 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.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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.
 *
 *	@(#)if_le.c	8.2 (Berkeley) 11/16/93
 */

#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: if_le_pci.c,v 1.52 2014/03/29 19:28:24 christos Exp $");

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/mbuf.h>
#include <sys/syslog.h>
#include <sys/socket.h>
#include <sys/device.h>

#include <net/if.h>
#include <net/if_ether.h>
#include <net/if_media.h>

#include <sys/cpu.h>
#include <sys/bus.h>
#include <sys/intr.h>

#include <dev/pci/pcireg.h>
#include <dev/pci/pcivar.h>
#include <dev/pci/pcidevs.h>

#include <dev/ic/lancereg.h>
#include <dev/ic/lancevar.h>
#include <dev/ic/am79900reg.h>
#include <dev/ic/am79900var.h>

#include <dev/pci/if_levar.h>

static int	le_pci_match(device_t, cfdata_t, void *);
static void	le_pci_attach(device_t, device_t, void *);
static int	le_pci_mediachange(struct lance_softc *);

CFATTACH_DECL_NEW(le_pci, sizeof(struct le_softc),
    le_pci_match, le_pci_attach, NULL, NULL);

/*
 * PCI constants.
 * XXX These should be in a common file!
 */
#define PCI_CBIO PCI_BAR(0)		/* Configuration Base IO Address */

#define	LE_PCI_MEMSIZE	16384

static int le_pci_supmedia[] = {
	IFM_ETHER|IFM_AUTO,
	IFM_ETHER|IFM_AUTO|IFM_FDX,
	IFM_ETHER|IFM_10_T,
	IFM_ETHER|IFM_10_T|IFM_FDX,
	IFM_ETHER|IFM_10_5,
	IFM_ETHER|IFM_10_5|IFM_FDX,
};

static void
le_pci_wrcsr(struct lance_softc *sc, uint16_t port, uint16_t val)
{
	struct le_softc *lesc = (struct le_softc *)sc;
	bus_space_tag_t iot = lesc->sc_iot;
	bus_space_handle_t ioh = lesc->sc_ioh;

	bus_space_write_2(iot, ioh, lesc->sc_rap, port);
	bus_space_write_2(iot, ioh, lesc->sc_rdp, val);
}

static uint16_t
le_pci_rdcsr(struct lance_softc *sc, uint16_t port)
{
	struct le_softc *lesc = (struct le_softc *)sc;
	bus_space_tag_t iot = lesc->sc_iot;
	bus_space_handle_t ioh = lesc->sc_ioh;
	uint16_t val;

	bus_space_write_2(iot, ioh, lesc->sc_rap, port);
	val = bus_space_read_2(iot, ioh, lesc->sc_rdp);
	return (val);
}

static int
le_pci_mediachange(struct lance_softc *sc)
{
	struct le_softc *lesc = (struct le_softc *)sc;
	bus_space_tag_t iot = lesc->sc_iot;
	bus_space_handle_t ioh = lesc->sc_ioh;
	int newmedia = sc->sc_media.ifm_media;
	uint16_t reg;

	if (IFM_SUBTYPE(newmedia) !=
	    IFM_SUBTYPE(lesc->sc_currentmedia)) {
		if (IFM_SUBTYPE(newmedia) == IFM_AUTO) {
			/* switch to autoselect - BCR2 bit 1 */
			bus_space_write_2(iot, ioh, PCNET_PCI_RAP, 2);
			reg = bus_space_read_2(iot, ioh, PCNET_PCI_BDP);
			reg |= 2;
			bus_space_write_2(iot, ioh, PCNET_PCI_RAP, 2);
			bus_space_write_2(iot, ioh, PCNET_PCI_BDP, reg);
		} else {
			/* force media type (in init block) */
			lance_reset(sc);
			if (IFM_SUBTYPE(newmedia) == IFM_10_T)
				sc->sc_initmodemedia = 1; /* UTP */
			else
				sc->sc_initmodemedia = 0; /* AUI */
			lance_init(&sc->sc_ethercom.ec_if);

			if (IFM_SUBTYPE(lesc->sc_currentmedia) == IFM_AUTO) {
				/* take away autoselect - BCR2 bit 1 */
				bus_space_write_2(iot, ioh, PCNET_PCI_RAP, 2);
				reg = bus_space_read_2(iot, ioh, PCNET_PCI_BDP);
				reg &= ~2;
				bus_space_write_2(iot, ioh, PCNET_PCI_RAP, 2);
				bus_space_write_2(iot, ioh, PCNET_PCI_BDP, reg);
			}
		}

	}

	if ((IFM_OPTIONS(newmedia) ^ IFM_OPTIONS(lesc->sc_currentmedia))
	    & IFM_FDX) {
		/* toggle full duplex - BCR9 */
		bus_space_write_2(iot, ioh, PCNET_PCI_RAP, 9);
		reg = bus_space_read_2(iot, ioh, PCNET_PCI_BDP);
		if (IFM_OPTIONS(newmedia) & IFM_FDX) {
			reg |= 1; /* FDEN */
			/* allow FDX on AUI only if explicitly chosen,
			 not in autoselect mode */
			if (IFM_SUBTYPE(newmedia) == IFM_10_5)
				reg |= 2; /* AUIFD */
			else
				reg &= ~2;
		} else
			reg &= ~1;
		bus_space_write_2(iot, ioh, PCNET_PCI_RAP, 9);
		bus_space_write_2(iot, ioh, PCNET_PCI_BDP, reg);
	}

	lesc->sc_currentmedia = newmedia;
	return (0);
}

static int
le_pci_match(device_t parent, cfdata_t cf, void *aux)
{
	struct pci_attach_args *pa = aux;

	if (PCI_VENDOR(pa->pa_id) != PCI_VENDOR_AMD)
		return (0);

	switch (PCI_PRODUCT(pa->pa_id)) {
	case PCI_PRODUCT_AMD_PCNET_PCI:
		return (1);
	}

	return (0);
}

static void
le_pci_attach(device_t parent, device_t self, void *aux)
{
	struct le_softc *lesc = device_private(self);
	struct lance_softc *sc = &lesc->sc_am79900.lsc;
	struct pci_attach_args *pa = aux;
	pci_intr_handle_t ih;
	bus_space_tag_t iot;
	bus_space_handle_t ioh;
	bus_dma_tag_t dmat = pa->pa_dmat;
	bus_dma_segment_t seg;
	pci_chipset_tag_t pc = pa->pa_pc;
	pcireg_t csr;
	int i, rseg;
	const char *model, *intrstr;
	char intrbuf[PCI_INTRSTR_LEN];

	sc->sc_dev = self;

	switch (PCI_PRODUCT(pa->pa_id)) {
	case PCI_PRODUCT_AMD_PCNET_PCI:
		model = "PCnet-PCI Ethernet";
		lesc->sc_rap = PCNET_PCI_RAP;
		lesc->sc_rdp = PCNET_PCI_RDP;
		break;

	default:
		model = "unknown model!";
	}

	aprint_normal(": %s\n", model);

	if (pci_mapreg_map(pa, PCI_CBIO, PCI_MAPREG_TYPE_IO, 0,
	    &iot, &ioh, NULL, NULL)) {
		aprint_error_dev(self, "can't map I/O space\n");
		return;
	}

	/*
	 * Extract the physical MAC address from the ROM.
	 */
	for (i = 0; i < sizeof(sc->sc_enaddr); i++)
		sc->sc_enaddr[i] = bus_space_read_1(iot, ioh, i);

	lesc->sc_iot = iot;
	lesc->sc_ioh = ioh;
	lesc->sc_dmat = dmat;

	/*
	 * Allocate a DMA area for the card.
	 */
	if (bus_dmamem_alloc(dmat, LE_PCI_MEMSIZE, PAGE_SIZE, 0, &seg, 1,
	    &rseg, BUS_DMA_NOWAIT)) {
		aprint_error_dev(self, "couldn't allocate memory for card\n");
		return;
	}
	if (bus_dmamem_map(dmat, &seg, rseg, LE_PCI_MEMSIZE,
	    (void **)&sc->sc_mem,
	    BUS_DMA_NOWAIT|BUS_DMA_COHERENT)) {
		aprint_error_dev(self, "couldn't map memory for card\n");
		return;
	}

	/*
	 * Create and load the DMA map for the DMA area.
	 */
	if (bus_dmamap_create(dmat, LE_PCI_MEMSIZE, 1,
	    LE_PCI_MEMSIZE, 0, BUS_DMA_NOWAIT, &lesc->sc_dmam)) {
		aprint_error_dev(self, "couldn't create DMA map\n");
		bus_dmamem_free(dmat, &seg, rseg);
		return;
	}
	if (bus_dmamap_load(dmat, lesc->sc_dmam,
	    sc->sc_mem, LE_PCI_MEMSIZE, NULL, BUS_DMA_NOWAIT)) {
		aprint_error_dev(self, "coundn't load DMA map\n");
		bus_dmamem_free(dmat, &seg, rseg);
		return;
	}

	sc->sc_conf3 = 0;
	sc->sc_addr = lesc->sc_dmam->dm_segs[0].ds_addr;
	sc->sc_memsize = LE_PCI_MEMSIZE;

	sc->sc_copytodesc = lance_copytobuf_contig;
	sc->sc_copyfromdesc = lance_copyfrombuf_contig;
	sc->sc_copytobuf = lance_copytobuf_contig;
	sc->sc_copyfrombuf = lance_copyfrombuf_contig;
	sc->sc_zerobuf = lance_zerobuf_contig;

	sc->sc_rdcsr = le_pci_rdcsr;
	sc->sc_wrcsr = le_pci_wrcsr;
	sc->sc_hwinit = NULL;

	sc->sc_supmedia = le_pci_supmedia;
	sc->sc_nsupmedia = sizeof(le_pci_supmedia) / sizeof(int);
	sc->sc_defaultmedia = le_pci_supmedia[0];
	sc->sc_mediachange = le_pci_mediachange;
	lesc->sc_currentmedia = le_pci_supmedia[0];

	aprint_normal("%s", device_xname(self));
	am79900_config(&lesc->sc_am79900);

	/* Chip is stopped. Set "software style" to 32-bit. */
	bus_space_write_2(iot, ioh, PCNET_PCI_RAP, 20);
	bus_space_write_2(iot, ioh, PCNET_PCI_BDP, 2);

	/* Enable the card. */
	csr = pci_conf_read(pc, pa->pa_tag,
	    PCI_COMMAND_STATUS_REG);
	pci_conf_write(pc, pa->pa_tag, PCI_COMMAND_STATUS_REG,
	    csr | PCI_COMMAND_MASTER_ENABLE);

	/* Map and establish the interrupt. */
	if (pci_intr_map(pa, &ih)) {
		aprint_error_dev(self, "couldn't map interrupt\n");
		return;
	}
	intrstr = pci_intr_string(pc, ih, intrbuf, sizeof(intrbuf));
	lesc->sc_ih = pci_intr_establish(pc, ih, IPL_NET, am79900_intr, sc);
	if (lesc->sc_ih == NULL) {
		aprint_error_dev(self, "couldn't establish interrupt");
		if (intrstr != NULL)
			aprint_error(" at %s", intrstr);
		aprint_error("\n");
		return;
	}
	aprint_normal_dev(self, "interrupting at %s\n", intrstr);
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Grey.Vox {
    public class RegionBoundaryState {
        readonly object lck = new object();
        public int State;

        public RegionBoundaryState() {
            State = 0;
        }

        public bool DoWork() {
            bool b = false;
            lock(lck) {
                if(State == 0) {
                    State = 1;
                    b = true;
                }
            }
            return b;
        }
    }

    public class Region {
        // Size Of Array
        public const int XZ_SHIFT = 4;
        public const int Y_SHIFT = 6;
        public const int WIDTH = 0x01 << XZ_SHIFT;
        public const int HEIGHT = 0x01 << Y_SHIFT;
        public const int DEPTH = 0x01 << XZ_SHIFT;
        public const int PLANE_SIZE = WIDTH * DEPTH;
        public const int VOXEL_COUNT = PLANE_SIZE * HEIGHT;

        public const int INDZ_SHIFT = XZ_SHIFT;
        public const int INDY_SHIFT = INDZ_SHIFT * 2;

        public const int REGION_VOXBYTE_SIZE = VOXEL_COUNT * Voxel.BYTE_SIZE;

        // Precondition That All Value Fall Within Range
        public static int ToIndex(int x, int y, int z) {
            return (y << INDY_SHIFT) | (z << INDZ_SHIFT) | x;
        }
        public static int ToIndex(Vector3I v) {
            return ToIndex(v.X, v.Y, v.Z);
        }

        // The World And Its Location Within It
        public VoxWorld World {
            get;
            private set;
        }
        public Point loc;

        // The Important Data
        public Voxel[] voxels;
        public int changedCount;
        public event Action<Region> OnFacesChanged;

        public bool IsLoaded {
            get;
            private set;
        }
        public readonly RegionBoundaryState[] rBS;

        public Region rNX, rPX, rNZ, rPZ;

        public Region(VoxWorld w) {
            World = w;
            loc = Point.Zero;

            // Create Empty Region
            voxels = new Voxel[VOXEL_COUNT];
            for(int i = 0; i < VOXEL_COUNT; i++)
                voxels[i] = Voxel.Empty;

            // Non-calculated Boundaries
            rBS = new RegionBoundaryState[4];
            for(int i = 0; i < 4; i++)
                rBS[i] = new RegionBoundaryState();

            // No Neighbors
            rNX = rPX = rNZ = rPZ = null;
        }

        public void ApplyToAll(Func<Voxel, Vector3I, Voxel> f) {
            int i = 0;
            Vector3I v = Vector3I.Zero;
            for(v.Y = 0; v.Y < HEIGHT; v.Y++) {
                for(v.Z = 0; v.Z < DEPTH; v.Z++) {
                    for(v.X = 0; v.X < WIDTH; v.X++) {
                        voxels[i] = f(voxels[i], v);
                        i++;
                    }
                }
            }
        }

        public bool RecalculateSeam(int vi1, int vi2, int f) {
            VoxData vd1 = World.Atlas[voxels[vi1].ID];
            VoxData vd2 = World.Atlas[voxels[vi2].ID];
            byte flag = Flags.BITS[f];
            if(vd1.FaceType.CanShowFace(vd2.FaceType, f)) {
                if(Flags.HasFlags(voxels[vi1].Flags, flag))
                    return false;
                else {
                    Flags.SetFlagsOn(ref voxels[vi1].Flags, flag);
                    return true;
                }
            }
            else {
                if(!Flags.HasFlags(voxels[vi1].Flags, flag))
                    return false;
                else {
                    Flags.SetFlagsOff(ref voxels[vi1].Flags, flag);
                    return true;
                }
            }
        }
        public bool RecalculateSeams(int vi1, int vi2, int f) {
            return RecalculateSeam(vi1, vi2, f) | RecalculateSeam(vi2, vi1, f ^ 0x01);
        }

        public void SetVoxel(int x, int y, int z, ushort id) {
            voxels[ToIndex(x, y, z)].ID = id;
        }
        public void AddVoxel(int x, int y, int z, ushort id) {
            // Check If A Voxel Exists There
            int i = ToIndex(x, y, z);
            if(voxels[i].ID == id) return;

            // Set The Voxel To Be Empty
            bool change = Flags.HasSomeFlags(voxels[i].Flags, Voxel.FACE_MASK);
            voxels[i].ID = id;
            voxels[i].Flags = 0x00;

            // TODO: Check Surrounding Faces
            if(x < WIDTH - 1)
                change |= RecalculateSeams(i + 1, i, Voxel.FACE_NX);
            if(x > 0)
                change |= RecalculateSeams(i - 1, i, Voxel.FACE_PX);
            if(z < DEPTH - 1)
                change |= RecalculateSeams(i + WIDTH, i, Voxel.FACE_NZ);
            if(z > 0)
                change |= RecalculateSeams(i - WIDTH, i, Voxel.FACE_PZ);
            if(y < HEIGHT - 1)
                change |= RecalculateSeams(i + PLANE_SIZE, i, Voxel.FACE_NY);
            if(y > 0)
                change |= RecalculateSeams(i - PLANE_SIZE, i, Voxel.FACE_PY);

            // TODO: Send Update To Neighboring Regions
            if(x == 0 && rNX != null) rNX.NotifyFacesChanged();
            else if(x == Region.WIDTH - 1 && rPX != null) rPX.NotifyFacesChanged();
            if(z == 0 && rNZ != null) rNZ.NotifyFacesChanged();
            else if(z == Region.DEPTH - 1 && rPZ != null) rPZ.NotifyFacesChanged();

            // TODO: Use The Change
            NotifyFacesChanged();
        }
        public void RemoveVoxel(int x, int y, int z) {
            // Check If A Voxel Exists There
            int i = ToIndex(x, y, z);
            if(voxels[i].ID == 0) return;

            // Set The Voxel To Be Empty
            bool change = Flags.HasSomeFlags(voxels[i].Flags, Voxel.FACE_MASK);
            voxels[i] = Voxel.Empty;

            // TODO: Check Surrounding Faces
            if(x < WIDTH - 1)
                change |= RecalculateSeam(i + 1, i, Voxel.FACE_NX);
            if(x > 0)
                change |= RecalculateSeam(i - 1, i, Voxel.FACE_PX);
            if(z < DEPTH - 1)
                change |= RecalculateSeam(i + WIDTH, i, Voxel.FACE_NZ);
            if(z > 0)
                change |= RecalculateSeam(i - WIDTH, i, Voxel.FACE_PZ);
            if(y < HEIGHT - 1)
                change |= RecalculateSeam(i + PLANE_SIZE, i, Voxel.FACE_NY);
            if(y > 0)
                change |= RecalculateSeam(i - PLANE_SIZE, i, Voxel.FACE_PY);

            // TODO: Send Update To Neighboring Regions
            if(x == 0 && rNX != null) rNX.NotifyFacesChanged();
            else if(x == Region.WIDTH - 1 && rPX != null) rPX.NotifyFacesChanged();
            if(z == 0 && rNZ != null) rNZ.NotifyFacesChanged();
            else if(z == Region.DEPTH - 1 && rPZ != null) rPZ.NotifyFacesChanged();

            // TODO: Use The Change
            NotifyFacesChanged();
        }

        public void LoadComplete() {
            IsLoaded = true;
        }
        public void NotifyFacesChanged() {
            System.Threading.Interlocked.Increment(ref changedCount);
            if(OnFacesChanged != null)
                OnFacesChanged(this);
        }
    }
}


text:
// @flow

import { createToolbarEvent, sendAnalytics } from '../../analytics';
import { openDialog } from '../../base/dialog';
import { IconMicSlash } from '../../base/icons';
import { AbstractButton, type AbstractButtonProps } from '../../base/toolbox/components';

import { MuteEveryoneDialog } from './';

export type Props = AbstractButtonProps & {

    /**
     * The redux {@code dispatch} function.
     */
    dispatch: Function,

    /**
     * The ID of the participant object that this button is supposed to keep unmuted.
     */
    participantID: string,

    /**
     * The function to be used to translate i18n labels.
     */
    t: Function
};

/**
 * An abstract remote video menu button which mutes all the other participants.
 */
export default class AbstractMuteEveryoneElseButton extends AbstractButton<Props, *> {
    accessibilityLabel = 'toolbar.accessibilityLabel.muteEveryoneElse';
    icon = IconMicSlash;
    label = 'videothumbnail.domuteOthers';

    /**
     * Handles clicking / pressing the button, and opens a confirmation dialog.
     *
     * @private
     * @returns {void}
     */
    _handleClick() {
        const { dispatch, participantID } = this.props;

        sendAnalytics(createToolbarEvent('mute.everyoneelse.pressed'));
        dispatch(openDialog(MuteEveryoneDialog, { exclude: [ participantID ] }));
    }
}


text:
using System.Windows.Media;

namespace LightBuzz.Vitruvius
{
    /// <summary>
    /// Holds some commonly used Kinect constant values.
    /// </summary>
    public static class Constants
    {
        #region Constants

        /// <summary>
        /// Kinect DPI.
        /// </summary>
        public static readonly double DPI = 96.0;

        /// <summary>
        /// Default format.
        /// </summary>
        public static readonly PixelFormat FORMAT = PixelFormats.Bgr32;

        /// <summary>
        /// Bytes per pixel.
        /// </summary>
        public static readonly int BYTES_PER_PIXEL = (FORMAT.BitsPerPixel + 7) / 8;

        #endregion
    }
}


text:
import React, {Component, PropTypes} from 'react';
import { reduxForm } from 'redux-form';
import axios from 'axios';

class Login extends Component {

  constructor(props) {
    super(props);
    this.state = {
      error: ''
    }
  }

  static contextTypes = {
    router: PropTypes.object
  };

  onSubmit(props) {
    this.props.fields.email.value = '';
    this.props.fields.password.value = '';
    axios.post("http://families-together.herokuapp.com/login", props)
     .then( resp => {
       console.log('RESP', resp);
        if ( resp.data.token ) {
          sessionStorage.setItem('token', resp.data.token);
          this.context.router.push('/requests');
         } else {
       console.log('RESP', resp.data.error);
           if ( resp.data.error ) {
             this.setState({ error: resp.data.error });
           }
         }
     })
     .catch( err => console.log( err ));

  }

  render() {

    const { fields: { email, password}, handleSubmit } = this.props;

    return(

Please sign in

    			  	  <form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
  			    	  	<div className={`form-group ${email.touched && email.invalid ? 'has-danger' : ''}`}>
  			    		    <input className='form-control' placeholder="E-mail" value={email.value || ''} type="text" {...email} />

                      {email.touched ? email.error : ''}

  			    	  	<div className={`form-group ${password.touched && password.invalid ? 'has-danger' : ''}`}>
  			    		    <input className="form-control" placeholder="Password" type="password" {...password} />

                      {password.touched ? password.error : ''}

                            { this.state.error }

    				    <button type="submit" className="btn btn-primary">Submit</button>
    			      </form>

    );
  }
}

function validate(values) {
  const errors = {};
  const emailPattern = /(.+)@(.+){2,}\.(.+){2,}/;

  if (!values.email || !emailPattern.test(values.email)) {
    errors.email = 'Please enter a valid email address.';
  }
  if (!values.password) {
    errors.password = 'Password required.';
  } else if ( values.password.length < 7) {
    errors.password = 'Passwords must be a least 6 characters long.';
  }
  return errors;
}

export default reduxForm({
  form: 'LoginForm',
  fields: ['email', 'password'],
  validate})(Login);


text:
import React, { Component } from 'react';
import { Text } from 'react-native';

import styles from '../../styles/styles';
import InPageImage from '../inPageImage';
import AnimalText from '../animalText';
import AnimalTemplate from '../animalTemplate';

const IMAGES = [
  require('../../images/animals/velbloudDvouhrby/01.jpg'),
  require('../../images/animals/velbloudDvouhrby/02.jpg'),
  require('../../images/animals/velbloudDvouhrby/03.jpg'),
];

const THUMBNAILS = [
  require('../../images/animals/velbloudDvouhrby/01-thumb.jpg'),
  require('../../images/animals/velbloudDvouhrby/02-thumb.jpg'),
  require('../../images/animals/velbloudDvouhrby/03-thumb.jpg'),
];

var AnimalDetail = React.createClass({
  render() {
    return (
      <AnimalTemplate firstIndex={[1]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator}>
        <AnimalText>
          Dobrý den, dovolte, abychom se vám představili. My jsme velbloudi, velbloudi dvouhrbí. Můžete nám říkat také drabaři, nebo chcete-li být za vzdělance, smíte nás oslovovat latinsky <Text style={styles.italic}>Camelus bactrianus</Text>, vadit nám to nebude.
        </AnimalText>
        <AnimalText>
          Jsme sudokopytníci z čeledi velbloudovitých a naši příbuzní žijící ve volné přírodě jsou druhem kriticky ohroženým. Najít je můžete ve stepích a pouštích Číny a Mongolska, kde žijí ve zhruba třicetičlenných stádech vedených dospělým samcem.
        </AnimalText>
      <InPageImage indexes={[0]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} />
        <AnimalText>
          Oblíbenou potravou nás velbloudů, ať už v Asii nebo tady v Brně, jsou trávy, byliny a keře. Již 4,5 tisíce let jsme domestikovaným druhem a v lidské péči se dožíváme 20–30 let.
        </AnimalText>
      <InPageImage indexes={[2]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} />
        <AnimalText>
          Naší známou předností je to, že vydržíme dlouhé týdny bez vody. A je to tak! Naše tělo je schopné překonat až 20% úbytek vody v těle. Zato když máme žízeň, jsme schopni vypít za 10 minut až 110 litrů vody. A ještě k tomu jsme jako jediní savci schopni pít i slanou vodu.
        </AnimalText>
        <AnimalText>
          Ještě jsme se vám nepředstavili osobně! Rychle to tedy napravíme. V Brně nás je celkem osm. Hlavou našeho stáda je Dred, pochází z Polska a v Brně je od roku 2014. Salika je brněnská rodačka a je z nás nejstarší, narodila se v roce 1992, Fatima se narodila v roce 2006 v Ostravě a k nám do Brna přesídlila v roce 2008. A pak tu máme mámu Majdu, která pochází ze Slovenska a do Brna přicestovala jako ani ne roční mládě v roce 2004. V roce 2014 se jí narodila Bella. Nejštědřejší k nám byl ale rok 2017, to se tady narodila hned tři mláďata – Valerie (Majdě), Báhir (Belle) a Fariha (Fatimě).
        </AnimalText>
      </AnimalTemplate>
    );
  }
});

module.exports = AnimalDetail;


text:
<?php

namespace Majespay\Ufc\Transaction\Result;

class CreditTransactionResult extends SimpleTransactionResult
{
}


text:
import vscode from 'vscode';
import path from 'path';
import axios, { AxiosRequestConfig } from 'axios';
import { RAILS } from './symbols/rails';
import { RUBY, VERSION } from './symbols/ruby';
import { getSymbol } from './utils';
// Track currently webview panel
// var currentPanel: vscode.WebviewPanel | undefined = undefined;

function injectBase(html: string, base: string) {
  const policy = `<meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src vscode-resource: http:; script-src vscode-resource: http: 'unsafe-inline' ; style-src vscode-resource: http: 'unsafe-inline';">`;
  const _base = path.dirname(base) + '/';
  // Remove any <base> elements inside <head>
  let _html = html.replace(
    /(<[^>/]*head[^>]*>)[\s\S]*?(<[^>/]*base[^>]*>)[\s\S]*?(<[^>]*head[^>]*>)/gim,
    '$1 $3'
  );

  // Add <base> just before </head>
  _html = _html.replace(
    /<head>/gim,
    `<head><base href="${_base}">\n${policy}\n<style> body{margin:20px;}</style>`
  );
  return _html;
}

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

function showSide(
  symbol: string,
  html: string,
  context: vscode.ExtensionContext
) {
  // const columnToShowIn = vscode.window.activeTextEditor
  //   ? vscode.window.activeTextEditor.viewColumn
  //   : undefined;
  // if (currentPanel) {
  //   // If we already have a panel, show it in the target column
  //   currentPanel.webview.html = html;
  //   currentPanel.title = `Document ${symbol}`;
  //   currentPanel.reveal(columnToShowIn);
  // } else {
  const currentPanel = vscode.window.createWebviewPanel(
    'Document',
    `Document ${symbol}`,
    vscode.ViewColumn.Two,
    {
      // Enable scripts in the webview
      enableScripts: true,
      retainContextWhenHidden: true,
    }
  );

  currentPanel.webview.html = html;
  // Reset when the current panel is closed
  // currentPanel.onDidDispose(
  //   () => {
  //     currentPanel = undefined;
  //     source.cancel('request canceled as WebviewPanel Disposed.');
  //   },
  //   null,
  //   context.subscriptions
  // );
}

function doRequest(
  this: vscode.ExtensionContext,
  _url: string,
  symbol: string
) {
  const request = axios({
    url: _url,
    timeout: 5e3,
    cancelToken: source.token,
  })
    .then((r: { data: any }) => {
      if (typeof r.data === 'string') {
        const html = injectBase(r.data, _url);
        showSide(symbol, html, this);
      } else {
        const html = 'No valid response content.';
        showSide(symbol, html, this);
      }
    })
    .catch((err) => {
      console.error(err);
      showSide(symbol, err.toString(), this);
    });
}

export function viewDoc(this: vscode.ExtensionContext) {
  const document = vscode.window.activeTextEditor.document;
  const position = vscode.window.activeTextEditor.selection.active;
  const symbol = getSymbol(document, position);
  if (typeof symbol === 'undefined') {
    showSide(
      'word range not found',
      "Can't find word range from your active editor selection.",
      this
    );
    return;
  }

  let endpoint = '';
  const lowerSymbol = symbol.toLowerCase();
  const isRailsSymbol = RAILS.prefix(lowerSymbol).prefix.length;
  const isRubySymbol = RUBY.prefix(lowerSymbol).prefix.length;
  console.log(
    `symbol:${lowerSymbol} isRailsSymbol:${isRailsSymbol},isRubySymbol:${isRubySymbol}`
  );
  if (symbol && (isRailsSymbol || isRubySymbol)) {
    endpoint = symbol.replace('::', '/');
  } else {
    showSide(
      'symbol not found',
      `symbol:${symbol} neither ruby nor rails symbol`,
      this
    );
    return;
  }
  console.log(`symbol:${lowerSymbol},endpoint:${endpoint}`);
  if (endpoint === null) {
    return;
  }
  let url = '';
  if (isRailsSymbol > isRubySymbol) {
    url = `https://api.rubyonrails.org/classes/${endpoint}.html`;
  } else if (isRubySymbol) {
    url = `https://docs.rubydocs.org/ruby-${VERSION.replace(
      /\./g,
      '-'
    )}/classes/${endpoint}.html`;
  } else {
    showSide(symbol, 'No matched symbol on extension side.', this);
    return;
  }
  console.log(`doc url:${url}`);
  // let info = vscode.window.showInformationMessage("Rails:Document-loading...")
  doRequest.call(this, url, symbol);
}


text:
package org.drooms.impl.util;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import org.drooms.impl.logic.PathTracker;
import org.kie.api.KieBase;
import org.kie.api.KieBaseConfiguration;
import org.kie.api.KieServices;
import org.kie.api.builder.ReleaseId;
import org.kie.api.conf.EventProcessingOption;
import org.kie.api.runtime.KieContainer;
import org.slf4j.Logger;

/**
 * A class to validate strategy's feasibility.
 *
 */
public class DroomsStrategyValidator {
    private final List<String> errors = new LinkedList<String>();
    private final List<String> warnings = new LinkedList<String>();

    public DroomsStrategyValidator(ReleaseId releaseId) {
        validate(releaseId);
    }

    /**
     * Retrieve problems that are critical to the strategy and will result in
     * the strategy not being accepted for the game.
     *
     * @return An unmodifiable collection of error messages.
     */
    public List<String> getErrors() {
        return Collections.unmodifiableList(this.errors);
    }

    /**
     * Retrieve problems that aren't critical to the strategy. The strategy may
     * be sub-optimal, but it will be allowed into the game.
     *
     * @return An unmodifiable collection of warnings.
     */
    public List<String> getWarnings() {
        return Collections.unmodifiableList(this.warnings);
    }

    /**
     * Whether or not the strategy is both valid and leverages all the available
     * options.
     *
     * @return True if clean.
     */
    public boolean isClean() {
        return (this.isValid() && this.warnings.size() == 0);
    }

    /**
     * Whether or not the strategy is valid. Invalid strategies may not be
     * accepted into the game.
     *
     * @return True if valid.
     */
    public boolean isValid() {
        return (this.errors.size() == 0);
    }

    private void validate(ReleaseId releaseId) {
        final KieServices ks = KieServices.Factory.get();

        try {
            final KieContainer container = ks.newKieContainer(releaseId);

            final KieBaseConfiguration config = ks.newKieBaseConfiguration();
            config.setOption(EventProcessingOption.STREAM);
            final KieBase kbase = container.newKieBase(config);

            final KnowledgeSessionValidationHelper helper = new KnowledgeSessionValidationHelper(kbase);

            this.validateGlobal(helper, "logger", Logger.class, false);
            this.validateGlobal(helper, "tracker", PathTracker.class, false);
            this.validateEntryPoint(helper, "rewardEvents", true);
            this.validateEntryPoint(helper, "playerEvents", true);
            this.validateEntryPoint(helper, "gameEvents", true);
        } catch (RuntimeException ex) {
            // KieServices throw RuntimeException when KieModule or default KieBase is not found
            report(ex.getMessage(), true);
        }
    }

    private void report(final String report, final boolean isError) {
        if (isError) {
            this.errors.add(report);
        } else {
            this.warnings.add(report);
        }
    }

    private void validateEntryPoint(final KnowledgeSessionValidationHelper helper, final String name, final boolean isError) {
        if (!helper.hasEntryPoint(name)) {
            this.report("Entry point '" + name + "' not declared.", isError);
        }
    }

    private void validateGlobal(final KnowledgeSessionValidationHelper helper, final String name, final Class<?> cls,
            final boolean isError) {
        if (!helper.hasGlobal(name, cls)) {
            this.report("Global '" + name + "' of type '" + cls.getCanonicalName() + "' not declared.", isError);
        }
    }
}


text:
using UnityEngine;
using System.Collections;

public class HorseAppearance : MonoBehaviour {

    [Header("Horse Color")]

     public Material[] HorseSkins;
    public Transform[] HorseMesh;

    [Header("Hair Color")]
    public Material[] HairColor;
    public Transform[] HairMesh;

    [Header("Horse Mount")]
    public bool Mount;
    public Material[] MountColor;
    public Transform[] MountMesh;

    [Header("Horse Armor")]
    public bool Armor;
    public Material[] ArmorColor;
    public Transform[] ArmorMesh;
}


text:
/*
  ToshibaLED I2C driver
*/
/*
   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <AP_HAL.h>
#include "ToshibaLED.h"
#include "ToshibaLED_I2C.h"

extern const AP_HAL::HAL& hal;

#define TOSHIBA_LED_ADDRESS 0x55    // default I2C bus address
#define TOSHIBA_LED_PWM0    0x01    // pwm0 register
#define TOSHIBA_LED_PWM1    0x02    // pwm1 register
#define TOSHIBA_LED_PWM2    0x03    // pwm2 register
#define TOSHIBA_LED_ENABLE  0x04    // enable register

bool ToshibaLED_I2C::hw_init()
{
    // get pointer to i2c bus semaphore
    AP_HAL::Semaphore* i2c_sem = hal.i2c->get_semaphore();

    // take i2c bus sempahore
    if (!i2c_sem->take(HAL_SEMAPHORE_BLOCK_FOREVER)) {
        return false;
    }

    // disable recording of i2c lockup errors
    hal.i2c->ignore_errors(true);

    // enable the led
    bool ret = (hal.i2c->writeRegister(TOSHIBA_LED_ADDRESS, TOSHIBA_LED_ENABLE, 0x03) == 0);

    // update the red, green and blue values to zero
    uint8_t val[3] = { TOSHIBA_LED_OFF, TOSHIBA_LED_OFF, TOSHIBA_LED_OFF };
    ret &= (hal.i2c->writeRegisters(TOSHIBA_LED_ADDRESS, TOSHIBA_LED_PWM0, 3, val) == 0);

    // re-enable recording of i2c lockup errors
    hal.i2c->ignore_errors(false);

    // give back i2c semaphore
    i2c_sem->give();

    return ret;
}

// set_rgb - set color as a combination of red, green and blue values
bool ToshibaLED_I2C::hw_set_rgb(uint8_t red, uint8_t green, uint8_t blue)
{
    // get pointer to i2c bus semaphore
    AP_HAL::Semaphore* i2c_sem = hal.i2c->get_semaphore();

    // exit immediately if we can't take the semaphore
    if (i2c_sem == NULL || !i2c_sem->take(5)) {
        return false;
    }

    // update the red value
    uint8_t val[3] = { (uint8_t)(blue>>4), (uint8_t)(green>>4), (uint8_t)(red>>4) };
    bool success = (hal.i2c->writeRegisters(TOSHIBA_LED_ADDRESS, TOSHIBA_LED_PWM0, 3, val) == 0);

    // give back i2c semaphore
    i2c_sem->give();
    return success;
}


text:
package Player;

public abstract class Callback_Server_playSong extends Ice.OnewayCallback
{
}


text:
<<<<<<< HEAD
# Api

To start your Phoenix app:

  * Install dependencies with `mix deps.get`
  * Create and migrate your database with `mix ecto.create && mix ecto.migrate`
  * Start Phoenix endpoint with `mix phoenix.server`

Now you can visit [`localhost:4000`](http://localhost:4000) from your browser.

Ready to run in production? Please [check our deployment guides](http://www.phoenixframework.org/docs/deployment).

## Learn more

  * Official website: http://www.phoenixframework.org/
  * Guides: http://phoenixframework.org/docs/overview
  * Docs: http://hexdocs.pm/phoenix
  * Mailing list: http://groups.google.com/group/phoenix-talk
  * Source: https://github.com/phoenixframework/phoenix
=======
# cases-api
Api Backend in Phoenix Elixir Postgresql for Customer care and support records using Emberjs Frontend
>>>>>>> f9e0ababbac408135af313bb6c489e122f8534bf


text:
package main

import (
	"flag"
	"go-common/app/service/live/resource/sdk"
	"os"
	"os/signal"
	"syscall"
	"time"

	"go-common/app/service/live/gift/conf"
	"go-common/app/service/live/gift/server/grpc"
	"go-common/app/service/live/gift/server/http"
	"go-common/app/service/live/gift/service"
	ecode "go-common/library/ecode/tip"
	"go-common/library/log"
	"go-common/library/net/trace"
)

func main() {
	flag.Parse()
	if err := conf.Init(); err != nil {
		panic(err)
	}
	log.Init(conf.Conf.Log)
	defer log.Close()
	log.Info("gift-service start")
	trace.Init(conf.Conf.Tracer)
	defer trace.Close()
	ecode.Init(conf.Conf.Ecode)
	svc := service.New(conf.Conf)
	http.Init(conf.Conf, svc)
	grpc.Init(conf.Conf)
	titansSdk.Init(conf.Conf.Titan)

	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
	for {
		s := <-c
		log.Info("get a signal %s", s.String())
		switch s {
		case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT:
			svc.Close()
			log.Info("gift-service exit")
			time.Sleep(time.Second)
			return
		case syscall.SIGHUP:
		default:
			return
		}
	}
}


text:
RedisORM v0.2.0
===============

.. image:: https://secure.travis-ci.org/JoshAshby/pyRedisORM.png?branch=master
        :target: http://travis-ci.org/JoshAshby/pyRedisORM

.. image:: https://coveralls.io/repos/JoshAshby/pyRedisORM/badge.png
        :target: https://coveralls.io/r/JoshAshby/pyRedisORM

.. image:: https://pypip.in/v/RedisORM/badge.png
    :target: https://crate.io/packages/RedisORM/
    :alt: Latest PyPI version

.. image:: https://pypip.in/d/RedisORM/badge.png
    :target: https://crate.io/packages/RedisORM/
    :alt: Number of PyPI downloads

RedisORM is just a quick and simple little Key-Value group to Python Object
mapper that makes it easier to have somewhat more complex structures in Redis.
While a similar structure could be achieved by using a Redis hash, this module
also allows for lists and future support for Redis data
structures is hopefully planed, making this more helpful than basic hashs.

There is a small test suite provided. It requires an actual Redis install that
is up and running. If you want too change the address then please take a look
in the test directory. The tests are automatically ran each commit,
thanks to `travis-ci.org <http://travis-ci.org>`__ and coverage is provided by
`Coveralls.io <http://coveralls.io>`__ and this documentation
is kindly hosted and automatically rebuilt by `readthedocs.org
<http://readthedocs.org>`__.

A Few Minor Warnings
--------------------
#. This is a very early release, and although I've been using a large part of
   this code for about a year now, things are still going to break and not
   function well. Don't be afraid to submit a bug report or a patch on Github
   to fix something.
#. I'm only a second year university student, and software
   isn't even my major; I'm working towards an Electrical and Computer
   Engineering degree, so not only do I have limited time to keep this
   maintained, but I also probably won't write the best code ever.
#. This project follows the semantic versioning specs. All Minor and
   patch versions will not break the major versions API, however a bump of the
   major version signifies that backwards compatibility will most likely be
   broken in some way.

Documentation
=============
For more information, a short quick start, and information about running the
test suit, please `read the documentation
<https://pyredisorm.readthedocs.org/en/latest/>`__ kindly hosted
on `readthedocs.org <http://readthedocs.org>`__

Contributing
------------
All code for this can be found online at
`github <https://github.com/JoshAshby/pyRedisORM>`__.
If something is broken, or a feature is missing, please submit a pull request
or open an issue. Most things I probably won't have time to get around to
looking at too deeply, so if you want it fixed, a pull request is the way
to go. In your pull request please provide an explanation as to what your
request is for, and what benefit it provides. Also, please try to match the
style of the code, or make sure your code is nearly all PEP8 compliant just to
maintain code consistency.

Besides that, this project is licensed under the MIT License as found in the
``LICENSE.txt`` file. Enjoy!


text:
package com.sfl.pms.persistence.repositories.payment.notification.adyen;

import com.sfl.pms.persistence.repositories.payment.notification.AbstractPaymentProviderNotificationRepository;
import com.sfl.pms.services.payment.notification.model.adyen.AdyenPaymentProviderNotification;
import org.springframework.stereotype.Repository;

/**
 * User: Ruben Dilanyan
 * Company: SFL LLC
 * Date: 4/25/15
 * Time: 11:53 PM
 */
@Repository
public interface AdyenPaymentProviderNotificationRepository extends AbstractPaymentProviderNotificationRepository<AdyenPaymentProviderNotification> {
}


text:
export default function errorHandler(err, req, res, next) {
  if (!err) {
    return res.sendStatus(500);
  }

  const error = {
    message: err.message || 'Internal Server Error.',
  };

  if (process.env.NODE_ENV) {
    error.stack = err.stack;
  }

  if (err.errors) {
    error.errors = {};
    const { errors } = err;
    for (const type in errors) {
      if (type in errors) {
        error.errors[type] = errors[type].message;
      }
    }
  }

  res.status(err.status || 500).json(error);
}


text:
#include "../include/easyTest.h"

#include <cstdlib>
#include <ctime>

#ifdef __linux__
#include <unistd.h>
#elif defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#else
#error Unsupported platform: currently supported platforms are\
       Linux and Windows
#endif //__linux__

TEST_SUITE(ThreadB)
{
public:
	ThreadB()
	{
		std::srand(static_cast<unsigned int>(std::time(nullptr)));
	}

	TEST_CASE(fastTest);
	TEST_CASE(longTest);
	TEST_CASE(mediumTest);

private:
	unsigned int waitAtMax(unsigned int ms) const;
};

TEST_IMPL(ThreadB, fastTest)
{
	TRACE_FORMAT("Waiting %u ms...", waitAtMax(800));
	return true;
}

TEST_IMPL(ThreadB, longTest)
{
	TRACE_FORMAT("Waiting %u ms...", waitAtMax(2000));
	return true;
}

TEST_IMPL(ThreadB, mediumTest)
{
	TRACE_FORMAT("Waiting %u ms...", waitAtMax(1000));
	return true;
}

unsigned int ThreadB::waitAtMax(unsigned int ms) const
{
	unsigned int u = ms >> 1;
	u += static_cast<unsigned int>(u * static_cast<float>(std::rand()) / RAND_MAX);

#ifdef __linux__
	usleep(1000 * u);
#else
	Sleep(u);
#endif //__linux__

	return u;
}


text:
package org.telegram.api.toppeer;

import org.telegram.api.peer.TLAbsPeer;
import org.telegram.tl.StreamingUtils;
import org.telegram.tl.TLContext;
import org.telegram.tl.TLObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author Ruben Bermudez
 * @version 1.0
 * @brief TODO
 * @date 07 of August of 2016
 */
public class TLTopPeer extends TLObject {
    public static final int CLASS_ID = 0xedcdc05b;

    private TLAbsPeer peer;
    private double rating;

    @Override
    public int getClassId() {
        return CLASS_ID;
    }

    public TLAbsPeer getPeer() {
        return peer;
    }

    public double getRating() {
        return rating;
    }

    @Override
    public void serializeBody(OutputStream stream) throws IOException {
        StreamingUtils.writeTLObject(peer, stream);
        StreamingUtils.writeDouble(rating, stream);
    }

    @Override
    public void deserializeBody(InputStream stream, TLContext context) throws IOException {
        peer = StreamingUtils.readTLObject(stream, context, TLAbsPeer.class);
        rating = StreamingUtils.readDouble(stream);
    }

    @Override
    public String toString() {
        return "topPeer#edcdc05b";
    }
}


text:
package org.kaaproject.kaa.server.sync;

import java.nio.ByteBuffer;

public final class LogEntry {
    private ByteBuffer data;

    public LogEntry() {
    }

    /**
     * All-args constructor.
     */
    public LogEntry(ByteBuffer data) {
        this.data = data;
    }

    /**
     * Gets the value of the 'data' field.
     */
    public ByteBuffer getData() {
        return data;
    }

    /**
     * Sets the value of the 'data' field.
     *
     * @param value
     *            the value to set.
     */
    public void setData(ByteBuffer value) {
        this.data = value;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((data == null) ? 0 : data.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        LogEntry other = (LogEntry) obj;
        if (data == null) {
            if (other.data != null) {
                return false;
            }
        } else if (!data.equals(other.data)) {
            return false;
        }
        return true;
    }
}


text:
<?php

namespace Pinq\Caching;

use Pinq\PinqException;

/**
 * Adapter class for a cache that implements \ArrayAccess
 *
 * @author Elliot Levin <elliotlevin@hotmail.com>
 */
class ArrayAccessCacheAdapter extends OneDimensionalCacheAdapter
{
    /**
     * The cache object implementing array access
     *
     * @var \ArrayAccess
     */
    private $arrayAccess;

    public function __construct(\ArrayAccess $innerCache)
    {
        parent::__construct();
        $this->arrayAccess = $innerCache;
    }

    public function save($key, $value)
    {
        $this->arrayAccess[$key] = $value;
    }

    public function contains($key)
    {
        return isset($this->arrayAccess[$key]);
    }

    public function tryGet($key)
    {
        return isset($this->arrayAccess[$key]) ? $this->arrayAccess[$key] : null;
    }

    public function remove($key)
    {
        unset($this->arrayAccess[$key]);
    }

    public function clear()
    {
        $this->doClear();
    }

    public function clearInNamespace($namespace)
    {
        $this->doClear($namespace);
    }

    public function doClear($namespace = null)
    {
        if ($this->arrayAccess instanceof \Traversable) {
            $keys = array_keys(iterator_to_array($this->arrayAccess, true));

            foreach ($keys as $key) {
                if ($namespace === null || strpos($key, $namespace) === 0) {
                    unset($this->arrayAccess[$key]);
                }
            }
        } else {
            throw new PinqException(
                    'Cannot clear cache %s: does not support clearing',
                    get_class($this->arrayAccess));
        }
    }
}


text:
#ifndef GDHELPERS_H
#define GDHELPERS_H 1

/* TBB: strtok_r is not universal; provide an implementation of it. */

extern char *gd_strtok_r(char *s, char *sep, char **state);

/* These functions wrap memory management. gdFree is
	in gd.h, where callers can utilize it to correctly
	free memory allocated by these functions with the
	right version of free(). */
void *gdCalloc(size_t nmemb, size_t size);
void *gdMalloc(size_t size);
void *gdRealloc(void *ptr, size_t size);

#endif /* GDHELPERS_H */


text:
import React, { Component } from 'react';
import { PropTypes } from 'prop-types';
import { Grid, Col } from 'react-bootstrap';
import './Logo.scss';

export default class Logo extends Component {
    static propTypes = {
    };

    constructor(props) {
        super(props);
    }

    render() {
        return (

                <Col md={12}>

                        React Skeleton

                </Col>

        );
    }
}


text:
import os
import subprocess
import sys

def du(path):
    """Return the size of the file or directory."""

    if not os.path.exists(path):
        raise Exception("Path does not exist: " + path)
    if os.path.isfile(path):
        return os.path.getsize(path)
    else:
        total = 0
        for root, dirs, files in os.walk(path):
            total += sum([os.path.getsize(os.path.join(root, f)) for f in files])
        return total

def sizeof_fmt(num, suffix='B'):
    for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
        if abs(num) < 1024.0:
            return "%3.1f%s%s" % (num, unit, suffix)
        num /= 1024.0
    return "%.1f%s%s" % (num, 'Yi', suffix)

def prompt_confirmation(msg):
    """Prompt user for confirmation. Returns True if yes, False if no. Defaults to no."""
    sys.stdout.write("%s (y/N): " % msg)
    choice = raw_input().lower()
    if choice == "y":
        return True
    return False

def prompt_confirm_or_exit(msg):
    if not prompt_confirmation(msg):
        print "Aborted"
        sys.exit(1)

def check_output(*args, **kwargs):
    """Workaround for Python 2.6 not having subprocess.check_output"""
    if "check_output" in dir(subprocess):
        return subprocess.check_output(*args, **kwargs)

    p = subprocess.Popen(stdout=subprocess.PIPE, *args, **kwargs)
    stdout, _ = p.communicate()
    ret = p.poll()
    if ret:
        raise Exception("Command %s failed." % (repr( (args, kwargs) )))
    return stdout


text:
'use strict';

// Field text input

// Inspiration and ideas for implementation http://making.fiftythree.com/fluid-text-inputs/
// NOTES:
//    - Chromium Android bug when have 25 characters (https://code.google.com/p/chromium/issues/detail?id=483497)
// TODOs:
//    - Implement granular character handling (user pair evaluation), performance issue with more than 250 characters
//    - Implement doubletap selection (selects all text)
//    - Better handling of draggable parent
//    - Fix bug when scroll rigth and delete with backspace, bad repositioning (may be bad offset handling).

BB.FieldTextInput = BB.Field.prototype.create({
  // TODO: invert text color when are selected, note that is not trivial.
  constructor: function(text, parent, options)  {
    BB.Field.prototype.constructor.call(this, 'TextInput');
    this.children = [];
    this.container = null; // contains attached elements(border)
    this.childContainer = null; // svg group that contains all children
    this.root = null; // contains the text, this is a nested SVG document (is a container an have it own viewport allowing 'overflow: hidden' css property)
    this.textRoot = null;
    this.fontFamily = 'sans-serif';
    this.fontColor = '#000'; // Must be in hex format to get the negative or modify utils.js/color2negative function to allows other color formats
    // (Not yet implemented negative color for selection, needs an individual tspan for selection and repositioning it beacuse some fonts overlaps letters)
    this.selectionColor = '#3399FF';
    this.backgroundColor = '#FFFFFF'; // background color when is focused
    this.size = 15; // px default metrics in svg.js library
    this.width_ = 0;
    this.minWidth = 10; // When this is not fluid this don't matters
    this.height_ = this.size + 3;
    // Intenals
    this.style = {
      className: 'BBFieldTextInput',
      editableTextBackground: 'BBEditableTextBackground'
    };
    this.textMetrics_ = null;
    this.textWidth_ = 0;
    this.lastTextWidth_ = 0;
    this.initialSpaceX_ = 1;
    this.initialSpaceY_ = 1;
    this.finalSpaceX_ = 1;
    this.finalSpaceY_ = 1;
    this.textRootOffset_ = 1;
    this.offsetX_ = 0; // X scroll offset relative to the text (one line textInput doesn't need offsetY)
    this.initialCursorY_ = 1; // Vertical cursor initial separation relative to SVG element
    this.initialCursorX_ = 0; // Horizontal cursor initial separation relative to SVG element
    this.cursor = null;
    this.cursorXY = {x: 0, y: 0};
    this.cursorState = 0; //0: off, 1: on
    this.cursorInterval = null;
    this.selectable = true;
    this.draggableIndex = -1; // Index of this in attachDraggable array in the parent (if exists)
    this.fluid = true; // fluid or normal text input, true by default

    if (text && typeof(text) == 'string') {
      this.text = text;
      this.mirrorText = text;
    } else {
      throw 'Text must be a valid string';
      return;
    }
    if (parent) {
      this.parent = parent;
    }
    if (!options) {
      return;
    }
    this.optionList = [['fontColor', 'public'],
                       ['fontFamily', 'public'],
                       ['fontSize', 'public'],
                       ['minWidth', 'public'],
                       ['height', 'private'],
                       ['fluid', 'public']];
    for (var i = 0,el; el = this.optionList[i]; i++) {
      if (options.hasOwnProperty(el[0])) {
        var opt = (el[1] == 'public') ? el[0] : el[0] + '_';
        this[opt] = options[el[0]];
      }
    }
    if (options.render) {
      this.render();
    }
  },

  render: function(){
    if (!this.parent) {
      throw 'FieldTextInput must have a parent to be rendered';
      return;
    }
    if (!this.rendered_) {
      this.container = this.parent.container.group().addClass(this.style.className);
      // Background
      this.mainBackground = this.container.rect(0,0);
      // Nested svg as a root allows to use overflow css property
      this.root = this.container.nested().attr('style', 'overflow: hidden;');
      //Mirror root for cursor position, this contains 0 to cursorPosition text (metrics)
      this.mirrorRoot = this.root.text(this.text).font({
        family: this.fontFamily
        , size: this.fontSize}).fill(this.fontColor).move(this.textRootOffset_, 0) //BUG: svg.js bug when add text to a group
        .style('text-rendering: geometricPrecision');
      // Computes text length
      var textLength = this.mirrorRoot.node.getComputedTextLength();
      this.textWidth_ = textLength;
      this.setWidth(textLength);
      this.mainBackground.size(this.width_ + this.initialSpaceX_ + this.finalSpaceX_, this.height_ + this.initialSpaceY_ + this.finalSpaceY_)
        .move(0, 0).addClass(this.style.editableTextBackground).radius(4);
      this.root.size(this.width_, this.height_).move(this.initialSpaceX_, this.initialSpaceY_);
      // Background hides mirrorRoot
      this.background = this.root.rect(this.width_, this.height_).move(0, 0);
      this.selectionRoot =  this.root.rect(0, this.initialCursorY_ + this.size).move(0, 0).fill(this.selectionColor);
      this.textRoot = this.root.text(this.text.replace(/ /g, '\u00a0')).font({
        family: this.fontFamily
        , size: this.fontSize}).fill(this.fontColor).move(this.textRootOffset_, 0) //BUG: svg.js bug when add text to a group
        .style('text-rendering: geometricPrecision'); // when scales keeps proportions
      // Text metrics
      this.getTextMetrics_();
      // Creates a foreign text input for listening keyboard events,
      // this isn't necesary when implemented editable svg text element from SVG 1.2 tiny specification
      // avoid some webkit and blink bugs with textinputs when are rotated and scaled.
      this.foreignTextInput = this.container.foreignObject(0,0).attr({id: 'fobj'})
        .appendChild("input", {type: 'text', value: this.text});
      if (this.fluid) {
        this.setMaxChars(120); // more than 120 characters in one line is not recomended for fluid text inputs
      } else {
        this.setMaxChars(250); // for performance not more than 250 characters
      }
      var this_ = this;

      // Keyboard handler
      var KeyboardHandler = function (e) { // Note that this handles keyup and keydown events
        // compatibility with Chrome and firefox
        var keyId, refreshCursor = false, textChanged = false;
        if (e.key) { // Firefox
          keyId = e.key;
        } else if (e.keyIdentifier) { // Chrome
          keyId = e.keyIdentifier;
        }
        if (keyId == 'Enter') {
          return; // Ignore some keys
        }
        if (e.which == 8 || e.which == 46 || keyId == 'Left' || keyId == 'Right'
            || keyId == 'Up' || keyId == 'Down' || keyId == 'Home' || keyId == 'End'
            // New keyboard API for firefox see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent.key
            || keyId == 'ArrowLeft' || keyId == 'ArrowRight' || keyId == 'ArrowUp' || keyId == 'ArrowDown'
           ) {
          // Special keys that changes the text: backspace, delete
          if (e.which == 8 || e.which == 46) {
            if (this_.text != e.target.value) {
              this_.text = e.target.value;
              this_.textRoot.text(this_.text.replace(/ /g, '\u00a0')); // Shows spaces with the &nbsp html character
              this_.getTextMetrics_(-1, this_.foreignTextInput.getChild(0).selectionStart); // Update text metrics
              textChanged = true; // flag
            }
          }
        } else { // normal keys
          if (this_.text != e.target.value) {
            this_.text = e.target.value;
            this_.textRoot.text(this_.text.replace(/ /g, '\u00a0'));
            this_.getTextMetrics_(-1, this_.foreignTextInput.getChild(0).selectionStart); // Update text metrics
            textChanged = true;
          }
        }
        // getCaretPosition function not used now
        var selectionStart = this_.foreignTextInput.getChild(0).selectionStart, mirrorText,
            selectionEnd = this_.foreignTextInput.getChild(0).selectionEnd, selectionWidth = 0, i,
            caretPos = selectionStart;
        // Computes the width of selectionRoot (the rect for selected text)
        for (i = selectionStart; i < selectionEnd; i++) {
          selectionWidth += this_.textMetrics_[i];
        }
        if (selectionWidth == 0) {
          this_.showCursor();
        } else {
          this_.hideCursor();
        }
        // The text before the caret
        mirrorText = this_.text.substr(0, caretPos);
        this_.mirrorText = mirrorText;
        this_.mirrorRoot.text(mirrorText.replace(/ /g, '\u00a0'));
        var textLength = this_.mirrorRoot.node.getComputedTextLength();
        // Scrolling and fluid text logic
        if (keyId == 'Left' || keyId == 'Right'
            || keyId == 'Up' || keyId == 'Down' || keyId == 'Home' || keyId == 'End'
            // New keyboard API for firefox see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent.key
            || keyId == 'ArrowLeft' || keyId == 'ArrowRight' || keyId == 'ArrowUp' || keyId == 'ArrowDown'
           ) { // Modify text have a diferent behavior that only moves in it
          if (-this_.offsetX_ > textLength) {
            this_.offsetX_ = -textLength;
          }
        } else { // Logic for scrolling when modify text
          if (!this_.fluid && -this_.offsetX_ + this_.width_ >= this_.lastTextWidth_ && this_.width_ < this_.lastTextWidth_) {
            this_.offsetX_ = (this_.width - this_.textWidth_ > 0) ? 0 : this_.width_ - this_.textWidth_;
          }
        }
        if (!this_.fluid) {
          if (this_.width_ - this_.offsetX_ <= textLength) {
            this_.offsetX_ = this_.width_ - textLength;
          }
        }
        this_.cursor.move(this_.initialCursorX_ + this_.textRootOffset_ + this_.offsetX_ + textLength, this_.initialCursorY_); // Position of cursor
        this_.textRoot.x(this_.initialCursorX_ + this_.offsetX_ + this_.textRootOffset_); // Scrolls the text
        // Moves and resize selectionRoot
        this_.selectionRoot.move(this_.initialCursorX_ + this_.textRootOffset_ + this_.offsetX_ + textLength, this_.initialCursorY_);
        this_.selectionRoot.width(selectionWidth);
        if (textChanged && this_.fluid) {
          this_.setWidth(this_.textWidth_);
        }
      }
      this.foreignTextInput.getChild(0).addEventListener('keyup', KeyboardHandler);
      this.foreignTextInput.getChild(0).addEventListener('keydown', KeyboardHandler);

      // Flag for trackstart
      this.trackStarted = false;
      // Sets caret position with pointer
      this.pointerCaretHandler = function (e) {
        var mousePos = mouseToSvg(e, this_.root.node), i, len, pos1 = 0, pos2 = 0;
        // Mouse position relative to scroll
        mousePos.x -= this_.initialCursorX_ + this_.offsetX_;
        // Find the caret position for this pointerdown event
        for (i = 0, len = this_.textMetrics_.length; i <= len; i++) {
          pos1 = pos2;
          pos2 += ((i == 0) ? 0 : this_.textMetrics_[i - 1]/2) + ((i == len) ? 0 : this_.textMetrics_[i]/2);
          //console.log(pos1 + '<=' + mousePos.x + '<' + pos2) // DEBUGGING LINE
          if (pos1 <= mousePos.x && mousePos.x < pos2) {
            break;
          }
        }
        this_.selectionRoot.width(0);
        this_.mirrorText = this_.text.substr(0, i);
        this_.mirrorRoot.text(this_.mirrorText.replace(/ /g, '\u00a0'));
        setCaretPosition(this_.foreignTextInput.getChild(0), i);
      };
      PolymerGestures.addEventListener(this.root.node, 'up', function(e) {
        if (this_.trackStarted == false && this_.selected_ == false) {
          this_.pointerCaretHandler(e);
          this_.showCursor();
          this_.setSelected(true);
        } else {
          this_.trackStarted = false;
        }
      });
      PolymerGestures.addEventListener(this.root.node, 'down', function(e) {
        if (this_.trackStarted == false && this_.selected_ == true) {
          this_.pointerCaretHandler(e);
          this_.showCursor();
          this_.setSelected(true);
          this_.referenceCursorSelection = this_.foreignTextInput.getChild(0).selectionStart;
          this_.referenceOffsetX_ = this_.offsetX_;
        } else {
          this_.trackStarted = false;
        }
      });
      //Pointertrackstart handler
      PolymerGestures.addEventListener(this.root.node, 'trackstart', function (e) {
        //console.log('trackstart')
        this_.trackStarted = true;
      });
      // Selects text with pointer
      this.pointerCaretSelectionHandler = function (e) {
        // console.log('track')
        // Keeps reference to viewport
        var mousePos = mouseToSvg(e, this_.root.node), i, len, pos1 = 0, pos2 = 0;
        // Mouse position relative to scroll
        mousePos.x -= this_.initialCursorX_ + this_.offsetX_;
        // Find the caret position for this pointerdown event
        if (mousePos.x < 0) {
          i = 0;
        } else {
          for (i = 0, len = this_.textMetrics_.length; i <= len; i++) {
            pos1 = pos2;
            pos2 += ((i == 0) ? 0 : this_.textMetrics_[i - 1]/2) + ((i == len) ? 0 : this_.textMetrics_[i]/2);
            //console.log(pos1 + '<=' + mousePos.x + '<' + pos2) // DEBUGGING LINE
            if (pos1 <= mousePos.x && mousePos.x < pos2) {
              break;
            }
          }
        }
        var reverseSelection = false;
        // Diferential of offset relative to trackstart event
        var doffsetX_ = this_.offsetX_ - this_.referenceOffsetX_;
        if (e.dx >= doffsetX_) {
          this_.foreignTextInput.getChild(0).selectionStart = this_.referenceCursorSelection;
          this_.foreignTextInput.getChild(0).selectionEnd = i;
        } else {
          this_.foreignTextInput.getChild(0).selectionStart = i;
          this_.foreignTextInput.getChild(0).selectionEnd = this_.referenceCursorSelection;
          reverseSelection = true;
        }
        /*console.log(i)
        console.log('d:'+this_.foreignTextInput.getChild(0).selectionEnd);
        console.log('d:'+this_.foreignTextInput.getChild(0).selectionStart);*/ // DEBUGGING lines
        var selectionStart = this_.foreignTextInput.getChild(0).selectionStart,
            mirrorText, selectionEnd = this_.foreignTextInput.getChild(0).selectionEnd, selectionWidth = 0;
        // Computes the width of selectionRoot (the rect for selected text)
        for (i = selectionStart; i < selectionEnd; i++) {
          selectionWidth += this_.textMetrics_[i];
        }
        if (selectionWidth == 0) {
          this_.showCursor();
        } else {
          this_.hideCursor();
        }
        //console.log('up:' + selectionWidth);
        var textLength = this_.mirrorRoot.node.getComputedTextLength();
        if (!this_.fluid)
        // Scrolling logic
        var selectionDx = (reverseSelection?-1:1)*selectionWidth;
        if (-this_.offsetX_ > textLength + selectionDx) {
          this_.offsetX_ = -textLength - selectionDx;
        }
        if (this_.width_ - this_.offsetX_ <= textLength + selectionDx) {
          this_.offsetX_ = this_.width_ - textLength - selectionDx;
        }
        this_.textRoot.x(this_.initialCursorX_ + this_.offsetX_ + this_.textRootOffset_); // Scrolls the text
        // Moves and resize selectionRoot
        this_.selectionRoot.move(this_.initialCursorX_ + this_.textRootOffset_ + this_.offsetX_ + textLength - (reverseSelection?selectionWidth:0), this_.initialCursorY_);
        this_.selectionRoot.width(selectionWidth);
        this_.setSelected(true);
      };
      this.rendered_ = true;
      var tempSelected = this.selected_;
      this.selected_ = !this.selected_;
      this.setSelected(tempSelected);
    }

  },

  showCursor: function (pos) {
    if (pos) {
      this.cursorXY = pos;
    } else {
      var textLength = this.mirrorRoot.node.getComputedTextLength();
      this.cursorXY.x = this.initialCursorX_ + this.textRootOffset_ + this.offsetX_ + textLength;
      this.cursorXY.y = this.initialCursorY_;
    }
    var x = this.cursorXY.x, y = this.cursorXY.y;
    if (!this.cursor) {
      this.cursor = this.root.line(x, y, x, y + this.size + 1).stroke({ width: 1 });
    } else { // If cursor exists moves it
      this.cursor.move(x, y);
    }
    this.hideCursor(); // resets the interval, for responsiveness
    if (!this.cursorInterval) {
      this.cursor.stroke({opacity: 1});
      this.cursorState = 1;
      var this_ = this;
      this.cursorInterval = setInterval(function () {
        if(this_.cursorState == 0) {
          this_.cursor.stroke({opacity: 1});
          this_.cursorState = 1;
        } else {
          this_.cursor.stroke({opacity: 0});
          this_.cursorState = 0;
        }
      }, 530 ); // Interval in ms for the caret
    }
  },

  hideCursor: function () {
    if (this.cursor) {
      this.cursor.stroke({opacity: 0});
      clearInterval(this.cursorInterval);
      this.cursorInterval = null;
    }
  },

  // TODO: optimizes this for performance, diff text, only recalc the necesary text
  // keydiff is the key where are changed, this is optional but improves performance
  // if keydiff are defined position is not optional
  // -1 is a normal key that adds text
  // 8 and 46 are backspace and supr keys
  getTextMetrics_: function (keydiff, position) {
    var tempMirrorText = this.text, lastWidth = 0;
    // Keeps last value
    this.lastTextWidth_ = this.textWidth_;
    // Calc text metrics
    var textMetrics_, textLength, textLength2, textLength3, dx1, dx2;
    if (keydiff == undefined || this.textMetrics_ == null) { // Calcs metrics of a whole text
      textMetrics_ = [];
      for (var i = 1, len = this.text.length; i <= len; i++) {
        tempMirrorText = this.text.substr(0, i);
        this.mirrorRoot.text(tempMirrorText.replace(/ /g, '\u00a0')); // TODO: make a setText method that functionality
        textLength = this.mirrorRoot.node.getComputedTextLength();
        textMetrics_.push(textLength - lastWidth);
        lastWidth = textLength;
      }
    } else {
      if (position == undefined) {
        throw 'If keydiff are defined position is not optional';
      }
      if (keydiff == -1 && this.text != this.lastText) {
        textMetrics_ = this.textMetrics_;
        tempMirrorText = this.text.substr(0, position - 1);
        this.mirrorRoot.text(tempMirrorText.replace(/ /g, '\u00a0')); // TODO: make a setText method that functionality
        textLength = this.mirrorRoot.node.getComputedTextLength();
        tempMirrorText = this.text.substr(0, position);
        this.mirrorRoot.text(tempMirrorText.replace(/ /g, '\u00a0')); // TODO: make a setText method that functionality
        textLength2 = this.mirrorRoot.node.getComputedTextLength();
        dx1 = textLength2 - textLength;
        tempMirrorText = this.text.substr(0, position + 1);
        this.mirrorRoot.text(tempMirrorText.replace(/ /g, '\u00a0')); // TODO: make a setText method that functionality
        textLength3 = this.mirrorRoot.node.getComputedTextLength();
        dx2 = textLength3 - textLength2;
        textMetrics_ =  textMetrics_.slice(0, position - 1).concat([dx1].concat(textMetrics_.slice(position)));
        if (dx2 != 0) {
          textMetrics_ =  textMetrics_.slice(0, position).concat([dx2].concat(textMetrics_.slice(position)));
        }
        //console.log(textMetrics_.length + ' : ' + this.text.length)
      }
    }
    // Keeps lastWidth
    this.textWidth_ =  this.textRoot.node.getComputedTextLength();
    // Keeps lastText
    this.lastText = this.text;
    // Restores mirrorRoot text
    this.mirrorRoot.text(this.text.replace(/ /g, '\u00a0'));
    if (textMetrics_ != undefined) {
      this.textMetrics_ = textMetrics_;
    }
  },

  onSelect: function() {
    this.foreignTextInput.getChild(0).focus();
    this.background.fill(this.backgroundColor);
    this.mainBackground.fill(this.backgroundColor);
    this.mainBackground.removeClass(this.style.editableTextBackground);
    this.background.opacity(1);
    this.mirrorRoot.opacity(1);
    this.container.removeClass('BBFieldTextInput');
    this.showCursor();
    PolymerGestures.addEventListener(this.root.node, 'track', this.pointerCaretSelectionHandler);
    //PolymerGestures.addEventListener(this.root.node, 'trackstart', this.pointerCaretHandler);
    if (this.parent.attachDraggable) {
      // if is focused not drag the parent
      if (this.parent.container.fixedDrag) {
        this.parent.container.fixedDrag();
      }
      this.parent.attachDraggable = this.parent.attachDraggable.slice(0, this.draggableIndex)
        .concat(this.parent.attachDraggable.slice(this.draggableIndex + 1));
      this.draggableIndex = -1;
    }
  },
  onBlur: function() {
    this.foreignTextInput.getChild(0).blur();
    this.selectionRoot.width(0); // Hides selectionRoot
    this.hideCursor();
    this.mainBackground.addClass(this.style.editableTextBackground);
    this.background.opacity(0);
    this.mirrorRoot.opacity(0);
    this.container.addClass('BBFieldTextInput');
    PolymerGestures.removeEventListener(this.root.node, 'track', this.pointerCaretSelectionHandler);
    // if is not focused drag the parent
    if (this.parent.attachDraggable) {
      this.parent.attachDraggable.push(this.container); // This text can drag all parent
      this.draggableIndex = this.parent.attachDraggable.length - 1;
    }
  },
  onSelectedChange: function() {
    // Updates parent draggable handler
    if (this.parent.attachDraggable) {
      this.parent.updateDraggable();
    }
  },
  onUnRender: function() {
    this.hideCursor();
    this.cursor = null;
  },

  // set the max number of chars in the field
  setMaxChars: function(num){
    if (num != undefined) {
      this.maxChars_ = num;
      this.foreignTextInput.getChild(0).maxLength = num;
    } else {
      throw 'Num is not optional';
    }
  },

  setWidth: function(width){
    if (width != undefined && typeof(width) == 'number') {
      if (width != this.width_) {
        this.width_ = Math.max(width + 2, this.minWidth);
        if (this.rendered_) {
          this.mainBackground.width(this.width_ + this.initialSpaceX_ + this.finalSpaceX_);
          this.background.width(this.width_);
          this.root.width(this.width_);
          this.parent.fieldChanged(this.index);
        }
      }
    } else {
      throw 'Not valid width';
    }
  },

  // get viewbox, override parent class method
  bbox: function(type){
    if (this.rendered_) {
      var bbox = this.root.viewbox();
      bbox.width_ += this.initialSpaceX_ + this.finalSpaceX_;
      bbox.height_ += this.initialSpaceY_ + this.finalSpaceY_;
      return bbox;
    } else {
      throw 'Only rendered fields have a container';
    }
  }

});


text:
Semantic React components
=========================

**WARNING** Alpha, missing components, documentation, tests and functionality

This package makes it easy to use the excellent [Semantic-UI](http://semantic-ui.com) css framework in React. It is __heavily__ borrowed/inspired by [react-semantify](https://github.com/jessy1092/react-semantify), but with some tweaks and additions. Having a meteor package was also a lot more convenient than messing around with browserify.

**Note!** You need to bring your own semantic-ui files, as they are not included.

## Table of Contents

<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
**Table of Contents**  *generated with [DocToc](https://github.com/thlorenz/doctoc)*

- [Installation](#installation)
- [Overview](#overview)
- [Docs](#docs)
  - [Elements](#elements)
    - [Input](#input)
    - [Flag](#flag)
    - [Icon](#icon)
    - [Step](#step)
  - [Collections](#collections)
    - [Form](#form)
    - [Grid / Column](#grid--column)
    - [Table](#table)
    - [Menu](#menu)
  - [Views](#views)
    - [Card](#card)
    - [Item](#item)
    - [Statistic](#statistic)
  - [Modules](#modules)
    - [Accordion](#accordion)
    - [Checkbox](#checkbox)
    - [Radio Input](#radio-input)
    - [Dropdown](#dropdown)
    - [Progress](#progress)
    - [Tab](#tab)

<!-- END doctoc generated TOC please keep comment here to allow auto update -->

## Installation

In a Meteor app directory, enter:

```
$ meteor add hubroedu:semantic-react
```

## Overview

General guidelies for components:

* Components are named after their semantic-ui equivalent. `ui segment` is `<Segment>` and `ui progress` is `<Progress>`. Some modules have exceptions.
* Most variations of components should have a separate prop for that variation, like `size="large"`, `color="blue"` or `disabled={true}`. This makes it easier to programmatically change the compoent. You can place this in the className prop if you want though.
* Modules are initialized by default. On a `<Progress>` component, the jquery initializer `.progress()` will be called.
* If it can be grouped, it has a group component. Example being
```html
<Buttons>
    <Button>Action</Button>
    <Button>Another action</Button>
</Buttons>
```
and
```html
<Cards>
    <Card>...</Card>
    <Card>...</Card>
</Cards>
```

## Docs

The aim of this project is to make the components as intuitive as possible. Most components work the same way, and if they don't, open an issue!

Refer to [Semantic UI docs](http://semantic-ui.com/) for a complete reference to all variations of components.

---
### Elements
---

#### Input

```html
<Input name="username" placeholder="Username here" label="Username" />
<Input id="my-age" name="age" type="number" min="1" max="110" step="1" label="Your age" />
<Input name="about" type="textarea" rows="10" label="About you" />
```
Renders to:
```html
<label for="input_username">Username</label>
<input id="input_username" type="text" name="username" placeholder="Username here" />

<label for="my-age">Your age</label>
<input id="my-age" type="number" name="age" min="1" max="110" step="1" />

<label for="input_about">About you</label>
<textarea id="input_about" name="about" rows="10" />
```

You can add buttons, icons and labels to the input.

```html
<Input name="search" className="left icon action" placeholder="Search term">
  <Icon icon="search" />
  <Button>Search</Button>
</Input>
```

Common props:

* *type*: text/textarea/number (range is a separate component)
* *name*: The built in name property of the input
* *id*: The id property will be added automatically if not specified, generated as "input_" + name
* *label*: Adds a label to the input
* *placeholder*: Placeholder text for text/textarea
* *onChange*: Hooks to the onChange handler, takes a callback function with three arguments:
    * name: The name prop
    * value: New value
    * event: Synthetic event

Textarea props:

* *rows*: Number of rows in a textarea input

Number props:

* *min*
* *max*
* *step*

#### Flag

```html
<Flag flag="no" />
```
Renders to
```html
<i class="flag no"></i>
```

Props:
* *flag*: Language code of flag

#### Icon

```html
<Icon icon="star" />
```
Renders to
```html
<i class="star icon"></i>
```

Props:
* *icon*: Name of the font awesome icon
* *size*: Size variation
* *loading*: Is loading boolean
* *disabled*: Disabled boolean

#### Step

```html
<Steps>
  <Step completed={true}> Step 1 </Step>
  <Step active={true}> Step 2 </Step>
  <Step disabled={true}> Step 3 </Step>
  <Step disabled={true}> Step 4 </Step>
</Steps>
```
Renders to
```html
<div class="ui steps">
  <div class="step completed"  > Step 1 </div>
  <div class="step active"> Step 2 </div>
  <div class="step disabled"> Step 3 </div>
  <div class="step disabled"> Step 4 </div>
</divb>
```

---
### Collections
---

#### Form

This component will additionally make sure that silly submits cause a refresh, so all propagation is stopped. Get access to the submit event by adding a `onSubmit` prop with your handle function.

```html
<Form>
  ...
</Form>
```
Renders to
```html
<form class="ui form">
  ...
</form>
```

#### Grid / Column

```html
<Grid>
  <Column>

  </Column>
  <Column>

  </Column>
</Grid>
```
Renders to
```html
<div class="ui grid">
  <div class="column"></div>
  <div class="column"></div>
</div>
```

#### Table

```html
<Table>
  ...
</Table>
```
Renders to
```html
<table class="ui table">
  ...
</table>
```

#### Menu

```html
<Menu>
  ...
</Menu>
```
Renders to
```html
<div class="ui menu">
  ...
</div>
```

---
### Views
---

#### Card

```html
<Cards>
  <Card>

  </Card>
  <Card>

  </Card>
</Cards>
```
Renders to
```html
<div class="ui cards">
  <div class="card">

  </div>
  <div class="card">

  </div>
</div>
```

#### Item

```html
<Items>
  <Item>

  </Item>
  <Item>

  </Item>
</Items>
```
Renders to
```html
<div class="ui items">
  <div class="item">

  </div>
  <div class="item">

  </div>
</div>
```

#### Statistic

This particular element has a bit of extra functionality.

```html
<Statistic value={3} label="Label" />
```
Renders to
```html
<div class="ui statistic">
  <div class="value">3</div>
  <div class="label">Label</div>
</div>
```

```html
<Statistic value={3} formatter={x => x * 2} label="Label" labelAbove="above" />
```
Renders to
```html
<div class="ui statistic">
  <div class="label">Above</div>
  <div class="value">6</div>
  <div class="label">Label</div>
</div>
```

------
### Modules
---

Modules are initialized by default, which is the same as passing the prop `init={true}`. To avoid initialization, pass `false` instead.

To configure a module, pass the configuration object to `init`.

#### Accordion

```html
<Accordion className="styled fluid">
  <Title>
    Tab 1
  </Title>
  <Content>
    Tab 1 content
  </Content>
  <Title>
    Tab 2
  </Title>
  <Content>
    Tab 2 content
  </Content>
  <Title>
    Tab 3
  </Title>
  <Content>
    Tab 3 content
  </Content>
  <Title>
    Tab 4
  </Title>
  <Content>
    Tab 4 content
  </Content>
</Accordion>
```

or if you have dynamic content

```html
<Accordion>
  {puppies.map(puppy => {
    return [
      <Title key={puppy.name}>
        <Icon icon="paw" className="right floated" />
        <Icon icon="dropdown" />

        {puppy.name}
      </Title>,
      <Content key={puppy.name + "content"}>
        <PuppyDetails puppy={puppy} />
      </Content>
    ];
  })}
</Accordion>
```

#### Checkbox

```html
<Checkbox
  onChange={this.handleChange}
  className="toggle"
  checked={true}
  name="kittens"
  label="Kittens" />
```
Renders to
```html
<div class="ui toggle  checkbox checked" color="null">
  <input type="checkbox" name="kittens" tabindex="0" class="hidden">
  <label>Kittens</label>
</div>
```

#### Radio Input

We have implemented a separate component for this variant of Checkbox.
It constsists of a RadioGroup, with several RadioInput elements.

```html
<RadioGroup name="fruit" defaultValue="banana" onChange={this.fruitHandler}>
  <RadioInput value="banana" label="Banana" />
  <RadioInput value="apple" label="Apple" />
  <RadioInput value="pear" label="Pear" />
</RadioGroup>
```
Renders to
```html
<div class="field">
  <div class="field">
    <div class="ui radio checkbox checked">
      <input type="radio" class="hidden" value="banana" name="fruit" tabindex="0">
      <label data-radio-name="fruit">
        Banana
      </label>
    </div>
  </div>
  <div class="field">
    <div class="ui radio checkbox">
      <input type="radio" class="hidden" value="apple" name="fruit" tabindex="0">
      <label data-radio-name="fruit">
        Apple
      </label>
    </div>
  </div>
  <div class="field">
    <div class="ui radio checkbox">
      <input type="radio" class="hidden" value="pear" name="fruit" tabindex="0">
      <label data-radio-name="fruit">
        Pear
      </label>
    </div>
  </div>

</div>
```

#### Dropdown

```html
<Dropdown
  name="name"
  label="Label"
  onChange={(newValue, name, element) => console.log(newValue)}
  default="Choose category"
  defaultValue="no"
  options={[
    { value: "no", name: "Norwegian"},
    { value: "en": name: "English" }
  ]}
  />
```
Renders to
```html
<div name="language" default="" class="ui link item pointing  dropdown " tabindex="0">
  <input type="hidden" name="language" value="no">
  <i class="dropdown icon"></i>
  <div class="text">
    Norwegian
  </div>
  <div class="menu" tabindex="-1">
    <div class="item active selected" data-value="no">
      Norwegian
    </div>
    <div class="item" data-value="en">
      English
    </div>
  </div>
</div>

```

#### Progress

```html
<Progress
  label="Hello"
  total={100}
  value={50} />
```
Renders to
```html
<div class="ui progress">
  <div class="bar">
    <div class="progress"></div>
  </div>
  <div class="label">Hello</div>
</div>
```

#### Tab

Tabs have been given some extra functionality. It is now divided into three components, Tab, TabContent and TabMenu. The TabMenu contains the Tabs, and handles the clicking and showing of TabContent.

```html
<TabMenu className="secondary pointing tabular top attached">
    <Tab tab="marketplace" active={true}>Marketplace</Tab>
    <Tab tab="caravans">Caravans</Tab>
    <Tab tab="trading">Trading</Tab>
    <Tab tab="connected-markets">Connected markets</Tab>
</TabMenu>

<TabContent tab="marketplace" active={true}>
  .... something
</TabContent>

<TabContent tab="caravans">
  .... something else
</TabContent>
```


text:
#import "MSOneNoteApiOperation.h"
#import "MSOneNoteApiFetchers.h"

/** Implementation for MSOneNoteApiOperationCollectionOperations
 *
 */
@implementation MSOneNoteApiOperationCollectionOperations

@end


text:
'use strict';

angular.module('cyanogenmodDistributionApp')
  .controller('MainCtrl', function ($scope, Statistics) {
    var getData = function(sortByVersion) {
      var downloadsPromise = Statistics.getDownloads(sortByVersion);
      downloadsPromise.then(function(data) {
        $scope.barData = data;
      });
    };

    getData();

    $scope.sort = function(byVersion) {
      getData(byVersion);
    };
  });