text:
/* -*- mode: C; c-basic-offset: 4; -*- */
/* ex: set shiftwidth=4 tabstop=4 expandtab: */
/*
 * Copyright (c) 2015, Rice University
 * All rights reserved.
 *
 * Author(s): Neil T. Dantam <ntd@rice.edu>
 *
 *   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 copyright holder 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 THE COPYRIGHT HOLDER 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 HEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *   LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *   ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *   POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include "baxter-demo.h"
#include "amino/rx/rxerr.h"
#include "amino/rx/scene_kin.h"
#include "amino/rx/scene_sub.h"
#include "amino/rx/scene_gl.h"

int main(int argc, char *argv[])
{
    (void)argc; (void)argv;

    // Initialize scene graph
    struct aa_rx_sg *scenegraph = baxter_demo_load_baxter(NULL);
    aa_rx_sg_init(scenegraph);

    /*--- setup window ---*/
    struct aa_rx_win * win = baxter_demo_setup_window(scenegraph);
    struct aa_gl_globals *globals = aa_rx_win_gl_globals(win);
    aa_gl_globals_set_show_visual(globals, 1);
    aa_gl_globals_set_show_collision(globals, 0);

    /* --- Solve IK --- */
    size_t n_q = aa_rx_sg_config_count(scenegraph);
    aa_rx_frame_id tip_id = aa_rx_sg_frame_id(scenegraph, "right_w2");
    struct aa_rx_sg_sub *ssg = aa_rx_sg_chain_create( scenegraph, AA_RX_FRAME_ROOT, tip_id);
    size_t n_qs = aa_rx_sg_sub_config_count(ssg);

    assert( 7 == n_qs );

    // seed position
    double qstart_all[n_q];
    {
        double qstart_s[7] = {
            .05 * M_PI, // s0
            -.25 * M_PI, // s1
            0, // e0
            .25*M_PI, // e1
            0, // w0
            .25*M_PI, // w1
            0 // w2
        };
        AA_MEM_ZERO(qstart_all, n_q);
        aa_rx_sg_config_set( scenegraph, n_q, n_qs, aa_rx_sg_sub_configs(ssg),
                             qstart_s, qstart_all );
    }

    // solver options
    struct aa_rx_ksol_opts *ko = aa_rx_ksol_opts_create();
    aa_rx_ksol_opts_center_configs( ko, ssg, .1 );
    aa_rx_ksol_opts_set_tol_dq( ko, .01 );
    aa_rx_ksol_opts_take_seed( ko, n_q, qstart_all, AA_MEM_BORROW );

    const struct aa_rx_ik_jac_cx *ik_cx = aa_rx_ik_jac_cx_create(ssg,ko);

    // solver goal
    double qs[n_qs];
    //double E_ref[7];

    double E_ref[7] = {0, 1, 0, 0,
                       .8, -.25, .3051};
    {
        double E0[7] = {0, 1, 0, 0,
                        0.6, -0.0, 0.3};
        double E1[7] = {0, 0, 0, 1,
                        0, 0, 0 };
        aa_tf_xangle2quat(-.5*M_PI, E1 );
        aa_tf_qutr_mul( E0, E1, E_ref );
    }
    aa_tick("Inverse Kinematics: ");
    int r = aa_rx_ik_jac_solve( ik_cx,
                                1, E_ref, 7,
                                n_qs, qs );

    aa_tock();
    if( r ) {
        char *e = aa_rx_errstr( aa_mem_region_local_get(), r );
        fprintf(stderr, "Oops, IK failed: `%s' (0x%x)\n", e, r);
        aa_mem_region_local_pop(e);
    }

    // set all-config joint position
    {
        double q_all[n_q];
        aa_rx_sg_config_set( scenegraph, n_q, n_qs, aa_rx_sg_sub_configs(ssg),
                             qs, q_all );

        aa_rx_win_set_config( win, n_q, q_all );
    }

    /*--- Do Display ---*/
    aa_rx_win_run();

    /*--- Cleanup ---*/
    aa_rx_sg_destroy(scenegraph);
    aa_rx_win_destroy(win);
    SDL_Quit();

    return 0;
}


text:
package br.ufsc.lehmann.msm.artigo.clusterers.util;

import static br.ufsc.lehmann.msm.artigo.clusterers.util.ClosedHashingUtil.DELETED;
import static br.ufsc.lehmann.msm.artigo.clusterers.util.ClosedHashingUtil.EMPTY;
import static br.ufsc.lehmann.msm.artigo.clusterers.util.ClosedHashingUtil.INT_MASK;
import static br.ufsc.lehmann.msm.artigo.clusterers.util.ClosedHashingUtil.OCCUPIED;
import static br.ufsc.lehmann.msm.artigo.clusterers.util.ClosedHashingUtil.getNextPow2TwinPrime;

import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * A hash map for storing the primitive types of integers (as keys) to doubles
 * (as table). The implementation is based on Algorithm D (Open addressing with
 * double hashing) from Knuth's TAOCP page 528.
 *
 * @author Edward Raff
 */
public final class IntDoubleMap extends AbstractMap<Integer, Double>
{

    private float loadFactor;

    private int used = 0;
    private byte[] status;
    private int[] keys;
    private double[] table;

    public IntDoubleMap()
    {
        this(32);
    }

    public IntDoubleMap(int capacity)
    {
        this(capacity, 0.75f);
    }

    public IntDoubleMap(Map<Integer, Double> collection)
    {
        this(Math.max(1, collection.size()));
        for(Entry<Integer, Double> entry : collection.entrySet())
            put(entry.getKey(), entry.getValue());
    }

    public IntDoubleMap(int capacity, float loadFactor)
    {
        if(capacity < 1)
            throw new IllegalArgumentException("Capacity must be a positive value, not " + capacity);
        if(loadFactor <= 0 || loadFactor >= 1 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("loadFactor must be in (0, 1), not " + loadFactor);
        this.loadFactor = loadFactor;

        int size = getNextPow2TwinPrime((int) Math.max(capacity/loadFactor, 4));
        status = new byte[size];
        keys = new int[size];
        table = new double[size];
    }

    @Override
    public int size()
    {
        return used;
    }

    public int[] getRawKeyTable()
    {
        return keys;
    }

    public double[] getRawValueTable()
    {
        return table;
    }

    public byte[] getRawStatusTable()
    {
        return status;
    }

    @Override
    public Double put(Integer key, Double value)
    {
        double prev = put(key.intValue(), value.doubleValue());
        if(Double.isNaN(prev))
            return null;
        else
            return prev;
    }

    public double put(int key, double value)
    {
        if(Double.isNaN(value))
            throw new IllegalArgumentException("NaN is not an allowable value");
        long pair_index = getIndex(key);
        int deletedIndex = (int) (pair_index >>> 32);
        int valOrFreeIndex = (int) (pair_index & INT_MASK);

        double prev;
        if(status[valOrFreeIndex] == OCCUPIED)//easy case
        {
            prev = table[valOrFreeIndex];
            table[valOrFreeIndex] = value;
            return prev;
        }
        //else, not present
        prev = Double.NaN;
        int i = valOrFreeIndex;
        if(deletedIndex >= 0)//use occupied spot instead
            i = deletedIndex;

        status[i] = OCCUPIED;
        keys[i] = key;
        table[i] = value;
        used++;

        enlargeIfNeeded();

        return prev;
    }

    /**
     *
     * @param key the key whose associated value is to be incremented. All
     * non-present keys behave as having an implicit value of zero, in which
     * case the delta value is directly inserted into the map.
     * @param delta the amount by which to increment the key's stored value.
     * @return the new value stored for the given key
     */
    public double increment(int key, double delta)
    {
        if(Double.isNaN(delta))
            throw new IllegalArgumentException("NaN is not an allowable value");

        long pair_index = getIndex(key);
        int deletedIndex = (int) (pair_index >>> 32);
        int valOrFreeIndex = (int) (pair_index & INT_MASK);

        if(status[valOrFreeIndex] == OCCUPIED)//easy case
            return (table[valOrFreeIndex] += delta);
        //else, not present
        double toReturn;
        int i = valOrFreeIndex;
        if(deletedIndex >= 0)//use occupied spot instead
            i = deletedIndex;

        status[i] = OCCUPIED;
        keys[i] = key;
        toReturn = table[i] = delta;
        used++;

        enlargeIfNeeded();

        return toReturn;
    }

    /**
     * Returns the value to which the specified key is mapped, or
     * {@link Double#NaN} if this map contains no mapping for the key.
     *
     * @param key the key whose associated value is to be returned
     * @return the value to which the specified key is mapped, or
     * {@link Double#NaN} if this map contains no mapping for the key
     */
    public double get(int key)
    {
        long pair_index = getIndex(key);
        int valOrFreeIndex = (int) (pair_index & INT_MASK);

        if(status[valOrFreeIndex] == OCCUPIED)//easy case
            return table[valOrFreeIndex];
        //else, return NaN for missing
        return Double.NaN;
    }

    @Override
    public Double get(Object key)
    {
        if(key == null)
            return null;

        if(key instanceof Integer)
        {
            double d = get( ((Integer)key).intValue());
            if(Double.isNaN(d))
                return null;
            return d;
        }
        else
            throw new ClassCastException("Key not of integer type");
    }

    @Override
    public Double remove(Object key)
    {
        if(key instanceof Integer)
        {
            double oldValue = remove(((Integer)key).intValue());
            if(Double.isNaN(oldValue))
                return null;
            else
                return oldValue;
        }

        return null;
    }

    /**
     *
     * @param key
     * @return the old value stored for this key, or {@link Double#NaN} if the
     * key was not present in the map
     */
    public double remove(int key)
    {
        long pair_index = getIndex(key);
        int valOrFreeIndex = (int) (pair_index & INT_MASK);
        if(status[valOrFreeIndex] == EMPTY)//ret index is always EMPTY or OCCUPIED
            return Double.NaN;
        //else
        double toRet = table[valOrFreeIndex];
        status[valOrFreeIndex] = DELETED;
        used--;
        return toRet;
    }

    @Override
    public void clear()
    {
        used = 0;
        Arrays.fill(status, EMPTY);
    }

    private void enlargeIfNeeded()
    {
        if(used < keys.length*loadFactor)
            return;
        //enlarge
        final byte[] oldSatus = status;
        final int[] oldKeys = keys;
        final double[] oldTable = table;

        int newSize = getNextPow2TwinPrime(status.length*3/2);//it will actually end up doubling in size since we have twin primes spaced that was
        status = new byte[newSize];
        keys = new int[newSize];
        table = new double[newSize];

        used = 0;
        for(int oldIndex = 0; oldIndex < oldSatus.length; oldIndex++)
            if(oldSatus[oldIndex] == OCCUPIED)
                put(oldKeys[oldIndex], oldTable[oldIndex]);
    }

    @Override
    public boolean containsKey(Object key)
    {
        if(key instanceof Integer)
            return containsKey( ((Integer)key).intValue());
        else
            return false;
    }

    public boolean containsKey(int key)
    {
        int index = (int) (getIndex(key) & INT_MASK);
        return status[index] == OCCUPIED;//would be FREE if we didn't have the key
    }

    private final static long EXTRA_INDEX_INFO = ((long)Integer.MIN_VALUE) << 32;

    /**
     * Gets the index of the given key. Based on that {@link #status} variable,
     * the index is either the location to insert OR the location of the key.
     *
     * This method returns 2 integer table in the long. The lower 32 bits are
     * the index that either contains the key, or is the first empty index.
     *
     * The upper 32 bits is the index of the first position marked as
     * {@link #DELETED} either {@link Integer#MIN_VALUE} if no position was
     * marked as DELETED while searching.
     *
     * @param key they key to search for
     * @return the mixed long containing the index of the first DELETED position
     * and the position that the key is in or the first EMPTY position found
     */
    private long getIndex(int key)
    {
        long extraInfo = EXTRA_INDEX_INFO;
        //D1
        final int hash = h(key) & INT_MASK;
        int i = hash % keys.length;

        //D2
        int satus_i = status[i];
        if((keys[i] == key && satus_i != DELETED) || satus_i == EMPTY)
            return extraInfo | i;
        if(extraInfo == EXTRA_INDEX_INFO && satus_i == DELETED)
            extraInfo = ((long)i) << 32;

        //D3
        final int c = 1 + (hash % (keys.length -2));

        while(true)//this loop will terminate
        {
            //D4
            i -= c;
            if(i < 0)
                i += keys.length;
            //D5
            satus_i = status[i];
            if( (keys[i] == key && satus_i != DELETED) || satus_i == EMPTY)
                return extraInfo | i;
            if(extraInfo == EXTRA_INDEX_INFO && satus_i == DELETED)
                extraInfo = ((long)i) << 32;
        }
    }

    /**
     * Returns a non-negative hash value
     * @param key
     * @return
     */
    public static int h(int key)
    {
        //http://stackoverflow.com/questions/664014/what-integer-hash-function-are-good-that-accepts-an-integer-hash-key
        key = ((key >>> 16) ^ key ) & 0x45f9f3b;
        key = ((key >>> 16) ^ key ) & 0x45f9f3b;
        key = ((key >>> 16) ^ key ) ;
        return key;
    }

    @Override
    public Set<Entry<Integer, Double>> entrySet()
    {
        return new EntrySet(this);
    }

    /**
     * EntrySet class supports remove operations
     */
    private final class EntrySet extends AbstractSet<Entry<Integer, Double>>
    {
        final IntDoubleMap parentRef;

        public EntrySet(IntDoubleMap parent)
        {
            this.parentRef = parent;
        }

        @Override
        public Iterator<Entry<Integer, Double>> iterator()
        {
            //find the first starting inded
            int START = 0;
            while(START < status.length && status[START] != OCCUPIED)
                START++;
            if(START == status.length)
                return Collections.emptyIterator();
            final int startPos = START;

            return new Iterator<Entry<Integer, Double>>()
            {
                int pos = startPos;
                int prevPos = -1;

                @Override
                public boolean hasNext()
                {
                    return pos < status.length;
                }

                @Override
                public Entry<Integer, Double> next()
                {
                    //final int make so that object remains good after we call next again
                    final int oldPos = prevPos = pos++;
                    //find next
                    while (pos < status.length && status[pos] != OCCUPIED)
                        pos++;
                    //and return new object
                    return new Entry<Integer, Double>()
                    {

                        @Override
                        public Integer getKey()
                        {
                            return keys[oldPos];
                        }

                        @Override
                        public Double getValue()
                        {
                            return table[oldPos];
                        }

                        @Override
                        public Double setValue(Double value)
                        {
                            double old = table[oldPos];
                            table[oldPos] = value;
                            return old;
                        }
                    };
                }

                @Override
                public void remove()
                {
                    //its ok to just call remove b/c nothing is re-ordered when we remove an element, we just set the status to DELETED
                    parentRef.remove(keys[prevPos]);
                }
            };
        }

        @Override
        public int size()
        {
            return used;
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
package pubsub

import (
	"log"
	"time"
)

type Channel struct {
	record        bool
	history       []interface{}
	timeout       time.Duration
	closed        chan bool
	broadcast     chan interface{}
	subscribe     chan *Subscription
	unsubscribe   chan *Subscription
	subscriptions map[*Subscription]bool
}

func NewChannel(opts *Opts) *Channel {
	return &Channel{
		timeout:       opts.Timeout,
		record:        opts.Record,
		history:       make([]interface{}, 0),
		closed:        make(chan bool),
		broadcast:     make(chan interface{}),
		subscribe:     make(chan *Subscription),
		unsubscribe:   make(chan *Subscription),
		subscriptions: make(map[*Subscription]bool),
	}
}

func (c *Channel) Publish(data interface{}) {
	go func() { c.broadcast <- data }()
}

func (c *Channel) Subscribe() *Subscription {
	s := NewSubscription(c)
	c.subscribe <- s
	return s
}

func (c *Channel) Close() {
	go func() { c.closed <- true }()
}

func (c *Channel) start() {
	// make sure we don't bring down the application
	// if somehow we encounter a nil pointer or some
	// other unexpected behavior.
	defer func() {
		if r := recover(); r != nil {
			log.Println("recoved from panic", r)
		}
	}()

	// timeout the channel after N duration
	// ignore the timeout if set to 0
	var timeout <-chan time.Time
	if c.timeout > 0 {
		timeout = time.After(c.timeout)
	}

	for {
		select {

		case sub := <-c.unsubscribe:
			delete(c.subscriptions, sub)
			close(sub.send)

		case sub := <-c.subscribe:
			c.subscriptions[sub] = true

			// if we are recording the output
			// we should send it to the subscriber
			// upon first connecting.
			if c.record && len(c.history) > 0 {
				history := make([]interface{}, len(c.history))
				copy(history, c.history)
				go replay(sub, history)
			}

		case msg := <-c.broadcast:
			// if we are recording the output, append
			// the message to the history
			if c.record {
				c.history = append(c.history, msg)
			}

			// loop through each subscription and
			// send the message.
			for sub := range c.subscriptions {
				select {
				case sub.send <- msg:
					// do nothing
					//default:
					//	log.Println("subscription closed in inner select")
					//	sub.Close()
				}
			}

		case <-timeout:
			log.Println("subscription's timedout channel received message")
			c.Close()

		case <-c.closed:
			log.Println("subscription's close channel received message")
			c.stop()
			return
		}
	}
}

func replay(s *Subscription, history []interface{}) {
	defer func() {
		if r := recover(); r != nil {
			log.Println("recoved from panic", r)
		}
	}()

	for _, msg := range history {
		s.send <- msg
	}
}

func (c *Channel) stop() {
	for sub := range c.subscriptions {
		sub.Close()
	}
}


text:
package org.gluu.oxauth.model.crypto;

import org.apache.commons.lang.StringUtils;
import org.gluu.oxauth.model.common.WebKeyStorage;
import org.gluu.oxauth.model.configuration.AppConfiguration;

/**
 * @author Javier Rojas Blum
 * @version April 25, 2017
 */
public class CryptoProviderFactory {

    private static OxAuthCryptoProvider keyStoreProvider = null;

    public static AbstractCryptoProvider getCryptoProvider(AppConfiguration configuration) throws Exception {
        AbstractCryptoProvider cryptoProvider = null;
        WebKeyStorage webKeyStorage = configuration.getWebKeysStorage();
        if (webKeyStorage == null) {
            return null;
        }

        switch (webKeyStorage) {
            case KEYSTORE:
                cryptoProvider = getKeyStoreProvider(configuration);

                break;
            case PKCS11:
                cryptoProvider = new OxElevenCryptoProvider(
                        configuration.getOxElevenGenerateKeyEndpoint(),
                        configuration.getOxElevenSignEndpoint(),
                        configuration.getOxElevenVerifySignatureEndpoint(),
                        configuration.getOxElevenDeleteKeyEndpoint(),
                        configuration.getOxElevenTestModeToken());
                break;
        }

        if (configuration.getKeyRegenerationEnabled()) { // set interval only if re-generation is enabled
            cryptoProvider.setKeyRegenerationIntervalInDays(configuration.getKeyRegenerationInterval() / 24);
        }
        return cryptoProvider;
    }

    private static AbstractCryptoProvider getKeyStoreProvider(AppConfiguration configuration) throws Exception {
        if (keyStoreProvider != null &&
                StringUtils.isNotBlank(keyStoreProvider.getKeyStoreFile()) &&
                StringUtils.isNotBlank(keyStoreProvider.getKeyStoreSecret()) &&
                StringUtils.isNotBlank(keyStoreProvider.getDnName()) &&
                keyStoreProvider.getKeyStoreFile().equals(configuration.getKeyStoreFile()) &&
                keyStoreProvider.getKeyStoreSecret().equals(configuration.getKeyStoreSecret()) &&
                keyStoreProvider.getDnName().equals(configuration.getDnName())) {
            return keyStoreProvider;
        }

        return keyStoreProvider = new OxAuthCryptoProvider(configuration.getKeyStoreFile(), configuration.getKeyStoreSecret(), configuration.getDnName(), configuration.getRejectJwtWithNoneAlg(), configuration.getKeySelectionStrategy());
    }

    public static void reset() {
        keyStoreProvider = null;
    }
}


text:
/**
 * The Resource File Provider.
 */
package org.apache.commons.vfs2.provider.res;


text:
package gwt.material.design.demo.client.application.addins.overlay;

import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.View;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.presenter.slots.NestedSlot;
import com.gwtplatform.mvp.client.proxy.ProxyPlace;
import gwt.material.design.demo.client.application.ApplicationPresenter;
import gwt.material.design.demo.client.event.SetPageTitleEvent;
import gwt.material.design.demo.client.place.NameTokens;

public class OverlayPresenter extends Presenter<OverlayPresenter.MyView, OverlayPresenter.MyProxy> {
    interface MyView extends View {
    }

    @NameToken(NameTokens.overlay)
    @ProxyCodeSplit
    interface MyProxy extends ProxyPlace<OverlayPresenter> {
    }

    @Inject
    OverlayPresenter(
            EventBus eventBus,
            MyView view,
            MyProxy proxy) {
        super(eventBus, view, proxy, ApplicationPresenter.SLOT_MAIN);

    }

    @Override
    protected void onReveal() {
        super.onReveal();
        SetPageTitleEvent.fire("Overlay", "Provides a meaningful transition of source widget to popup or overlay panel.", "addins/scrollfire/OverlayView", "", this);
    }

}


text:
package net.md_5.bungee.util;

import net.md_5.bungee.Util;
import org.junit.Assert;
import org.junit.Test;

import java.util.UUID;

import static org.junit.Assert.*;

public class UtilTest {

    private static final String FULL_UUID = "982709b9-6fd8-4627-929d-e7d3b91166ea";
    private static final String MOJANG_UUID = "982709b96fd84627929de7d3b91166ea";

    @Test
    public void testGetUUID() throws Exception {
        Assert.assertEquals(FULL_UUID, Util.getUUID(MOJANG_UUID).toString());
    }

    @Test
    public void testGetMojangUUID() throws Exception {
        assertEquals(MOJANG_UUID, Util.getMojangUUID(UUID.fromString(FULL_UUID)));
    }
}


text:
from twisted.internet.defer import inlineCallbacks

from vumi.transports.smpp import SmppTransceiverTransport

class SmsghSmppTransport(SmppTransceiverTransport):

    @inlineCallbacks
    def handle_outbound_message(self, message):
        if 'customized_id' in message['transport_metadata']:
            message['from_addr'] = message['transport_metadata']['customized_id']
        yield super(SmsghSmppTransport, self).handle_outbound_message(message)


text:
pyaviosys8800
=============

Python USB driver for the [Aviosys USB Net Power 8800](http://www.aviosys.com/8800.html) switch.

With thanks to [Lance](http://raspberrypi.stackexchange.com/users/1237/lance) and [this](http://raspberrypi.stackexchange.com/a/1685/19199) answer on StackExchange.

## Dependencies:

[pyusb](http://walac.github.io/pyusb/)

pyusb is dependent on libusb.

## Installation:

To install libusb on Mac OS X using homebrew use:

    brew install libusb

## Testing:

There is a small test program that allows you to turn the switch on and off via the command line.

    git clone git@github.com:yellowfeather/pyaviosys8800.git
    cd pyaviosys8800
    python test.py


text:
<?php
/**
 * Created by PhpStorm.
 * User: fernandobritofl
 * Date: 4/21/15
 * Time: 4:58 PM
 */

namespace veyselsahin\l5generators\Makes;

use Illuminate\Filesystem\Filesystem;
use veyselsahin\l5generators\Commands\ScaffoldMakeCommand;
use veyselsahin\l5generators\Migrations\SchemaParser;
use veyselsahin\l5generators\Migrations\SyntaxBuilder;
use Illuminate\Support\Facades\Cache;

class MakeView
{
    use MakerTrait;

    protected $scaffoldCommandObj;
    protected $viewName;

    public function __construct(ScaffoldMakeCommand $scaffoldCommand, Filesystem $files, $viewName)
    {
        $this->files = $files;
        $this->scaffoldCommandObj = $scaffoldCommand;
        $this->viewName = $viewName;

        $this->start();
    }

    private function start()
    {
        $this->generateView($this->viewName); // index, show, edit and create
    }

    protected function generateView($nameView = 'index')
    {
        // Get path
        $path = $this->getPath($this->scaffoldCommandObj->getObjName('name'), 'view-' . $nameView);

        // Create directory
        $this->makeDirectory($path);

        if ($this->files->exists($path))
        {
            unlink($path);
        }

        $this->files->put($path, $this->compileViewStub($nameView));

    }

    /**
     * Compile the migration stub.
     *
     * @param $nameView
     * @return string
     * @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
     */
    protected function compileViewStub($nameView)
    {
        $stub = $this->files->get(__DIR__ . '/../stubs/html_assets/' . $nameView . '.stub');

        if ($nameView == 'show')
        {
            // show.blade.php
            $this->replaceName($stub)
                ->replaceSchemaShow($stub);

        } elseif ($nameView == 'edit')
        {
            // edit.blade.php
            $this->replaceName($stub)
                ->replaceSchemaEdit($stub);

        } elseif ($nameView == 'create')
        {
            // edit.blade.php
            $this->replaceName($stub)
                ->replaceSchemaCreate($stub);

        } else
        {
            // index.blade.php
            $this->replaceName($stub)
                ->replaceSchemaIndex($stub);
        }

        return $stub;
    }

    /**
     * Replace the class name in the stub.
     *
     * @param  string $stub
     * @return $this
     */
    protected function replaceName(&$stub)
    {
        //$this->scaffoldCommandObj->getObjName('names')  tekil almak ıcın kucuk name ile degistirildi
        $stub = str_replace('{{Class}}', $this->scaffoldCommandObj->getObjName('Names'), $stub);
        $stub = str_replace('{{class}}', $this->scaffoldCommandObj->getObjName('name'), $stub);
        $stub = str_replace('{{classSingle}}', $this->scaffoldCommandObj->getObjName('names'), $stub);

        return $this;
    }

    /**
     * Replace the schema for the index.stub.
     *
     * @param  string $stub
     * @return $this
     */
    protected function replaceSchemaIndex(&$stub)
    {

        $schemaArray = [];
        if ($schema = $this->scaffoldCommandObj->option('schema'))
        {
            $schemaArray = (new SchemaParser)->parse($schema);
        }

        $serialize_results = Cache::get("table_serialize_results");

        $m = $this->scaffoldCommandObj->getMeta();

        $table_columns = [];//ilgili tablonun kolonlarını ıcerek

        foreach ($serialize_results as $res)
        {

            if ($res["table3name"] == $m["table"])
            {
                $table_columns = $res;
            }
        }

        unset($table_columns["table1name"]);
        unset($table_columns["table2name"]);
        unset($table_columns["table3name"]);

        $newSchemeArray = [];
        foreach ($table_columns as $key => $column)
        {
            for ($i = 0; $i < count($schemaArray); $i++)
            {
                if ($schemaArray[$i]["name"] == $key)
                {
                    if (isset($column["listeyee"]) && ($column["listeyee"] == true || $column["listeyee"] == "on"))
                    {
                        $newSchemeArray[] = $schemaArray[$i];
                    }
                }
            }
        }

        $schemaArray = $newSchemeArray;
        // Create view index header fields
        $schema = (new SyntaxBuilder)->create($schemaArray, $this->scaffoldCommandObj->getMeta(), 'view-index-header');
        $stub = str_replace('{{header_fields}}', $schema, $stub);

        // Create view index content fields
        $schema = (new SyntaxBuilder)->create($schemaArray, $this->scaffoldCommandObj->getMeta(), 'view-index-content');
        $stub = str_replace('{{content_fields}}', $schema, $stub);

        return $this;
    }

    /**
     * Replace the schema for the show.stub.
     *
     * @param  string $stub
     * @return $this
     */
    protected function replaceSchemaShow(&$stub)
    {
        $schemaArray=[];
        if ($schema = $this->scaffoldCommandObj->option('schema'))
        {
            $schemaArray = (new SchemaParser)->parse($schema);
        }

        // Create view index content fields
        $schema = (new SyntaxBuilder)->create($schemaArray, $this->scaffoldCommandObj->getMeta(), 'view-show-content');
        $stub = str_replace('{{content_fields}}', $schema, $stub);

        return $this;
    }

    /**
     * Replace the schema for the edit.stub.
     *
     * @param  string $stub
     * @return $this
     */
    private function replaceSchemaEdit(&$stub)
    {

        if ($schema = $this->scaffoldCommandObj->option('schema'))
        {
            $schemaArray = (new SchemaParser)->parse($schema);
        }

        $serialize_results = Cache::get("table_serialize_results");

        $m = $this->scaffoldCommandObj->getMeta();

        $table_columns = [];//ilgili tablonun kolonlarını ıcerek

        foreach ($serialize_results as $res)
        {

            if ($res["table3name"] == $m["table"])
            {
                $table_columns = $res;
            }
        }

        unset($table_columns["table1name"]);
        unset($table_columns["table2name"]);
        unset($table_columns["table3name"]);

        $newSchemeArray = [];
        foreach ($table_columns as $key => $column)
        {
            for ($i = 0; $i < count($schemaArray); $i++)
            {
                if ($schemaArray[$i]["name"] == $key)
                {
                    if (isset($column["formae"]) && ($column["formae"] == true || $column["formae"] == "on"))
                    {
                        $newSchemeArray[] = $schemaArray[$i];
                    }
                }
            }
        }

        $schemaArray = $newSchemeArray;

        // Create view index content fields
        $schema = (new SyntaxBuilder)->create($schemaArray, $this->scaffoldCommandObj->getMeta(), 'view-edit-content');
        $stub = str_replace('{{content_fields}}', $schema, $stub);

        return $this;

    }

    /**
     * Replace the schema for the edit.stub.
     *
     * @param  string $stub
     * @return $this
     */
    private function replaceSchemaCreate(&$stub)
    {

        if ($schema = $this->scaffoldCommandObj->option('schema'))
        {
            $schemaArray = (new SchemaParser)->parse($schema);
        }

        $serialize_results = Cache::get("table_serialize_results");

        $m = $this->scaffoldCommandObj->getMeta();

        $table_columns = [];//ilgili tablonun kolonlarını ıcerek

        foreach ($serialize_results as $res)
        {

            if ($res["table3name"] == $m["table"])
            {
                $table_columns = $res;
            }
        }

        unset($table_columns["table1name"]);
        unset($table_columns["table2name"]);
        unset($table_columns["table3name"]);

        $newSchemeArray = [];
        foreach ($table_columns as $key => $column)
        {
            for ($i = 0; $i < count($schemaArray); $i++)
            {
                if ($schemaArray[$i]["name"] == $key)
                {
                    if (isset($column["formae"]) && ($column["formae"] == true || $column["formae"] == "on"))
                    {
                        $newSchemeArray[] = $schemaArray[$i];
                    }
                }
            }
        }

        $schemaArray = $newSchemeArray;

        // Create view index content fields
        $schema = (new SyntaxBuilder)->create($schemaArray, $this->scaffoldCommandObj->getMeta(), 'view-create-content');
        $stub = str_replace('{{content_fields}}', $schema, $stub);

        return $this;

    }

}


text:
layout: post
title: 230. Kth Smallest Element in a BST
subtitle: Medium
author: Bin Li
tags: [Coding, LeetCode, Medium, Tree]
image:
comments: true
published: true
---

## Description

Given a binary search tree, write a function `kthSmallest` to find the **k**th smallest element in it.

**Note:**
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.

**Example 1:**

```
Input: root = [3,1,4,null,2], k = 1
   3
  / \
 1   4
  \
   2
Output: 1
```

**Example 2:**

```
Input: root = [5,3,6,2,4,null,null,1], k = 3
       5
      / \
     3   6
    / \
   2   4
  /
 1
Output: 3
```

**Follow up:**
What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine?

## Solutions
### 1. Inorder

```python
# Time: O(logn)
# Space: O(n)
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def kthSmallest(self, root: TreeNode, k: int) -> int:
        inorder = []
        node = root
        stack = []
        while node or stack:
            while node:
                stack.append(node)
                node = node.left
            node = stack.pop()
            inorder.append(node.val)
            if len(inorder) >= k:
                return inorder[-1]
            node = node.right
        return -1

# 91/91 cases passed (48 ms)
# Your runtime beats 80.57 % of python3 submissions
# Your memory usage beats 98.18 % of python3 submissions (16.8 MB)
```

## References
1. [230. Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/)


text:
using System;

namespace Soloco.EventStore.Core.Infrastructure
{
    public interface IConsole
    {
        void Log(ConsoleColor color, string message, params object[] arguments);
        void Log(string message, params object[] arguments);
        void Green(string message, params object[] arguments);
        void Timings(string message, params object[] arguments);
        void Magenta(string message, params object[] arguments);
        void Cyan(string message, params object[] arguments);
        void Error(string message, params object[] arguments);
        void Important(string message, params object[] arguments);

        void ReadKey(string message = null);
    }
}


text:
'use strict';

const {ipcMain} = require('electron');
const portfinder = require('portfinder');
const express = require('express');
const querystring = require('querystring');
const vga_module = require('./vga-module');
const accountController = require('./controller/account');
const serverController = require('./controller/server');
const classeController = require('./controller/classe');
const characterController = require('./controller/character');
const settingController = require('./controller/setting');
const teamController = require('./controller/team');
const log = require('./log-module').getLog();
const constants = require('./constants');

const server = express();
portfinder.getPort((err, port) => {
	ipcMain.on(constants.asynchronousGetPort, (event, arg) => {
		event.sender.send(constants.asynchronousGetPortReply, port);
	});

	server.get('/', async (request, response) => {
		//account
		if (request.query.ajaxAccount != undefined || request.query.removeAccount != undefined || request.query.editAccount != undefined) {
			if (request.query.removeAccount != undefined) {
				accountController.remove(request.query.removeAccount);
			}
			if (request.query.editAccount != undefined) {
				response.send(await accountController.findOneById(request.query.editAccount));
			} else {
				response.send(await accountController.findAllForDT());
			}
		}
		if (request.query.getAllAccountsNames != undefined) {
			response.send(await accountController.findAllAccountsNames());
		}
		//character
		if (request.query.ajaxCharacter != undefined || request.query.removeCharacter != undefined || request.query.editCharacter != undefined) {
			if (request.query.removeCharacter != undefined) {
				characterController.remove(request.query.removeCharacter);
			}
			if (request.query.editCharacter != undefined) {
				response.send(await characterController.findOneById(request.query.editCharacter));
			} else {
				response.send(await characterController.findAllForDT());
			}
		}
		if (request.query.getAllCharacterNames != undefined) {
			response.send(await characterController.findAllCharacterNames());
		}
		//setting
		if (request.query.ajaxSetting != undefined) {
			response.send(await settingController.getAllSettingsForDT());
		}
		if (request.query.editSetting != undefined) {
			response.send(await settingController.findOneById(request.query.editSetting));

		}
		//team
		if (request.query.ajaxTeam != undefined) {
			response.send(await teamController.getAllTeamsForDT());
		}
		//server
		if (request.query.getAllServersNames != undefined) {
			response.send(await serverController.findAllServersNames());
		}
		//classes
		if (request.query.getAllClassesNames != undefined) {
			response.send(await classeController.findAllClassesNames());
		}
		//vga
		if (request.query.getAllResolutions != undefined) {
			response.send(await vga_module.getAllResolutions());
		}
	});

	server.post('/', (request, response) => {
		let body = '';
		request.on('data', (data) => {
			body += data;
			if (body.length > 1e6) {
				request.connection.destroy();
			}
		});

		request.on('end', async function () {
			const post = querystring.parse(body);
			//account
			if (request.query.addAccount != undefined || request.query.editAccount != undefined) {
				if (request.query.addAccount != undefined) {
					response.send(await accountController.create(post));
				} else if (request.query.editAccount != undefined) {
					response.send(await accountController.update(request.query.editAccount, post));
				}
			}
			//char
			if (request.query.addCharacter != undefined || request.query.editCharacter != undefined) {
				if (request.query.addCharacter != undefined) {
					response.send(await characterController.create(post));
				} else if (request.query.editCharacter != undefined) {
					response.send(await characterController.update(request.query.editCharacter, post));
				}
			}
			if (request.query.importFromAppData != undefined) {
				response.send(await characterController.importFromAppData(post));
			}
			//team
			if (request.query.addTeam != undefined) {
				response.send(await teamController.create(post));
			}
			//setting
			if (request.query.editSetting != undefined) {
				response.send(settingController.update(request.query.editSetting, post));
			}
		});
	});

	server.listen(port, () => {
		log.info(constants.infoExpress, port);
	});
});


text:
set -u

if [ $# -ne 3 ]; then
    echo "Usage: "$0" [output_dir] [run_length] [trim_length]"
    exit
fi

output_dir=$1
run_length=$2
trim=$3

used_length=$((run_length - trim - trim))
unset run_length

cd $output_dir

#extract the average throughput from the trimmed part of each run to +tput files
for f in $(ls *+data); do
    base_file_name=$(echo $f | sed 's/+data//')

    #trim to run_length
    line_count=$(cat $f | wc -l)

    #ensure number of lines is enough we can trim and still have run_length data left
    if [[ $line_count -lt $((2 + used_length)) ]]; then
        echo; echo "SKIPPING $f: $line_count !< $((2 + used_length))"; echo;
        continue
    fi

    #skip first 2 lines because they aren't data
    #skip next $trim lines
    #then include the next $used_length lines
    #write that into the file+trim
    # also skip the lines related to errors

    trim_file=$base_file_name"+trim"
    cat $f | grep -v " retried 10 times " | grep -v "^$" | head -n $((2 + trim + used_length)) | tail -n $used_length > $trim_file

    #just care about throughput here, so:
    #  extract throughput
    #  total it
    #  average it
    # but we'll get all 4 kinds
    sum_lines='awk { sum = sum + $1 } END { print sum }'

    total_tput_ops=$(cat $trim_file | awk -F"," '{ print $2 }' | awk '{ sum = sum + $1 } END { print sum }')
    avg_tput_ops=$(echo "$total_tput_ops / $used_length" | bc)

    total_tput_keys=$(cat $trim_file | awk -F"," '{ print $3 }' | awk '{ sum = sum + $1 } END { print sum }')
    avg_tput_keys=$(echo "$total_tput_keys / $used_length" | bc)

    total_tput_cols=$(cat $trim_file | awk -F"," '{ print $4 }' | awk '{ sum = sum + $1 } END { print sum }')
    avg_tput_cols=$(echo "$total_tput_cols / $used_length" | bc)

    total_tput_bytes=$(cat $trim_file | awk -F"," '{ print $5 }' | awk '{ sum = sum + $1 } END { print sum }')
    avg_tput_bytes=$(echo "$total_tput_bytes / $used_length" | bc)

    echo $avg_tput_ops $avg_tput_keys $avg_tput_cols $avg_tput_bytes > $base_file_name"+tput"
done

#generate the +graph file from the +tput files
#format of files is XXX+control_var+data
graph_file="all+graph"
echo -n > ${graph_file}
for data_point in $(ls *+*+tput); do
    control_var=$(echo $data_point | awk -F"+" '{ print $2 }')
    all_tput=$(cat $data_point)
    echo -e "${control_var}\t${all_tput}" >> ${graph_file}
done
cat $graph_file | sort -n > tmp
mv tmp $graph_file


text:
<?php

class OmniwebShowtimes_AdminPageFramework_Form_View___Attribute_Fields extends OmniwebShowtimes_AdminPageFramework_Form_View___Attribute_FieldContainer_Base {
    public $sContext = 'fields';
    public $iFieldsCount = 0;
    public function __construct() {
        $_aParameters = func_get_args() + array($this->aArguments, $this->aAttributes, $this->iFieldsCount,);
        $this->aArguments = $_aParameters[0];
        $this->aAttributes = $_aParameters[1];
        $this->iFieldsCount = $_aParameters[2];
    }
    protected function _getAttributes() {
        return array('id' => $this->sContext . '-' . $this->aArguments['tag_id'], 'class' => 'omniweb-showtimes-' . $this->sContext . $this->getAOrB($this->aArguments['repeatable'], ' repeatable dynamic-fields', '') . $this->getAOrB($this->aArguments['sortable'], ' sortable dynamic-fields', ''), 'data-type' => $this->aArguments['type'], 'data-largest_index' => max(( int )$this->iFieldsCount - 1, 0), 'data-field_name_model' => $this->aArguments['_field_name_model'], 'data-field_name_flat' => $this->aArguments['_field_name_flat'], 'data-field_name_flat_model' => $this->aArguments['_field_name_flat_model'], 'data-field_tag_id_model' => $this->aArguments['_tag_id_model'], 'data-field_address' => $this->aArguments['_field_address'], 'data-field_address_model' => $this->aArguments['_field_address_model'],);
    }
}


text:
package org.gamepad4j.base;

import java.util.HashMap;
import java.util.Map;

import org.gamepad4j.AxisID;
import org.gamepad4j.ButtonID;
import org.gamepad4j.DpadDirection;
import org.gamepad4j.IAxis;
import org.gamepad4j.IButton;
import org.gamepad4j.IController;
import org.gamepad4j.IStick;
import org.gamepad4j.ITrigger;
import org.gamepad4j.StickID;
import org.gamepad4j.TriggerID;
import org.gamepad4j.util.Log;

/**
 * Base class for controller wrappers. Handles creation of buttons,
 * sticks, triggers and d-pad based on mapping configuration.
 *
 * @author Marcel Schoen
 * @version $Revision: $
 */
public abstract class AbstractBaseController implements IController {

	/** Stores the deviceID of this controller. */
	protected int deviceID = -1;

	/** Stores the vendorID of this controller. */
	protected int vendorID = -1;

	/** Stores the productID of this controller. */
	protected int productID = -1;

	/** Stores the description of this controller. */
	protected String description = "";

	/** Stores the last d-pad direction. */
	protected DpadDirection lastDirection = null;

	// ----------------------- d-pad -----------------------------

	/** Stores a map for the axes used by an analog d-pad */
	protected Map<AxisID, BaseAxis> dpadAxisMap = new HashMap<AxisID, BaseAxis>();

	// ----------------------- buttons ---------------------------

	/** Lookup map for buttons based on their type. */
	protected Map<ButtonID, IButton> buttonMap = new HashMap<ButtonID, IButton>();

	/** Lookup map for button aliases. */
	protected Map<ButtonID, IButton> buttonAliasMap = new HashMap<ButtonID, IButton>();

	/** Stores the buttons of this controller. */
	protected BaseButton[] buttons = null;

	// ----------------------- triggers ---------------------------

	/** Lookup map for buttons based on their type. */
	protected Map<TriggerID, ITrigger> triggerMap = new HashMap<TriggerID, ITrigger>();

	/** Stores the buttons of this controller. */
	protected BaseTrigger[] triggers = null;

	// ----------------------- sticks ---------------------------

	/** Lookup map for sticks based on their type. */
	protected Map<StickID, IStick> stickMap = new HashMap<StickID, IStick>();

	/** Stores the sticks of this controller. */
	protected BaseStick[] sticks = null;

	// ----------------------- axes (for triggers AND sticks) ---------------------------

	/** Stores the axes of this controller. */
	protected BaseAxis[] axes = null;

	/**
	 * Creates a controller wrapper.
	 *
	 * @param id The deviceID of the controller.
	 */
	protected AbstractBaseController(int deviceID) {
		this(deviceID, "");
	}

	/**
	 * Creates a controller wrapper.
	 *
	 * @param id The deviceID of the controller.
	 */
	protected AbstractBaseController(int deviceID, String description) {
		this.deviceID = deviceID;
		if(this.deviceID < 0) {
			throw new IllegalArgumentException("Device ID must be positive integer value.");
		}
		if(description != null) {
			this.description = description;
		}
	}

	/**
	 * Adds a button to the map of buttons.
	 *
	 * @param button The button to add.
	 */
	protected void addButton(IButton button) {
		this.buttonMap.put(button.getID(), button);
	}

	/* (non-Javadoc)
	 * @see org.gamepad4j.IController#getButton(int)
	 */
	@Override
	public IButton getButton(int buttonCode) {
		return this.buttons[buttonCode];
	}

	/* (non-Javadoc)
	 * @see org.gamepad4j.util.IController#getDescription()
	 */
	@Override
	public String getDescription() {
		return this.description;
	}

	/**
	 * Sets the description for this controller.
	 *
	 * @param description The description text.
	 */
	public void setDescription(String description) {
		this.description = description;
	}

	/* (non-Javadoc)
	 * @see org.gamepad4j.util.IController#getID()
	 */
	@Override
	public int getDeviceID() {
		return this.deviceID;
	}

	/**
	 * @param deviceID the deviceID to set
	 */
	public void setDeviceID(int deviceID) {
		this.deviceID = deviceID;
	}

	/*
	 * (non-Javadoc)
	 * @see org.gamepad4j.IController#getVendorID()
	 */
	@Override
	public int getVendorID() {
		return vendorID;
	}

	/**
	 * @param vendorID the vendorID to set
	 */
	public void setVendorID(int vendorID) {
		if(Log.debugEnabled) {
			Log.logger.debug("Set controller vendor ID: " + Integer.toHexString(vendorID));
		}
		this.vendorID = vendorID;
	}

	/*
	 * (non-Javadoc)
	 * @see org.gamepad4j.IController#getProductID()
	 */
	@Override
	public int getProductID() {
		return productID;
	}

	/**
	 * @param productID the productID to set
	 */
	public void setProductID(int productID) {
		if(Log.debugEnabled) {
			Log.logger.debug("Set controller product ID: " + Integer.toHexString(productID));
		}
		this.productID = productID;
	}

	/* (non-Javadoc)
	 * @see org.gamepad4j.IController#getDeviceIdentifier()
	 */
	@Override
	public long getDeviceTypeIdentifier() {
		if(this.vendorID == -1) {
			throw new IllegalArgumentException("Vendor ID not set for controller " + this.deviceID + " / " + this.description);
		}
		if(this.productID == -1) {
			throw new IllegalArgumentException("Product ID not set for controller " + this.deviceID + " / " + this.description);
		}
		return (vendorID << 16) + productID;
	}

	/* (non-Javadoc)
	 * @see org.gamepad4j.util.IController#getDpadDirectionOnce()
	 */
	@Override
	public DpadDirection getDpadDirectionOnce() {
		DpadDirection current = getDpadDirection();
		if(current != lastDirection) {
			lastDirection = current;
			return current;
		}
		return null;
	}

	/* (non-Javadoc)
	 * @see org.gamepad4j.util.IController#isButtonPressedOnce(org.gamepad4j.util.ButtonID)
	 */
	@Override
	public boolean isButtonPressedOnce(ButtonID buttonID) {
		return getButton(buttonID).isPressedOnce();
	}

	/* (non-Javadoc)
	 * @see org.gamepad4j.util.IController#getButtons()
	 */
	@Override
	public IButton[] getButtons() {
		return this.buttons;
	}

	/* (non-Javadoc)
	 * @see org.gamepad4j.IController#getDpadDirection()
	 */
	@Override
	public DpadDirection getDpadDirection() {
		int value = 0;
		if(this.dpadAxisMap.size() > 0) {
			// It's an analog axes d-pad
			BaseAxis xAxis = this.dpadAxisMap.get(AxisID.D_PAD_X);
			if(xAxis != null) {
				if(xAxis.getValue() == -1) {
					value += DpadDirection.LEFT.getValue();
				} else if(xAxis.getValue() == 1) {
					value += DpadDirection.RIGHT.getValue();
				}
			}
			BaseAxis yAxis = this.dpadAxisMap.get(AxisID.D_PAD_Y);
			if(yAxis != null) {
				if(yAxis.getValue() == -1) {
					value += DpadDirection.UP.getValue();
				} else if(yAxis.getValue() == 1) {
					value += DpadDirection.DOWN.getValue();
				}
			}
		} else {
			// It's a digital button d-pad
			IButton dpadUp = this.buttonMap.get(ButtonID.D_PAD_UP);
			IButton dpadRight = this.buttonMap.get(ButtonID.D_PAD_RIGHT);
			IButton dpadDown = this.buttonMap.get(ButtonID.D_PAD_DOWN);
			IButton dpadLeft = this.buttonMap.get(ButtonID.D_PAD_LEFT);
			if(dpadUp != null && dpadUp.isPressed()) {
				value += DpadDirection.UP.getValue();
			}
			if(dpadDown != null && dpadDown.isPressed()) {
				value += DpadDirection.DOWN.getValue();
			}
			if(dpadLeft != null && dpadLeft.isPressed()) {
				value += DpadDirection.LEFT.getValue();
			}
			if(dpadRight != null && dpadRight.isPressed()) {
				value += DpadDirection.RIGHT.getValue();
			}
		}
		return DpadDirection.fromIntValue(value);
	}

	/* (non-Javadoc)
	 * @see org.gamepad4j.IController#getTriggers()
	 */
	@Override
	public ITrigger[] getTriggers() {
		return this.triggers;
	}

	/* (non-Javadoc)
	 * @see org.gamepad4j.IController#getTrigger(org.gamepad4j.TriggerID)
	 */
	@Override
	public ITrigger getTrigger(TriggerID triggerID) {
		return this.triggerMap.get(triggerID);
	}

	/* (non-Javadoc)
	 * @see org.gamepad4j.util.IController#getButton(org.gamepad4j.util.ButtonID)
	 */
	@Override
	public IButton getButton(ButtonID buttonID) {
		IButton button = this.buttonMap.get(buttonID);
		if(button == null) {
			button = this.buttonAliasMap.get(buttonID);
		}
		return button;
	}

	/* (non-Javadoc)
	 * @see org.gamepad4j.util.IController#isButtonPressed(org.gamepad4j.util.ButtonID)
	 */
	@Override
	public boolean isButtonPressed(ButtonID buttonID) {
		return this.buttonMap.get(buttonID).isPressed();
	}

	/* (non-Javadoc)
	 * @see org.gamepad4j.util.IController#getAnalogButtonPressure(org.gamepad4j.util.ButtonID)
	 */
	@Override
	public float getTriggerPressure(TriggerID buttonID)
			throws IllegalArgumentException {
		return this.triggerMap.get(buttonID).analogValue();
	}

	/* (non-Javadoc)
	 * @see org.gamepad4j.IController#getSticks()
	 */
	@Override
	public IStick[] getSticks() {
		return this.sticks;
	}

	/* (non-Javadoc)
	 * @see org.gamepad4j.IController#getStick(org.gamepad4j.StickID)
	 */
	@Override
	public IStick getStick(StickID stick) throws IllegalArgumentException {
		return stickMap.get(stick);
	}

	/*
	 * (non-Javadoc)
	 * @see org.gamepad4j.IController#getAxes()
	 */
	@Override
	public IAxis[] getAxes() {
		if(this.axes == null) {
			this.axes = new BaseAxis[0];
		}
		return this.axes;
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<style-scheme version="1.0" name="Base16 Eighties">
  <!--
  base16-qtcreator (https://github.com/ilpianista/base16-qtcreator)
  by Chris Kempson (http://chriskempson.com)
  Eighties scheme by Chris Kempson (http://chriskempson.com)
  -->

  <!-- main colors, skipping one of attributes (backgroud/foreground) will use color from here -->
  <style name="Text" foreground="#d3d0c8" background="#2d2d2d"/>

  <!-- it will be underlined by default -->
  <style name="Link"/>

  <!-- selection, current line, search, matching brackets -->
  <style name="Selection" background="#a09f93"/>
  <style name="CurrentLine" background="#747369"/>
  <style name="LineNumber" foreground="#747369"/>
  <style name="CurrentLineNumber" foreground="#a09f93" bold="true"/>
  <style name="SearchResult" background="#393939"/>
  <style name="Parentheses" background="#515151" />
  <style name="ParenthesesMismatch" background="#cc99cc" />

  <!-- Selection whilst searching in it -->
  <style name="SearchScope" foreground="#f2f0ec" background="#747369"/>

  <!-- word (symbol) under cursor: background - color of marking frame, foreground - ignored -->
  <style name="Occurrences" background="#747369"/>
  <style name="Occurrences.Rename" background="#a09f93"/>
  <!-- unused variable: foreground - color of underlining -->
  <style name="Occurrences.Unused" foreground="#f99157"/>

  <!-- language primitives -->
  <style name="Number" foreground="#f99157"/>
  <style name="String" foreground="#99cc99"/>
  <style name="Keyword" foreground="#cc99cc"/>
  <style name="Operator" foreground="#d3d0c8"/>
  <style name="Preprocessor" foreground="#6699cc"/>
  <style name="Label" foreground="#f2777a"/>

  <!-- types, classes -->
  <style name="Type" foreground="#ffcc66"/>
  <style name="PrimitiveType" foreground="#cc99cc"/>

  <!-- functions, methods -->
  <style name="Function" foreground="#6699cc"/>
  <style name="VirtualMethod" foreground="#6699cc" italic="true"/>

  <!-- variables -->
  <style name="Field" foreground="#e8e6df"/>
  <style name="Local" foreground="#d3d0c8"/>
  <style name="Global" foreground="#d3d0c8"/>
  <style name="Static" foreground="#d3d0c8"/>
  <style name="JsScopeVar" foreground="#d3d0c8" italic="true"/>
  <style name="JsImportVar" foreground="#d3d0c8" italic="true"/>
  <style name="JsGlobalVar" foreground="#d3d0c8" italic="true"/>

  <!-- whitespace -->
  <style name="VisualWhitespace" foreground="#515151"/>

  <!-- comments -->
  <style name="Comment" foreground="#747369"/>
  <style name="DisabledCode" foreground="#747369"/>
  <style name="Doxygen.Comment" foreground="#747369"/>
  <style name="Doxygen.Tag" foreground="#747369"/>

  <!-- QML -->
  <style name="QmlTypeId" foreground="#cc99cc"/>
  <style name="Binding" foreground="#f2777a"/>
  <style name="QmlExternalId" foreground="#6699cc" italic="true"/>
  <style name="QmlExternalObjectProperty" foreground="#6699cc" italic="true"/>
  <style name="QmlLocalId" italic="true"/>
  <style name="QmlRootObjectProperty" italic="true"/>
  <style name="QmlScopeObjectProperty" italic="true"/>
  <style name="QmlStateName" italic="true"/>

  <!-- inline diff -->
  <style name="DiffFile" foreground="#cc99cc"/>
  <style name="DiffLocation" foreground="#6699cc"/>
  <style name="AddedLine" foreground="#99cc99"/>
  <style name="RemovedLine" foreground="#ffcc66"/>
  <style name="LogChangeLine" foreground="#f2777a"/>

  <!-- side-by-side diff -->
  <style name="DiffFileLine" foreground="#cc99cc"/>
  <style name="DiffContextLine" foreground="#6699cc"/>
  <style name="DiffSourceLine" foreground="#99cc99"/>
  <style name="DiffSourceChar" foreground="#ffcc66" background="#393939"/>
  <style name="DiffDestLine" foreground="#99cc99"/>
  <style name="DiffDestChar" foreground="#ffcc66" background="#393939"/>

  <!-- errors, warnings -->
  <style name="Error" underlineColor="#f2777a" underlineStyle="SingleUnderline"/>
  <style name="ErrorContext" underlineColor="#f2777a" underlineStyle="DotLine"/>
  <style name="Warning" underlineColor="#ffcc66" underlineStyle="SingleUnderline"/>
  <style name="WarningContext" underlineColor="#ffcc66" underlineStyle="DotLine"/>
</style-scheme>


text:
@value Accent from 'components/styles/colors.css';

.link {
  color: Accent;
}


text:
enum class Game_Stage
{
    OPENING,
    ENDGAME
};

//! \brief A class for holding a value that is the interpolation of two terminal values as a game progresses.
class Interpolated_Gene_Value
{
    public:
        //! \brief Create a pair of values to interpolate between.
        //!
        //! \param name The name of this value for reading and writing to files.
        //! \param game_start_value The value to return when the game starts.
        //! \param game_end_value The value to return when the is near over.
        //! \param mutation_size The width of the mutation probability distribution.
        Interpolated_Gene_Value(const std::string& name,
                                double game_start_value,
                                double game_end_value,
                                double mutation_size) noexcept;

        //! \brief Interpolate between the two terminal values.
        //!
        //! \param game_progress How far along the number line (in the range [0,1]) to move between the start and end values.
        //! \returns A value that is linearly interpolated between the two terminal values.
        //!
        //! Mathematically, return s + (e-s)*t where s is the start, e is the end, and t is the interpolation parameter.
        double interpolate(double game_progress) const noexcept;

        //! \brief Get the start value.
        double opening_value() const noexcept;

        //! \brief Get a modifiable start value.
        double& opening_value() noexcept;

        //! \brief Get the end value.
        double endgame_value() const noexcept;

        //! \brief Get a modifiable end value.
        double& endgame_value() noexcept;

        //! \brief Get the value at a given stage of the game.
        double value_at(Game_Stage stage) const noexcept;

        //! \brief Get a modifiable value at a given stage of the game.
        double& value_at(Game_Stage stage) noexcept;

        //! \brief Create a name for this value at different game stages for reading and writing files.
        std::string name(Game_Stage stage) const noexcept;

        //! \brief Read values from a std::map that was read from a genome file.
        void load_from_map(const std::map<std::string, std::string>& properties);

        //! \brief Write values to a std::map that will write a genome file.
        void write_to_map(std::map<std::string, std::string>& properties) const noexcept;

        //! \brief Randomly mutate one of the values.
        void mutate() noexcept;

    private:
        std::array<Gene_Value, 2> values;
};

#endif // INTERPOLATED_GENE_VALUE_H


text:
import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.GraphicsConfiguration;
import java.util.ArrayList;
import java.util.Random;
import com.sun.j3d.utils.applet.MainFrame;
import com.sun.j3d.utils.geometry.GeometryInfo;
import com.sun.j3d.utils.geometry.NormalGenerator;
import com.sun.j3d.utils.geometry.Stripifier;
import com.sun.j3d.utils.universe.SimpleUniverse;
import javax.media.j3d.Alpha;
import javax.media.j3d.AmbientLight;
import javax.media.j3d.Appearance;
import javax.media.j3d.Background;
import javax.media.j3d.BoundingSphere;
import javax.media.j3d.BranchGroup;
import javax.media.j3d.Canvas3D;
import javax.media.j3d.ColoringAttributes;
import javax.media.j3d.DirectionalLight;
import javax.media.j3d.GeometryArray;
import javax.media.j3d.Light;
import javax.media.j3d.LineArray;
import javax.media.j3d.Link;
import javax.media.j3d.Material;
import javax.media.j3d.Node;
import javax.media.j3d.PolygonAttributes;
import javax.media.j3d.RotationInterpolator;
import javax.media.j3d.Shape3D;
import javax.media.j3d.SharedGroup;
import javax.media.j3d.Transform3D;
import javax.media.j3d.TransformGroup;
import javax.media.j3d.TriangleArray;
import javax.vecmath.AxisAngle4f;
import javax.vecmath.Color3f;
import javax.vecmath.Point3d;
import javax.vecmath.Point3f;
import javax.vecmath.Vector3f;

public class Torus extends Applet{

  // how many triangles make up the torus
  private static final int MAJOR_STEPS = 80;
  private static final int MINOR_STEPS = 70;

  // sets the torus size
  private static final float MAJOR_RADIUS = 0.8f;
  private static final float MINOR_RADIUS = 0.1f;

  // set odd-shaped torus (oval)
  private static final float ECCENTRICITY = 1.0f;

  // time for one rotation, in ms (smaller=faster)
  private static final int PERIOD = 1300;

  // set colors for scene
  private static final Color3f AMBIENT_COLOR = new Color3f(0.2f, 0.3f, 0.5f);
  private static final Color3f OBJECT_COLOR = new Color3f(0.4f, 0.1f, 0.9f);
  private static final Color3f EMISSIVE_COLOR = new Color3f(0.2f, 0.3f, 0.5f);
  private static final Color3f SPECULAR_COLOR = new Color3f(0.3f, 0.1f, 0.9f);

  // how many tori to create
  private static final int NUMB_TORI = 5;

  // variables for storagae
  private ArrayList<TransformGroup> tori = new ArrayList<TransformGroup>();
  private SimpleUniverse u = null;
  private Random rng = new Random();
  private int RANDOM = rng.nextInt(2);

  // create the scene graph of the program
  public BranchGroup createSceneGraph(){

    // create the root of the branch graph
    BranchGroup objRoot = new BranchGroup();
    SharedGroup objShare = new SharedGroup();
    objShare.addChild(makeWheel(MAJOR_RADIUS, MINOR_RADIUS, ECCENTRICITY));

    // generates all objects, rotating
    this.createTori(objShare);
    for(TransformGroup tg:tori){
      objRoot.addChild(tg);
      this.generateSpin(objRoot, tg);
    }

    // add light to the scene graph
    objRoot.addChild(this.createDirectionalLight());
    objRoot.addChild(this.createAmbientLight());

    // perform optimizations & return scene graph
    objRoot.compile();
    return objRoot;
  }

  // create several torus shapes (inside each other)
  private void createTori(SharedGroup sg){
    for(int i = 0; i < NUMB_TORI; i++){
      TransformGroup obj = new TransformGroup();
      obj.setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE);

      // shrink the torus size, so they fit inside each other
      TransformGroup rot = new TransformGroup();
      float shrink = 1.0f - ((1.0f / NUMB_TORI) * i);

      // rotate the tori so they look more interesting
      float[] xzMatrix = {0f,0f,shrink,0f, 0f,shrink,0f,0f, shrink,0f,0f,0f, 0f,0f,0f,1f};
      Transform3D rotate = new Transform3D(xzMatrix);
      rot.setTransform(rotate);
      obj.addChild(rot);

      // add the torus to the scene graph
      rot.addChild(new Link(sg));
      tori.add(obj);
    }
  }

  // tell the scene graph to spin the torus objects over time
  private void generateSpin(BranchGroup bg, TransformGroup tg){
    Transform3D yAxis = new Transform3D();
    Alpha rotationAlpha = new Alpha(-1, PERIOD);
    BoundingSphere bounds = new BoundingSphere(new Point3d(0.0, 0.0, 0.0), 100.0);
    int rotBit = tori.indexOf(tg);
    float[] rotMatrix;

    // transform the torus objects correctly, depending on the number of objects
    if(rotBit == NUMB_TORI - 1){
      TransformGroup tg2 = (TransformGroup) tg.getChild(0);
      float shrink = 1.0f - ((1.0f / NUMB_TORI) * (NUMB_TORI - 1));
      float[] flipMatrix = {shrink,0f,0f,0f, 0f,shrink,0f,0f, 0f,0f,shrink,0f, 0f,0f,0f,1f};
      Transform3D rotate = new Transform3D(flipMatrix);
      tg2.setTransform(rotate);
      float[] matrix = {-1f,0f,0f,0f, 0f,0f,1f,0f, 0f,1f,0f,0f, 0f,0f,0f,1f};
      rotMatrix = matrix;
    }else if((rotBit + RANDOM) % 2 == 1){
      float[] matrix = {0f,1f,0f,0f, 1f,0f,0f,0f, 0f,0f,-1f,0f, 0f,0f,0f,1f};
      rotMatrix = matrix;
    }else{
      float[] matrix = {1f,0f,0f,0f, 0f,1f,0f,0f, 0f,0f,1f,0f, 0f,0f,0f,1f};
      rotMatrix = matrix;
    }

    // perform the rotation
    Transform3D axis = new Transform3D(rotMatrix);
    RotationInterpolator rotator = new RotationInterpolator(rotationAlpha, tg, axis, 0.0f, (float) Math.PI * 2.0f);
    rotator.setSchedulingBounds(bounds);
    bg.addChild(rotator);
  }

  // set up scene directional light
  private Light createDirectionalLight(){
    DirectionalLight light = new DirectionalLight();
    BoundingSphere infinite = new BoundingSphere(new Point3d(0.0, 0.0, 0.0),Double.MAX_VALUE);
    light.setInfluencingBounds(infinite);
    light.setColor(new Color3f(1.0f, 1.0f, 1.0f));
    light.setCapability(Light.ALLOW_STATE_WRITE);
    light.setDirection(new Vector3f(-1.0f, 0.0f, -1.0f));
    light.setEnable(true);
    return light;
  }

  // set up scene ambient light
  private Light createAmbientLight(){
    AmbientLight light = new AmbientLight();
    BoundingSphere infinite = new BoundingSphere(new Point3d(0.0, 0.0, 0.0),Double.MAX_VALUE);
    light.setInfluencingBounds(infinite);
    light.setColor(new Color3f(1.0f, 1.0f, 1.0f));
    light.setCapability(Light.ALLOW_STATE_WRITE);
    light.setEnable(true);
    return light;
  }

  // set up scene appearances of objects
  private Appearance createAppearance(){

    // general appearance settings
    Appearance appearance = new Appearance();
    ColoringAttributes ca = new ColoringAttributes();
    ca.setShadeModel(ColoringAttributes.SHADE_GOURAUD);
    appearance.setColoringAttributes(ca);

    // polygon appearance settings
    PolygonAttributes pa = new PolygonAttributes();
    pa.setPolygonMode(PolygonAttributes.POLYGON_FILL);
    appearance.setPolygonAttributes(pa);

    // light-material interaction colors
    Color3f ambientColor = AMBIENT_COLOR;
    Color3f objectColor = OBJECT_COLOR;
    Color3f emissiveColor = EMISSIVE_COLOR;
    Color3f specularColor = SPECULAR_COLOR;

    // material apperance settings
    Material material = new Material(ambientColor,emissiveColor,objectColor,specularColor,100.0f);
    material.setLightingEnable(true);
    appearance.setMaterial(material);

    return appearance;
  }

  // how to generate the torus (wheel)
  public Node makeWheel(float majorRadius, float minorRadius,float eccentricity){

    // number of steps to generate each torus
    int majorSteps = MAJOR_STEPS;
    int minorSteps = MINOR_STEPS;

    // generate points
    Point3f[] v = new Point3f[minorSteps];
    for(int j = 0; j < minorSteps; j++){
      float angle = (float) (2.0 * Math.PI * ((double) j) / minorSteps);
      float x = (float) (eccentricity * minorRadius * Math.cos(angle));
      float y = (float) (minorRadius * Math.sin(angle));
      v[j] = new Point3f(x, y + majorRadius, 0.0f);
    }

    // generate vertices from the points, with the proper rotations
    Point3f[][] vertices = new Point3f[majorSteps][minorSteps];
    for(int i = 0; i < majorSteps; i++){
      float angle = (float) (2.0 * Math.PI * ((double) i) / majorSteps);
      Transform3D rotation = new Transform3D();
      AxisAngle4f axisAngle = new AxisAngle4f(1.0f, 0.0f, 0.0f, angle);
      rotation.setRotation(axisAngle);
      for(int j = 0; j < minorSteps; j++){
        vertices[i][j] = new Point3f();
        rotation.transform(v[j], vertices[i][j]);
      }
    }

    // draw lines with the torus
    int numberOfLines = 2 * majorSteps * minorSteps;
    int code = GeometryArray.COORDINATES;
    LineArray lines = new LineArray(numberOfLines * 2, code);

    // set coordinates of the object
    TriangleArray t = new TriangleArray(6 * majorSteps * minorSteps, GeometryArray.COORDINATES);
    int k = 0;
    int index = 0;
    for(int i = 0; i < majorSteps; i++){
      for(int j = 0; j < minorSteps; j++){
        t.setCoordinate(index++, vertices[i][j]);
        t.setCoordinate(index++, vertices[i][(j + 1) % minorSteps]);
        t.setCoordinate(index++, vertices[(i + 1) % majorSteps][j]);
        t.setCoordinate(index++, vertices[i][(j + 1) % minorSteps]);
        t.setCoordinate(index++, vertices[(i + 1) % majorSteps][(j + 1) % minorSteps]);
        t.setCoordinate(index++, vertices[(i + 1) % majorSteps][j]);
      }
    }

    // set up geometry info
    GeometryInfo geometryInfo = new GeometryInfo(t);
    NormalGenerator normalGenerator = new NormalGenerator();
    normalGenerator.generateNormals(geometryInfo);
    Stripifier stripifier = new Stripifier();
    stripifier.stripify(geometryInfo);

    return new Shape3D(geometryInfo.getGeometryArray(), this.createAppearance());
  }

  // created object, empty
  public Torus(){}

  // set up graphics canvas
  @Override
  public void init(){
    setLayout(new BorderLayout());
    GraphicsConfiguration config = SimpleUniverse.getPreferredConfiguration();
    Canvas3D c = new Canvas3D(config);
    add("Center", c);

    // create a simple scene and attach it to the virtual universe
    BranchGroup scene = createSceneGraph();
    u = new SimpleUniverse(c);

    // move viewport to see objects in the scene
    u.getViewingPlatform().setNominalViewingTransform();
    u.addBranchGraph(scene);
  }

  // clearing the scene
  @Override
  public void destroy(){
    u.removeAllLocales();
  }

  // calculate an average off of t
  private float avg(float a, float b, float t){
    return (1 - t) * a + t * b;
  }

  // generate an average point (vector) from two points
  private Point3f avg(Point3f a, Point3f b, float t){
    float x = avg(a.x, b.x, t);
    float y = avg(a.y, b.y, t);
    float z = avg(a.z, b.z, t);
    return new Point3f(x, y, z);
  }

  // generate an average point (vector) from three points
  private Point3f avg(Point3f a, Point3f b, Point3f c, float t){
    return avg(avg(a, b, t), avg(b, c, t), t);
  }

  // generate an average point (vector) from four points
  private Point3f avg(Point3f a, Point3f b, Point3f c, Point3f d, float t){
    return avg(avg(a, b, c, t), avg(b, c, d, t), t);
  }

  // main method to run application as an applet
  public static void main(String[] args){
    new MainFrame(new Torus(), 800, 800);
  }
}


text:
title: How-to Guide
layout: wide
nav: resources_nav
---

How to teach one Hour of Code

## 1) Watch this how-to video

## 2) Try the tutorials:
We'll host a variety of fun, hour-long tutorials for students of all ages, created by a variety of partners. New tutorials are coming to kick off the Hour of Code before December 7-13.

**All Hour of Code tutorials:**

- Require minimal prep-time for teachers
- Are self-guided - allowing students to work at their own pace and skill-level

<a href="http://<%=codeorg_url() %>/learn"><img src="http://<%= codeorg_url() %>/images/tutorials.png">

## 3) Plan your hardware needs - computers are optional

The best Hour of Code experience will be with Internet-connected computers. But you don't need a computer for every child, and can even do the Hour of Code without a computer at all.

- **Test tutorials on student computers or devices.** Make sure they work properly (with sound and video).
- **Preview the congrats page** to see what students will see when they finish.
- **Provide headphones for your class**, or ask students to bring their own, if the tutorial you choose works best with sound.

## 4) Plan ahead based on your technology available

- **Don't have enough devices?** Use [pair programming](http://www.ncwit.org/resources/pair-programming-box-power-collaborative-learning). When students partner up, they help each other and rely less on the teacher. They'll also see that computer science is social and collaborative.
- **Have low bandwidth?** Plan to show videos at the front of the class, so each student isn't downloading their own videos. Or try the unplugged / offline tutorials.

## 5) Inspire students - show them a video

Show students an inspirational video to kick off the Hour of Code. Examples:

- The original Code.org launch video, featuring Bill Gates, Mark Zuckerberg, and NBA star Chris Bosh (There are [1 minute](https://www.youtube.com/watch?v=qYZF6oIZtfc), [5 minute](https://www.youtube.com/watch?v=nKIu9yen5nc), and [9 minute](https://www.youtube.com/watch?v=dU1xS07N-FA) versions)
- The [Hour of Code 2013 launch video](https://www.youtube.com/watch?v=FC5FbmsH4fw), or the <% if @country == 'uk' %> [Hour of Code 2014 video](https://www.youtube.com/watch?v=96B5-JGA9EQ) <% else %> [Hour of Code 2014 video](https://www.youtube.com/watch?v=rH7AjDMz_dc&index=2&list=PLzdnOPI1iJNe1WmdkMG-Ca8cLQpdEAL7Q) <% end %>
- [President Obama calling on all students to learn computer science](https://www.youtube.com/watch?v=6XvmhE1J9PY)

**Get your students excited - give them a short intro**

Most kids don't know what computer science is. Here are some ideas:

- Explain it in a simple way that includes examples of applications that both boys and girls will care about (saving lives, helping people, connecting people, etc.).
- Try: "Think about things in your everyday life that use computer science: a cell phone, a microwave, a computer, a traffic light… all of these things needed a computer scientist to help build them."
- Or: "Computer science is the art of blending human ideas and digital tools to increase our power. Computer scientists work in so many different areas: writing apps for phones, curing diseases, creating animated movies, working on social media, building robots that explore other planets and so much more."
- See tips for getting girls interested in computer science <a href="http://<%= codeorg_url() %>/girls">here.

## 6) Start your Hour of Code

**Direct students to the activity**

- Write the tutorial link on a whiteboard. Find the link listed on the <a href="http://<%= codeorg_url() %>/learn">information for your selected tutorial under the number of participants.
- Tell students to visit the URL and start the tutorial.

**When your students come across difficulties**

- Tell students, "Ask 3 then me." Ask 3 classmates, and if they don't have the answer, then ask the teacher.
- Encourage students and offer positive reinforcement: "You're doing great, so keep trying."
- It's okay to respond: "I don't know. Let's figure this out together." If you can't figure out a problem, use it as a good learning lesson for the class: "Technology doesn't always work out the way we want. Together, we're a community of learners." And: "Learning to program is like learning a new language; you won't be fluent right away."

**What to do if a student finishes early?**

- Students can see all tutorials and try another Hour of Code activity at <a href="http://<%= codeorg_url() %>/learn"><%= codeorg_url() %>/learn
- Or, ask students who finish early to help classmates who are having trouble with the activity.

**How do I print certificates for my students?**

Each student gets a chance to get a certificate via email when they finish the [Code.org tutorials](http://studio.code.org). You can click on the certificate to print it. However, if you want to make new certificates for your students, visit our <a href="http://<%= codeorg_url() %>/certificates">Certificates page to print as many certificates as you like, in one fell swoop!

**What comes after the Hour of Code?**

The Hour of Code is just the first step on a journey to learn more about how technology works and how to create software applications. <% if @country == 'uk' %> The Hour of Code is just the first step on a journey to learn more about how technology works and how to create software applications. To continue this journey, [encourage your children to learn online](http://uk.code.org/learn/beyond). <% else %> To continue this journey, find additional resources for educators <a href="http://<%= codeorg_url() %>/educate">here. Or encourage your children to learn <a href="http://<%= codeorg_url() %>/learn/beyond">online. <% end %>


text:
import PageTitle from './pageTitle';
export default PageTitle;


text:
This inspection reports .wait()
being called unconditionally within a synchronized context.
Normally, .wait() is
used to block a thread until some condition is true. If .wait()
is called unconditionally, that often indicates that the condition was checked before a lock was
acquired. In that case a data race may occur, with the condition becoming true between the time
it was checked and the time the lock was acquired. While constructs found by this inspection
are not necessarily incorrect, they are certainly worth examining.

Powered by InspectionGadgets


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?actionBarSize"
        android:background="?colorPrimary"
        android:elevation="4dp"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clipToPadding="false"
            android:paddingBottom="8dp"
            android:paddingTop="8dp" />

        <com.pluscubed.recyclerfastscroll.RecyclerFastScroller
            android:id="@+id/fast_scroller"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="end" />

    </FrameLayout>

</LinearLayout>


text:
var util = require('util'),
    events = require('events'),
    fs = require('fs'),
    url = require('url');

//
// ### function ProxyTable (router, silent)
// #### @router {Object} Object containing the host based routes
// #### @silent {Boolean} Value indicating whether we should suppress logs
// #### @hostnameOnly {Boolean} Value indicating if we should route based on __hostname string only__
// #### @pathnameOnly {Boolean} Value indicating if we should route based on only the pathname.  __This causes hostnames to be ignored.__.  Using this along with hostnameOnly wont work at all.
// Constructor function for the ProxyTable responsible for getting
// locations of proxy targets based on ServerRequest headers; specifically
// the HTTP host header.
//
var ProxyTable = exports.ProxyTable = function (options) {
  events.EventEmitter.call(this);

  this.silent       = options.silent || options.silent !== true;
  this.target       = options.target || {};
  this.pathnameOnly = options.pathnameOnly === true;
  this.hostnameOnly = options.hostnameOnly === true;

  if (typeof options.router === 'object') {
    //
    // If we are passed an object literal setup
    // the routes with RegExps from the router
    //
    this.setRoutes(options.router);
  }
  else if (typeof options.router === 'string') {
    //
    // If we are passed a string then assume it is a
    // file path, parse that file and watch it for changes
    //
    var self = this;
    this.routeFile = options.router;
    this.setRoutes(JSON.parse(fs.readFileSync(options.router)).router);

    fs.watchFile(this.routeFile, function () {
      fs.readFile(self.routeFile, function (err, data) {
        if (err) {
          self.emit('error', err);
        }

        self.setRoutes(JSON.parse(data).router);
        self.emit('routes', self.hostnameOnly === false ? self.routes : self.router);
      });
    });
  }
  else {
    throw new Error('Cannot parse router with unknown type: ' + typeof router);
  }
};

//
// Inherit from `events.EventEmitter`
//
util.inherits(ProxyTable, events.EventEmitter);

//
// ### function addRoute (route, target)
// #### @route {String} String containing route coming in
// #### @target {String} String containing the target
// Adds a host-based route to this instance.
//
ProxyTable.prototype.addRoute = function (route, target) {
  if (!this.router) {
    throw new Error('Cannot update ProxyTable routes without router.');
  }

  this.router[route] = target;
  this.setRoutes(this.router);
};

//
// ### function removeRoute (route)
// #### @route {String} String containing route to remove
// Removes a host-based route from this instance.
//
ProxyTable.prototype.removeRoute = function (route) {
  if (!this.router) {
    throw new Error('Cannot update ProxyTable routes without router.');
  }

  delete this.router[route];
  this.setRoutes(this.router);
};

//
// ### function setRoutes (router)
// #### @router {Object} Object containing the host based routes
// Sets the host-based routes to be used by this instance.
//
ProxyTable.prototype.setRoutes = function (router) {
  if (!router) {
    throw new Error('Cannot update ProxyTable routes without router.');
  }

  var self = this;
  this.router = router;

  if (this.hostnameOnly === false) {
    this.routes = [];

    Object.keys(router).forEach(function (path) {
      if (!/http[s]?/.test(router[path])) {
        router[path] = (self.target.https ? 'https://' : 'http://')
          + router[path];
      }

      var target = url.parse(router[path]),
          defaultPort = self.target.https ? 443 : 80;

      //
      // Setup a robust lookup table for the route:
      //
      //    {
      //      source: {
      //        regexp: /^foo.com/i,
      //        sref: 'foo.com',
      //        url: {
      //          protocol: 'http:',
      //          slashes: true,
      //          host: 'foo.com',
      //          hostname: 'foo.com',
      //          href: 'http://foo.com/',
      //          pathname: '/',
      //          path: '/'
      //        }
      //    },
      //    {
      //      target: {
      //        sref: '127.0.0.1:8000/',
      //        url: {
      //          protocol: 'http:',
      //          slashes: true,
      //          host: '127.0.0.1:8000',
      //          hostname: '127.0.0.1',
      //          href: 'http://127.0.0.1:8000/',
      //          pathname: '/',
      //          path: '/'
      //        }
      //    },
      //
      self.routes.push({
        source: {
          regexp: new RegExp('^' + path, 'i'),
          sref: path,
          url: url.parse('http://' + path)
        },
        target: {
          sref: target.hostname + ':' + (target.port || defaultPort) + target.path,
          url: target
        }
      });
    });
  }
};

//
// ### function getProxyLocation (req)
// #### @req {ServerRequest} The incoming server request to get proxy information about.
// Returns the proxy location based on the HTTP Headers in the  ServerRequest `req`
// available to this instance.
//
ProxyTable.prototype.getProxyLocation = function (req) {
  if (!req || !req.headers || !req.headers.host) {
    return null;
  }

  var targetHost = req.headers.host.split(':')[0];
  if (this.hostnameOnly === true) {
    var target = targetHost;
    if (this.router.hasOwnProperty(target)) {
      var location = this.router[target].split(':'),
          host = location[0],
          port = location.length === 1 ? 80 : location[1];

      return {
        port: port,
        host: host
      };
    }
  }
  else if (this.pathnameOnly === true) {
    var target = req.url;
    for (var i in this.routes) {
      var route = this.routes[i];
      //
      // If we are matching pathname only, we remove the matched pattern.
      //
      // IE /wiki/heartbeat
      // is redirected to
      // /heartbeat
      //
      // for the route "/wiki" : "127.0.0.1:8020"
      //
      if (target.match(route.source.regexp)) {
        req.url = url.format(target.replace(route.source.regexp, ''));
        return {
          protocol: route.target.url.protocol.replace(':', ''),
          host: route.target.url.hostname,
          port: route.target.url.port
            || (this.target.https ? 443 : 80)
        };
      }
    }

  }
  else {
    var target = targetHost + req.url;
    for (var i in this.routes) {
      var route = this.routes[i];
      if (target.match(route.source.regexp)) {
        //
        // Attempt to perform any path replacement for differences
        // between the source path and the target path. This replaces the
        // path's part of the URL to the target's part of the URL.
        //
        // 1. Parse the request URL
        // 2. Replace any portions of the source path with the target path
        // 3. Set the request URL to the formatted URL with replacements.
        //
        var parsed = url.parse(req.url);

        parsed.pathname = parsed.pathname.replace(
          route.source.url.pathname,
          route.target.url.pathname
        );

        req.url = url.format(parsed);

        return {
          protocol: route.target.url.protocol.replace(':', ''),
          host: route.target.url.hostname,
          port: route.target.url.port
            || (this.target.https ? 443 : 80)
        };
      }
    }
  }

  return null;
};

//
// ### close function ()
// Cleans up the event listeneners maintained
// by this instance.
//
ProxyTable.prototype.close = function () {
  if (typeof this.routeFile === 'string') {
    fs.unwatchFile(this.routeFile);
  }
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://www.netbeans.org/ns/project/1">
    <type>org.netbeans.modules.java.j2seproject</type>
    <configuration>
        <data xmlns="http://www.netbeans.org/ns/j2se-project/3">
            <name>ShortestPath</name>
            <source-roots>
                <root id="src.dir" name="src"/>
            </source-roots>
            <test-roots/>
        </data>
    </configuration>
</project>


text:
import os
import ast
import csv
from sys import maxsize
csv.field_size_limit(maxsize)

'''Schreib Operationen'''
def write_iterable_to_file(path, data):
    with open(path, 'w') as f:
        for tupl in data:
            f.write(str(tupl) + '\n')

def append_to_file(path, data):
    with open(path, 'a') as f:
        f.write(data + '\n')

def append_row_to_csv(path, row):
    with open (path, 'a') as outcsv:
        writer = csv.writer(outcsv)
        writer.writerow(row)

'''Lese Operationen'''
def file_to_set(file_name):
    out = set()
    with open(file_name, 'rt') as f:
        try: # If a line in the file seems to be a tuple: Create set of tuples
            for line in f:
                line.replace('\n', '')
                out.add(ast.literal_eval(line))
        except SyntaxError: #Else: create set of strings
            for line in f:
                out.add(line.replace('\n', ''))
    return out

def csv_to_list(file_name):
    out = []
    with open(file_name, 'r') as f:
        reader = csv.reader(f)
        for row in reader:
            out.append(row)
    return out

def length_of_csv(file):
    with open(file) as f:
        return len(list(csv.reader(f)))


text:
package org.cleanas2.cmd.system;

import org.cleanas2.server.ServerSession;
import org.cleanas2.cmd.CommandBase;
import org.cleanas2.cmd.CommandResult;
import org.cleanas2.common.annotation.Command;
import org.cleanas2.common.service.AdminDump;

import java.util.List;

import static org.cleanas2.util.AS2Util.ofType;

/**
 * @author Andrew Backer {@literal awbacker@gmail.com / andrew.backer@powere2e.com}
 */
@Command(name = "status", description = "Shows status for all running modules")
public class StatusCommand extends CommandBase {

    @Override
    public CommandResult run(String... params) throws Exception {
        CommandResult cr = new CommandResult();
        List<Object> allServices = ServerSession.getSession().getAllServices();
        List<AdminDump> adminDumps = ofType(allServices, AdminDump.class);

        for (AdminDump svc : adminDumps) {
            cr.add(svc.getClass().getSimpleName());
            try {
                for (String line : svc.dumpCurrentStatus()) {
                    cr.add("    " + line);
                }
            } catch (Throwable e) {
                cr.add("    error getting status: " + e.getLocalizedMessage());
            }
        }

        cr.add("== additional modules ==");
        for (Object svc : allServices) {
            if (adminDumps.contains(svc)) continue;
            cr.add("    " + svc.getClass().getSimpleName());
        }

        return cr;
    }
}


text:
package jenkins.model;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import hudson.ExtensionList;
import hudson.model.FreeStyleProject;
import hudson.model.labels.LabelAtom;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.CaptureEnvironmentBuilder;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.recipes.LocalData;

public class BuiltInNodeMigrationTest {
    @Rule
    public JenkinsRule j = new JenkinsRule();

    @Test
    public void newInstanceHasNewTerminology() throws Exception {
        assertStatus(j, true, false, "built-in", "built-in");
        assertFalse(ExtensionList.lookupSingleton(BuiltInNodeMigration.class).isActivated());
    }

    @Test
    @LocalData
    public void oldDataStartsWithOldTerminology() throws Exception {
        assertStatus(j, false, true, "master", "master");
        final BuiltInNodeMigration builtInNodeMigration = ExtensionList.lookupSingleton(BuiltInNodeMigration.class);
        assertTrue(builtInNodeMigration.isActivated());

        // Now perform rename and confirm it's done
        j.jenkins.performRenameMigration();
        assertStatus(j, true, false, "built-in", "built-in");
        assertFalse(builtInNodeMigration.isActivated());
    }

    @Test
    @LocalData
    public void migratedInstanceStartsWithNewTerminology() throws Exception {
        assertStatus(j, true, false, "built-in", "built-in");
        assertFalse(ExtensionList.lookupSingleton(BuiltInNodeMigration.class).isActivated());
    }

    public static void assertStatus(JenkinsRule j, boolean migrationDoneGetterValue, Boolean migrationNeededFieldValue, String label, String nodeName) throws Exception {
        assertEquals(migrationDoneGetterValue, j.jenkins.getRenameMigrationDone());
        assertEquals(migrationNeededFieldValue, j.jenkins.nodeRenameMigrationNeeded);
        assertEquals(new LabelAtom(label), j.jenkins.getSelfLabel());
        final FreeStyleProject freeStyleProject = j.createFreeStyleProject();
        final CaptureEnvironmentBuilder environmentBuilder = new CaptureEnvironmentBuilder();
        freeStyleProject.getBuildersList().add(environmentBuilder);
        j.buildAndAssertSuccess(freeStyleProject);
        assertEquals(nodeName, environmentBuilder.getEnvVars().get("NODE_NAME"));
    }
}