text:
package com.azure.resourcemanager.machinelearning.generated;

import com.azure.core.util.BinaryData;
import com.azure.resourcemanager.machinelearning.models.ContainerResourceRequirements;
import com.azure.resourcemanager.machinelearning.models.ContainerResourceSettings;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public final class ContainerResourceRequirementsTests {
    @Test
    public void testDeserialize() {
        ContainerResourceRequirements model =
            BinaryData
                .fromString(
                    "{\"containerResourceLimits\":{\"cpu\":\"wllcolsr\",\"gpu\":\"apte\",\"memory\":\"excgjokjljnhvl\"},\"containerResourceRequests\":{\"cpu\":\"ek\",\"gpu\":\"eksnbksdqhjvyk\",\"memory\":\"eslk\"}}")
                .toObject(ContainerResourceRequirements.class);
        Assertions.assertEquals("wllcolsr", model.containerResourceLimits().cpu());
        Assertions.assertEquals("apte", model.containerResourceLimits().gpu());
        Assertions.assertEquals("excgjokjljnhvl", model.containerResourceLimits().memory());
        Assertions.assertEquals("ek", model.containerResourceRequests().cpu());
        Assertions.assertEquals("eksnbksdqhjvyk", model.containerResourceRequests().gpu());
        Assertions.assertEquals("eslk", model.containerResourceRequests().memory());
    }

    @Test
    public void testSerialize() {
        ContainerResourceRequirements model =
            new ContainerResourceRequirements()
                .withContainerResourceLimits(
                    new ContainerResourceSettings().withCpu("wllcolsr").withGpu("apte").withMemory("excgjokjljnhvl"))
                .withContainerResourceRequests(
                    new ContainerResourceSettings().withCpu("ek").withGpu("eksnbksdqhjvyk").withMemory("eslk"));
        model = BinaryData.fromObject(model).toObject(ContainerResourceRequirements.class);
        Assertions.assertEquals("wllcolsr", model.containerResourceLimits().cpu());
        Assertions.assertEquals("apte", model.containerResourceLimits().gpu());
        Assertions.assertEquals("excgjokjljnhvl", model.containerResourceLimits().memory());
        Assertions.assertEquals("ek", model.containerResourceRequests().cpu());
        Assertions.assertEquals("eksnbksdqhjvyk", model.containerResourceRequests().gpu());
        Assertions.assertEquals("eslk", model.containerResourceRequests().memory());
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
    id="com.github.athieriot.cordova.media.discoverer.plugin"
    version="1.0.0">

    <name>MediaDiscovererPlugin</name>

  <description>
    Media Discoverer Plugin for Steroids.js
  </description>

  <asset src="www/MediaDiscovererPlugin.js" target="javascripts/plugins/MediaDiscovererPlugin.js" />

  <engines>
    <engine name="cordova" version=">=2.7.0" />
  </engines>

  <!-- android -->
  <platform name="android">
    <config-file target="res/xml/config.xml" parent="/*">
      <feature name="MediaDiscoverer">
        <param name="android-package" value="com.github.athieriot.cordova.media.discoverer.plugin.MediaDiscoverer"/>
      </feature>
    </config-file>

    <source-file src="src/android/com/github/athieriot/cordova/media/discoverer/plugin/MediaDiscoverer.java"
      target-dir="src/com/github/athieriot/cordova/plugins" />
  </platform>

  <!-- ios -->
  <platform name="ios">
    <config-file target="config.xml" parent="/*/plugins">
      <plugin name="MediaDiscoverer" value="MediaDiscoverer" onload="true" />
    </config-file>

    <config-file target="config.xml" parent="/widget">
      <feature name="MediaDiscoverer">
        <param name="ios-package" value="MediaDiscoverer"/>
        <param name="onload" value="true" />
      </feature>
    </config-file>

    <header-file src="src/ios/MediaDiscoverer.h" />

    <source-file src="src/ios/MediaDiscoverer.m" />

  </platform>
</plugin>

redpajama_set_name: RedPajamaGithub


text:
import pytest
import mock
import datetime as dt

from . import unbound_server

@pytest.mark.plugin('cluster_filesystem')
@mock.patch('cluster_filesystem.Cluster')
def test_date_parser(cluster, unbound_server):
    from cluster_filesystem.server.dateutils import date_parser
    # pass a string in the format:
    # May  2 09:06
    # assumes it is within 6 months from now
    now = dt.datetime.now()
    now = dt.datetime(
        year=now.year, month=now.month, day=now.day,
        hour=now.hour, minute=now.minute, second=0,
        microsecond=0
    )
    timestamp = dt.datetime.strftime(now, "%b %d %H:%M")
    assert now.isoformat() == date_parser(timestamp)

    # pass a string in the format:
    # May  2 2018
    # assumes it is further tha 6 months from now
    now = dt.datetime.now()
    now = dt.datetime(
        year=now.year, month=now.month, day=now.day,
        hour=0, minute=0, second=0,
        microsecond=0
    )
    now += dt.timedelta(days=200)
    timestamp = dt.datetime.strftime(now, "%b %d %Y")
    assert now.isoformat() == date_parser(timestamp)

    now -= dt.timedelta(days=400)
    timestamp = dt.datetime.strftime(now, "%b %d %Y")
    assert now.isoformat() == date_parser(timestamp)

    # pass any other string
    timestamp = "Some other weird date format"
    assert timestamp == date_parser(timestamp)


text:
package roomdisco

import (
	"fmt"
	"net"
	"os"
	"strconv"
	"time"

	"github.com/bmatsuo/mdns"
	"github.com/bmatsuo/rex/room"
)

// Discoverable is an opaque type that contains an mDNS discovery server.
type Discoverable interface {
	Close() error
	discoveryServer()
}

// NewDiscoverableServer returns a Discoverable using the default ZoneConfig
// for s.
func NewDiscoverableServer(s *room.Server) (Discoverable, error) {
	zc, err := ServerConfig(s)
	if err != nil {
		return nil, fmt.Errorf("invalid server address: %v", err)
	}
	return NewDiscoverable(zc)
}

// NewDiscoverable returns a new Discoverable server that is advertizing the
// Room in zc.
func NewDiscoverable(zc *ZoneConfig) (Discoverable, error) {
	config, err := zc.mdnsConfig(nil)
	if err != nil {
		return nil, fmt.Errorf("invalid discovery configuration: %v", err)
	}
	srv, err := mdns.NewServer(config)
	if err != nil {
		return nil, err
	}
	d := &mdnsDiscoverable{
		zc:  zc,
		srv: srv,
	}
	return d, nil
}

type mdnsDiscoverable struct {
	zc  *ZoneConfig
	srv *mdns.Server
}

var _ Discoverable = &mdnsDiscoverable{}

func (d *mdnsDiscoverable) Close() error {
	defer func() { d.srv = nil }()
	return d.srv.Shutdown()
}

func (d *mdnsDiscoverable) discoveryServer() {
}

// ZoneConfig configures mDNS for a Room.
type ZoneConfig struct {
	Room *room.Room
	Port int
	IPs  []net.IP
	TXT  []string
}

// NewZoneConfig returns a new ZoneConfig for r.
func NewZoneConfig(r *room.Room) *ZoneConfig {
	return &ZoneConfig{
		Room: r,
	}
}

// ServerConfig returns a ZoneConfig with address information derived from s.
func ServerConfig(s *room.Server) (*ZoneConfig, error) {
	zc := NewZoneConfig(s.Room())
	err := zc.initAddr(s.Addr())
	if err != nil {
		return nil, err
	}
	return zc, nil
}

func (zc *ZoneConfig) initAddr(addr string) error {
	if addr == "" {
		return fmt.Errorf("server not bound to a port")
	}
	host, _port, err := net.SplitHostPort(addr)
	if err != nil {
		return err
	}
	if host != "" && host != "::" {
		ip := net.ParseIP(host)
		if ip == nil {
			return fmt.Errorf("invalid host ip: %v", err)
		}
		zc.IPs = append(zc.IPs, ip)
	}
	zc.Port, err = strconv.Atoi(_port)
	if err != nil {
		return fmt.Errorf("invalid port: %v", err)
	}
	return nil
}

// Instance returns the mdns instance identifier corresponding to zc.Room.Name.
func (zc *ZoneConfig) Instance() string {
	now := time.Now().Format("20060102150405")
	return fmt.Sprintf("%s_%d_%s", now, os.Getpid(), zc.Room.Name)
}

func (zc *ZoneConfig) mdnsService() (*mdns.MDNSService, error) {
	return mdns.NewMDNSService(
		zc.Instance(),
		zc.Room.Service,
		"",
		"",
		zc.Port,
		zc.IPs,
		zc.TXT,
	)
}

func (zc *ZoneConfig) mdnsConfig(iface *net.Interface) (*mdns.Config, error) {
	zone, err := zc.mdnsService()
	if err != nil {
		return nil, err
	}
	config := &mdns.Config{
		Zone:  zone,
		Iface: iface,
	}
	return config, nil
}


text:
package org.springframework.security.oauth2.client.web;

import java.util.Map;

import jakarta.servlet.http.HttpSession;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClient;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.TestClientRegistrations;
import org.springframework.security.oauth2.core.OAuth2AccessToken;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.mockito.Mockito.mock;

/**
 * Tests for {@link HttpSessionOAuth2AuthorizedClientRepository}.
 *
 * @author Joe Grandja
 */
public class HttpSessionOAuth2AuthorizedClientRepositoryTests {

	private String principalName1 = "principalName-1";

	private ClientRegistration registration1 = TestClientRegistrations.clientRegistration().build();

	private ClientRegistration registration2 = TestClientRegistrations.clientRegistration2().build();

	private String registrationId1 = this.registration1.getRegistrationId();

	private String registrationId2 = this.registration2.getRegistrationId();

	private HttpSessionOAuth2AuthorizedClientRepository authorizedClientRepository = new HttpSessionOAuth2AuthorizedClientRepository();

	private MockHttpServletRequest request;

	private MockHttpServletResponse response;

	@BeforeEach
	public void setup() {
		this.request = new MockHttpServletRequest();
		this.response = new MockHttpServletResponse();
	}

	@Test
	public void loadAuthorizedClientWhenClientRegistrationIdIsNullThenThrowIllegalArgumentException() {
		assertThatIllegalArgumentException()
				.isThrownBy(() -> this.authorizedClientRepository.loadAuthorizedClient(null, null, this.request));
	}

	@Test
	public void loadAuthorizedClientWhenPrincipalNameIsNullThenExceptionNotThrown() {
		this.authorizedClientRepository.loadAuthorizedClient(this.registrationId1, null, this.request);
	}

	@Test
	public void loadAuthorizedClientWhenRequestIsNullThenThrowIllegalArgumentException() {
		assertThatIllegalArgumentException().isThrownBy(
				() -> this.authorizedClientRepository.loadAuthorizedClient(this.registrationId1, null, null));
	}

	@Test
	public void loadAuthorizedClientWhenClientRegistrationNotFoundThenReturnNull() {
		OAuth2AuthorizedClient authorizedClient = this.authorizedClientRepository
				.loadAuthorizedClient("registration-not-found", null, this.request);
		assertThat(authorizedClient).isNull();
	}

	@Test
	public void loadAuthorizedClientWhenSavedThenReturnAuthorizedClient() {
		OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration1, this.principalName1,
				mock(OAuth2AccessToken.class));
		this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, null, this.request, this.response);
		OAuth2AuthorizedClient loadedAuthorizedClient = this.authorizedClientRepository
				.loadAuthorizedClient(this.registrationId1, null, this.request);
		assertThat(loadedAuthorizedClient).isEqualTo(authorizedClient);
	}

	@Test
	public void saveAuthorizedClientWhenAuthorizedClientIsNullThenThrowIllegalArgumentException() {
		assertThatIllegalArgumentException().isThrownBy(
				() -> this.authorizedClientRepository.saveAuthorizedClient(null, null, this.request, this.response));
	}

	@Test
	public void saveAuthorizedClientWhenAuthenticationIsNullThenExceptionNotThrown() {
		OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration2, this.principalName1,
				mock(OAuth2AccessToken.class));
		this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, null, this.request, this.response);
	}

	@Test
	public void saveAuthorizedClientWhenRequestIsNullThenThrowIllegalArgumentException() {
		OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration2, this.principalName1,
				mock(OAuth2AccessToken.class));
		assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientRepository
				.saveAuthorizedClient(authorizedClient, null, null, this.response));
	}

	@Test
	public void saveAuthorizedClientWhenResponseIsNullThenThrowIllegalArgumentException() {
		OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration2, this.principalName1,
				mock(OAuth2AccessToken.class));
		assertThatIllegalArgumentException().isThrownBy(
				() -> this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, null, this.request, null));
	}

	@Test
	public void saveAuthorizedClientWhenSavedThenSavedToSession() {
		OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration2, this.principalName1,
				mock(OAuth2AccessToken.class));
		this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, null, this.request, this.response);
		HttpSession session = this.request.getSession(false);
		assertThat(session).isNotNull();
		@SuppressWarnings("unchecked")
		Map<String, OAuth2AuthorizedClient> authorizedClients = (Map<String, OAuth2AuthorizedClient>) session
				.getAttribute(HttpSessionOAuth2AuthorizedClientRepository.class.getName() + ".AUTHORIZED_CLIENTS");
		assertThat(authorizedClients).isNotEmpty();
		assertThat(authorizedClients).hasSize(1);
		assertThat(authorizedClients.values().iterator().next()).isSameAs(authorizedClient);
	}

	@Test
	public void removeAuthorizedClientWhenClientRegistrationIdIsNullThenThrowIllegalArgumentException() {
		assertThatIllegalArgumentException().isThrownBy(
				() -> this.authorizedClientRepository.removeAuthorizedClient(null, null, this.request, this.response));
	}

	@Test
	public void removeAuthorizedClientWhenPrincipalNameIsNullThenExceptionNotThrown() {
		this.authorizedClientRepository.removeAuthorizedClient(this.registrationId1, null, this.request, this.response);
	}

	@Test
	public void removeAuthorizedClientWhenRequestIsNullThenThrowIllegalArgumentException() {
		assertThatIllegalArgumentException().isThrownBy(() -> this.authorizedClientRepository
				.removeAuthorizedClient(this.registrationId1, null, null, this.response));
	}

	@Test
	public void removeAuthorizedClientWhenResponseIsNullThenExceptionNotThrown() {
		this.authorizedClientRepository.removeAuthorizedClient(this.registrationId1, null, this.request, null);
	}

	@Test
	public void removeAuthorizedClientWhenNotSavedThenSessionNotCreated() {
		this.authorizedClientRepository.removeAuthorizedClient(this.registrationId2, null, this.request, this.response);
		assertThat(this.request.getSession(false)).isNull();
	}

	@Test
	public void removeAuthorizedClientWhenClient1SavedAndClient2RemovedThenClient1NotRemoved() {
		OAuth2AuthorizedClient authorizedClient1 = new OAuth2AuthorizedClient(this.registration1, this.principalName1,
				mock(OAuth2AccessToken.class));
		this.authorizedClientRepository.saveAuthorizedClient(authorizedClient1, null, this.request, this.response);
		// Remove registrationId2 (never added so is not removed either)
		this.authorizedClientRepository.removeAuthorizedClient(this.registrationId2, null, this.request, this.response);
		OAuth2AuthorizedClient loadedAuthorizedClient1 = this.authorizedClientRepository
				.loadAuthorizedClient(this.registrationId1, null, this.request);
		assertThat(loadedAuthorizedClient1).isNotNull();
		assertThat(loadedAuthorizedClient1).isSameAs(authorizedClient1);
	}

	@Test
	public void removeAuthorizedClientWhenSavedThenRemoved() {
		OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration2, this.principalName1,
				mock(OAuth2AccessToken.class));
		this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, null, this.request, this.response);
		OAuth2AuthorizedClient loadedAuthorizedClient = this.authorizedClientRepository
				.loadAuthorizedClient(this.registrationId2, null, this.request);
		assertThat(loadedAuthorizedClient).isSameAs(authorizedClient);
		this.authorizedClientRepository.removeAuthorizedClient(this.registrationId2, null, this.request, this.response);
		loadedAuthorizedClient = this.authorizedClientRepository.loadAuthorizedClient(this.registrationId2, null,
				this.request);
		assertThat(loadedAuthorizedClient).isNull();
	}

	@Test
	public void removeAuthorizedClientWhenSavedThenRemovedFromSession() {
		OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration1, this.principalName1,
				mock(OAuth2AccessToken.class));
		this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, null, this.request, this.response);
		OAuth2AuthorizedClient loadedAuthorizedClient = this.authorizedClientRepository
				.loadAuthorizedClient(this.registrationId1, null, this.request);
		assertThat(loadedAuthorizedClient).isSameAs(authorizedClient);
		this.authorizedClientRepository.removeAuthorizedClient(this.registrationId1, null, this.request, this.response);
		HttpSession session = this.request.getSession(false);
		assertThat(session).isNotNull();
		assertThat(session
				.getAttribute(HttpSessionOAuth2AuthorizedClientRepository.class.getName() + ".AUTHORIZED_CLIENTS"))
						.isNull();
	}

	@Test
	public void removeAuthorizedClientWhenClient1Client2SavedAndClient1RemovedThenClient2NotRemoved() {
		OAuth2AuthorizedClient authorizedClient1 = new OAuth2AuthorizedClient(this.registration1, this.principalName1,
				mock(OAuth2AccessToken.class));
		this.authorizedClientRepository.saveAuthorizedClient(authorizedClient1, null, this.request, this.response);
		OAuth2AuthorizedClient authorizedClient2 = new OAuth2AuthorizedClient(this.registration2, this.principalName1,
				mock(OAuth2AccessToken.class));
		this.authorizedClientRepository.saveAuthorizedClient(authorizedClient2, null, this.request, this.response);
		this.authorizedClientRepository.removeAuthorizedClient(this.registrationId1, null, this.request, this.response);
		OAuth2AuthorizedClient loadedAuthorizedClient2 = this.authorizedClientRepository
				.loadAuthorizedClient(this.registrationId2, null, this.request);
		assertThat(loadedAuthorizedClient2).isNotNull();
		assertThat(loadedAuthorizedClient2).isSameAs(authorizedClient2);
	}

}


text:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class AuthorityRelationship extends Model
{
    protected $table = 'authority_relationships';
    public $timestamps = false;
    protected $fillable = array(
            'authority_id',
            'related_authority_id',
            'name',
            'type',
        );
}


text:
using System;
using System.Buffers;
using SuperSocket.ProtoBase;

namespace SwitchPipelineFilter
{
    public class SwitchPipelineFilter : PipelineFilterBase<TextPackageInfo>
    {
        private IPipelineFilter<TextPackageInfo> _filterA;
        private byte _beginMarkA = (byte)'Y';

        private IPipelineFilter<TextPackageInfo> _filterB;
        private byte _beginMarkB = (byte)'*';

        public SwitchPipelineFilter()
        {
            _filterA = new PipelineFilterA(this);
            _filterB = new PipelineFilterB(this);
        }

        public override TextPackageInfo Filter(ref SequenceReader<byte> reader)
        {
            if (!reader.TryRead(out byte flag))
                throw new ProtocolException("Flag byte cannot be read.");

            if (flag == _beginMarkA)
                NextFilter = _filterA;
            else if (flag == _beginMarkB)
                NextFilter = _filterB;
            else
                throw new ProtocolException($"Unknown flag at the first postion: {flag}.");

            reader.Rewind(1);
            return null;
        }
    }
}


text:
require File.dirname(__FILE__) + '/../../../spec_helper'
require 'rexml/document'

describe "REXML::Text#node_type" do
  it "returns :text" do
    REXML::Text.new("test").node_type.should == :text
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>StageGestureDetector</title>
<meta name="date" content="2015-01-10">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.haw.projecthorse.level.util.swipehandler

Class StageGestureDetector

java.lang.Object

com.badlogic.gdx.InputAdapter

com.badlogic.gdx.input.GestureDetector

com.haw.projecthorse.level.util.swipehandler.StageGestureDetector

All Implemented Interfaces:

com.badlogic.gdx.InputProcessor

public class StageGestureDetector
extends com.badlogic.gdx.input.GestureDetector

Klasse, um Gesten auf einer Stage zu erkennen.

Version:

1.0

Author:

Oliver

Nested Class Summary

Nested classes/interfaces inherited from class com.badlogic.gdx.input.GestureDetector

com.badlogic.gdx.input.GestureDetector.GestureAdapter, com.badlogic.gdx.input.GestureDetector.GestureListener

Constructor Summary

Constructors

Constructor and Description

StageGestureDetector(com.badlogic.gdx.scenes.scene2d.Stage stage,
                    boolean fullScreen)

Konstruktor.

StageGestureDetector(com.badlogic.gdx.scenes.scene2d.Stage stage,
                    boolean fullScreen,
                    ControlMode controlMode)

Konstruktor.

Method Summary

Methods

Modifier and Type
Method and Description

boolean
keyDown(int keycode)

boolean
keyTyped(char character)

boolean
keyUp(int keycode)

boolean
mouseMoved(int screenX,
          int screenY)

boolean
scrolled(int amount)

boolean
touchDown(int screenX,
         int screenY,
         int pointer,
         int button)

boolean
touchDragged(int screenX,
            int screenY,
            int pointer)

boolean
touchUp(int screenX,
       int screenY,
       int pointer,
       int button)

Methods inherited from class com.badlogic.gdx.input.GestureDetector

cancel, invalidateTapSquare, isLongPressed, isLongPressed, isPanning, reset, setLongPressSeconds, setMaxFlingDelay, setTapCountInterval, setTapSquareSize, touchDown, touchDragged, touchUp

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

StageGestureDetector

public StageGestureDetector(com.badlogic.gdx.scenes.scene2d.Stage stage,
                    boolean fullScreen)

Konstruktor.

Parameters:

stage - Stage für den Detector

fullScreen - Gibt an, ob auf der gesamten Stage gehört werden soll oder
            jeder Actor für sich

StageGestureDetector

public StageGestureDetector(com.badlogic.gdx.scenes.scene2d.Stage stage,
                    boolean fullScreen,
                    ControlMode controlMode)

Konstruktor.

Parameters:

stage - Stage für den Detector

fullScreen - Gibt an, ob auf der gesamten Stage gehört werden soll oder
            jeder Actor für sich

controlMode - der ControlMode

Method Detail

keyDown

public boolean keyDown(int keycode)

Specified by:

keyDown in interface com.badlogic.gdx.InputProcessor

Overrides:

keyDown in class com.badlogic.gdx.InputAdapter

keyUp

public boolean keyUp(int keycode)

Specified by:

keyUp in interface com.badlogic.gdx.InputProcessor

Overrides:

keyUp in class com.badlogic.gdx.InputAdapter

keyTyped

public boolean keyTyped(char character)

Specified by:

keyTyped in interface com.badlogic.gdx.InputProcessor

Overrides:

keyTyped in class com.badlogic.gdx.InputAdapter

touchDown

public boolean touchDown(int screenX,
                int screenY,
                int pointer,
                int button)

Specified by:

touchDown in interface com.badlogic.gdx.InputProcessor

Overrides:

touchDown in class com.badlogic.gdx.input.GestureDetector

touchUp

public boolean touchUp(int screenX,
              int screenY,
              int pointer,
              int button)

Specified by:

touchUp in interface com.badlogic.gdx.InputProcessor

Overrides:

touchUp in class com.badlogic.gdx.input.GestureDetector

touchDragged

public boolean touchDragged(int screenX,
                   int screenY,
                   int pointer)

Specified by:

touchDragged in interface com.badlogic.gdx.InputProcessor

Overrides:

touchDragged in class com.badlogic.gdx.input.GestureDetector

mouseMoved

public boolean mouseMoved(int screenX,
                 int screenY)

Specified by:

mouseMoved in interface com.badlogic.gdx.InputProcessor

Overrides:

mouseMoved in class com.badlogic.gdx.InputAdapter

scrolled

public boolean scrolled(int amount)

Specified by:

scrolled in interface com.badlogic.gdx.InputProcessor

Overrides:

scrolled in class com.badlogic.gdx.InputAdapter

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
Simple wrappers for ZFS command line tools.

[![GoDoc](https://godoc.org/github.com/mistifyio/go-zfs?status.svg)](https://godoc.org/github.com/mistifyio/go-zfs)

## Requirements ##

You need a working ZFS setup.  To use on Ubuntu 14.04, setup ZFS:

    sudo apt-get install python-software-properties
    sudo apt-add-repository ppa:zfs-native/stable
    sudo apt-get update
    sudo apt-get install ubuntu-zfs libzfs-dev

Developed using Go 1.3, but currently there isn't anything 1.3 specific. Don't use Ubuntu packages for Go, use http://golang.org/doc/install

Generally you need root privileges to use anything zfs related.

## Status ##

This has been only been tested on Ubuntu 14.04

In the future, we hope to work directly with libzfs.

# Hacking #

The tests have decent examples for most functions.

```go
//assuming a zpool named test
//error handling omitted

f, err := zfs.CreateFilesystem("test/snapshot-test", nil)
ok(t, err)

s, err := f.Snapshot("test", nil)
ok(t, err)

// snapshot is named "test/snapshot-test@test"

c, err := s.Clone("test/clone-test", nil)

err := c.Destroy()
err := s.Destroy()
err := f.Destroy()

```

# Contributing #

See the [contributing guidelines](./CONTRIBUTING.md)


text:
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
#

import cocos
from cocos.director import director
from cocos.sprite import Sprite
from cocos import draw
import pyglet

import random
ri = random.randint

class TestFigure(draw.Canvas):
    def render(self):
        x,y = director.get_window_size()

        for i in range(100):
            start = ri(0,640), ri(0,480)
            end = ri(0,640), ri(0,480)
            color = ri(00,255),ri(00,255),ri(00,255),ri(00,255)
            width = ri(1,20)
            if (random.random() < 0.3) :
                self.set_color( color )
                self.set_stroke_width( width )
                self.move_to( start )
            self.line_to( end  )

class TestLayer(cocos.layer.Layer):
    def __init__(self):
        super( TestLayer, self ).__init__()

        self.add( TestFigure() )
        self.schedule( lambda x: 0 )

if __name__ == "__main__":
    director.init()
    test_layer = TestLayer ()
    main_scene = cocos.scene.Scene (test_layer)
    director.run (main_scene)


text:
var App = function(){

  //resize map container based on window size
  var height = $(window).height() - 200;
  var width = $(window).width();
  $('#map').css('height', height+'px');
  $('#congress-seal').css('margin-left', (width / 2) - 25 + 'px');

  //global loader across top of page
  $( document ).ajaxStart(function() {
    NProgress.start();
  });

  $( document ).ajaxStop(function() {
    NProgress.done();
  });

  this._mapStyle = "default";

  //right off the bat kick off calls to Sunlight for data
  this._getAllCommittees();
  this._getAllLegNames();

  //init map
  this.initMap();

};

/*
* Setup map
* Custom basemap
* FeatureLayers with U.S. congressional districts
*/
App.prototype.initMap = function() {
  var self = this;

  require(["esri/map", "esri/layers/ArcGISTiledMapServiceLayer",
    "esri/layers/FeatureLayer"],
    function(Map, ArcGISTiledMapServiceLayer, FeatureLayer) {

    //custom basemap
    esriConfig.defaults.map.basemaps.dotted = {
      baseMapLayers: [
        { url: "http://studio.esri.com/arcgis/rest/services/World/WorldBasemapBlack/MapServer" }
      ],
      title: "Dots"
    };

    self.map = new Map("map", {
      center: [-92.049, 41.485],
      zoom: 4,
      basemap: "dotted",
      smartNavigation: false
    });
      self.map.on('load', function(){
      self.map.disableScrollWheelZoom();
    });

    self.placeNames = new FeatureLayer("http://studio.esri.com/arcgis/rest/services/World/WorldLabelsWhite/MapServer/2", {
      mode: esri.layers.FeatureLayer.MODE_SNAPSHOT,
      outFields: ["CITY_NAME"]
    });

    self.featureLayerGen = new FeatureLayer("http://services1.arcgis.com/o90r8yeUBWgKSezU/ArcGIS/rest/services/Congressional_Districts_outlines/FeatureServer/0",{
      outFields: ["*"]
    });

    self.featureLayer = new FeatureLayer("http://services1.arcgis.com/o90r8yeUBWgKSezU/arcgis/rest/services/Congressional_Districts_outlines/FeatureServer/1",{
      mode: esri.layers.FeatureLayer.MODE_SNAPSHOT,
      outFields: ["*"]
    });

    self.states = new FeatureLayer("http://services.arcgis.com/P3ePLMYs2RVChkJx/ArcGIS/rest/services/USA_States_Generalized/FeatureServer/0", {
      mode: esri.layers.FeatureLayer.MODE_SNAPSHOT,
      outFields: ["STATE_ABBR"],
      opacity:0
    })

    self.map.addLayer(self.states);
    self.map.addLayer(self.featureLayerGen);
    self.map.addLayer(self.featureLayer);
    self.map.addLayer(self.placeNames);

    self.featureLayerGen.on('update-end', function(obj) {
      var style = self._getMapStyle();

      if ( style === "default" ) {
        self._defaultStyle();
      } else {
        self._styleByCommitteeCount();
      }

    });

    self.featureLayer.on('update-end', function(obj) {
      var style = self._getMapStyle();

      if ( style === "default" ) {
        self._defaultStyle();
      } else {
        self._styleByCommitteeCount();
      }
    });

    self._wire();

  });

}

App.prototype._getLocation = function() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(this._showPosition);
  }
}

App.prototype._showPosition = function(position) {
  app._getLegByLatLong( position.coords );
}

/*
* Wire events within map
* Setup search and typeahead
*/
App.prototype._wire = function() {
  var self = this;

  //bind map resize
  $(window).on('resize', function() {
    self.map.resize();

    var height = $(window).height() - 200;
    var width = $(window).width();

    $('#map').css('height', height+'px');
    $('#congress-seal').css('margin-left', (width / 2) - 25 + 'px');

  });

  //location
  $('#location-btn').on('click', function(e) {
    $(this).toggleClass('btn-primary');
    if ( $(this).hasClass('btn-primary') ) {
      self._getLocation();
    }
  });

  //map events
  this.map.on('click', function(e) {
    self._getLegByLatLong(e);
  });

  self.featureLayer.on('mouse-over', function(e) {
    self._featureSelected( e.graphic, 'mouse-over' );
    self._showHoverWindow(e);
  });

  self.featureLayer.on('mouse-out', function(e) {
    self._removeSelectedFeature( 'mouse-over' );
    $('#hoverinfo').hide();
  });

  //layer EVENTS
  self.featureLayer.on('click', function(e) {
    self._featureSelected( e.graphic, 'click' );
  });

  //typeahead search
  $('#search-reps').on('typeahead:selected', function(e,data) {
    self._getLegByName(data.value);
  });

  //zipcode search
  $('#search-reps').on('keydown', function(e) {
    if ( e.keyCode === 13 ) {
      self._getLegByZipcode($(this).val());
    }
  });

  //bind legislator name click for GET committees
  $('.legislator').on('click', function(e) {
    var name = $(this).find('.media-heading').html();

    $('.legislator-inner').removeClass('selected');
    $(this).find('.legislator-inner').addClass('selected');

    self._showMemberDetails(name);
    self._showCommittees(name.split('.')[1]);
  });

  //LEGEND
  $('#style-by-count').on('change', function() {
    var checked = $(this).is(':checked');
    if ( checked ) {

      self._mapStyle = "byCommitteeSize";
      self._styleByCommitteeCount();
      $('#by-count-container').show();

    } else {

      self._mapStyle = "default"
      self._defaultStyle();
      $('#by-count-container').hide();

    }
  });

}

/* returns how map is currently styled */
App.prototype._getMapStyle = function() {
  return this._mapStyle;
}

/*
* Set Map Extent
*
*/
App.prototype._setMapExtent = function() {
  var extent = this.selectedGraphic.geometry.getExtent();
  this.map.setExtent(extent.expand(5));
}

/*
* On polygon click, show as SELECTED on map
*
*/
App.prototype._featureSelected = function(graphicJson, type) {

  if (!graphicJson) return;

  //remove previously selected graphic
  this._removeSelectedFeature(type);

  //set selected graphic on the app
  if ( type === "click" ) {
    this._removeSelectedState();
    this.selectedGraphic = graphicJson;
    this._setMapExtent();
  }

  //add selected graphic
  var id = ( type === "mouse-over" ) ? "hoverGraphic" : "selectedGraphic";

  var graphic = {};
  graphic.geometry = graphicJson.geometry;
  graphic.symbol = {};
  graphic.attributes = { id: id }

  graphic.symbol = {
    "color":[255,255,255,64],"outline":{"color":[255,255,255,255],
    "width":0.8,"type":"esriSLS","style":"esriSLSSolid"},
    "type":"esriSFS","style":"esriSFSSolid"
  };

  var g = new esri.Graphic( graphic );

  //add to map
  this.map.graphics.add( g );
}

/*
* Pass a district (#) AND state to select on map
*
*
*/
App.prototype._selectDistrict = function(district, state) {
  var self = this;
  var g;
  $.each(this.featureLayer.graphics, function(i, graphic) {
    if ( parseInt(graphic.attributes.CD113FIPS) === district && graphic.attributes.STATE_ABBR === state ) {
      g = graphic;
    }
  });
  this._featureSelected(g, 'click');
}

/*
*
*
*
*/
App.prototype._selectState = function(state) {
  var self = this;

  $.each(this.states.graphics, function(i, s) {
    if ( s.attributes.STATE_ABBR === state ) {

      self._removeSelectedFeature('mouse-over');
      self._removeSelectedFeature();
      self._removeSelectedState();
      self.selectedGraphic = s;
      self._setMapExtent();

      var graphic = {};
      graphic.geometry = s.geometry;
      graphic.symbol = {};
      graphic.attributes = { id: "stateSelected" }

      graphic.symbol = {
        "color":[255,255,255,64],"outline":{"color":[255,255,255,255],
        "width":0.8,"type":"esriSLS","style":"esriSLSSolid"},
        "type":"esriSFS","style":"esriSFSSolid"
      };

      var g = new esri.Graphic( graphic );

      //add to map
      self.map.graphics.add( g );
    }
  });

}

/*
* Remove selected polygon
*
*/
App.prototype._removeSelectedFeature = function(type) {
  var self = this;

  //do not remove selected state polygon on hover events!
  if ( type === "mouse-over" ) {
    $.each(this.map.graphics.graphics, function(index,gra){
      if (gra) {
        if(gra.attributes && gra.attributes.id === "hoverGraphic"){
          self.map.graphics.remove( gra );
        }
      }
    });
  } else {
    $.each(this.map.graphics.graphics, function(index,gra){
      if (gra) {
        if(gra.attributes && gra.attributes.id === "selectedGraphic"){
          self.map.graphics.remove( gra );
        }
      }
    });
  }

}

App.prototype._removeSelectedState = function() {
  var self = this;

  $.each(this.map.graphics.graphics, function(index,gra){
    if (gra) {
      if(gra.attributes && gra.attributes.id === "stateSelected"){
        self.map.graphics.remove( gra );
      }
    }
  });

}

/*
* Populate infowindow with attributes from FeatureLayer
*
*/
App.prototype._showHoverWindow = function(e) {
  var self = this;
  $('#hoverinfo').show().css({left:e.clientX+10+'px', top:e.clientY+10+'px'});

  var html = '
['+e.graphic.attributes.PARTY.charAt(0)+'] '+e.graphic.attributes.NAME+'
\

State: '+e.graphic.attributes.STATE_ABBR+'
\

District: '+e.graphic.attributes.CD113FIPS+'
'

  $('#hoverinfo').html( html );
}

/*
* Get ALL member names, store as app.legislators for search typeahead
* Get ALL legislators, store as app.allLegislators for feature use
*
*/
App.prototype._getAllLegNames = function() {
  var self = this;
  var url = "https://congress.api.sunlightfoundation.com/legislators?per_page=all&apikey=88036ea903bf4dffbbdc4a9fa7acb2ad";

  //store on app
  this.legislators = [];
  this.allLegislators = [];

  //sunlight api lookup
  $.getJSON(url, function(data) {
    //console.log(data);
    //save array of all leg for later use
    self.allLegislators = data.results;

    //save just names for 'typeahead'
    $.each(data.results, function(i, rep) {
      self.legislators.push(rep.first_name + ' ' + rep.last_name);
    });

    //wire typeahead with new legislators array
    $('#search-reps').typeahead({
      name: "reps",
      local: self.legislators
    });

  });

}

/*
* Get ALL committees
*
*/
App.prototype._getAllCommittees = function() {
  var self = this;
  var url = "https://congress.api.sunlightfoundation.com/committees?per_page=all&fields=members,name&apikey=88036ea903bf4dffbbdc4a9fa7acb2ad";
  $.getJSON(url, function(data) {
    self.allCommittees = data;
  });
}

/*
* To style map based on number of committees rep is a member of, calculate this
*
*/
App.prototype._buildStyler = function() {
  var self = this;

  if ( this.allLegislators.length <= 0 || this.allCommittees === undefined || this.memberCommitteeCount !== undefined ) return;

  this.memberCommitteeCount = {};
  $.each(self.legislators, function(i, name) {
    self.memberCommitteeCount[ name ] = 0;
  });

  $.each(self.allCommittees.results, function(i, comm) {
    for (var mem in comm.members ) {

      var n = comm.members[ mem ].legislator.first_name + ' ' + comm.members[ mem ].legislator.last_name;
      self.memberCommitteeCount[ n ]++;

    }
  });

  if ( !self._mapStyled === "default" ) this._defaultStyle();

}

/*
* Default style for map | Blue and Red
*
*
*/
App.prototype._defaultStyle = function() {
  var self = this;

  require(["esri/renderers/SimpleRenderer", "esri/layers/LabelLayer", "esri/symbols/TextSymbol",
    "esri/renderers/ClassBreaksRenderer", "esri/symbols/SimpleFillSymbol",
    "dojo/_base/Color", "dojo/dom-style", "esri/renderers/UniqueValueRenderer", "esri/symbols/SimpleLineSymbol"],
    function(SimpleRenderer, LabelLayer, TextSymbol, ClassBreaksRenderer, SimpleFillSymbol, Color, domStyle, UniqueValueRenderer, SimpleLineSymbol) {

    var defaultSymbol = new SimpleFillSymbol();
        defaultSymbol.outline.setStyle(SimpleLineSymbol.STYLE_DASH, new Color([255,255,255,255]), 3);

      var renderer = new UniqueValueRenderer(defaultSymbol, "PARTY");
      renderer.addValue("Democrat", new SimpleFillSymbol().setColor(new Color([49,130,189, 0.7])));
      renderer.addValue("Republican", new SimpleFillSymbol().setColor(new Color([222,45,38, 0.7])));
      renderer.addValue("Vacant", new SimpleFillSymbol().setColor(new Color([222,45,38, 0.7])));

      var json = renderer.toJson();
      $.each(json.uniqueValueInfos, function(i,sys) {
        sys.symbol.outline = {
          color: [225,225,225,255],
          style:"esriSLSSolid",
          width:0.3,
          type:"esriSLS"
        }
      });

      var rend = new UniqueValueRenderer(json);

      self.featureLayerGen.setRenderer( rend );
      self.featureLayerGen.redraw();

      self.featureLayer.setRenderer( rend );
      self.featureLayer.redraw();

      //TEXT
      var labelField = "CITY_NAME";

      // create a renderer for the states layer to override default symbology
      var namesColor = new Color("#FFF");

      // create a text symbol to define the style of labels
      var namesLabel = new TextSymbol().setColor( namesColor );
      namesLabel.font.setSize( "10pt" );
      namesLabel.font.setFamily( "arial" );
      namesLabel.x = 10;
      namesLabelRenderer = new SimpleRenderer( namesLabel );
      var labels = new LabelLayer( { id: "labels" } );

      labels.addFeatureLayer(self.placeNames, namesLabelRenderer, "${" + labelField + "}");

      // add the label layer to the map
      self.map.addLayer(labels);
  });

}

/*
* Classbreaks styling of main feature layer
* INSANE
*
*/
App.prototype._styleByCommitteeCount = function() {
  var self = this;

  this._buildStyler();

  if ( !this.memberCommitteeCount || this.featureLayer.graphics.length <= 5 ) return;

  require(["esri/renderers/SimpleRenderer",
    "esri/renderers/ClassBreaksRenderer", "esri/symbols/SimpleFillSymbol",
    "dojo/_base/Color", "dojo/dom-style", "esri/renderers/UniqueValueRenderer", "esri/symbols/SimpleLineSymbol"],
    function(SimpleRenderer, ClassBreaksRenderer, SimpleFillSymbol, Color, domStyle, UniqueValueRenderer, SimpleLineSymbol) {

    //console.log('grpahics', app.featureLayer.graphics.length);
    var layers = [self.featureLayer, self.featureLayerGen];

    $.each(layers, function(i,layer) {
      $.each(layer.graphics, function(i, graphic) {
        if ( graphic.attributes.PARTY === "Republican" ) {

          var name = graphic.attributes.NAME.split(' ')[0] + ' ' +graphic.attributes.LAST_NAME;

          if ( self.memberCommitteeCount[ name ] <= 1 ) {
            graphic.attributes[ "schema" ] = "r0";
          } else if ( self.memberCommitteeCount[ name ] > 1 && self.memberCommitteeCount[ name ] < 5 ) {
            graphic.attributes[ "schema" ] = "r1";
          } else if ( self.memberCommitteeCount[ name ] >= 5 && self.memberCommitteeCount[ name ] < 9 ) {
            graphic.attributes[ "schema" ] = "r2";
          } else {
            graphic.attributes[ "schema" ] = "r3";
          }

        } else {

          var name = graphic.attributes.NAME.split(' ')[0] + ' ' +graphic.attributes.LAST_NAME;

          if ( self.memberCommitteeCount[ name ] <= 1 ) {
            graphic.attributes[ "schema" ] = "d0";
          } else if ( self.memberCommitteeCount[ name ] > 1 && self.memberCommitteeCount[ name ] < 5 ) {
            graphic.attributes[ "schema" ] = "d1";
          } else if ( self.memberCommitteeCount[ name ] >= 5 && self.memberCommitteeCount[ name ] < 9 ) {
            graphic.attributes[ "schema" ] = "d2";
          } else {
            graphic.attributes[ "schema" ] = "d3";
          }

        }
      });
    });

    var defaultSymbol = new SimpleFillSymbol();
      defaultSymbol.outline.setStyle(SimpleLineSymbol.STYLE_DASH, new Color([255,255,255,255]), 3);

    var renderer = new UniqueValueRenderer(defaultSymbol, "schema");
    renderer.addValue("d0", new SimpleFillSymbol().setColor(new Color([222,235,247, 0.7])));
    renderer.addValue("d1", new SimpleFillSymbol().setColor(new Color([189,215,231, 0.7])));
    renderer.addValue("d2", new SimpleFillSymbol().setColor(new Color([158,202,225, 0.7])));
    renderer.addValue("d3", new SimpleFillSymbol().setColor(new Color([49,130,189, 0.7])));

    renderer.addValue("r0", new SimpleFillSymbol().setColor(new Color([254,224,210, 0.7])));
    renderer.addValue("r1", new SimpleFillSymbol().setColor(new Color([252,174,145, 0.7])));
    renderer.addValue("r2", new SimpleFillSymbol().setColor(new Color([252,146,114, 0.7])));
    renderer.addValue("r3", new SimpleFillSymbol().setColor(new Color([222,45,38, 0.7])));

    var json = renderer.toJson();
    $.each(json.uniqueValueInfos, function(i,sys) {
      sys.symbol.outline = {
        color: [225,225,225,255],
        style:"esriSLSSolid",
        width:0.3,
        type:"esriSLS"
      }
    });

    var rend = new UniqueValueRenderer(json);

    self.featureLayerGen.setRenderer( rend );
    self.featureLayerGen.redraw();

    self.featureLayer.setRenderer( rend );
    self.featureLayer.redraw();

  });

}

/*
* Get legislator by point on map [ via mapClick ]
*
*/
App.prototype._getLegByLatLong = function(e) {
  var self = this;

  $('#col-left').fadeOut();
  $('#committees').hide();
  $('#committees-empty').hide();
  $('#pie-chart-votes').empty();
  $('#pie-chart-party-line').empty();

  this._clearUI();

  var lat, lon;
  if ( e.mapPoint ) {
    var mapPoint = e.mapPoint;
    lon = mapPoint.getLongitude().toFixed(2);
    lat = mapPoint.getLatitude().toFixed(2);
  } else {
    lat = e.latitude;
    lon = e.longitude;
  };

  var url = "https://congress.api.sunlightfoundation.com/legislators/locate?latitude="+lat+"&longitude="+lon+"&apikey=88036ea903bf4dffbbdc4a9fa7acb2ad";

  $('.legislator').hide(); //hide previous selection

  //sunlight api lookup
  $.getJSON(url, function(data) {

    var leg_ordered_arr = [];
    $.each(data.results, function(i, rep ) {
      if(rep.chamber === 'house'){
        leg_ordered_arr[0] = rep;
      } else if (rep.chamber === 'senate' && rep.state_rank === 'junior') {
        leg_ordered_arr[1] = rep;
      } else {
        leg_ordered_arr[2] = rep;
      }
    });

    self.committees = {}; //reset committees array
    $('.media-object').show(); //make sure all images are viz
    $('.glyphicon-user').hide();

    $.each(leg_ordered_arr, function(i, rep) {

      //highlight map
      if ( rep.district ) {
        self._selectDistrict( rep.district, rep.state );
      }

      //set current committees
      self._getCommittees(rep);

      //update UI
      $($('.legislator')[ i ]).find('.media-object').attr('src', 'assets/images/'+rep.bioguide_id+'.jpg');
      $($('.legislator')[ i ]).find('.media-heading').html('['+rep.party+'] '+ rep.title + '. ' + rep.first_name + ' ' + rep.last_name);
      $($('.legislator')[ i ]).find('.state-name').html(rep.state_name);
      $($('.legislator')[ i ]).find('.rank-name').html( (rep.state_rank) ? rep.state_rank.slice(0,1).toUpperCase() + rep.state_rank.slice(1) : rep.district );
      $($('.legislator')[ i ]).find('.rank-title').html( (rep.state_rank) ? "State Rank" : "District" );

      //set bottom border of info card to affiliated party
      if(rep.party === "D"){
        $($('.legislator')[ i ]).find('.legislator-inner-party-border').css( "border-bottom", "solid 8px #2171b5" );
      } else if( rep.party === "R") {
        $($('.legislator')[ i ]).find('.legislator-inner-party-border').css( "border-bottom", "solid 8px #cb181d" );
      } else {
        $($('.legislator')[ i ]).find('.legislator-inner-party-border').css( "border-bottom", "solid 8px #FFF" );
      };

      $($('.legislator')[ i ]).show();

      //show icon for missing rep photos
      $("img").error(function () {
        $(this).parent().parent().find('.glyphicon-user').show();
        $(this).unbind("error").hide(); //attr("src", "broken.gif");
      });

    });

    //select first rep
    setTimeout(function() {
      $($('.legislator')[0]).trigger('click');
    },1000);

  });

}

/*
* Get legislator by first name -- matches with last
*
*/
App.prototype._getLegByName = function(name) {
  var self = this;

  $('#col-left').fadeOut();
  $('#committees').hide();
  $('#committees-empty').hide();
  $('#pie-chart-votes').empty();
  $('#pie-chart-party-line').empty();

  this._clearUI();

  var first_name = name.split(' ')[ 0 ];
  var last_name = name.split(' ')[ 1 ];

  //sunlight api lookup by FIRST NAME & LAST NAME
  var url = "https://congress.api.sunlightfoundation.com/legislators?first_name="+first_name+"&last_name="+last_name+"&apikey=88036ea903bf4dffbbdc4a9fa7acb2ad";

  $.getJSON(url, function(data) {

    var leg_ordered_arr = [];
    $.each(data.results, function(i, rep ) {
      if(data.results > 1){
        if(rep.chamber === 'house'){
        leg_ordered_arr[0] = rep;
        } else if (rep.chamber === 'senate' && rep.state_rank === 'junior') {
          leg_ordered_arr[1] = rep;
        } else {
          leg_ordered_arr[2] = rep;
        }
      } else {
        leg_ordered_arr.push(data.results[0]);
      }

    });

    self.committees = {}; //reset committees array
    $('.legislator').hide(); //hide previous selection
    $('.media-object').show(); //make sure all images are viz
    $('.glyphicon-user').hide();

    $.each(leg_ordered_arr, function(i, rep) {
      if ( rep.last_name === last_name ) {
        self._getCommittees(rep);

        //highlight map
        if ( rep.district ) {
          self._selectDistrict( rep.district, rep.state );
        } else {
          self._selectState( rep.state );
        }

        //Update UI
        $('.legislator').hide();
        $($('.legislator')[ 0 ]).find('.media-object').attr('src', 'assets/images/'+rep.bioguide_id+'.jpg');
        $($('.legislator')[ 0 ]).find('.media-heading').html('['+rep.party+'] '+ rep.title + '. ' + rep.first_name + ' ' + rep.last_name);
        $($('.legislator')[ 0 ]).find('.state-name').html(rep.state_name);
        $($('.legislator')[ 0 ]).find('.rank-name').html( (rep.state_rank) ? rep.state_rank : rep.district );
        $($('.legislator')[ 0 ]).find('.rank-title').html( (rep.state_rank) ? "State Rank" : "District" );

        //set bottom border of info card to affiliated party
        if(rep.party === "D"){
          $($('.legislator')[ 0 ]).find('.legislator-inner-party-border').css( "border-bottom", "solid 10px #2171b5" );
        } else if( rep.party === "R") {
          $($('.legislator')[ 0 ]).find('.legislator-inner-party-border').css( "border-bottom", "solid 10px #cb181d" );
        } else {
          $($('.legislator')[ 0 ]).find('.legislator-inner-party-border').css( "border-bottom", "solid 10px #FFF" );
        };

        $($('.legislator')[ 0 ]).show();
      }

      $("img").error(function () {
        $(this).parent().parent().find('.glyphicon-user').show();
        $(this).unbind("error").hide(); //attr("src", "broken.gif");
      });

    });

    //select first rep
    setTimeout(function() {
      $($('.legislator')[0]).trigger('click');
    },1000);

  });

};

/*
* Get legislators by ZIPCODE
*
*/
App.prototype._getLegByZipcode = function(zipcode) {
  var self = this;

  $('#col-left').fadeOut();
  $('#committees').hide();
  $('#committees-empty').hide();
  this._clearUI();

  var url = "https://congress.api.sunlightfoundation.com/legislators/locate?zip="+zipcode+"&apikey=88036ea903bf4dffbbdc4a9fa7acb2ad";

  //sunlight api lookup
  $.getJSON(url, function(data) {
    self.committees = {}; //reset committees array
    $('.legislator').hide(); //hide previous selection

    var leg_ordered_arr = [];
    $.each(data.results, function(i, rep ) {
      if(rep.chamber === 'house'){
        leg_ordered_arr[0] = rep;
      } else if (rep.chamber === 'senate' && rep.state_rank === 'junior') {
        leg_ordered_arr[1] = rep;
      } else {
        leg_ordered_arr[2] = rep;
      }
    });

    $.each(leg_ordered_arr, function(i, rep) {

      //highlight map
      if ( rep.district ) {
        self._selectDistrict( rep.district, rep.state );
      }

      //set current committees
      self._getCommittees(rep);

      $($('.legislator')[ i ]).find('.media-object').attr('src', 'assets/images/'+rep.bioguide_id+'.jpg');
      $($('.legislator')[ i ]).find('.media-heading').html('['+rep.party+'] '+ rep.title + '. ' + rep.first_name + ' ' + rep.last_name);
      $($('.legislator')[ i ]).find('.state-name').html(rep.state_name);
      $($('.legislator')[ i ]).find('.rank-name').html( (rep.state_rank) ? rep.state_rank.slice(0,1).toUpperCase() + rep.state_rank.slice(1) : rep.district );
      $($('.legislator')[ i ]).find('.rank-title').html( (rep.state_rank) ? "State Rank" : "District" );

      //set bottom border of info card to affiliated party
      if(rep.party === "D"){
        $($('.legislator')[ i ]).find('.legislator-inner-party-border').css( "border-bottom", "solid 10px #2171b5" );
      } else if( rep.party === "R") {
        $($('.legislator')[ i ]).find('.legislator-inner-party-border').css( "border-bottom", "solid 10px #cb181d" );
      } else {
        $($('.legislator')[ i ]).find('.legislator-inner-party-border').css( "border-bottom", "solid 10px #FFF" );
      };

      $($('.legislator')[ i ]).show();

    });

  });

  //select first rep
  setTimeout(function() {
    $($('.legislator')[0]).trigger('click');
  },1000);

};

/*
* Get committees
* Function gets list of committees the CURRENTLY SELECTED members are a member of
* this.committees is recreated each time a new district is selected
*
*/
App.prototype._getCommittees = function(rep) {
  var self = this;

  //committee by member id url
  var url = "https://congress.api.sunlightfoundation.com/committees?member_ids="+rep.bioguide_id+"&apikey=88036ea903bf4dffbbdc4a9fa7acb2ad";

  //get all committees for member
  var member = (rep.first_name + rep.last_name).replace(/ /g, '');

  this.committees[ member ] = { committees: [] };

  $.getJSON(url, function(data) {
    //console.log(data);
    self.committees[ member ].committees = data.results;
  });

}

/*
* Show committees
* Shows list of committees in UI
*
*/
App.prototype._showCommittees = function(name) {
  var self = this;

  this._clearUI();
  $('#committees').show().height('400px');

  var committees = this.committees[ name.replace(/ /g, '') ].committees;
  $.each(committees, function(i, committee) {
    var cmte = '
'+committee.name+' ('+committee.chamber+')
';
    $('#committees').append(cmte);
  });

  var header = '
'+name+' is a Member of '+ committees.length + ' Committees
';
  $('#committees').prepend(header);

  //bind committee hovers
  $('.committee').on('click', function(e) {
    $('.committee').removeClass('selected');
    $(this).addClass('selected');
    var id = $(this).attr('title');
    self._showCommitteeMembers( id );
  });
}

/*
* Show MEMBERS OF a committee
* On committee select, show all members of that committee, wire ability to search off that committee member
*
*/
App.prototype._showCommitteeMembers = function(name) {
  var self = this;
  var committees = this.allCommittees.results;

  $('#committee-members').show();

  $.each(committees, function(i, committee) {
    if (committee.name === name) {
      if ( committee.members.length > 0 ) {

        $('#committee-members').empty();
        var header = '
Members of the '+name+' Committee
';
        $('#committee-members').append(header);

        $.each(committee.members, function(i, rep) {
          var face;
          if(rep.legislator.party === 'D'){
            face = '';
          } else if (rep.legislator.party === 'R'){
            face = '';
          } else {
            face = '';
          }
          $('#committee-members').append( face );
        });
      }
    }
  });
  $('#committees').css({'height': '125px'});
  $('.committee-member-photos').tooltip();
  $('.committee-member-photos').on('click', function(e) {
    $('#pie-chart-votes').empty();
    $('#pie-chart-party-line').empty();
    var id = e.target.id;
    self._getLegByName( id );
  });

  $("img").error(function () {
        $(this).parent().parent().find('.glyphicon-user').show();
        $(this).unbind("error").hide(); //attr("src", "broken.gif");
  });
}

/*
* Member details
* When member is selected, show their details (address, phone, contact)
* Initiates call to GET VOTES, which populates voting record for specified Rep
*/
App.prototype._showMemberDetails = function(name) {
  var self = this;

  $('#col-left').show();
  $('#member-name').html(name);

  $.each(this.allLegislators, function(i, leg) {
    var n = name.split('.')[1].split(' ');
    if ( leg.first_name === n[1] && leg.last_name === n[2]) {
      self.selectedLeg = leg;
      $('#member-details').fadeIn();
      $('#address').html(leg.office);
      $('#telephone').html(leg.phone);

      $('.icon-homepage').attr("href", leg.website);
      $('.icon-homepage').attr("target", "_blank");

      $('.icon-twitter').attr("href", "http://www.twitter.com/"+leg.twitter_id);
      $('.icon-twitter').attr("target", "_blank");

      $('.icon-facebook').attr("href", "http://www.facebook.com/"+leg.facebook_id);
      $('.icon-facebook').attr("target", "_blank");

      $('.icon-youtube').attr("href", "http://www.youtube.com/"+leg.youtube_id);
      $('.icon-youtube').attr("target", "_blank");

      $('.icon-email').attr("href", leg.contact_form);
      $('.icon-email').attr("target", "_blank");

      self._getVotesById(leg.bioguide_id);
    }
  });

}

/*
* Takes rep id
* Does search to Sunlight votes API
* Populates UI with voting record, and break down of last 50 votes by specified Rep
*
*/
App.prototype._getVotesById = function(id) {
  var self = this;

  $('#voting-record').hide();
  $('.voting-loader').show();

  //get vote history for selected member
  var url = "https://congress.api.sunlightfoundation.com/votes?apikey=88036ea903bf4dffbbdc4a9fa7acb2ad&voter_ids."+id+"__exists=true&per_page=100&fields=voter_ids,result,bill,breakdown.total,breakdown.party"

  var votes = {"Yea": 0, "Nay": 0, "Present": 0, "Not Voting": 0};
  self.partyLine = {"With": 0, "Against": 0};

  if (self.voteRequest !== undefined ) {
    self.voteRequest.abort();
  }
  self.voteRequest = $.getJSON(url, function(data) {

    $.each(data.results, function(i, res) {
      for ( var voter in res.voter_ids ) {
        if ( voter === id ) {
          if (res.breakdown.party) {
            self._getPartyLine(voter, res);
          }
          if (res.bill) {
            $('#bills-container').show();
            var d = ( res.bill.last_vote_at ) ? res.bill.last_vote_at : res.bill.last_action_at;
            var item = '

'+res.bill.bill_id+'
\

'+res.bill.official_title+'
\

Result: '+res.result+'
\

Yea: '+res.breakdown.total.Yea+'
\

Nay: '+res.breakdown.total.Nay+'
\

Present: '+res.breakdown.total.Present+'
\

How '+self.selectedLeg.title+'. ' + self.selectedLeg.first_name + ' ' +self.selectedLeg.last_name + ' voted: '+ res.voter_ids[ voter ] +'
\

URL: '+res.bill.urls.congress+'
\

Last Vote At: '+new Date( d ).toLocaleString()+'
\

';

            $('#bills').append(item);
          }
          //tally recent votes!
          votes[ res.voter_ids[ voter ] ]++;

          $('#term-start').html(moment(self.selectedLeg.term_start).format("MMMM DD, YYYY"));
          $('#term-end').html(moment(self.selectedLeg.term_end).format("MMMM DD, YYYY"));
        }
      };
    });

    $('#pie-chart-votes').empty();
    $('#pie-chart-party-line').empty();
    self._partyLinePie();
    self._pieChart(votes);

    $('.voting-loader').hide();
    $('#voting-record').fadeIn();
    $('#total-votes').html(data.count.toLocaleString());
  });

}

/*
* Calculate how often a rep votes with party (last 50 votes)
*
*/
App.prototype._getPartyLine = function(voter, res) {
  var self = this;
  var voted = res.voter_ids[ voter ];
  var party = self.selectedLeg.party;
  var partyline = ( res.breakdown.party[ party ].Yea > res.breakdown.party[ party ].Nay ) ? "Yea" : "Nay";

  if ( voted === partyline ) {
    this.partyLine['With']++;
  } else {
    this.partyLine['Against']++;
  }
}

/*
* Empties, clears, hides UI elements as needed
* TODO Build this out to handle more
*
*/
App.prototype._clearUI = function() {
  $('#committees').empty();
  $('#committee-members').empty();
  $('#bills').empty();
  $('#pie-chart-votes').empty();
  $('#pie-chart-party-line').empty();
  $('#committees').hide();
  $('#committees-empty').hide();
  $('#bills-container').hide();
}


text:
using RotatorPtr = std::shared_ptr<Rotator>;

API FishEngine::Script* CreateCustomScript(const char* className)
{
	std::cout << className << std::endl;
	if (std::string(className) == "Rotator")
	{
		return new Rotator();
	}
	return nullptr;
}

API void DestroyCustomScript(FishEngine::Script * script)
{
	delete script;
}


text:
import * as path from "path";
import {getWasmInstance} from "./utils/utils";

test('for loop', async () => {
    let imports = {
        global: {
            print: (v1, v2) => {
                console.log(v1, v2);
            }
        }
    };
    const instance: WebAssembly.Instance = await getWasmInstance(path.resolve(__dirname, 'for-loop.tbs'), imports);
    expect(instance.exports.test(10)).toBe(10);
});


text:
//
//  SimpleGeoTest+Places10.m
//  SimpleGeo.framework
//
//  Copyright (c) 2010, SimpleGeo Inc.
//  All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * 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.
//     * Neither the name of the <organization> 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 COPYRIGHT HOLDERS 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 <COPYRIGHT HOLDER> 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.
//

#import "SimpleGeoTest.h"
#import "SimpleGeo+Places.h"

#define SGTestPlacesEditLatitude 22.917923
#define SGTestPlacesEditLongitude -125.859375
#define SGTestPlaceID @"SG_7gm91gq6GfsVja5zFsRz6x_37.771718_-122.405139"
#define SGTestPlacesRadius 1.0 // km
#define SGTestPlaceSearchString @"Mexican"
#define SGTestPlaceCategory SGFeatureTypeFoodAndDrink

@interface Places10Tests : SimpleGeoTest
@end
@implementation Places10Tests

#pragma mark Set Up Places 1.0

- (SimpleGeo *)client
{
    SimpleGeo *client = super.client;
    [client setPlacesVersion:@"1.0"];
    return client;
}

#pragma mark Places Add/Update Tests

- (void)testAddDeletePlace
{
    [self prepare];
    SGPlace *place = [SGPlace placeWithName:@"Simple Place"
                                      point:[SGPoint pointWithLat:SGTestPlacesEditLatitude
                                                              lon:SGTestPlacesEditLongitude]];
    NSDictionary *classifier1 = [NSDictionary classifierWithType:SGFeatureTypePublicPlace
                                                        category:SGPlaceCategoryArtsAndPerformance
                                                     subcategory:SGPlaceCategoryArena];
    NSDictionary *classifier2 = [NSDictionary classifierWithType:SGFeatureTypePublicPlace
                                                        category:SGPlaceCategoryPark
                                                     subcategory:SGPlaceCategoryShopping];
    [place setClassifiers:[NSMutableArray arrayWithObjects:classifier1, classifier2, nil]];
    [place setTags:[NSArray arrayWithObjects:@"tag1", @"tag2", @"tag3", nil]];
    [[self client] addPlace:place
                   callback:[SGCallback callbackWithSuccessBlock:
                             ^(id response) {
                                 [self prepare];
                                 [[self client] deletePlace:[(NSDictionary *)response objectForKey:@"id"]
                                                   callback:[SGCallback callbackWithSuccessBlock:
                                                             ^(id response) {
                                                                 [self requestDidSucceed:response];
                                                             } failureBlock:[self failureBlock]]];
                                 [self waitForStatus:kGHUnitWaitStatusSuccess timeout:SGTestTimeout];
                             } failureBlock:[self failureBlock]]];
    [self waitForStatus:kGHUnitWaitStatusSuccess timeout:SGTestTimeout];
}

#pragma mark Places Requests Tests

- (void)testGetSGPlaceAndConvertFeature
{
    [self prepare];
    [[self client] getFeatureWithHandle:SGTestPlaceID
                                   zoom:nil
                               callback:[SGCallback callbackWithSuccessBlock:
                                         ^(id response) {
                                             SGPlace *place = [SGPlace placeWithGeoJSON:(NSDictionary *)response];
                                             [self checkSGFeatureConversion:(NSDictionary *)response object:place];
                                             [self requestDidSucceed:response];
                                         } failureBlock:[self failureBlock]]];
    [self waitForStatus:kGHUnitWaitStatusSuccess timeout:SGTestTimeout];
}

- (void)testGetSGPlacesForPoint
{
    [self prepare];
    SGPlacesQuery *query = [SGPlacesQuery queryWithPoint:[self point]];
    [[self client] getPlacesForQuery:query callback:[SGCallback callbackWithSuccessBlock:
                                                     ^(id response) {
                                                         GHAssertGreaterThan((int)[[response objectForKey:@"features"] count], 1,
                                                                             @"Query should return at least one feature.");
                                                         [self requestDidSucceed:response];
                                                     } failureBlock:[self failureBlock]]];
    [self waitForStatus:kGHUnitWaitStatusSuccess timeout:SGTestTimeout];
}

- (void)testGetSGPlacesForAddress
{
    [self prepare];
    SGPlacesQuery *query = [SGPlacesQuery queryWithAddress:SGTestAddress];
    [[self client] getPlacesForQuery:query callback:[SGCallback callbackWithSuccessBlock:
                                                     ^(id response) {
                                                         GHAssertGreaterThan((int)[[response objectForKey:@"features"] count], 1,
                                                                             @"Query should return at least one feature.");
                                                         [self requestDidSucceed:response];
                                                     } failureBlock:[self failureBlock]]];
    [self waitForStatus:kGHUnitWaitStatusSuccess timeout:SGTestTimeout];
}

- (void)testGetSGPlacesForEnvelope
{
    [self prepare];
    SGPlacesQuery *query = [SGPlacesQuery queryWithEnvelope:[self envelope]];
    [[self client] getPlacesForQuery:query callback:[SGCallback callbackWithSuccessBlock:
                                                     ^(id response) {
                                                         GHAssertGreaterThan((int)[[response objectForKey:@"features"] count], 1,
                                                                             @"Query should return at least one feature.");
                                                         [self requestDidSucceed:response];
                                                     } failureBlock:[self failureBlock]]];
    [self waitForStatus:kGHUnitWaitStatusSuccess timeout:SGTestTimeout];
}

- (void)testGetSGPlacesWithFilters
{
    [self prepare];
    SGPlacesQuery *query = [SGPlacesQuery queryWithPoint:[self point]];
    [query setCategories:[NSArray arrayWithObject:SGTestPlaceCategory]];
    [query setSearchString:SGTestPlaceSearchString];
    [[self client] getPlacesForQuery:query
                            callback:[SGCallback callbackWithSuccessBlock:
                                      ^(id response) {
                                          /*GHAssertGreaterThan((int)[[response objectForKey:@"features"] count], 1,
                                                         @"Query should return at least one matching place.");*/
                                          [self requestDidSucceed:response];
                                      } failureBlock:[self failureBlock]]];
    [self waitForStatus:kGHUnitWaitStatusSuccess timeout:SGTestTimeout];
}

- (void)testGetSGPlacesWithLimitsAndConvertFeatureCollection
{
    [self prepare];
    SGPlacesQuery *query = [SGPlacesQuery queryWithPoint:[self point]];
    [query setRadius:SGTestPlacesRadius];
    [query setLimit:SGTestLimit];
    [[self client] getPlacesForQuery:query
                            callback:[SGCallback callbackWithSuccessBlock:
                                      ^(id response) {
                                          NSArray *places = [NSArray arrayWithSGCollection:(NSDictionary *)response type:SGCollectionTypePlaces];
                                          GHAssertEquals((int)[places count], SGTestLimit, @"Query should return the limit.");
                                          [self checkSGCollectionConversion:(NSDictionary *)response type:SGCollectionTypePlaces];
                                          [self requestDidSucceed:response];
                                      } failureBlock:[self failureBlock]]];
    [self waitForStatus:kGHUnitWaitStatusSuccess timeout:SGTestTimeout];
}

@end


text:
<?php

namespace Demos\StartBundle\Repository;

use Doctrine\ORM\EntityRepository;

class ItemRepository extends EntityRepository
{
    public function getLatest()
    {
        $query = $this->createQueryBuilder('p')
                ->orderBy('p.createDate', 'DESC')
                ->setMaxResults(5)
                ->getQuery();

        return $query->getResult();
    }
}


text:
class Autoload
  def self.allocate
    Rubinius.primitive :autoload_allocate
    raise PrimtiveFailure, "Autoload.allocate primitive failed"
  end

  attr_reader :name
  attr_reader :scope
  attr_reader :path

  def initialize(name, scope, path)
    @name = name
    @scope = scope
    @path = path
  end

  ##
  # When any code that finds a constant sees an instance of Autoload as its match,
  # it calls this method on us
  def call(honor_require=false)
    # Remove the autoload object from the constant table it was in, so
    # we don't recurse back into ourself.
    scope.constant_table.delete @name
    Rubinius.inc_global_serial

    worked = Rubinius::CodeLoader.require @path
    if !honor_require or worked
      scope.const_get @name
    end
  end

  ##
  #
  # Change the file to autoload. Used by Module#autoload
  def set_path(path)
    @path = path
  end
end


text:
package com.shakenearth.rhyme_essentials;

import java.util.ArrayList;

public class OrderedPair {

	private String shorterWordPhoneme = "", longerWordPhoneme = "";
	private ArrayList<Integer> indexes = new ArrayList<Integer>();
	private double originalRhymeValue = 0.0;
	private double rhymeValue = 0.0;

	public OrderedPair(Phoneme p1, Phoneme p2, int l){

		shorterWordPhoneme = p1.getPhoneme();
		longerWordPhoneme = p2.getPhoneme();
		setRhymeValue(findRVBetweenPhonemes(p1, p2));
		setOriginalRhymeValue(getRhymeValue());
		getIndexes().add(l);

	}

	private double findRVBetweenPhonemes(Phoneme p1, Phoneme p2){

		ArrayList<Integer> p1Features = p1.getFeatures();
		ArrayList<Integer> p2Features = p2.getFeatures();
		ArrayList<Integer> biggerList = null;

		if(p1Features.size() >= p2Features.size()){

			biggerList = p1Features;

		}else{

			biggerList = p2Features;

		}

		//contains just the features that the phonemes share
		ArrayList<Integer> commonFeatures = new ArrayList<Integer>(p1Features);
		commonFeatures.retainAll(p2Features);

		int difference = biggerList.size() - commonFeatures.size();

		if(p1.isAVowelPhoneme() && p2.isAVowelPhoneme()){

			int stressDifference = Math.abs(p1.getStress() - p2.getStress());

			return 5.0 - (1*difference) - stressDifference;

		}else if(p1.isAVowelPhoneme() == false && p2.isAVowelPhoneme() == false){

			int commonFeaturesSize = commonFeatures.size();
			double specialDifference = 0; /*this is used for keeping track of differences that need different values to be subtracted
			as opposed to the standard amount*/

			if(p1.getPhoneme().equals(p2.getPhoneme()) == false){ /*This is here so that when homophonic rhyme value is being
			calculated, the homophonic rhyme value won't differ according to feature sets and thus rhyme percentile won't be
			altered based on the order in which the words were entered*/

				if(commonFeatures.contains(9) == false){ //difference in voicing

					specialDifference = specialDifference + 0.1;
					commonFeaturesSize = commonFeaturesSize - 1;

				}

				if(commonFeatures.contains(2)){ //difference in sonority

					specialDifference = specialDifference + 1;
					commonFeaturesSize = commonFeaturesSize - 1;

				}

			}

			difference = biggerList.size() - commonFeaturesSize;

			return 2.0 - (0.15*difference) - specialDifference;

		}else{ /*this is a bit different because we're starting at the assumption that they won't have much in common so it's structured
		for rewarding common features rather than punishing for differences*/

			//run same sonority and voicing tests but perhaps with different amounts rewarded for each

			int commonFeaturesSize = commonFeatures.size();
			double specialDifference = 0; /*this is used for keeping track of differences that need different values to be subtracted
			as opposed to the standard amount*/

			if(commonFeatures.contains(9) == false){ //difference in voicing

				specialDifference = specialDifference + 0.1;
				commonFeaturesSize = commonFeaturesSize - 1;

			}

			if(commonFeatures.contains(2)){ //difference in sonority

				specialDifference = specialDifference + 1;
				commonFeaturesSize = commonFeaturesSize - 1;

			}

			difference = biggerList.size() - commonFeaturesSize;

			return 0.1*commonFeaturesSize + specialDifference;

		}

	}

	public void resetRV(){

		rhymeValue = originalRhymeValue;

	}

	public String getShorterWordPhoneme() {
		return shorterWordPhoneme;
	}

	public void setShorterWordPhoneme(String shorterWordPhoneme) {
		this.shorterWordPhoneme = shorterWordPhoneme;
	}

	public String getLongerWordPhoneme() {
		return longerWordPhoneme;
	}

	public void setLongerWordPhoneme(String longerWordPhoneme) {
		this.longerWordPhoneme = longerWordPhoneme;
	}

	public double getRhymeValue() {
		return rhymeValue;
	}

	public void setRhymeValue(double rhymeValue) {
		this.rhymeValue = rhymeValue;
	}

	public String toString(){

		return "(" + shorterWordPhoneme + ", " + longerWordPhoneme + ")";

	}

	public ArrayList<Integer> getIndexes() {
		return indexes;
	}

	public void setIndexes(ArrayList<Integer> indexes) {
		this.indexes = indexes;
	}

	public void calculateGapPenalty(int lSize) {

		double deduction = 0.0;

		for(int i = 0; i < getIndexes().size() - 1; i++){

			int index1 = getIndexes().get(i);
			int index2 = getIndexes().get(i + 1);

			deduction = deduction + (0.25 * (index1 - index2-1));

		}

		if(getIndexes().get(getIndexes().size() - 1) < 0){

			if(getIndexes().get(getIndexes().size() - 1) > 1){

				deduction = deduction + Math.log10(getIndexes().get(0));

			}else{

				deduction = deduction + 0.25;

			}

		}

		if(lSize - getIndexes().get(getIndexes().size()-1) < 0){

			deduction = deduction + Math.log10(lSize - getIndexes().get(getIndexes().size()-1));

		}

		setRhymeValue(getRhymeValue() - deduction);

	}

	public double getOriginalRhymeValue() {
		return originalRhymeValue;
	}

	public void setOriginalRhymeValue(double originalRhymeValue) {
		this.originalRhymeValue = originalRhymeValue;
	}

}


text:
/**
 *
 */
package de.m_bleil.java_api.streams;

import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

import java.util.Arrays;
import java.util.stream.Collectors;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

/**
 * @author Marcus Bleil, www.marcusbleil.de
 */
public class CollectorsTest {

	@Rule
	public ExpectedException expectedException = ExpectedException.none();

	@Test
	public void test() {
		String[] tupples = {};

		String tuppelsJoined = Arrays.stream(tupples).collect(Collectors.joining("_"));

		assertThat(tuppelsJoined, is(equalTo("")));
	}

	@Test
	public void test2() {
		String[] tupples = null;

		expectedException.expect(NullPointerException.class);
		Arrays.stream(tupples).collect(Collectors.joining("_"));
	}
}


text:
package models

import (
	"log"
	"sync"
	"time"

	"github.com/influxdata/telegraf"
	"github.com/influxdata/telegraf/internal/buffer"
	"github.com/influxdata/telegraf/metric"
	"github.com/influxdata/telegraf/selfstat"
)

const (
	// Default size of metrics batch size.
	DEFAULT_METRIC_BATCH_SIZE = 1000

	// Default number of metrics kept. It should be a multiple of batch size.
	DEFAULT_METRIC_BUFFER_LIMIT = 10000
)

// RunningOutput contains the output configuration
type RunningOutput struct {
	Name              string
	Output            telegraf.Output
	Config            *OutputConfig
	MetricBufferLimit int
	MetricBatchSize   int

	MetricsFiltered selfstat.Stat
	MetricsWritten  selfstat.Stat
	BufferSize      selfstat.Stat
	BufferLimit     selfstat.Stat
	WriteTime       selfstat.Stat

	metrics     *buffer.Buffer
	failMetrics *buffer.Buffer

	// Guards against concurrent calls to the Output as described in #3009
	sync.Mutex
}

func NewRunningOutput(
	name string,
	output telegraf.Output,
	conf *OutputConfig,
	batchSize int,
	bufferLimit int,
) *RunningOutput {
	if bufferLimit == 0 {
		bufferLimit = DEFAULT_METRIC_BUFFER_LIMIT
	}
	if batchSize == 0 {
		batchSize = DEFAULT_METRIC_BATCH_SIZE
	}
	ro := &RunningOutput{
		Name:              name,
		metrics:           buffer.NewBuffer(batchSize),
		failMetrics:       buffer.NewBuffer(bufferLimit),
		Output:            output,
		Config:            conf,
		MetricBufferLimit: bufferLimit,
		MetricBatchSize:   batchSize,
		MetricsWritten: selfstat.Register(
			"write",
			"metrics_written",
			map[string]string{"output": name},
		),
		MetricsFiltered: selfstat.Register(
			"write",
			"metrics_filtered",
			map[string]string{"output": name},
		),
		BufferSize: selfstat.Register(
			"write",
			"buffer_size",
			map[string]string{"output": name},
		),
		BufferLimit: selfstat.Register(
			"write",
			"buffer_limit",
			map[string]string{"output": name},
		),
		WriteTime: selfstat.RegisterTiming(
			"write",
			"write_time_ns",
			map[string]string{"output": name},
		),
	}
	ro.BufferLimit.Set(int64(ro.MetricBufferLimit))
	return ro
}

// AddMetric adds a metric to the output. This function can also write cached
// points if FlushBufferWhenFull is true.
func (ro *RunningOutput) AddMetric(m telegraf.Metric) {
	if m == nil {
		return
	}
	// Filter any tagexclude/taginclude parameters before adding metric
	if ro.Config.Filter.IsActive() {
		// In order to filter out tags, we need to create a new metric, since
		// metrics are immutable once created.
		name := m.Name()
		tags := m.Tags()
		fields := m.Fields()
		t := m.Time()
		if ok := ro.Config.Filter.Apply(name, fields, tags); !ok {
			ro.MetricsFiltered.Incr(1)
			return
		}
		// error is not possible if creating from another metric, so ignore.
		m, _ = metric.New(name, tags, fields, t)
	}

	ro.metrics.Add(m)
	if ro.metrics.Len() == ro.MetricBatchSize {
		batch := ro.metrics.Batch(ro.MetricBatchSize)
		err := ro.write(batch)
		if err != nil {
			ro.failMetrics.Add(batch...)
		}
	}
}

// Write writes all cached points to this output.
func (ro *RunningOutput) Write() error {
	nFails, nMetrics := ro.failMetrics.Len(), ro.metrics.Len()
	ro.BufferSize.Set(int64(nFails + nMetrics))
	log.Printf("D! Output [%s] buffer fullness: %d / %d metrics. ",
		ro.Name, nFails+nMetrics, ro.MetricBufferLimit)
	var err error
	if !ro.failMetrics.IsEmpty() {
		// how many batches of failed writes we need to write.
		nBatches := nFails/ro.MetricBatchSize + 1
		batchSize := ro.MetricBatchSize

		for i := 0; i < nBatches; i++ {
			// If it's the last batch, only grab the metrics that have not had
			// a write attempt already (this is primarily to preserve order).
			if i == nBatches-1 {
				batchSize = nFails % ro.MetricBatchSize
			}
			batch := ro.failMetrics.Batch(batchSize)
			// If we've already failed previous writes, don't bother trying to
			// write to this output again. We are not exiting the loop just so
			// that we can rotate the metrics to preserve order.
			if err == nil {
				err = ro.write(batch)
			}
			if err != nil {
				ro.failMetrics.Add(batch...)
			}
		}
	}

	batch := ro.metrics.Batch(ro.MetricBatchSize)
	// see comment above about not trying to write to an already failed output.
	// if ro.failMetrics is empty then err will always be nil at this point.
	if err == nil {
		err = ro.write(batch)
	}

	if err != nil {
		ro.failMetrics.Add(batch...)
		return err
	}
	return nil
}

func (ro *RunningOutput) write(metrics []telegraf.Metric) error {
	nMetrics := len(metrics)
	if nMetrics == 0 {
		return nil
	}
	ro.Lock()
	defer ro.Unlock()
	start := time.Now()
	err := ro.Output.Write(metrics)
	elapsed := time.Since(start)
	if err == nil {
		log.Printf("D! Output [%s] wrote batch of %d metrics in %s\n",
			ro.Name, nMetrics, elapsed)
		ro.MetricsWritten.Incr(int64(nMetrics))
		ro.WriteTime.Incr(elapsed.Nanoseconds())
	}
	return err
}

// OutputConfig containing name and filter
type OutputConfig struct {
	Name   string
	Filter Filter
}


text:
"""
Copyright (c) 2015, 2016, 2017 Red Hat, Inc
All rights reserved.

This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
from __future__ import print_function, absolute_import, unicode_literals

import re
import sys

PY3 = sys.version_info[0] >= 3

BUILD_JSON_STORE = "/usr/share/osbs/"
DEFAULT_GIT_REF = "master"
DEFAULT_BUILD_IMAGE = "buildroot:latest"
DEFAULT_CONFIGURATION_FILE = "/etc/osbs.conf"
DEFAULT_CONFIGURATION_SECTION = "default"
DEFAULT_OUTER_TEMPLATE = "prod.json"
WORKER_OUTER_TEMPLATE = "worker.json"
ORCHESTRATOR_OUTER_TEMPLATE = "orchestrator.json"
DEFAULT_INNER_TEMPLATE = "prod_inner.json"
WORKER_INNER_TEMPLATE = "worker_inner:{arrangement_version}.json"
ORCHESTRATOR_INNER_TEMPLATE = "orchestrator_inner:{arrangement_version}.json"
DEFAULT_ARRANGEMENT_VERSION = 4  # this should be the highest-numbered version
DEFAULT_CUSTOMIZE_CONF = "prod_customize.json"
WORKER_CUSTOMIZE_CONF = "worker_customize.json"
ORCHESTRATOR_CUSTOMIZE_CONF = "orchestrator_customize.json"
GENERAL_CONFIGURATION_SECTION = "general"
POD_FINISHED_STATES = ["failed", "succeeded"]
POD_FAILED_STATES = ["failed"]
POD_SUCCEEDED_STATES = ["succeeded"]
POD_RUNNING_STATES = ["pending", "running"]
# https://github.com/GoogleCloudPlatform/kubernetes/blob/master/pkg/api/types.go
# type PodPhase string
# fixme: what about "unknown" state?
BUILD_CANCELLED_STATE = "cancelled"
BUILD_FINISHED_STATES = ["failed", "complete", "error", BUILD_CANCELLED_STATE]
BUILD_FAILED_STATES = ["failed", "error", "cancelled"]  # meaning no image produced
BUILD_SUCCEEDED_STATES = ["complete"]
BUILD_PENDING_STATES = ["pending", "new"]
BUILD_RUNNING_STATES = ["running"]

# Watch response types
WATCH_ADDED = 'added'
WATCH_DELETED = 'deleted'
WATCH_MODIFIED = 'modified'
WATCH_ERROR = 'error'

# https://github.com/openshift/origin/blob/master/pkg/build/api/types.go
# type BuildStatus string
DEFAULT_NAMESPACE = "default"

# How to authenticate from within a pod
SERVICEACCOUNT_SECRET = "/var/run/secrets/kubernetes.io/serviceaccount"
SERVICEACCOUNT_TOKEN = "token"
SERVICEACCOUNT_CACRT = "ca.crt"

# Where will secrets be mounted?
SECRETS_PATH = "/var/run/secrets/atomic-reactor"

# Backup/restore
BACKUP_RESOURCES = ('buildconfigs', 'imagestreams', 'builds',)

CLI_LIST_BUILDS_DEFAULT_COLS = ["name", "status", "image"]
CLI_WATCH_BUILDS_DEFAULT_COLS = ["changetype", "status", "created", "name"]

# number of digits used for unique image tags
RAND_DIGITS = 5

# Logging format used in Atomic Reactor
ATOMIC_REACTOR_LOGGING_FMT = \
    '%(asctime)s platform:%(arch)s - %(name)s - %(levelname)s - %(message)s'

REPO_CONFIG_FILE = '.osbs-repo-config'
ADDITIONAL_TAGS_FILE = 'additional-tags'

# number of retries for http requests
HTTP_MAX_RETRIES = 8

# how many seconds should request wait for in case non-critical error has occurred
HTTP_BACKOFF_FACTOR = 4

# Statuses which should trigger automatic retry
HTTP_RETRIES_STATUS_FORCELIST = [408, 500, 502, 503, 504]

# HTTP methods that we should retry on
HTTP_RETRIES_METHODS_WHITELIST = ['GET', 'PUT', 'POST', 'DELETE']

BUILD_TYPE_ORCHESTRATOR = object()
BUILD_TYPE_WORKER = object()

ISOLATED_RELEASE_FORMAT = re.compile(r'^\d+\.\d+(\..+)?$')


text:
import { Component, ChangeDetectionStrategy } from '@angular/core';
import { TodosService } from "./todos.service";

import { Observable } from "rxjs/Observable";
import { User } from "app/models/user";
import { Todo } from "app/models/todo";

@Component({
  selector: 'app-todos',
  templateUrl: './todos.component.html',
  styleUrls: ['./todos.component.scss'],
  providers: [TodosService]
})
export class TodosComponent {

  users: Observable<User[]>;
  todos: Observable<Todo[]>;
  selectedUser: string;

  loadingUsers: Observable<boolean>;
  loadingTodos: Observable<boolean>;

  constructor(private service: TodosService) {
    this.users = this.service.getFbUsers();
    this.todos = this.service.getFbTodos();
    this.selectedUser = null;

    this.loadingUsers = this.service.getFireLoadingUsers();
    this.loadingTodos = this.service.getFireLoadingTodos();
  }

  onSelectUser(id: string) {
    this.service.loadFbTodos(id);
    this.selectedUser = id;
  }

}


text:
#include "Electric_SpeciesAppDelegate.h"

#import "EAGLView.h"
#import "GameCommon.h"
#import "GameViewController.h"
#import "Sounds.h"

@implementation Electric_SpeciesAppDelegate(Crystal)

- (void) splashScreenFinishedWithActivateCrystal:(BOOL)activateCrystal
{
    if (activateCrystal) {
        [CrystalSession activateCrystalUIAtProfile];
        [viewController.glView changeFlowState:kFlowState_CrystalSplash];
        g_bInBackground = true;
    }
    else {
        [viewController.glView changeFlowState:kFlowState_CompanySplash];
        g_bInBackground = false;
    }
}

- (void) crystalUiDeactivated {
    g_bInBackground = false;

    if (viewController.glView.flowState == kFlowState_CrystalSplash) {
        [viewController.glView changeFlowState:kFlowState_CompanySplash];
    }
    else {
        [viewController.glView crystalUiDeactivated];
        [[SimpleAudioEngine sharedEngine] resumeBackgroundMusic];
    }
}

- (void) challengeStartedWithGameConfig:(NSString*)gameConfig
{
 // Start a challenge with the specified game config
 // The game config will match the config shown in the Developer Dashboard
}

@end


text:
namespace Ogre {
	class Camera;
}

namespace XE {

	class GraphicsManager;
	class Scene;
	struct BodyComponent;

	///lives in Rendererthread
	class GizmoUIState : public IEditorUIState {

	public:
		GizmoUIState(Scene& scene, GraphicsManager& graphicsMgr, Ogre::Camera* camera);

		void render();

		Ogre::Camera* m_camera;
		GraphicsManager& m_graphicsMgr;
		Scene& m_scene;

	private:

		Ogre::Vector3 m_snap;

		Ogre::Vector3 m_position;
		Ogre::Vector3 m_scale;
		Ogre::Quaternion m_orientation;

		Ogre::Matrix4 _delta;

		void EditTransform();

	};
}


text: for topic_folder ($DOT/*) if [ -d $topic_folder ]; then  fpath=($topic_folder $fpath); fi;