text:
module("Element methods tests", {});
test("xml3d methods test", function() {
    var node = document.createElementNS("http://www.xml3d.org/2009/xml3d", "xml3d");
    ok(node);

    equal(node.getElementByPoint(0,0, new XML3DVec3(), new XML3DVec3()), null, "xml3d::getElementByPoint returns ");
    ok(node.generateRay(0,0) instanceof XML3DRay, "xml3d::generateRay returns ");
    equal(node.getElementByRay(new XML3DRay(), new XML3DVec3(), new XML3DVec3()), null, "xml3d::getElementByRay returns ");

    ok(node.getLocalBoundingBox() instanceof XML3DBox, "xml3d::getLocalBoundingBox returns ");
    ok(node.getLocalBoundingBox().isEmpty(), "Empty xml3d delivers empty BoundingBox");

    ok(node.getWorldBoundingBox() instanceof XML3DBox, "xml3d::getWorldBoundingBox returns ");
    ok(node.getWorldBoundingBox().isEmpty(), "Empty xml3d delivers empty BoundingBox");
});
test("group interface test", function() {
    var node = document.createElementNS("http://www.xml3d.org/2009/xml3d", "group");
    ok(node);

    ok(node.getWorldMatrix() instanceof XML3DMatrix, "group::getWorldMatrix returns XML3DMatrix");
    deepEqual(node.getWorldMatrix(), new XML3DMatrix(),
            "group::getWorldMatrix returns identity matrix if not in hierarchy.");

    ok(node.getLocalMatrix() instanceof XML3DMatrix, "group::getLocalMatrix returns XML3DMatrix");
    deepEqual(node.getLocalMatrix(), new XML3DMatrix(),
            "group::getLocalMatrix returns identity matrix with default attributes.");

    ok(node.getLocalBoundingBox() instanceof XML3DBox, "group::getLocalBoundingBox returns ");
    ok(node.getLocalBoundingBox().isEmpty(), "Empty group delivers empty BoundingBox");

    ok(node.getWorldBoundingBox() instanceof XML3DBox, "group::getWorldBoundingBox returns ");
    ok(node.getWorldBoundingBox().isEmpty(), "Empty group delivers empty BoundingBox");
});
test("mesh interface test", function() {
    var node = document.createElementNS("http://www.xml3d.org/2009/xml3d", "mesh");
    ok(node);

    ok(node.getWorldMatrix() instanceof XML3DMatrix, "mesh::getWorldMatrix returns XML3DMatrix");
    deepEqual(node.getWorldMatrix(), new XML3DMatrix(),
            "mesh::getWorldMatrix returns identity matrix if not in hierarchy.");

    ok(node.getLocalBoundingBox() instanceof XML3DBox, "mesh::getLocalBoundingBox returns ");
    ok(node.getLocalBoundingBox().isEmpty(), "Empty mesh delivers empty BoundingBox");

    ok(node.getWorldBoundingBox() instanceof XML3DBox, "mesh::getWorldBoundingBox returns ");
    ok(node.getWorldBoundingBox().isEmpty(), "Empty mesh delivers empty BoundingBox");
});
test("light interface test", function() {
    var node = document.createElementNS("http://www.xml3d.org/2009/xml3d", "light");
    ok(node);

    ok(node.getWorldMatrix() instanceof XML3DMatrix, "light::getWorldMatrix returns XML3DMatrix");
    deepEqual(node.getWorldMatrix(), new XML3DMatrix(),
            "light::getWorldMatrix returns identity matrix if not in hierarchy.");
});
test("view interface test", function() {
    var node = document.createElementNS("http://www.xml3d.org/2009/xml3d", "view");
    ok(node);

    ok(node.getWorldMatrix() instanceof XML3DMatrix, "view::getWorldMatrix returns XML3DMatrix");
    deepEqual(node.getWorldMatrix(), new XML3DMatrix(),
            "view::getWorldMatrix returns identity matrix if not in hierarchy.");

    ok(node.getViewMatrix() instanceof XML3DMatrix, "view::getViewMatrix returns XML3DMatrix");
    deepEqual(node.getViewMatrix(), new XML3DMatrix(), "view::getViewMatrix returns with default parameters.");

    equal(node.setDirection(new XML3DVec3(1, 0, 0)), undefined, "view::setDirection returns nothing");
    equal(node.setUpVector(new XML3DVec3(1, 0, 0)), undefined, "view::setUpVector returns nothing");
    equal(node.lookAt(new XML3DVec3(1, 0, 0)), undefined, "view::lookAt returns nothing");
    ok(node.getDirection() instanceof XML3DVec3, "view::getDirection returns XML3DVec3");
    ok(node.getUpVector() instanceof XML3DVec3, "view::getUpVector returns XML3DVec3");
});
test("data interface test", function() {
    var node = document.createElementNS("http://www.xml3d.org/2009/xml3d", "data");
    ok(node);

    ok(node.getResult() instanceof XML3DDataResult, "data::getResult returns XML3DDataResult");
    ok(node.getOutputNames() instanceof Array, "data::getOutputNames returns an Array");
});

test("view::lookAt tests", function() {
    var node = document.createElementNS("http://www.xml3d.org/2009/xml3d", "view");
    ok(node);
    QUnit.closeVector(node.position, new XML3DVec3(), EPSILON, "Default position");
    QUnit.closeRotation(node.orientation, new XML3DRotation(), EPSILON, "Default orientation");
    node.lookAt(new XML3DVec3(0,0,-10));
    QUnit.closeRotation(node.orientation, new XML3DRotation(), EPSILON, "Look along default direction");
    node.lookAt(new XML3DVec3(10,0,0));
    QUnit.closeRotation(node.orientation, new XML3DRotation(new XML3DVec3(0,-1,0),Math.PI/2.0), EPSILON, "Look to the right");
    node.lookAt(new XML3DVec3(0,0,10));
    QUnit.closeRotation(node.orientation, new XML3DRotation(new XML3DVec3(0,1,0),Math.PI), EPSILON, "Look to the back");
    node.lookAt(new XML3DVec3(-10,0,0));
    QUnit.closeRotation(node.orientation, new XML3DRotation(new XML3DVec3(0,1,0),Math.PI/2.0), EPSILON, "Look to the left");
});

test("view::setUpVector tests", function() {
    var node = document.createElementNS("http://www.xml3d.org/2009/xml3d", "view");
    ok(node);
    QUnit.closeVector(node.position, new XML3DVec3(), EPSILON, "Default position");
    QUnit.closeRotation(node.orientation, new XML3DRotation(), EPSILON, "Default orientation");
    node.setUpVector(new XML3DVec3(0,0,1));
    QUnit.closeRotation(node.orientation, new XML3DRotation(new XML3DVec3(1,0,0),Math.PI/2.0), EPSILON, "Up vector is +z");
    node.orientation.set(new XML3DRotation());
    node.setUpVector(new XML3DVec3(0,-1,0));
    QUnit.closeRotation(node.orientation, new XML3DRotation(new XML3DVec3(0,0,1),Math.PI), EPSILON, "Up vector is -y");
});

test("view::setDirection tests", function() {
    var node = document.createElementNS("http://www.xml3d.org/2009/xml3d", "view");
    ok(node);
    QUnit.closeVector(node.position, new XML3DVec3(), EPSILON, "Default position");
    QUnit.closeRotation(node.orientation, new XML3DRotation(), EPSILON, "Default orientation");
    node.setDirection(new XML3DVec3(0,1,0));
    QUnit.closeRotation(node.orientation, new XML3DRotation(new XML3DVec3(1,0,0),Math.PI/2.0), EPSILON, "Up vector is +z");
});


text:
<?php
/**
 * @package WPSEO\Internals\Options
 */

/**
 * Option: wpseo_internallinks
 */
class WPSEO_Option_InternalLinks extends WPSEO_Option {

	/**
	 * @var  string  option name
	 */
	public $option_name = 'wpseo_internallinks';

	/**
	 * @var  array  Array of defaults for the option
	 *        Shouldn't be requested directly, use $this->get_defaults();
	 * @internal  Note: Some of the default values are added via the translate_defaults() method
	 */
	protected $defaults = array(
		'breadcrumbs-404crumb'      => '', // Text field.
		'breadcrumbs-blog-remove'   => false,
		'breadcrumbs-boldlast'      => false,
		'breadcrumbs-archiveprefix' => '', // Text field.
		'breadcrumbs-enable'        => false,
		'breadcrumbs-home'          => '', // Text field.
		'breadcrumbs-prefix'        => '', // Text field.
		'breadcrumbs-searchprefix'  => '', // Text field.
		'breadcrumbs-sep'           => '»', // Text field.

		/**
		 * Uses enrich_defaults() to add more along the lines of:
		 * - 'post_types-' . $pt->name . '-maintax'    => 0 / string
		 * - 'taxonomy-' . $tax->name . '-ptparent'    => 0 / string
		 */
	);

	/**
	 * @var  array  Array of variable option name patterns for the option
	 */
	protected $variable_array_key_patterns = array(
		'post_types-',
		'taxonomy-',
	);

	/**
	 * Get the singleton instance of this class
	 *
	 * @return object
	 */
	public static function get_instance() {
		if ( ! ( self::$instance instanceof self ) ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	/**
	 * Translate strings used in the option defaults
	 *
	 * @return void
	 */
	public function translate_defaults() {
		$this->defaults['breadcrumbs-404crumb']      = __( 'Error 404: Page not found', 'wordpress-seo' );
		$this->defaults['breadcrumbs-archiveprefix'] = __( 'Archives for', 'wordpress-seo' );
		$this->defaults['breadcrumbs-home']          = __( 'Home', 'wordpress-seo' );
		$this->defaults['breadcrumbs-searchprefix']  = __( 'You searched for', 'wordpress-seo' );
	}

	/**
	 * Add dynamically created default options based on available post types and taxonomies
	 *
	 * @return  void
	 */
	public function enrich_defaults() {

		// Retrieve all the relevant post type and taxonomy arrays.
		$post_type_names       = get_post_types( array( 'public' => true ), 'names' );
		$taxonomy_names_custom = get_taxonomies( array( 'public' => true, '_builtin' => false ), 'names' );

		if ( $post_type_names !== array() ) {
			foreach ( $post_type_names as $pt ) {
				$pto_taxonomies = get_object_taxonomies( $pt, 'names' );
				if ( $pto_taxonomies !== array() ) {
					$this->defaults[ 'post_types-' . $pt . '-maintax' ] = 0; // Select box.
				}
				unset( $pto_taxonomies );
			}
			unset( $pt );
		}

		if ( $taxonomy_names_custom !== array() ) {
			foreach ( $taxonomy_names_custom as $tax ) {
				$this->defaults[ 'taxonomy-' . $tax . '-ptparent' ] = 0; // Select box;.
			}
			unset( $tax );
		}
	}

	/**
	 * Validate the option
	 *
	 * @param  array $dirty New value for the option.
	 * @param  array $clean Clean value for the option, normally the defaults.
	 * @param  array $old   Old value of the option.
	 *
	 * @return  array      Validated clean value for the option to be saved to the database
	 */
	protected function validate_option( $dirty, $clean, $old ) {

		$allowed_post_types = $this->get_allowed_post_types();

		foreach ( $clean as $key => $value ) {

			$switch_key = $this->get_switch_key( $key );

			switch ( $switch_key ) {
				/* text fields */
				case 'breadcrumbs-404crumb':
				case 'breadcrumbs-archiveprefix':
				case 'breadcrumbs-home':
				case 'breadcrumbs-prefix':
				case 'breadcrumbs-searchprefix':
				case 'breadcrumbs-sep':
					if ( isset( $dirty[ $key ] ) ) {
						$clean[ $key ] = wp_kses_post( $dirty[ $key ] );
					}
					break;

				/* 'post_types-' . $pt->name . '-maintax' fields */
				case 'post_types-':
					$post_type  = str_replace( array( 'post_types-', '-maintax' ), '', $key );
					$taxonomies = get_object_taxonomies( $post_type, 'names' );

					if ( isset( $dirty[ $key ] ) ) {
						if ( $taxonomies !== array() && in_array( $dirty[ $key ], $taxonomies, true ) ) {
							$clean[ $key ] = $dirty[ $key ];
						}
						elseif ( (string) $dirty[ $key ] === '0' || (string) $dirty[ $key ] === '' ) {
							$clean[ $key ] = 0;
						}
						elseif ( sanitize_title_with_dashes( $dirty[ $key ] ) === $dirty[ $key ] ) {
							// Allow taxonomies which may not be registered yet.
							$clean[ $key ] = $dirty[ $key ];
						}
						else {
							if ( isset( $old[ $key ] ) ) {
								$clean[ $key ] = sanitize_title_with_dashes( $old[ $key ] );
							}
							if ( function_exists( 'add_settings_error' ) ) {
								/**
								 * @todo [JRF => whomever] maybe change the untranslated $pt name in the
								 * error message to the nicely translated label ?
								 */
								add_settings_error(
									$this->group_name, // Slug title of the setting.
									'_' . $key, // Suffix-id for the error message box.
									sprintf( __( 'Please select a valid taxonomy for post type "%s"', 'wordpress-seo' ), $post_type ), // The error message.
									'error' // Error type, either 'error' or 'updated'.
								);
							}
						}
					}
					elseif ( isset( $old[ $key ] ) ) {
						$clean[ $key ] = sanitize_title_with_dashes( $old[ $key ] );
					}
					unset( $taxonomies, $post_type );
					break;

				/* 'taxonomy-' . $tax->name . '-ptparent' fields */
				case 'taxonomy-':
					if ( isset( $dirty[ $key ] ) ) {
						if ( $allowed_post_types !== array() && in_array( $dirty[ $key ], $allowed_post_types, true ) ) {
							$clean[ $key ] = $dirty[ $key ];
						}
						elseif ( (string) $dirty[ $key ] === '0' || (string) $dirty[ $key ] === '' ) {
							$clean[ $key ] = 0;
						}
						elseif ( sanitize_key( $dirty[ $key ] ) === $dirty[ $key ] ) {
							// Allow taxonomies which may not be registered yet.
							$clean[ $key ] = $dirty[ $key ];
						}
						else {
							if ( isset( $old[ $key ] ) ) {
								$clean[ $key ] = sanitize_key( $old[ $key ] );
							}
							if ( function_exists( 'add_settings_error' ) ) {
								/**
								 * @todo [JRF =? whomever] maybe change the untranslated $tax name in the
								 * error message to the nicely translated label ?
								 */
								$tax = str_replace( array( 'taxonomy-', '-ptparent' ), '', $key );
								add_settings_error(
									$this->group_name, // Slug title of the setting.
									'_' . $tax, // Suffix-id for the error message box.
									sprintf( __( 'Please select a valid post type for taxonomy "%s"', 'wordpress-seo' ), $tax ), // The error message.
									'error' // Error type, either 'error' or 'updated'.
								);
								unset( $tax );
							}
						}
					}
					elseif ( isset( $old[ $key ] ) ) {
						$clean[ $key ] = sanitize_key( $old[ $key ] );
					}
					break;

				/*
				Boolean fields
				*/

				/*
				Covers:
				 * 		'breadcrumbs-blog-remove'
				 * 		'breadcrumbs-boldlast'
				 * 		'breadcrumbs-enable'
				 */
				default:
					$clean[ $key ] = ( isset( $dirty[ $key ] ) ? WPSEO_Utils::validate_bool( $dirty[ $key ] ) : false );
					break;
			}
		}

		return $clean;
	}

	/**
	 * Retrieve a list of the allowed post types as breadcrumb parent for a taxonomy
	 * Helper method for validation
	 *
	 * @internal don't make static as new types may still be registered
	 *
	 * @return array
	 */
	protected function get_allowed_post_types() {
		$allowed_post_types = array();

		$post_types = get_post_types( array( 'public' => true ), 'objects' );

		if ( get_option( 'show_on_front' ) == 'page' && get_option( 'page_for_posts' ) > 0 ) {
			$allowed_post_types[] = 'post';
		}

		if ( is_array( $post_types ) && $post_types !== array() ) {
			foreach ( $post_types as $type ) {
				if ( $type->has_archive ) {
					$allowed_post_types[] = $type->name;
				}
			}
		}

		return $allowed_post_types;
	}

	/**
	 * Clean a given option value
	 *
	 * @param  array  $option_value          Old (not merged with defaults or filtered) option value to
	 *                                       clean according to the rules for this option.
	 * @param  string $current_version       (optional) Version from which to upgrade, if not set,
	 *                                       version specific upgrades will be disregarded.
	 * @param  array  $all_old_option_values (optional) Only used when importing old options to have
	 *                                       access to the real old values, in contrast to the saved ones.
	 *
	 * @return  array            Cleaned option
	 */
	protected function clean_option( $option_value, $current_version = null, $all_old_option_values = null ) {

		/* Make sure the old fall-back defaults for empty option keys are now added to the option */
		if ( isset( $current_version ) && version_compare( $current_version, '1.5.2.3', '<' ) ) {
			if ( has_action( 'init', array( 'WPSEO_Options', 'bring_back_breadcrumb_defaults' ) ) === false ) {
				add_action( 'init', array( 'WPSEO_Options', 'bring_back_breadcrumb_defaults' ), 3 );
			}
		}

		/*
		Make sure the values of the variable option key options are cleaned as they
			   may be retained and would not be cleaned/validated then
		*/
		if ( is_array( $option_value ) && $option_value !== array() ) {

			$allowed_post_types = $this->get_allowed_post_types();

			foreach ( $option_value as $key => $value ) {
				$switch_key = $this->get_switch_key( $key );

				// Similar to validation routine - any changes made there should be made here too.
				switch ( $switch_key ) {
					/* 'post_types-' . $pt->name . '-maintax' fields */
					case 'post_types-':
						$post_type  = str_replace( array( 'post_types-', '-maintax' ), '', $key );
						$taxonomies = get_object_taxonomies( $post_type, 'names' );

						if ( $taxonomies !== array() && in_array( $value, $taxonomies, true ) ) {
							$option_value[ $key ] = $value;
						}
						elseif ( (string) $value === '0' || (string) $value === '' ) {
							$option_value[ $key ] = 0;
						}
						elseif ( sanitize_title_with_dashes( $value ) === $value ) {
							// Allow taxonomies which may not be registered yet.
							$option_value[ $key ] = $value;
						}
						unset( $taxonomies, $post_type );
						break;

					/* 'taxonomy-' . $tax->name . '-ptparent' fields */
					case 'taxonomy-':
						if ( $allowed_post_types !== array() && in_array( $value, $allowed_post_types, true ) ) {
							$option_value[ $key ] = $value;
						}
						elseif ( (string) $value === '0' || (string) $value === '' ) {
							$option_value[ $key ] = 0;
						}
						elseif ( sanitize_key( $option_value[ $key ] ) === $option_value[ $key ] ) {
							// Allow post types which may not be registered yet.
							$option_value[ $key ] = $value;
						}
						break;
				}
			}
		}

		return $option_value;
	}

	/**
	 * With the changes to v1.5, the defaults for some of the textual breadcrumb settings are added
	 * dynamically, but empty strings are allowed.
	 * This caused issues for people who left the fields empty on purpose relying on the defaults.
	 * This little routine fixes that.
	 * Needs to be run on 'init' hook at prio 3 to make sure the defaults are translated.
	 */
	public function bring_back_defaults() {
		$option = get_option( $this->option_name );

		$values_to_bring_back = array(
			'breadcrumbs-404crumb',
			'breadcrumbs-archiveprefix',
			'breadcrumbs-home',
			'breadcrumbs-searchprefix',
			'breadcrumbs-sep',
		);
		foreach ( $values_to_bring_back as $key ) {
			if ( $option[ $key ] === '' && $this->defaults[ $key ] !== '' ) {
				$option[ $key ] = $this->defaults[ $key ];
			}
		}
		update_option( $this->option_name, $option );
	}
}

redpajama_set_name: RedPajamaGithub


text:
#include <environment.h>
#include <image.h>
#include <mousebuttonevent.h>
#include <joystickevent.h>
#include <keyboardevent.h>

#include "frontend.h"

FrontEnd::FrontEnd(const string& next, const string& image,
    unsigned long duration)
    : Level("", next), m_image(nullptr), m_start(0), m_duration(duration)
{
    Environment *env = Environment::get_instance();
    env->events_manager->register_mouse_button_event_listener(this);
    env->events_manager->register_keyboard_event_listener(this);
    env->events_manager->register_joystick_event_listener(this);

    m_image = env->resources_manager->get_image(image);

    m_x = (env->canvas->w() - m_image->w())/2;
    m_y = (env->canvas->h() - m_image->h())/2;
}

FrontEnd::~FrontEnd()
{
    Environment *env = Environment::get_instance();
    env->events_manager->unregister_mouse_button_event_listener(this);
    env->events_manager->unregister_keyboard_event_listener(this);
    env->events_manager->unregister_joystick_event_listener(this);
}

void
FrontEnd::draw_self()
{
    Environment *env = Environment::get_instance();
    env->canvas->clear();
    env->canvas->draw(m_image.get(), m_x, m_y);
}

void
FrontEnd::update_self(unsigned long elapsed)
{
    if (not m_start)
    {
        m_start = elapsed;
    }

    if (elapsed - m_start > m_duration)
    {
        m_done = true;
    }
}

bool
FrontEnd::onMouseButtonEvent(const MouseButtonEvent& event)
{
    if (event.state() == MouseButtonEvent::PRESSED)
    {
        m_done = true;
        return true;
    }

    return false;
}

bool
FrontEnd::onJoyStickEvent(const JoyStickEvent& event)
{
    if (event.state() == JoyStickEvent::PRESSED)
    {
        m_done = true;
        return true;
    }

    return false;
}

bool
FrontEnd::onKeyboardEvent(const KeyboardEvent& event)
{
    if (event.state() == KeyboardEvent::PRESSED)
    {
        m_done = true;
        return true;
    }

    return false;
}


text:
package mnm.mods.itemdash;

import static org.lwjgl.input.Keyboard.*;

public class Konami {

    private static final int[] CODE = { KEY_UP, KEY_UP, KEY_DOWN, KEY_DOWN, KEY_LEFT, KEY_RIGHT, KEY_LEFT, KEY_RIGHT, KEY_B, KEY_A, KEY_RETURN };

    private final Runnable toRun;
    private int current;

    public Konami(Runnable onComplete) {
        this.toRun = onComplete;
    }

    public void onKey(int code) {
        if (code == CODE[current]) {
            current++;
        } else {
            current = 0;
        }
        if (current == CODE.length) {
            toRun.run();
            current = 0;
        }
    }
}


text:
package main

import (
	"encoding/json"
	"errors"
	"flag"
	//"fmt"

	c "github.com/gcloud/compute"
	p "github.com/gcloud/providers"
	_ "github.com/gcloud/providers/digitalocean"
	_ "github.com/gcloud/providers/vbox"
)

var provider = flag.String("p", "vbox", "Provider to use for actions.")
var name = flag.String("name", "", "Name of the object.")

func DoServers(provider string, method string) ([]byte, error) {
	s := &c.Servers{Provider: provider}
	switch method {
	case "list":
		r, err := s.List()
		return respond(r, err)
	case "show":
		r, err := s.Show(*name)
		return respond(r, err)
	case "add":
		r, err := s.Create(s.NewServer(p.Map{"name": *name}))
		return respond(r, err)
	case "destroy":
		r, err := s.Destroy(*name)
		return respond(r, err)
	}
	return nil, errors.New("Missing method for Servers.")
}

func main() {
	flag.Parse()
	method := flag.Arg(0)
	pkg := flag.Arg(1)
	switch pkg {
	case "servers":
		result, err := DoServers(*provider, method)
		if err != nil {
			println(string(err.Error()))
			return
		}
		println(string(result))
	}
}

func respond(r interface{}, err error) ([]byte, error) {
	if err != nil {
		return nil, err
	}
	switch response := r.(type) {
	case nil:
		return nil, err
	case []byte:
		return response, err
	case bool:
		return []byte(`true`), err
	case string:
		return []byte(response), err
	default:
		return json.Marshal(r)
	}
	return nil, err
}


text:
import axios from 'axios';

const tokenConfig = function (token) {
    return {
        headers: {
            'Authorization': token
        }
    }
};

export function validate_token(token) {
    return axios.post('/api/is_token_valid', {
        token: token,
    })
}

export function get_github_access() {
    window.open(
        '/github-login',
        '_blank' // <- This is what makes it open in a new window.
    );
}

export function create_user(email, password) {
    return axios.post('api/user', {
        email: email,
        password: password
    })
}

export function get_token(email, password) {
    return axios.post('api/get_token', {
        email: email,
        password: password
    })
}

export function get_transactions(token) {
    return axios.get('api/transactions', tokenConfig(token))
}

export function protected_endpoint(token,endpoint) {
    return axios.get(endpoint, tokenConfig(token))
}


text:
<?php

namespace Cygnite\Exception\Http;

class ResponseException extends \RuntimeException
{
}


text:
#!/usr/local/bin/php
<?php

$pgtitle = array("Diagnostics", "Reboot system");
require("guiconfig.inc");

if ($_POST) {
	if ($_POST['Submit'] == " Yes ") {
		system_reboot();
		$rebootmsg = "The system is rebooting now. This may take one minute.";
	} else {
		header("Location: index.php");
		exit;
	}
}
?>
<?php include("fbegin.inc"); ?>
<?php if ($rebootmsg): echo print_info_box($rebootmsg); else: ?>
      <form action="reboot.php" method="post">

Are you sure you want to reboot the system?

          <input name="Submit" type="submit" class="formbtn" value=" Yes ">
          <input name="Submit" type="submit" class="formbtn" value=" No ">

      </form>
<?php endif; ?>
<?php include("fend.inc"); ?>


text:
layout: page
title: Contact
---

<p class="message">
  Hey there!  Thanks for visiting, if you'd like to get in touch I'd love to hear from you!
</p>

{% include contact.html %}


text:
namespace Google.Cloud.Dataplex.V1.Snippets
{
    // [START dataplex_v1_generated_MetadataService_CreateEntity_async_flattened_resourceNames]
    using System.Threading.Tasks;
    using gcdv = Google.Cloud.Dataplex.V1;

    public sealed partial class GeneratedMetadataServiceClientSnippets
    {
        /// <summary>Snippet for CreateEntityAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task CreateEntityResourceNamesAsync()
        {
            // Create client
            MetadataServiceClient metadataServiceClient = await MetadataServiceClient.CreateAsync();
            // Initialize request argument(s)
            ZoneName parent = ZoneName.FromProjectLocationLakeZone("[PROJECT]", "[LOCATION]", "[LAKE]", "[ZONE]");
            Entity entity = new Entity();
            // Make the request
            Entity response = await metadataServiceClient.CreateEntityAsync(parent, entity);
        }
    }
    // [END dataplex_v1_generated_MetadataService_CreateEntity_async_flattened_resourceNames]
}


text:
<?php

declare(strict_types = 1);

namespace Unicity\EVT\EventWriter {

	use \Unicity\EVT;

	class StdOut extends EVT\EventWriter {

		/**
		 * This constructor initializes the class with the specified resource.
		 *
		 * @access public
		 * @param array $metadata                                   the metadata to be set
		 */
		public function __construct(array $metadata = array()) {
			parent::__construct(array_merge(array(
				'eol' => "\n",
			), $metadata));
		}

		/**
		 * This method writes an array of events to the event storage.
		 *
		 * @access public
		 * @param array $events                                     the events to be written
		 */
		public function write(array $events) {
			foreach ($events as $event) {
				fwrite(STDOUT, json_encode($event) . $this->metadata['eol']);
			}
		}

	}

}


text:
[![Build Status](https://travis-ci.org/codeforamerica/ohana-web-search.png?branch=master)](https://travis-ci.org/codeforamerica/ohana-web-search) [![Coverage Status](https://coveralls.io/repos/codeforamerica/ohana-web-search/badge.png?branch=master)](https://coveralls.io/r/codeforamerica/ohana-web-search?branch=master) [![Dependency Status](https://gemnasium.com/codeforamerica/ohana-web-search.png)](https://gemnasium.com/codeforamerica/ohana-web-search) [![Code Climate](https://codeclimate.com/github/codeforamerica/ohana-web-search.png)](https://codeclimate.com/github/codeforamerica/ohana-web-search)

Ohana Web Search is one of two Rails apps that come out of the box with the [Ohana API](https://github.com/codeforamerica/ohana-api) platform. The other app is an [admin interface](https://github.com/codeforamerica/ohana-api-admin) that allows people to update the data. Both apps also serve as examples of what can be built on top of the social services data that the Ohana API exposes.

This project was developed by [Code for America's 2013 San Mateo County, CA,](http://codeforamerica.org/2013-partners/san-mateo-county/) fellowship team. Thanks to a [grant from the Knight Foundation](http://www.knightfoundation.org/grants/201447979/), [@monfresh](https://github.com/monfresh), [@spara](https://github.com/spara), and [@anselmbradford](https://github.com/anselmbradford) will continue to push code in 2014.

Ohana Web Search aims to make it easy to find available services in a community, and to provide as much pertinent information as possible, such as travel directions, hours of operation, other services residents in need might be eligible for, etc.
You can see a live example for services in San Mateo County, CA, here: [http://smc-connect.org](http://smc-connect.org)

We gladly welcome contributions. Below you will find instructions for installing the project and contributing.

## Demo
You can see a running version of the application at
[https://ohana-web-search-demo.herokuapp.com/](https://ohana-web-search-demo.herokuapp.com/).

## Stack Overview

* Ruby version 2.2.1
* Rails version 4.2.1
* Template Engines: ERB and HAML
* Testing Frameworks: RSpec, Capybara, Poltergeist

## Deploying to Heroku
See the [Wiki](https://github.com/codeforamerica/ohana-web-search/wiki/How-to-deploy-Ohana-Web-Search-to-your-Heroku-account).

## Local Installation (for developers)

Follow the instructions in [INSTALL.md][install].

[install]: https://github.com/codeforamerica/ohana-web-search/blob/master/INSTALL.md

## Customization

Follow the instructions in [CUSTOMIZE.md][customize].

[customize]: https://github.com/codeforamerica/ohana-web-search/blob/master/CUSTOMIZE.md

## Running the tests
To test locally, you can run tests with this simple command:

    script/test

To configure the way RSpec displays test results, create a file called `.rspec` in the root directory, and add the following to it:

    --color
    --format progress

The `--color` option allows you to see passing tests in green and failing ones in red. Otherwise, by default, you would just see a series of dots for passing tests, and the letter "F" for failing ones.

Parameters for the `--format` option are: `progress` (default - shows a series of dots), `documentation`, `html`, or `textmate`. [More information can be found on the RSpec website](https://www.relishapp.com/rspec/rspec-core/v/3-0/docs/configuration/read-command-line-configuration-options-from-files).

To see the actual tests, browse through the [spec](https://github.com/codeforamerica/ohana-web-search/tree/master/spec) directory.

## Contributing
We'd love to get your help developing this project! Take a look at the [Contribution Document](https://github.com/codeforamerica/ohana-web-search/blob/master/CONTRIBUTING.md) to see how you can make a difference.

## Copyright
Copyright (c) 2013-2014 Code for America. See [LICENSE](https://github.com/codeforamerica/ohana-web-search/blob/master/LICENSE.md) for details.


text:
package org.kuali.rice.kns.datadictionary.validation.fieldlevel;

import org.kuali.rice.krad.datadictionary.validation.FieldLevelValidationPattern;

/**
 * Validation pattern for matching standard-format (yyyy-mm-dd hh:mm:ss.m) timestamps
 *
 * @deprecated Use {@link org.kuali.rice.krad.datadictionary.validation.constraint.ConfigurationBasedRegexPatternConstraint}.
 */
@Deprecated
public class TimestampValidationPattern extends FieldLevelValidationPattern {

    /**
     * @see org.kuali.rice.krad.datadictionary.validation.FieldLevelValidationPattern#getPatternTypeName()
     */
    protected String getPatternTypeName() {
        return "timestamp";
    }
}


text:
package com.amazonaws.services.lightsail.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.lightsail.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * ContainerServicePowerMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class ContainerServicePowerMarshaller {

    private static final MarshallingInfo<String> POWERID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("powerId").build();
    private static final MarshallingInfo<Float> PRICE_BINDING = MarshallingInfo.builder(MarshallingType.FLOAT).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("price").build();
    private static final MarshallingInfo<Float> CPUCOUNT_BINDING = MarshallingInfo.builder(MarshallingType.FLOAT).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("cpuCount").build();
    private static final MarshallingInfo<Float> RAMSIZEINGB_BINDING = MarshallingInfo.builder(MarshallingType.FLOAT).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("ramSizeInGb").build();
    private static final MarshallingInfo<String> NAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("name").build();
    private static final MarshallingInfo<Boolean> ISACTIVE_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("isActive").build();

    private static final ContainerServicePowerMarshaller instance = new ContainerServicePowerMarshaller();

    public static ContainerServicePowerMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(ContainerServicePower containerServicePower, ProtocolMarshaller protocolMarshaller) {

        if (containerServicePower == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(containerServicePower.getPowerId(), POWERID_BINDING);
            protocolMarshaller.marshall(containerServicePower.getPrice(), PRICE_BINDING);
            protocolMarshaller.marshall(containerServicePower.getCpuCount(), CPUCOUNT_BINDING);
            protocolMarshaller.marshall(containerServicePower.getRamSizeInGb(), RAMSIZEINGB_BINDING);
            protocolMarshaller.marshall(containerServicePower.getName(), NAME_BINDING);
            protocolMarshaller.marshall(containerServicePower.getIsActive(), ISACTIVE_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
package tubame.wsearch.biz.util.resource;

import java.io.IOException;
import java.io.InputStream;
import java.util.MissingResourceException;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

/**
 * This is a class to manage the resource information.

 */
public class ResourceUtil {

    /**
     * Resource bundle
     */
    private static ResourceBundle resource = null;

    static {
        try {
            resource = PropertyResourceBundle
                    .getBundle("properties.wsearch.resource");
        } catch (MissingResourceException e) {
            resource = null;
        }
    }

    /**
     * Specify the input stream, set the bundle of resources.

     *
     * @param in
     *            Input stream
     * @throws IOException
     *             If it fails to load the stream
     */
    public static void setBundle(InputStream in) throws IOException {
        resource = new PropertyResourceBundle(in);
    }

    /**
     * Get the set value corresponding to the key from the properties file.

     *
     * @param key
     *            Key
     * @return Setting
     */
    public static String getResourceString(String key) {
        if (resource == null) {
            return key;
        }
        try {
            return resource.getString(key);
        } catch (MissingResourceException e) {
            return key;
        }
    }
}


text:
//
// ToyBox library - framework for matchmaking networked games
// Copyright (C) 2005-2012 Three Rings Design, Inc., All Rights Reserved
// http://github.com/threerings/game-gardens
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

package com.threerings.toybox.client;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;

import com.samskivert.io.StreamUtil;
import com.samskivert.swing.HGroupLayout;
import com.samskivert.swing.SimpleSlider;

import com.threerings.util.MessageBundle;
import com.threerings.util.MessageManager;

import com.threerings.parlor.game.client.SwingGameConfigurator;
import com.threerings.parlor.game.data.GameAI;

import com.threerings.parlor.data.ChoiceParameter;
import com.threerings.parlor.data.Parameter;
import com.threerings.parlor.data.RangeParameter;
import com.threerings.parlor.data.ToggleParameter;

import com.threerings.toybox.data.AIParameter;
import com.threerings.toybox.data.ToyBoxGameConfig;
import com.threerings.toybox.data.FileParameter;
import com.threerings.toybox.data.GameDefinition;
import com.threerings.toybox.util.ToyBoxContext;

import static com.threerings.toybox.Log.log;

/**
 * Handles the configuration of a ToyBox game. This works in conjunction with the {@link
 * ToyBoxGameConfig} to provide a generic mechanism for defining and obtaining game configuration
 * settings.
 */
public class ToyBoxGameConfigurator extends SwingGameConfigurator
{
    // documentation inherited
    @Override
    protected void gotGameConfig ()
    {
        super.gotGameConfig();

        ToyBoxContext ctx = (ToyBoxContext)_ctx;
        ToyBoxGameConfig config = (ToyBoxGameConfig)_config;
        GameDefinition gamedef = config.getGameDefinition();

        // create our parameter editors
        if (_editors == null) {
            MessageBundle msgs = ctx.getMessageManager().getBundle(config.getGameIdent());
            _editors = new ParamEditor[gamedef.params.length];
            for (int ii = 0; ii < _editors.length; ii++) {
                _editors[ii] = createEditor(ctx, msgs, gamedef.params[ii]);
                addControl(new JLabel(msgs.get(gamedef.params[ii].getLabel())),
                           (JComponent) _editors[ii]);
            }
        }

        // now read our parameters
        for (int ii = 0; ii < gamedef.params.length; ii++) {
            _editors[ii].readParameter(gamedef.params[ii], config);
        }
    }

    // documentation inherited
    @Override
    protected void flushGameConfig ()
    {
        super.flushGameConfig();

        ToyBoxGameConfig config = (ToyBoxGameConfig)_config;
        GameDefinition gamedef = config.getGameDefinition();
        for (int ii = 0; ii < gamedef.params.length; ii++) {
            _editors[ii].writeParameter(gamedef.params[ii], config);
        }
    }

    protected ParamEditor createEditor (ToyBoxContext ctx, MessageBundle msgs, Parameter param)
    {
        if (param instanceof AIParameter) {
            return new AIEditor((AIParameter)param);
        } else if (param instanceof RangeParameter) {
            return new RangeEditor((RangeParameter)param);
        } else if (param instanceof ToggleParameter) {
            return new ToggleEditor((ToggleParameter)param);
        } else if (param instanceof ChoiceParameter) {
            return new ChoiceEditor(msgs, (ChoiceParameter)param);
        } else if (param instanceof FileParameter) {
            return new FileEditor(ctx, (FileParameter)param);
        } else {
            log.warning("Unknown parameter type! " + param + ".");
            return null;
        }
    }

    /** Provides a uniform interface to our UI components. */
    protected static interface ParamEditor
    {
        public void readParameter (Parameter param, ToyBoxGameConfig config);
        public void writeParameter (Parameter param, ToyBoxGameConfig config);
    }

    protected class RangeEditor extends SimpleSlider implements ParamEditor
    {
        public RangeEditor (RangeParameter param)
        {
            super(null, param.minimum, param.maximum, param.start);
        }

        public void readParameter (Parameter param, ToyBoxGameConfig config)
        {
            setValue((Integer)config.params.get(param.ident));
        }

        public void writeParameter (Parameter param, ToyBoxGameConfig config)
        {
            config.params.put(param.ident, getValue());
        }
    }

    protected class ToggleEditor extends JPanel implements ParamEditor
    {
        public ToggleEditor (ToggleParameter param)
        {
            setLayout(new HGroupLayout(HGroupLayout.NONE, HGroupLayout.LEFT));
            add(_box = new JCheckBox(null, null, param.start));
        }

        public void readParameter (Parameter param, ToyBoxGameConfig config)
        {
            _box.setSelected((Boolean)config.params.get(param.ident));
        }

        public void writeParameter (Parameter param, ToyBoxGameConfig config)
        {
            config.params.put(param.ident, _box.isSelected());
        }

        protected JCheckBox _box;
    }

    protected class ChoiceEditor extends JPanel implements ParamEditor
    {
        public ChoiceEditor (MessageBundle msgs, ChoiceParameter param)
        {
            setLayout(new HGroupLayout(HGroupLayout.NONE, HGroupLayout.LEFT));
            Choice[] choices = new Choice[param.choices.length];
            Choice selection = null;
            for (int ii = 0; ii < choices.length; ii++) {
                String choice = param.choices[ii];
                choices[ii] = new Choice();
                choices[ii].choice = choice;
                choices[ii].label = msgs.get(param.getChoiceLabel(ii));
                if (choice.equals(param.start)) {
                    selection = choices[ii];
                }
            }
            add(_combo = new JComboBox(choices));
            if (selection != null) {
                _combo.setSelectedItem(selection);
            }
        }

        public void readParameter (Parameter param, ToyBoxGameConfig config)
        {
            Choice selected = new Choice();
            selected.choice = (String)config.params.get(param.ident);
            _combo.setSelectedItem(selected);
        }

        public void writeParameter (Parameter param, ToyBoxGameConfig config)
        {
            config.params.put(param.ident, ((Choice)_combo.getSelectedItem()).choice);
        }

        protected JComboBox _combo;
    }

    protected static class Choice
    {
        public String choice;
        public String label;

        @Override
        public String toString () {
            return label;
        }

        @Override public boolean equals (Object other) {
            return (other instanceof Choice) && choice.equals(((Choice) other).choice);
        }

        @Override public int hashCode () {
            return choice.hashCode();
        }
    }

    protected class FileEditor extends JPanel
        implements ParamEditor, ActionListener
    {
        public FileEditor (ToyBoxContext ctx, FileParameter param)
        {
            _ctx = ctx;
            _param = param;
            setLayout(new HGroupLayout(HGroupLayout.NONE, HGroupLayout.LEFT));
            String label = ctx.getMessageManager().getBundle(
                MessageManager.GLOBAL_BUNDLE).get("m.file_unset");
            add(_show = new JButton(label));
            _show.addActionListener(this);
        }

        public void readParameter (Parameter param, ToyBoxGameConfig config)
        {
            // nothing doing
        }

        public void writeParameter (Parameter param, ToyBoxGameConfig config)
        {
            if (_data != null) {
                config.params.put(param.ident, _data);
            }
        }

        public void actionPerformed (ActionEvent event)
        {
            if (event.getSource() == _show) {
                if (_chooser == null) {
                    _chooser = new JFileChooser();
                }

                int rv = _chooser.showOpenDialog(this);
                if (rv == JFileChooser.APPROVE_OPTION) {
                    File file = _chooser.getSelectedFile();

                    try {
                        if (_param.binary) {
                            _data = StreamUtil.toByteArray(new FileInputStream(file));
                        } else {
                            _data = StreamUtil.toString(new FileReader(file));
                        }
                        _show.setText(file.getName());

                    } catch (IOException ioe) {
                        String msg = MessageBundle.tcompose(
                            "m.file_read_failure", ioe.getMessage());
                        _ctx.getChatDirector().displayFeedback(null, msg);
                        log.warning("Failed to read '" + file + "': " + ioe.getMessage());
                    }
                }
            }
        }

        protected ToyBoxContext _ctx;
        protected FileParameter _param;
        protected JButton _show;
        protected JFileChooser _chooser;
        protected Object _data;
    }

    protected class AIEditor extends SimpleSlider implements ParamEditor
    {
        public AIEditor (AIParameter param)
        {
            super(null, 0, param.maximum, 0);
        }

        public void readParameter (Parameter param, ToyBoxGameConfig config)
        {
            setValue((config.ais == null) ? 0 : config.ais.length);
        }

        public void writeParameter (Parameter param, ToyBoxGameConfig config)
        {
            config.ais = new GameAI[getValue()];
            for (int ii = 0; ii < config.ais.length; ii++) {
                // TODO: allow specification of difficulty and personality
                config.ais[ii] = new GameAI(0, 0);
            }
        }
    }

    protected ParamEditor[] _editors;
}


text:
_Noreturn void* start_udp_server(void *_data) {
    struct udp_server_data *restrict data = _data;

    int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if(sock < 0)
        die("Unable to create a UDP server socket");

    struct sockaddr_in server_address;
    memset(&server_address, 0, sizeof(struct sockaddr_in));
    server_address.sin_family = AF_INET;
    server_address.sin_addr.s_addr = htonl(INADDR_ANY);
    server_address.sin_port = htons(data->port);

    if(bind(sock, (struct sockaddr *) &server_address,
                (socklen_t) sizeof(server_address)) < 0)
        die("Unable to bind the UDP server socket to port %d\n", data->port);

    while(true) {
        uint64_t data[2];
        struct sockaddr_in addr;
        socklen_t addrlen = sizeof(addr);

        ssize_t len = recvfrom(sock, data, sizeof(uint64_t), 0,
                (struct sockaddr*) &addr, &addrlen);

        if(len < 0)
            die("Unable to receive UDP packet");
        else if(len != sizeof(uint64_t))
            continue;

        data[1] = htobe64(gettime());

        len = sendto(sock, data, sizeof(data), 0, (struct sockaddr*) &addr, addrlen);

        if(len < 0)
            die("Unable to send UDP reply packet");
    }
}


text:
package org.waabox.bomb;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

import org.objenesis.ObjenesisHelper;

/** Proxy helper that isolates the Proxy generation.
 *
 * Has 2 strategies, the 1st one use sun.misc.Unsafe if could not create the
 * instance, will use Objenesis.
 *
 * @author waabox (waabox[at]gmail[dot]com)
 */
public class Proxy {

  /** The unsafe instance, it's Object because some JVM could not have the
   * Unsafe class, or could have a protection, etc.
   */
  private static Object unsafe;

  /** The Unsafe method to execute.*/
  private static final String UNSAFE_METHOD = "allocateInstance";

  /** Checks the existence of the sun.misc.Unsafe and tries to initialize it.*/
  static {
    try {
      Class<?> klass = Class.forName("sun.misc.Unsafe");

      if (klass.getMethod(UNSAFE_METHOD, Class.class) == null) {
        throw new Exception("does not have the allocateInstance method, exit");
      }

      Constructor<?> constructor;
      constructor = klass.getDeclaredConstructor();
      constructor.setAccessible(true);

      unsafe = constructor.newInstance();

    } catch (Exception e) {
      unsafe = null;
    }
  }

  /** Creates a new Proxy for the given class.
   * @param proxyClass the proxy class.
   * @return the object or null.#
   */
  public static Object create(final Class<?> proxyClass) {
    if (unsafe != null) {
      return fromUnsafe(proxyClass);
    } else {
      return fromObjenesis(proxyClass);
    }
  }

  /** Creates a new Proxy instance using {@link Unsafe}.
   * @param proxyClass the Proxy class.
   * @return the instance, or null.
   */
  private static Object fromUnsafe(final Class<?> proxyClass) {
    try {
      Method method = unsafe.getClass().getMethod(UNSAFE_METHOD, Class.class);
      return method.invoke(unsafe, proxyClass);
    } catch (Exception e) {
      return null;
    }
  }

  /** Creates a new instance using {@link ObjenesisHelper}.
   * @param proxyClass the Proxy class.
   * @return the instance.
   */
  private static Object fromObjenesis(final Class<?> proxyClass) {
    return ObjenesisHelper.newInstance(proxyClass);
  }

}


text:
@interface ExampleView : UIView

@property (nonatomic, readonly) UITextField *textField;
@property (nonatomic, readonly) UIButton *button;
@property (nonatomic, readonly) UITextView *statusTextView;
@property (nonatomic, readonly) UILabel *bottomLabel;

@property (nonatomic, assign) CGFloat keyboardHeight;

@end


text:
require 'test_helper'

module MystroVolley
  class ProjectsHelperTest < ActionView::TestCase
  end
end


text:
api_user = DryAuth::User.create! username: 'pbx-user-max', email: 'api-pbx-max@example.com', password: '62946294'
api_user.add_role :api
api_user.save # generate authentication_token  after role is assigned


text:
namespace language {
class LanguageModelManager;
}  // namespace language

namespace user_prefs {
class PrefRegistrySyncable;
}  // namespace user_prefs

namespace ios_web_view {

class WebViewBrowserState;

class WebViewLanguageModelManagerFactory
    : public BrowserStateKeyedServiceFactory {
 public:
  static language::LanguageModelManager* GetForBrowserState(
      WebViewBrowserState* browser_state);
  static WebViewLanguageModelManagerFactory* GetInstance();

 private:
  friend class base::NoDestructor<WebViewLanguageModelManagerFactory>;

  WebViewLanguageModelManagerFactory();
  ~WebViewLanguageModelManagerFactory() override = default;

  // BrowserStateKeyedServiceFactory implementation.
  std::unique_ptr<KeyedService> BuildServiceInstanceFor(
      web::BrowserState* context) const override;
  void RegisterBrowserStatePrefs(
      user_prefs::PrefRegistrySyncable* const registry) override;
  web::BrowserState* GetBrowserStateToUse(
      web::BrowserState* state) const override;

  DISALLOW_COPY_AND_ASSIGN(WebViewLanguageModelManagerFactory);
};

}  // namespace ios_web_view

#endif  // IOS_WEB_VIEW_INTERNAL_LANGUAGE_WEB_VIEW_LANGUAGE_MODEL_MANAGER_FACTORY_H_


text:
var Node = function(val, next) {
  this.val = val;
  this.next = next;
}
var printList = function(node) {
  if (!node) return;

  console.log(node.val);
  printList(node.next);
}

var reverseList = function(node) {
  if (!node.next) return node;
  var nodeNext = node.next;
  var nodeNextNext = node.next.next;
  nodeNext.next = node;
  nodeNext = node.next;
  nodeNextNext
  reverseList(node.next);
}
var six = new Node(6, null);
var five = new Node(5, six);
var four = new Node(4, five);
var three = new Node(3, four);
var two = new Node(2, three);
var one = new Node(1, two);

printList(one)


text:
module VirtualMonkey
  module TestCaseInterface
    def set_var(sym, *args)
      behavior(sym, *args)
    end

    def behavior(sym, *args)
      begin
        rerun_test
        #pre-command
        populate_settings unless @populated
        #command
        result = __send__(sym, *args)
        #post-command
        continue_test
      rescue Exception => e
        dev_mode?(e)
      end while @rerun_last_command.pop
      result
    end

    def verify(method, expectation, *args)
      if expectation =~ /((exception)|(error)|(fatal)|(fail))/i
        expect = "fail"
        error_msg = expectation.split(":")[1..-1].join(":")
      elsif expectation =~ /((success)|(succeed)|(pass))/i
        expect = "pass"
      elsif expectation =~ /nil/i
        expect = "nil"
      else
        raise 'Syntax Error: verify expects a "pass", "fail", or "nil"'
      end

      begin
        rerun_test
        result = __send__(command, *args)
        if expect != "pass" and not (result == nil and expect == "nil")
          raise "FATAL: Failed verification"
        end
        continue_test
      rescue Exception => e
        if not ("#{e}" =~ /#{error_msg}/ and expect == "fail")
          dev_mode?(e)
        end
      end while @rerun_last_command.pop
    end

    def probe(server, command, &block)
      # run command on servers matching "server" over ssh
      result = ""
      @servers.select { |s| s.nickname =~ /#{server}/ }.each { |s|
        begin
          rerun_test
          result_temp = s.spot_check_command(command)
          if not yield(result_temp[:output])
            raise "FATAL: Server #{s.nickname} failed probe. Got #{result_temp[:output]}"
          end
          continue_test
        rescue Exception => e
          dev_mode?(e)
        end while @rerun_last_command.pop
        result += result_temp[:output]
      }
    end

    private

    def dev_mode?(e)
      if not ENV['MONKEY_NO_DEBUG'] =~ /true/i
        puts e
        puts "Pausing for debugging..."
        debugger
      else
        exception_handle(e)
      end
    end

    def exception_handle(e)
      puts "ATTENTION: Using default exception_handle(e). This can be overridden in mixin classes."
      if e.message =~ /Insufficient capacity/
        puts "Got \"#{e.message}\". Retrying...."
        sleep 60
      else
        raise e
      end
    end

    def help
      puts "Here are some of the wrapper methods that may be of use to you in your debugging quest:\n"
      puts "behavior(sym, *args): Pass the method name (as a symbol or string) and the optional arguments"
      puts "                      that you wish to pass to that method; behavior() will call that method"
      puts "                      with those arguments while handling nested exceptions, retries, and"
      puts "                      debugger calls.\n"
      puts "                      Examples:"
      puts "                        behavior(:launch_all)"
      puts "                        behavior(:launch_set, 'Load Balancer')\n"
      puts "verify(sym, expectation_string, *args): Pass the method name (as a symbol or string), the expected"
      puts "                                        result, and any arguments to pass to that method. The"
      puts "                                        expectation_string should consist of 'Error: MyRegex',"
      puts "                                        'Pass', or 'nil'. 'Error: MyRegex' tells verify() that it"
      puts "                                        should expect an exception to be raised, and the message "
      puts "                                        or exception name should match /MyRegex/. 'Pass' tells"
      puts "                                        verify() that it should expect the method to return normally,"
      puts "                                        and 'nil' tells verify() that it should expect the method to"
      puts "                                        return nil.\n"
      puts "                                        Example:"
      puts "                                          verify(:launch_all, 'Error: execution expired')\n"
      puts "probe(server_regex, shell_command, &block): Provides a one-line interface for running a command on"
      puts "                                            a set of servers and verifying their output. The block"
      puts "                                            should take one argument, the output string from one of"
      puts "                                            the servers, and return true or false based on however"
      puts "                                            the developer wants to verify correctness.\n"
      puts "                                            Examples:"
      puts "                                              probe('.*', 'ls') { |s| puts s }"
      puts "                                              probe('.*', 'uname -a') { |s| s =~ /x64/ }\n"
      puts "continue_test: Disables the retry loop that reruns the last command (the current command that you're"
      puts "               debugging.\n"
      puts "help: Prints this help message."
    end

    def populate_settings
      @servers.each { |s| s.settings }
      lookup_scripts
      @populated = 1
    end

    def object_behavior(obj, sym, *args)
      begin
        rerun_test
        #pre-command
        populate_settings unless @populated
        #command
        result = obj.__send__(sym, *args)
        #post-command
        continue_test
      rescue Exception => e
        dev_mode?(e)
      end while @rerun_last_command.pop
      result
    end

    def rerun_test
      @rerun_last_command.push(true)
    end

    def continue_test
      @rerun_last_command.pop
      @rerun_last_command.push(false)
    end
  end
end


text:
"""Transformer block implementation in JAX based on official TF model."""

from __future__ import absolute_import
from __future__ import division
from __future__ import REDACTED
from __future__ import print_function

import math
from typing import List
from typing import TypeVar
from absl import flags
from flax import nn
from flax.nn import attention
import jax
from jax import lax
import jax.numpy as jnp
from REDACTED.tensorflow_models.mlperf.models.rough.bert_jax import utils

flags.DEFINE_bool(
    'use_einsum', False, help='Whether to use einsums instead dense generals.')
FLAGS = flags.FLAGS

Precision = TypeVar('Precision', bound=lax.Precision)
NEG_INFINITY = -10000.0
LAYER_NORM_EPSILON = 1e-12

class Dense3D(nn.Module):
  """Embedding Module.

  A parameterized function from integers [0, n) to d-dimensional vectors.
  """

  def apply(self, input_tensor, num_attention_heads, size_per_head,
            kernel_init, bias_init, dtype):
    """A dense layer with 3D kernel.

    Args:
      input_tensor: float Tensor of shape [batch, seq_length, hidden_size].
      num_attention_heads: Number of attention heads.
      size_per_head: The size per attention head.
      kernel_init: Kernel initializer.
      bias_init: Bias initializer.
      dtype: data type.
    Returns:
      float logits Tensor.
    """
    last_dim = input_tensor.shape[-1]
    w = self.param('kernel', (last_dim, num_attention_heads * size_per_head),
                   kernel_init)

    w = jnp.reshape(w, [last_dim, num_attention_heads, size_per_head])
    w = w.astype(dtype)
    b = self.param('bias', (num_attention_heads * size_per_head,),
                   bias_init)

    b = jnp.reshape(b, [num_attention_heads, size_per_head])
    b = b.astype(dtype)
    ret = jnp.einsum('abc,cde->abde', input_tensor, w)
    ret += b
    return ret

class Dense2D(nn.Module):
  """Embedding Module.

  A parameterized function from integers [0, n) to d-dimensional vectors.
  """

  def apply(self, input_tensor, output_size, kernel_init, bias_init, dtype):
    """A dense layer with 3D kernel.

    Args:
      input_tensor: float Tensor of shape [batch, seq_length, hidden_size].
      output_size: Number of attention heads.
      kernel_init: Kernel initializer.
      bias_init: Bias initializer.
      dtype: data type.
    Returns:
      float logits Tensor.
    """
    last_dim = input_tensor.shape[-1]
    w = self.param('kernel', (last_dim, output_size), kernel_init)
    w = w.astype(dtype)
    b = self.param('bias', (output_size,), bias_init)
    b = b.astype(dtype)
    ret = jnp.einsum('abc,cd->abd', input_tensor, w)
    ret += b
    return ret

def self_attention(inputs,
                   variable_dictionary,
                   num_heads: int,
                   qkv_features: int = None,
                   padding_mask: List[bool] = None,
                   dropout_rate: float = 0.,
                   deterministic: bool = False,
                   precision: Precision = None,
                   kernel_init: List[float] = nn.linear.default_kernel_init,
                   bias_init: List[float] = nn.initializers.zeros,
                   dtype: jnp.dtype = jnp.float32,
                   bias: bool = True):
  """Applies Multi-head self-attention on the input data.

  Args:
    inputs: input data of shape `[bs, dim1, dim2, ..., dimN, features]`.
    variable_dictionary: Parameter dictionary.
    num_heads: number of attention heads. Features (i.e. inputs.shape[-1])
      should be divisible by the number of heads.
    qkv_features: dimension of the key, query, and value.
    padding_mask: boolean specifying tokens that are pad token.
    dropout_rate: dropout rate
    deterministic: bool, deterministic or not (to apply dropout)
    precision: numerical precision of the computation see `jax.lax.Precision`
      for details.
    kernel_init: initializer for the kernel of the Dense layers.
    bias_init: initializer for the bias of the Dense layers.
    dtype: datatype for the activiations, jnp.bfloat16 or jnp.float32
    bias: bool: whether pointwise QKVO dense transforms use bias.

  Returns:
    output of shape `[bs, dim1, dim2, ..., dimN, features//num_heads]`.
  """

  features = inputs.shape[-1]
  qkv_features = qkv_features or features

  assert qkv_features % num_heads == 0, (
      'Memory dimension must be divisible by number of heads.')
  head_dim = qkv_features // num_heads
  inputs = inputs.astype(dtype)
  if FLAGS.use_einsum:
    dense_module = Dense3D
  else:
    dense_module = attention.DenseGeneral

  query = dense_module.call(
      variable_dictionary['query'],
      inputs,
      axis=-1,
      features=(num_heads, head_dim),
      kernel_init=kernel_init,
      bias_init=bias_init,
      bias=bias,
      precision=precision,
      dtype=dtype,
      name='query')
  query = jnp.multiply(query, 1.0 / math.sqrt(float(head_dim)))
  key = dense_module.call(
      variable_dictionary['key'],
      inputs,
      axis=-1,
      features=(num_heads, head_dim),
      kernel_init=kernel_init,
      bias_init=bias_init,
      bias=bias,
      precision=precision,
      dtype=dtype,
      name='key')
  value = dense_module.call(
      variable_dictionary['value'],
      inputs,
      axis=-1,
      features=(num_heads, head_dim),
      kernel_init=kernel_init,
      bias_init=bias_init,
      bias=bias,
      precision=precision,
      dtype=dtype,
      name='value')

  assert query.dtype == dtype
  assert key.dtype == dtype
  assert value.dtype == dtype
  # get raw attention scores from dot product between key and query
  #   B = batch size (number of sequences)
  #   F = `from_tensor` sequence length
  #   T = `to_tensor` sequence length
  #   N = `num_heads`
  #   H = `head_dim` (qkv_features // num_heads)
  attention_scores = jnp.einsum('BTNH,BFNH->BNFT', key, query)
  assert attention_scores.dtype == dtype

  assert attention_scores.dtype == dtype
  # create attention masks
  if padding_mask is not None:
    assert padding_mask.dtype == bool, ('Mask should have bool type.')
    attention_mask = jnp.expand_dims(padding_mask, axis=1)
    adder = (1.0 - attention_mask) * NEG_INFINITY
    attention_scores += adder.astype(dtype)
  assert attention_scores.dtype == dtype

  attention_scores = attention_scores - lax.stop_gradient(
      jnp.max(attention_scores, axis=-1, keepdims=True))
  attention_scores = jnp.exp(attention_scores)
  attention_sum = jnp.sum(attention_scores, axis=-1, keepdims=True)

  keep_prob = 1 - dropout_rate
  if not deterministic:
    keep_mask = jax.random.bernoulli(nn.make_rng(), keep_prob,
                                     attention_scores.shape).astype(dtype)
    assert keep_mask.dtype == dtype
    attention_probs = jnp.multiply(keep_mask, attention_scores)
  else:
    attention_probs = attention_scores

  assert attention_probs.dtype == dtype

  attention_probs = jnp.einsum('BNFT,BTNH->BFNH', attention_probs, value)
  assert attention_probs.dtype == dtype
  attention_probs = attention_probs / jnp.transpose(attention_sum, [0, 2, 1, 3])

  # split mask and scaling ops in dropout
  # move the scaling from dropout to here to save same mul ops
  # TODO(yuemmawang) automate this optimization in xla
  if not deterministic:
    scale = 1 / keep_prob
    if dtype == jnp.bfloat16:
      scale = jnp.bfloat16(scale)
    attention_probs = jnp.multiply(attention_probs, scale)
  assert attention_probs.dtype == dtype

  return attention_probs

def transformer_block(
    inputs,
    variable_dictionary,
    qkv_dim: int,
    mlp_dim: int,
    num_heads: int,
    padding_mask: bool = None,
    dropout_rate: float = 0.0,
    attention_dropout_rate: float = 0.1,
    intermediate_activation: str = 'gelu',
    kernel_initializer: List[float] = nn.initializers.xavier_uniform(),
    dtype: jnp.dtype = jnp.float32,
    deterministic: bool = False):
  """Applies TransformerBlock module.

  Args:
    inputs: input data
    variable_dictionary: Parameter dictionary.
    qkv_dim: int dimension of the query/key/value
    mlp_dim: int dimension of the mlp on top of attention block
    num_heads: number of heads
    padding_mask: bool, mask padding tokens
    dropout_rate: dropout rate
    attention_dropout_rate: dropout rate for attention weights
    intermediate_activation: activation function applied to intermediate layer
    kernel_initializer: initializer for dense layer kernels
    dtype: datatype for the activiations, jnp.bfloat16 or jnp.float32
    deterministic: bool, deterministic or not (to apply dropout)

  Returns:
    output after transformer block.
  """

  # Attention block.
  assert inputs.ndim == 3
  attention_output = self_attention(
      inputs,
      variable_dictionary['self_attention'],
      num_heads=num_heads,
      qkv_features=qkv_dim,
      padding_mask=padding_mask,
      kernel_init=kernel_initializer,
      dropout_rate=attention_dropout_rate,
      deterministic=deterministic,
      dtype=dtype)
  attention_output = nn.linear.DenseGeneral.call(
      variable_dictionary['self_attention_output'],
      attention_output,
      features=qkv_dim,
      axis=(-2, -1),
      kernel_init=kernel_initializer,
      dtype=dtype,
      name='self_attention_output')
  assert attention_output.dtype == dtype

  attention_output = nn.dropout(
      attention_output, rate=dropout_rate, deterministic=deterministic)
  assert attention_output.dtype == dtype
  attention_output = inputs + attention_output
  assert attention_output.dtype == dtype

  # Mlp block
  attention_output = nn.LayerNorm.call(
      variable_dictionary['self_attention_layer_norm'],
      attention_output,
      epsilon=LAYER_NORM_EPSILON,
      dtype=dtype,
      name='self_attention_layer_norm')
  assert attention_output.dtype == dtype
  if FLAGS.use_einsum:
    intermediate_output = Dense2D.call(
        variable_dictionary['intermediate'],
        attention_output,
        mlp_dim,
        kernel_initializer,
        bias_init=nn.initializers.zeros,
        dtype=dtype,
        name='intermediate')
  else:
    intermediate_output = nn.Dense.call(
        variable_dictionary['intermediate'],
        attention_output,
        mlp_dim,
        kernel_init=kernel_initializer,
        dtype=dtype,
        name='intermediate')

  assert intermediate_output.dtype == dtype
  intermediate_output = utils.apply_activation(intermediate_output,
                                               intermediate_activation)
  assert intermediate_output.dtype == dtype
  if FLAGS.use_einsum:
    layer_output = Dense2D.call(
        variable_dictionary['output'],
        intermediate_output, qkv_dim, kernel_initializer,
        bias_init=nn.initializers.zeros, dtype=dtype,
        name='output')
  else:
    layer_output = nn.Dense.call(
        variable_dictionary['output'],
        intermediate_output,
        qkv_dim,
        kernel_init=kernel_initializer,
        dtype=dtype,
        name='output')

  assert layer_output.dtype == dtype

  layer_output = nn.dropout(
      layer_output, rate=dropout_rate, deterministic=deterministic)
  assert layer_output.dtype == dtype

  layer_output = nn.LayerNorm.call(
      variable_dictionary['output_layer_norm'],
      layer_output + attention_output,
      epsilon=LAYER_NORM_EPSILON,
      name='output_layer_norm',
      dtype=dtype)
  assert layer_output.dtype == dtype
  return layer_output


text:
#ifndef DMTEST_H
#define DMTEST_H

#include "dmnamespace.h"

DM_BEGIN_NAMESPACE
class DM_DLL_EXPORT Test
{
public:
    virtual dbool init() = 0;
    virtual void cleanup() = 0;

    virtual void run() = 0;
};
DM_END_NAMESPACE
#endif // DMTEST_H


text:
#ifndef _MAXIM_GAP_H_
#define _MAXIM_GAP_H_

#include "mbed.h"
#include "ble/blecommon.h"
#include "ble/GapAdvertisingParams.h"
#include "ble/GapAdvertisingData.h"
#include "ble/Gap.h"
#include "ble/GapScanningParams.h"
#include "dm_api.h"
#include "att_api.h"

/**************************************************************************/
/*!
    \brief

*/
/**************************************************************************/
class MaximGap : public Gap
{
public:
    static MaximGap &getInstance();

    /* Functions that must be implemented from Gap */
    virtual ble_error_t setAddress(AddressType_t  type,  const Address_t address);
    virtual ble_error_t getAddress(AddressType_t *typeP, Address_t address);
    virtual ble_error_t setAdvertisingData(const GapAdvertisingData &, const GapAdvertisingData &);

    #define BLE_GAP_ADV_INTERVAL_MIN        0x0020 /**< Minimum Advertising interval in 625 us units, i.e. 20 ms. */
    #define BLE_GAP_ADV_NONCON_INTERVAL_MIN 0x00A0 /**< Minimum Advertising interval in 625 us units for non connectable mode, i.e. 100 ms. */
    #define BLE_GAP_ADV_INTERVAL_MAX        0x4000 /**< Maximum Advertising interval in 625 us units, i.e. 10.24 s. */

    virtual uint16_t getMinAdvertisingInterval(void) const { return BLE_GAP_ADV_INTERVAL_MIN; }
    virtual uint16_t getMinNonConnectableAdvertisingInterval(void) const { return BLE_GAP_ADV_NONCON_INTERVAL_MIN; }
    virtual uint16_t getMaxAdvertisingInterval(void) const { return BLE_GAP_ADV_INTERVAL_MAX; }

    virtual ble_error_t startAdvertising(const GapAdvertisingParams &);
    virtual ble_error_t stopAdvertising(void);
    virtual ble_error_t disconnect(Handle_t connectionHandle, DisconnectionReason_t reason);
    virtual ble_error_t disconnect(DisconnectionReason_t reason);

    virtual ble_error_t setDeviceName(const uint8_t *deviceName);
    virtual ble_error_t getDeviceName(uint8_t *deviceName, unsigned *lengthP);
    virtual ble_error_t setAppearance(GapAdvertisingData::Appearance appearance);
    virtual ble_error_t getAppearance(GapAdvertisingData::Appearance *appearanceP);

    virtual ble_error_t setTxPower(int8_t txPower);
    virtual void        getPermittedTxPowerValues(const int8_t **valueArrayPP, size_t *countP);

    void     setConnectionHandle(uint16_t m_connectionHandle);
    uint16_t getConnectionHandle(void);

    virtual ble_error_t getPreferredConnectionParams(ConnectionParams_t *params);
    virtual ble_error_t setPreferredConnectionParams(const ConnectionParams_t *params);
    virtual ble_error_t updateConnectionParams(Handle_t handle, const ConnectionParams_t *params);

    virtual ble_error_t startRadioScan(const GapScanningParams &scanningParams);
    virtual ble_error_t stopScan(void);

    void     advertisingStopped(void);

private:
    uint16_t m_connectionHandle;
    addr_type_t m_type;
    MaximGap() {
        m_connectionHandle = DM_CONN_ID_NONE;
        m_type = BLEProtocol::AddressType::RANDOM_STATIC;
    }

    MaximGap(MaximGap const &);
    void operator=(MaximGap const &);

    uint8_t advDataCache[HCI_LEN_LE_SET_ADV_DATA];
    uint8_t scanResponseCache[HCI_LEN_LE_SET_SCAN_RESP_DATA];
    int advDataLen;
    int scanResponseLen;
};

#endif /* _MAXIM_GAP_H_ */


text:
from numpy import array, dot, arccos, where, minimum
import math

# Define assert_unorderable() depending on the language
# implicit ordering rules. This keeps things consistent
# across major Python versions
try:
    3 > ""
except TypeError: # pragma: no cover
    # No implicit ordering (newer Python)
    def assert_unorderable(a, b):
        """Assert that a and b are unorderable"""
        return NotImplemented
else: # pragma: no cover
    # Implicit ordering by default (older Python)
    # We must raise an exception ourselves
    # To prevent nonsensical ordering
    def assert_unorderable(a, b):
        """Assert that a and b are unorderable"""
        raise TypeError("unorderable types: %s and %s"
            % (type(a).__name__, type(b).__name__))

def cached_property(func):
    """Special property decorator that caches the computed
    property value in the object's instance dict the first
    time it is accessed.
    """

    def getter(self, name=func.func_name):
        try:
            return self.__dict__[name]
        except KeyError:
            self.__dict__[name] = value = func(self)
            return value

    getter.func_name = func.func_name
    return property(getter, doc=func.func_doc)

def cos_sin_deg(deg):
    """Return the cosine and sin for the given angle
    in degrees, with special-case handling of multiples
    of 90 for perfect right angles
    """
    deg = deg % 360.0
    if deg == 90.0:
        return 0.0, 1.0
    elif deg == 180.0:
        return -1.0, 0
    elif deg == 270.0:
        return 0, -1.0
    rad = math.radians(deg)
    return math.cos(rad), math.sin(rad)

# vim: ai ts=4 sts=4 et sw=4 tw=78

def signed_angle_diff(x,y):
    return (array(x) - array(y) + 180)%360 - 180

def counterclockwise(A,B,C):
    ccw = (C.y-A.y)*(B.x-A.x) > (B.y-A.y)*(C.x-A.x)
    return 1 if ccw > 0.0 else -1 if ccw < 0.0 else 0

def intersects(A,B,C,D):
    return counterclockwise(A,C,D) != counterclockwise(B,C,D) and \
           counterclockwise(A,B,C) != counterclockwise(A,B,D)

def segments_intersect(seg1,seg2):
    A,B = seg1.points
    C,D = seg2.points
    return intersects(A,B,C,D)

def norm(x,axis):
    return sum(abs(x)**2,axis=axis)**0.5

def angle_between(a,b):
    """Return the angle in radians between two vectors of equal
    cardinality.
    """
    a = array(a)
    if len(a.shape) == 1: a = a.reshape((1,len(a)))
    b = array(b).T
    if len(b.shape) == 1: b = b.reshape((len(b),1))
    arccosInput = dot(a,b)[0]/norm(a,axis=-1)/norm(b,axis=-2)
    arccosInput[where(arccosInput > 1.0)] = 1.0
    arccosInput[where(arccosInput < -1.0)] = -1.0
    return arccos(arccosInput)


text:
Keeper::Keeper()
	: m_renderer(nullptr)
	, m_framerate(0) {
	m_windowMgr = new WindowManager();
	m_textureMgr = new TextureManager();
	m_sceneMgr = new SceneManager();
	m_camera = new Camera(m_windowMgr->getWindowSize());
}

Keeper & Keeper::getInstance() {
	static Keeper inst;
	return inst;
}

TextureManager* Keeper::getTextureManager() {
	return m_textureMgr;
}

void Keeper::initRenderer(SDL_Renderer* _renderer) {
	assert(_renderer != nullptr);
	m_renderer = _renderer;
}

SDL_Renderer* Keeper::getRenderer() {
	assert(m_renderer != nullptr);
	return m_renderer;
}

WindowManager * Keeper::getWindowManager() {
	return m_windowMgr;
}

SceneManager * Keeper::getSceneManager() {
	return m_sceneMgr;
}

void Keeper::replaceCurrentScene(std::shared_ptr<Scene> _newScene) {
	m_sceneMgr->replaceCurrentScene(_newScene);
}

void Keeper::runFirstScene(std::shared_ptr<Scene> _newScene) {
	m_sceneMgr->runFirstScene(_newScene);
}

EventHandler Keeper::getEventHandler() {
	return m_sceneMgr->getCurrentSceneEventHandler();
}

void Keeper::drawCurrentScene() {
	m_sceneMgr->drawCurrentScene();
}

void Keeper::updateCurrentScene(float _dt) {
	m_sceneMgr->updateCurrentScene(_dt);
}

void Keeper::setFPS(uint32_t _fps) {
	m_framerate = _fps;
}

uint32_t Keeper::getFPS() {
	return m_framerate;
}

Camera* Keeper::getCamera() {
	return m_camera;
}

void Keeper::end() {
	delete m_camera;
	delete m_sceneMgr;
	delete m_textureMgr;
	delete m_windowMgr;

	SDL_DestroyRenderer(m_renderer);
	TTF_Quit();
	SDL_Quit();
}


text:
using System;
using Xwt.Drawing;

namespace Xwt.Backends
{
	public static class ExtensionMethods
	{
		public static object GetBackend (this XwtComponent obj)
		{
			if (obj != null)
				return ((IFrontend)obj).Backend;
			else
				return null;
		}

		public static IWidgetBackend GetBackend (this Widget obj)
		{
			if (obj != null)
				return (IWidgetBackend)((IFrontend)obj).Backend;
			else
				return null;
		}

		public static object GetBackend (this XwtObject obj)
		{
			if (obj != null)
				return ((IFrontend)obj).Backend;
			else
				return null;
		}

		public static ImageDescription ToImageDescription (this Image img)
		{
			return img != null ? img.ImageDescription : ImageDescription.Null;
		}

		public static double GetValue (this WidgetPlacement al)
		{
			switch (al) {
			case WidgetPlacement.Center:
				return 0.5;
			case WidgetPlacement.End:
				return 1;
			default:
				return 0;
			}
		}

		public static Widget GetInternalParent (this Widget widget)
		{
			return widget.InternalParent;
		}

		public static void RaiseKeyPressed (this CellView cellView, KeyEventArgs args)
		{
			cellView.OnKeyPressed (args);
		}

		public static void RaiseKeyReleased (this CellView cellView, KeyEventArgs args)
		{
			cellView.OnKeyReleased (args);
		}

		public static void RaiseMouseEntered (this CellView cellView)
		{
			cellView.OnMouseEntered ();
		}

		public static void RaiseMouseExited (this CellView cellView)
		{
			cellView.OnMouseExited ();
		}

		public static void RaiseMouseMoved (this CellView cellView, MouseMovedEventArgs args)
		{
			cellView.OnMouseMoved (args);
		}

		public static void RaiseButtonPressed (this CellView cellView, ButtonEventArgs args)
		{
			cellView.OnButtonPressed (args);
		}

		public static void RaiseButtonReleased (this CellView cellView, ButtonEventArgs args)
		{
			cellView.OnButtonReleased (args);
		}
	}
}


text:
<bill session="110" type="h" number="7176" updated="2009-01-09T07:35:14-05:00">
	<status><introduced date="1222488000" datetime="2008-09-27"/></status>

	<introduced date="1222488000" datetime="2008-09-27"/>
	<titles>
		<title type="short" as="introduced">Informed P2P User Act</title>
		<title type="official" as="introduced">To prohibit the installation on a computer of certain "peer-to-peer" file sharing software without first providing notice and obtaining consent from the owner or authorized user of the computer.</title>
	</titles>
	<sponsor id="400039"/>
	<cosponsors>
		<cosponsor id="400018" joined="2008-09-27"/>
		<cosponsor id="400628" joined="2008-09-27"/>
	</cosponsors>
	<actions>
		<action date="1222488000" datetime="2008-09-27"><text>Referred to the House Committee on Energy and Commerce.</text></action>
		<action date="1222488000" datetime="2008-09-27"><text>Referred to the Subcommittee on Telecommunications and the Internet.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>
	<summary>

	</summary>
</bill>