text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Usuario extends CI_Model {

	private $nombre;
	private $apellidos;
	private $deporte;
	private $ciudad;
	private $nombre_usuario;
	private $correo;
	private $contraseña;
	private $tipo_usuario;

	public function __construct($value = null) {
		parent::__construct();

		if ($value != null) {
			if (is_array($value))
				settype($value, 'object');

			if (is_object($value)) {
				$this->nombre = isset($value->nombre)? $value->nombre : null;
				$this->apellidos = isset($value->apellidos)? $value->apellidos : null;
				$this->deporte = isset($value->deporte)? $value->deporte : null;
				$this->ciudad = isset($value->ciudad)? $value->ciudad : null;
				$this->nombre_usuario = isset($value->nombre_usuario)? $value->nombre_usuario : null;
				$this->correo = isset($value->correo)? $value->correo : null;
				$this->contraseña = isset($value->contraseña)? $value->contraseña : null;
				$this->tipo_usuario='Deportista';
			}
		}
	}

	public function __get($key) {
		switch ($key) {
			case 'nombre':
			case 'apellidos':
			case 'deporte':
			case 'ciudad':
			case 'nombre_usuario':
			case 'correo':
			case 'contraseña':
				return $this->$key;
			default:
				return parent::__get($key);
		}
	}

	public function validar() {
		$errores = [];

		if ($this->nombre == null) {
			$errores[] = 'El campo nombre no puede ser vacío';
		}

		if ($this->apellidos == null) {
			$errores[] = 'El campo apellidos no puede estar vacío';
		}

		if ($this->deporte == null) {
			$errores[] = 'El campo deporte no puede estar vacío';
		}

		if ($this->ciudad == null) {
			$errores[] = 'El campo ciudad no puede estar vacío';
		}

		if ($this->correo == null) {
			$errores[] = 'El campo correo electrónico no puede estar vacío';
		}

		if ($this->nombre_usuario == null) {
			$errores[] = 'El campo nombre de usuario no puede estar vacío';
		}

		if ($this->contraseña == null) {
			$errores[] = 'El campo contraseña no puede estar vacío';
		}

		if (empty($errores)) {
			return TRUE;
		} else {
			return $errores;
		}
	}

	public function traer_usuarios($nom_Usuario){

		$this->db->select('nombre_usuario,,nombre, apellidos,id');
		$this->db->from('usuario');
		$this->db->where('nombre_usuario',$nom_Usuario);

		$query=$this->db->get();

		return $query->result();
	}

		public function datos_usuario($id){

		$this->db->select('nombre_usuario');
		$this->db->from('usuario');
		$this->db->where('id',$id);

		$query=$this->db->get();

		return $query->result();
	}

	public function actualizar() {
		$data = [
			'nombre' => $this->nombre,
			'apellidos' => $this->apellidos,
			'deporte' => $this->deporte,
			'ciudad' => $this->ciudad,
			'correo' => $this->correo,
			'nombre_usuario' => $this->nombre_usuario,
			'contraseña' => $this->contraseña,
			'tipo_usuario' => $this->tipo_usuario,
		];

		$this->db->where('nombre_usuario',$this->nombre_usuario);
		return $this->db->update('usuario', $data);
	}

	public function registrar() {
		$data = [
			'nombre' => $this->nombre,
			'apellidos' => $this->apellidos,
			'deporte' => $this->deporte,
			'ciudad' => $this->ciudad,
			'correo' => $this->correo,
			'nombre_usuario' => $this->nombre_usuario,
			'contraseña' => $this->contraseña,
			'tipo_usuario' => $this->tipo_usuario,
		];

		return $this->db->insert('usuario', $data);
	}

	public function login(){
		$this->db->select('nombre_usuario,contraseña');
		$this->db->from('usuario');
		$this->db->where('nombre_usuario',$this->nombre_usuario);
		$this->db->where('contraseña',$this->contraseña);

		$query=$this->db->get();

		if($query->num_rows() ==1){
			return true;
		}else{
			return false;
		}
	}

	public function todos_datos_usuario($usuario){

		$query = $this->db->get_where('usuario', ['nombre_usuario' => $usuario]);
		return $query->result();
	}

	public function consultar_id()
	{
		$this->db->select('id');
		$query = $this->db->get_where('usuario', ['nombre_usuario' => $_GET['itemid']]);

		return $query->result();
	}

	public function consultar_tipo_usuario($nombre_usuario)
	{
		$this->db->select('tipo_usuario');
		$query = $this->db->get_where('usuario', ['nombre_usuario' => $nombre_usuario]);

		return $query->result();
	}

	public function actualizar_Usuario($data){
		if($this->db->update('usuario', $data)) {
			return TRUE;
		} else {
			return FALSE;
		}
	}

	public function delete($id){

		$this->db->delete('usuario', array('nombre_usuario' => $id ));

	}

	public function agregar_motivo($mensaje){

		$this->db->insert('motivos', array('motivos' => $mensaje));

	}

	public function actualizarUsuario($data, $email) {
		$this->db->where('correo', $email);
		$this->db->update('usuario', $data);
	}

	public function update_user($data, $email) {
		$this->db->where('correo', $email);
		$this->db->update('usuario', $data);
	}

	public function does_email_exist($email) {
		$this->db->where('correo', $email);
		$this->db->from('usuario');
		$num_res = $this->db->count_all_results();
		if ($num_res == 1) {
			return TRUE;
		} else {
			return FALSE;
		}
	}

	public function does_code_match($code, $email) {
		$this->db->where('correo', $email);
		$this->db->where('olvidoContrasenia', $code);
		$this->db->from('usuario');
		$num_res = $this->db->count_all_results();

		if ($num_res == 1) {
			return TRUE;
		} else {
			return FALSE;
		}
	}
}


text:
define("vs/code/node/cliProcessMain.nls.es", {
	"vs/base/common/json": [
		"Símbolo no válido",
		"Invalid number format",
		"Property name expected",
		"Value expected",
		"Colon expected",
		"Comma expected",
		"Closing brace expected",
		"Closing bracket expected",
		"Se esperaba un fin de archivo",
	],
	"vs/base/common/severity": [
		"Error",
		"Advertencia",
		"Información",
	],
	"vs/base/node/zip": [
		"{0} no se encontró dentro del archivo zip.",
	],
	"vs/code/node/cliProcessMain": [
		"Extension \'{0}\' not found.",
		"Extension \'{0}\' is not installed.",
		"Asegúrese de usar el identificador de extensión completo, incluido el publicador, por ejemplo: {0}.",
		"Extension \'{0}\' was successfully installed!",
		"Extension \'{0}\' is already installed.",
		"Found \'{0}\' in the marketplace.",
		"Installing...",
		"Extension \'{0}\' v{1} was successfully installed!",
		"Uninstalling {0}...",
		"Extension \'{0}\' was successfully uninstalled!",
	],
	"vs/platform/configuration/common/configurationRegistry": [
		"Aporta opciones de configuración.",
		"Resumen de la configuración. Esta etiqueta se usará en el archivo de configuración como comentario divisor.",
		"Descripción de las propiedades de configuración.",
		"si se establece, \"configuration.type\" debe establecerse en \"object\"",
		"configuration.title debe ser una cadena",
		"configuration.properties debe ser un objeto",
	],
	"vs/platform/extensionManagement/common/extensionManagement": [
		"Extensions",
	],
	"vs/platform/extensionManagement/node/extensionManagementService": [
		"Extension invalid: package.json is not a JSON file.",
		"Extension invalid: manifest name mismatch.",
		"Extension invalid: manifest publisher mismatch.",
		"Extension invalid: manifest version mismatch.",
		"Please restart Code before reinstalling {0}.",
		"No se encontró una versión de {0} compatible con esta versión de Code.",
		"Could not find extension",
	],
	"vs/platform/extensions/common/extensionsRegistry": [
		"Se obtuvo una descripción vacía de la extensión.",
		"la propiedad `{0}` es obligatoria y debe ser de tipo \"string\"",
		"la propiedad `{0}` es obligatoria y debe ser de tipo \"string\"",
		"la propiedad `{0}` es obligatoria y debe ser de tipo \"string\"",
		"la propiedad `{0}` es obligatoria y debe ser de tipo \"object\"",
		"la propiedad `{0}` es obligatoria y debe ser de tipo \"string\"",
		"la propiedad `{0}` se puede omitir o debe ser de tipo \"string[]\"",
		"la propiedad `{0}` se puede omitir o debe ser de tipo \"string[]\"",
		"las propiedades `{0}` y `{1}` deben especificarse u omitirse conjuntamente",
		"la propiedad `{0}` se puede omitir o debe ser de tipo \"string\"",
		"Se esperaba que \"main\" ({0}) se hubiera incluido en la carpeta de la extensión ({1}). Esto puede hacer que la extensión no sea portátil.",
		"las propiedades `{0}` y `{1}` deben especificarse u omitirse conjuntamente",
		"Nombre para mostrar de la extensión que se usa en la galería de VS Code.",
		"Categorías que usa la galería de VS Code para clasificar la extensión.",
		"Banner usado en VS Code Marketplace.",
		"Color del banner en el encabezado de página de VS Code Marketplace.",
		"Tema de color de la fuente que se usa en el banner.",
		"El publicador de la extensión VS Code.",
		"Eventos de activación de la extensión VS Code.",
		"Dependencias a otras extensiones. El identificador de una extensión siempre es ${publisher}.${name}. Por ejemplo: vscode.csharp.",
		"Script que se ejecuta antes de publicar el paquete como extensión VS Code.",
		"Todas las contribuciones de la extensión VS Code representadas por este paquete.",
	],
	"vs/platform/extensions/node/extensionValidator": [
		"No se pudo analizar el valor {0} de \"engines.vscode\". Por ejemplo, use: ^0.10.0, ^1.2.3, ^0.11.0, ^0.10.x, etc.",
		"La versión indicada en \"engines.vscode\" ({0}) no es suficientemente específica. Para las versiones de vscode anteriores a la 1.0.0, defina como mínimo la versión principal y secundaria deseadas. Por ejemplo: ^0.10.0, 0.10.x, 0.11.0, etc.",
		"La versión indicada en \"engines.vscode\" ({0}) no es suficientemente específica. Para las versiones de vscode posteriores a la 1.0.0, defina como mínimo la versión principal deseada. Por ejemplo: ^1.10.0, 1.10.x, 1.x.x, 2.x.x, etc.",
		"La extensión no es compatible con {0} de Code y requiere: {1}.",
		"La versión de la extensión no es compatible con semver.",
	],
	"vs/platform/telemetry/common/telemetryService": [
		"Telemetry",
		"Enable usage data and errors to be sent to Microsoft.",
	]
});

redpajama_set_name: RedPajamaGithub


text:
program t
  write (*,'(a)') 'do if yes; otherwise don''t'
end program t


text:
<?php

/**
 * The concrete command that renders the event.
 *
 * @author     Time.ly Network Inc.
 * @since      2.0
 *
 * @package    AI1EC
 * @subpackage AI1EC.Command
 */
class Ai1ec_Command_Render_Event extends Ai1ec_Command_Render_Calendar {

	/* (non-PHPdoc)
	 * @see Ai1ec_Command::is_this_to_execute()
	 */
	public function is_this_to_execute() {
		global $post;
		if (
			! isset( $post ) ||
			! is_object( $post ) ||
			(int)$post->ID <= 0 ||
			post_password_required( $post->ID )
		) {
			return false;
		}
		return $this->_registry->get( 'acl.aco' )->is_our_post_type();
	}

	/* (non-PHPdoc)
	 * @see Ai1ec_Command::do_execute()
	 */
	public function do_execute() {
		// If not on the single event page, return nothing.
		if ( ! is_single() ) {
			return array(
				'data'     => '',
				'is_event' => true,
			);
		}

		// Else proceed with rendering valid event. Fetch all relevant details.
		$instance      = -1;
		if ( isset( $_REQUEST['instance_id'] ) ) {
			$instance    = (int)$_REQUEST['instance_id'];
		}
		$event         = $this->_registry->get(
			'model.event',
			get_the_ID(),
			$instance
		);
		$event_page    = $this->_registry->get( 'view.event.single' );
		$footer_html   = $event_page->get_footer( $event );
		$css = $this->_registry->get( 'css.frontend' )
			->add_link_to_html_for_frontend();
		$js  = $this->_registry->get( 'controller.javascript' )
			->load_frontend_js( false );

		// If requesting event by JSON (remotely), return fully rendered event.
		if ( 'html' !== $this->_request_type ) {
			return array(
				'data'     => array(
					'html'   => $event_page->get_full_article( $event, $footer_html )
				),
				'callback' => Ai1ec_Request_Parser::get_param( 'callback', null ),
			);
		}
		// Else return event details as components.
		return array(
			'data'     => $event_page->get_content( $event ),
			'is_event' => true,
			'footer'   => $footer_html,
		);
	}
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <title>Utilization Chart</title>
  <meta name="Name" content="App: Utilization Chart" />
  <meta name="Version" content="2012.11.21" />
  <meta name="Vendor" content="Rally Software" />

              loading chart...


text:
layout: page
title: Valley Holdings Conference
date: 2016-05-24
author: Elizabeth Mills
tags: weekly links, java
status: published
summary: Nunc dapibus leo a ipsum consequat, quis finibus urna elementum.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 04/02/2018
  endDate: 04/06/2018
  ctyhocn: SBNSQHX
  groupCode: VHC
published: true
---
Cras volutpat nunc ut nibh condimentum viverra. Praesent nec arcu vel nunc feugiat luctus tempus et ligula. Fusce condimentum congue condimentum. Vivamus congue dui sit amet eros maximus consectetur. In hac habitasse platea dictumst. Pellentesque pretium imperdiet massa, id volutpat erat finibus feugiat. Suspendisse a augue augue. Donec lobortis lobortis velit, sed egestas purus mattis vitae.

* Aliquam hendrerit enim vestibulum massa aliquam, a dictum ligula malesuada
* Quisque eget augue ut tortor sagittis porta nec sit amet augue.

Praesent ullamcorper gravida egestas. Praesent vel congue magna. Maecenas mattis, enim eu porta vehicula, augue dui sodales dui, a accumsan augue nulla sit amet nisl. Curabitur tellus erat, euismod quis arcu non, euismod pharetra quam. Pellentesque a rhoncus nisi. Phasellus tortor elit, dignissim in ante ac, placerat dignissim odio. Aenean lacinia scelerisque enim, eu viverra magna tristique semper. Sed mi quam, varius quis elit ut, consectetur aliquet elit. Donec sit amet augue vel augue tempor lacinia in id arcu. Mauris tincidunt malesuada est at pretium.
Pellentesque imperdiet pulvinar nibh, laoreet convallis justo tincidunt non. Cras efficitur quam sit amet laoreet porttitor. Donec aliquam dui quis libero placerat sagittis. Nam id lacinia magna, id hendrerit velit. Maecenas nec diam at turpis fringilla viverra. Aenean et nibh quam. Sed lectus magna, vestibulum et enim eu, auctor suscipit velit. Aenean sit amet viverra massa. Duis luctus sit amet eros non venenatis. In massa nibh, facilisis a laoreet eget, fermentum a turpis. Proin id velit erat. Donec nec semper justo, ut sodales quam. Maecenas molestie pulvinar cursus.


text:
package org.apache.rocketmq.logging;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Slf4jLoggerFactory extends InternalLoggerFactory {

    public Slf4jLoggerFactory() {
        LoggerFactory.getILoggerFactory();
        doRegister();
    }

    @Override
    protected String getLoggerType() {
        return InternalLoggerFactory.LOGGER_SLF4J;
    }

    @Override
    protected InternalLogger getLoggerInstance(String name) {
        return new Slf4jLogger(name);
    }

    @Override
    protected void shutdown() {

    }

    public static class Slf4jLogger implements InternalLogger {

        private Logger logger = null;

        public Slf4jLogger(String name) {
            logger = LoggerFactory.getLogger(name);
        }

        @Override
        public String getName() {
            return logger.getName();
        }

        @Override
        public void debug(String s) {
            logger.debug(s);
        }

        @Override
        public void debug(String s, Object o) {
            logger.debug(s, o);
        }

        @Override
        public void debug(String s, Object o, Object o1) {
            logger.debug(s, o, o1);
        }

        @Override
        public void debug(String s, Object... objects) {
            logger.debug(s, objects);
        }

        @Override
        public void debug(String s, Throwable throwable) {
            logger.debug(s, throwable);
        }

        @Override
        public void info(String s) {
            logger.info(s);
        }

        @Override
        public void info(String s, Object o) {
            logger.info(s, o);
        }

        @Override
        public void info(String s, Object o, Object o1) {
            logger.info(s, o, o1);
        }

        @Override
        public void info(String s, Object... objects) {
            logger.info(s, objects);
        }

        @Override
        public void info(String s, Throwable throwable) {
            logger.info(s, throwable);
        }

        @Override
        public void warn(String s) {
            logger.warn(s);
        }

        @Override
        public void warn(String s, Object o) {
            logger.warn(s, o);
        }

        @Override
        public void warn(String s, Object... objects) {
            logger.warn(s, objects);
        }

        @Override
        public void warn(String s, Object o, Object o1) {
            logger.warn(s, o, o1);
        }

        @Override
        public void warn(String s, Throwable throwable) {
            logger.warn(s, throwable);
        }

        @Override
        public void error(String s) {
            logger.error(s);
        }

        @Override
        public void error(String s, Object o) {
            logger.error(s, o);
        }

        @Override
        public void error(String s, Object o, Object o1) {
            logger.error(s, o, o1);
        }

        @Override
        public void error(String s, Object... objects) {
            logger.error(s, objects);
        }

        @Override
        public void error(String s, Throwable throwable) {
            logger.error(s, throwable);
        }
    }
}


text: console.log('test 3');


text:
import unittest

import roomai.common
from roomai.texas import TexasHoldemAction
from roomai.texas import TexasHoldemEnv

class TexasUtilsTester(unittest.TestCase):
    """
    """

    def test_pattern(self):
        """

        """

        handcards1 =[roomai.common.PokerCard(0, 0), roomai.common.PokerCard(1, 1)]
        keepcards  =[roomai.common.PokerCard(2, 2), roomai.common.PokerCard(3, 3), roomai.common.PokerCard(4, 0), roomai.common.PokerCard(5, 1), roomai.common.PokerCard(6, 2)]
        pattern    = TexasHoldemEnv.__cards2pattern_cards__(handcards1, keepcards)

    def test_cards1(self):
        """

        """
        handcards1 = [roomai.common.PokerCard(0, 0), roomai.common.PokerCard(0, 1)]
        handcards2 = [roomai.common.PokerCard(3, 1), roomai.common.PokerCard(3, 2)]
        keepcards  = [roomai.common.PokerCard(0, 2), roomai.common.PokerCard(0, 3), roomai.common.PokerCard(2, 0), roomai.common.PokerCard(2, 1), roomai.common.PokerCard(3, 3)]
        pattern = TexasHoldemEnv.__cards2pattern_cards__(handcards2, keepcards)[0]
        cards   = TexasHoldemEnv.__cards2pattern_cards__(handcards2, keepcards)[1]

        self.assertEqual(pattern[0],'3_2')
        self.assertEqual(pattern[1],False)
        self.assertEqual(pattern[2],True)
        self.assertEqual(pattern[3],False)
        self.assertEqual(pattern[4][0], 3)
        self.assertEqual(pattern[4][1], 2)
        self.assertEqual(cards[0].point_rank, 3)
        self.assertEqual(cards[1].point_rank, 3)
        self.assertEqual(cards[2].point_rank, 3)
        self.assertEqual(cards[3].point_rank, 2)
        self.assertEqual(cards[4].point_rank, 2)

        self.assertEqual(cards[0].suit_rank, 1)
        self.assertEqual(cards[1].suit_rank, 2)
        self.assertEqual(cards[2].suit_rank, 3)
        self.assertEqual(cards[3].suit_rank, 0)
        self.assertEqual(cards[4].suit_rank, 1)

    def test_cards2(self):
        """

        """

        h1     = [roomai.common.PokerCard(7, 0), roomai.common.PokerCard(7, 1)]
        keep   = [roomai.common.PokerCard(3, 1), roomai.common.PokerCard(4, 2), roomai.common.PokerCard(5, 3), roomai.common.PokerCard(6, 0), roomai.common.PokerCard(7, 2)]
        pattern = TexasHoldemEnv.__cards2pattern_cards__(h1, keep)[0]
        self.assertEqual(pattern[0],"3_1_1")

    def test_cards(self):
        """

        """
        handcards1 = [roomai.common.PokerCard(0, 0), roomai.common.PokerCard(0, 1)]
        handcards2 = [roomai.common.PokerCard(3, 1), roomai.common.PokerCard(3, 2)]
        keepcards  = [roomai.common.PokerCard(0, 2), roomai.common.PokerCard(0, 3), roomai.common.PokerCard(2, 0), roomai.common.PokerCard(2, 1), roomai.common.PokerCard(3, 3)]
        pattern = TexasHoldemEnv.__cards2pattern_cards__(handcards1, keepcards)[0]
        cards   = TexasHoldemEnv.__cards2pattern_cards__(handcards1, keepcards)[1]
        self.assertEqual(pattern[0],'4_1')
        self.assertEqual(pattern[1],False)
        self.assertEqual(pattern[2],True)
        self.assertEqual(pattern[3],False)
        self.assertEqual(pattern[4][0], 4)
        self.assertEqual(pattern[4][1], 1)
        self.assertEqual(cards[0].point_rank, 0)
        self.assertEqual(cards[1].point_rank, 0)
        self.assertEqual(cards[2].point_rank, 0)
        self.assertEqual(cards[3].point_rank, 0)
        self.assertEqual(cards[4].point_rank, 3)

        self.assertEqual(cards[0].suit_rank, 0)
        self.assertEqual(cards[1].suit_rank, 1)
        self.assertEqual(cards[2].suit_rank, 2)
        self.assertEqual(cards[3].suit_rank, 3)
        self.assertEqual(cards[4].suit_rank, 3)

        pattern1 = TexasHoldemEnv.__cards2pattern_cards__(handcards1, keepcards)
        pattern2 = TexasHoldemEnv.__cards2pattern_cards__(handcards2, keepcards)

        diff = TexasHoldemEnv.__compare_handcards__(handcards1, handcards2, keepcards)
        self.assertTrue(diff > 0)

    def test_available_actions(self):
        """

        """
        env = TexasHoldemEnv()
        env.init()

        actions = TexasHoldemEnv.available_actions(env.public_state, env.person_states[env.public_state.turn])
        self.assertTrue("Allin_1000" in actions)

        env.public_state.__raise_account__ = 200
        actions = TexasHoldemEnv.available_actions(env.public_state, env.person_states[env.public_state.turn])
        self.assertTrue("Call_10" in actions)
        self.assertTrue("Raise_210" in actions)
        self.assertTrue("Raise_410" in actions)
        self.assertTrue("Raise_410" in actions)
        self.assertTrue("Raise_810" in actions)
        self.assertTrue("Allin_1000" in actions)
        for key in actions:
            act = actions[key]
            self.assertTrue(TexasHoldemEnv.is_action_valid(act,env.public_state, env.person_states[env.public_state.turn]))

    def test_is_action_valid(self):
        """

        """
        env = TexasHoldemEnv()
        env.init()

        print (TexasHoldemAction.AllIn)
        action = TexasHoldemAction("Allin_1000")
        print (action.key)
        self.assertTrue(env.is_action_valid(action, env.public_state, env.person_states[env.public_state.turn]))

    def test_compare(self):
        """

        """
        h1 = [roomai.common.PokerCard(7, 0), roomai.common.PokerCard(7, 1)]
        h2 = [roomai.common.PokerCard(2, 0), roomai.common.PokerCard(2, 1)]
        h3 = [roomai.common.PokerCard(2, 2), roomai.common.PokerCard(2, 3)]
        k  = [roomai.common.PokerCard(3, 1), roomai.common.PokerCard(4, 2), roomai.common.PokerCard(5, 3), roomai.common.PokerCard(6, 0), roomai.common.PokerCard(7, 2)]

        p1 = TexasHoldemEnv.__cards2pattern_cards__(h1, k)
        p2 = TexasHoldemEnv.__cards2pattern_cards__(h2, k)
        p3 = TexasHoldemEnv.__cards2pattern_cards__(h3, k)


text:
process.env.NODE_ENV = 'test';

var mongoose = require("mongoose");
var User = require('../models/user');

var chai = require('chai');
var chaiHttp = require('chai-http');
var server = require('../server');
var should = chai.should();

chai.use(chaiHttp);

describe('Authentication', () =>{
  before((done) => {
    User.remove({}, (err) => {
       done();
    });
  });
  describe('SIGNIN - Empty DB', () => {
    it('It should NOT signin, email doesnt exist', (done) => {
      var user = {
        email: "a@b.com",
        password: "12345"
      };
      chai.request(server)
          .post('/api/signin')
          .send(user)
          .end((err, res) => {
              res.should.have.status(401);
              res.body.success.should.be.eql(false);
              res.body.message.should.be.eql("Authentication failed. User not found!");
            done();
          });
    });
  });
  describe('SIGNUP', () => {
    it('It should signup', (done) => {
      var user = {
        name: 'Test',
        email: 'a@b.com',
        password: '12345'
      }
      chai.request(server)
          .post('/api/signup')
          .send(user)
          .end((err, res) => {
            res.should.have.status(200);
            res.body.success.should.be.eql(true);
            res.body.user.should.have.property("_id");
            res.body.user.should.have.property("name").eql("Test");
            res.body.user.should.have.property("email").eql("a@b.com");
            res.body.user.should.have.property("isValidated").eql(false);
            res.body.user.should.have.property("hasPayed").eql(false);
            res.body.user.should.have.property("verificationCode").eql(null);
            done();
          });
    });
    it('It should NOT signup, email duplicated', (done) => {
      var user = {
        name: 'Test',
        email: 'a@b.com',
        password: '12345'
      }
      chai.request(server)
          .post('/api/signup')
          .send(user)
          .end((err, res) => {
            res.should.have.status(409);
            res.body.success.should.be.eql(false);
            done();
          });
    });
  });
  describe('SIGNIN', () => {
    it('It should NOT signin, null password', (done) => {
    var user = {
      email: 'a@b.com',
      password: ''
    }
    chai.request(server)
      .post('/api/signin')
      .send(user)
      .end((err, res) => {
          res.should.have.status(401);
          res.body.success.should.be.eql(false);
          res.body.message.should.be.eql("Authentication failed. Incorrect password!");
        done();
      });
    });
    it('It should NOT signin, null email', (done) => {
      var user = {
        email: "",
        password: "12345"
      };
      chai.request(server)
        .post('/api/signin')
        .send(user)
        .end((err, res) => {
            res.should.have.status(401);
            res.body.success.should.be.eql(false);
            res.body.message.should.be.eql("Authentication failed. User not found!");
          done();
        });
    });
    it('It should NOT signin, wrong password', (done) => {
      var user = {
        email: "a@b.com",
        password: "123"
      };
      chai.request(server)
        .post('/api/signin')
        .send(user)
        .end((err, res) => {
            res.should.have.status(401);
            res.body.success.should.be.eql(false);
            res.body.message.should.be.eql("Authentication failed. Incorrect password!");
          done();
        });
    });
  });
});


text:
"use strict";

module.exports = function (sequelize, DataTypes) {
    let User = sequelize.define("user", {
        id : {type : DataTypes.INTEGER ,
            primaryKey : true,
        autoIncrement :true} ,
        name: DataTypes.STRING(60)
    }, {
        timestamps: false,
        freezeTableName: true
    });
    User.sync();
    return User;
};


text:
package mesosphere.marathon.core.task.update.impl.steps

import javax.inject.Named

import akka.event.EventStream
import com.google.inject.Inject
import mesosphere.marathon.core.base.Clock
import mesosphere.marathon.core.task.bus.MarathonTaskStatus.WithMesosStatus
import mesosphere.marathon.core.task.bus.TaskChangeObservables.TaskChanged
import mesosphere.marathon.core.task.update.TaskUpdateStep
import mesosphere.marathon.core.task.{ EffectiveTaskStateChange, Task, TaskStateOp }
import mesosphere.marathon.event.{ EventModule, MesosStatusUpdateEvent }
import mesosphere.marathon.state.Timestamp
import org.apache.mesos.Protos.TaskStatus
import org.slf4j.LoggerFactory

import scala.concurrent.Future

/**
  * Post this update to the internal event stream.
  */
class PostToEventStreamStepImpl @Inject() (
    @Named(EventModule.busName) eventBus: EventStream, clock: Clock) extends TaskUpdateStep {

  private[this] val log = LoggerFactory.getLogger(getClass)

  override def name: String = "postTaskStatusEvent"

  override def processUpdate(taskChanged: TaskChanged): Future[_] = {
    import TaskStateOp.MesosUpdate

    taskChanged match {
      // case 1: Mesos status update => update or expunge
      // In this case, we post the OLD state - when terminated, a persistent task no longer has a launched
      case TaskChanged(MesosUpdate(task, WithMesosStatus(status), now), EffectiveTaskStateChange(_)) =>
        postEvent(clock.now(), Some(status), task)

      // case 2: Any TaskStateOp => update or expunge
      // In this case, we post the NEW state
      case TaskChanged(_, EffectiveTaskStateChange(task)) =>
        postEvent(clock.now(), task.mesosStatus, task)

      case _ =>
        log.debug("Ignoring noop for {}", taskChanged.taskId)
    }

    Future.successful(())
  }

  private[this] def postEvent(timestamp: Timestamp, maybeStatus: Option[TaskStatus], task: Task): Unit = {
    val taskId = task.taskId

    for {
      launched <- task.launched
      status <- maybeStatus
    } {
      log.info(
        "Sending event notification for {} of app [{}]: {}",
        Array[Object](taskId, taskId.runSpecId, status.getState): _*
      )
      eventBus.publish(
        MesosStatusUpdateEvent(
          slaveId = status.getSlaveId.getValue,
          taskId = Task.Id(status.getTaskId),
          taskStatus = status.getState.name,
          message = if (status.hasMessage) status.getMessage else "",
          appId = taskId.runSpecId,
          host = task.agentInfo.host,
          ipAddresses = Task.MesosStatus.ipAddresses(status),
          ports = launched.hostPorts,
          version = launched.runSpecVersion.toString,
          timestamp = timestamp.toString
        )
      )

    }
  }

}


text:
import unittest

from triangle import Triangle, TriangleError

class TriangleTests(unittest.TestCase):
    def test_equilateral_triangles_have_equal_sides(self):
        self.assertEqual("equilateral", Triangle(2, 2, 2).kind())

    def test_larger_equilateral_triangles_also_have_equal_sides(self):
        self.assertEqual("equilateral", Triangle(10, 10, 10).kind())

    def test_isosceles_triangles_have_last_two_sides_equal(self):
        self.assertEqual("isosceles", Triangle(3, 4, 4).kind())

    def test_isosceles_triangles_have_first_and_last_sides_equal(self):
        self.assertEqual("isosceles", Triangle(4, 3, 4).kind())

    def test_isosceles_triangles_have_two_first_sides_equal(self):
        self.assertEqual("isosceles", Triangle(4, 4, 3).kind())

    def test_isosceles_triangles_have_in_fact_exactly_two_sides_equal(self):
        self.assertEqual("isosceles", Triangle(10, 10, 2).kind())

    def test_scalene_triangles_have_no_equal_sides(self):
        self.assertEqual("scalene", Triangle(3, 4, 5).kind())

    def test_scalene_triangles_have_no_equal_sides_at_a_larger_scale_too(self):
        self.assertEqual("scalene", Triangle(10, 11, 12).kind())

        self.assertEqual("scalene", Triangle(5, 4, 2).kind())

    def test_very_small_triangles_are_legal(self):
        self.assertEqual("scalene", Triangle(0.4, 0.6, 0.3).kind())

    def test_triangles_with_no_size_are_illegal(self):
        self.assertRaises(
            TriangleError,
            Triangle, 0, 0, 0
        )

    def test_triangles_with_negative_sides_are_illegal(self):
        self.assertRaises(
            TriangleError,
            Triangle, 3, 4, -5
        )

    def test_triangles_violating_triangle_inequality_are_illegal(self):
        self.assertRaises(
            TriangleError,
            Triangle, 1, 1, 3
        )

    def test_triangles_violating_triangle_inequality_are_illegal_2(self):
        self.assertRaises(
            TriangleError,
            Triangle, 2, 4, 2
        )

    def test_triangles_violating_triangle_inequality_are_illegal_3(self):
        self.assertRaises(
            TriangleError,
            Triangle, 7, 3, 2
        )

if __name__ == '__main__':
    unittest.main()


text:
<!DOCTYPE html>
  <title>Dummy</title>
  <link data-turbolinks-track="true" href="/assets/application.css" media="all" rel="stylesheet">

Questions

      Question text
      Question type
      Enabled
      Updated at

New Question


text:
"""An example that prints Splunk service info & settings."""

import sys, os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))

import splunklib.client as client

try:
    from utils import parse
except ImportError:
    raise Exception("Add the SDK repository to your PYTHONPATH to run the examples "
                "(e.g., export PYTHONPATH=~/splunk-sdk-python.")

if __name__ == "__main__":
    opts = parse(sys.argv[1:], {}, ".splunkrc")
    service = client.connect(**opts.kwargs)

    content = service.info
    for key in sorted(content.keys()):
        value = content[key]
        if isinstance(value, list):
            print "%s:" % key
            for item in value: print "    %s" % item
        else:
            print "%s: %s" % (key, value)

    print "Settings:"
    content = service.settings.content
    for key in sorted(content.keys()):
        value = content[key]
        print "    %s: %s" % (key, value)


text:
NSString *const kMOSouthwestLat = @"lat";
NSString *const kMOSouthwestLng = @"lng";

@interface MOSouthwest ()

- (id)objectOrNilForKey:(id)aKey fromDictionary:(NSDictionary *)dict;

@end

@implementation MOSouthwest

@synthesize lat = _lat;
@synthesize lng = _lng;

+ (MOSouthwest *)modelObjectWithDictionary:(NSDictionary *)dict
{
    MOSouthwest *instance = [[MOSouthwest alloc] initWithDictionary:dict];
    return instance;
}

- (instancetype)initWithDictionary:(NSDictionary *)dict
{
    self = [super init];

    // This check serves to make sure that a non-NSDictionary object
    // passed into the model class doesn't break the parsing.
    if(self && [dict isKindOfClass:[NSDictionary class]]) {
            self.lat = [[self objectOrNilForKey:kMOSouthwestLat fromDictionary:dict] doubleValue];
            self.lng = [[self objectOrNilForKey:kMOSouthwestLng fromDictionary:dict] doubleValue];

    }

    return self;

}

- (NSDictionary *)dictionaryRepresentation
{
    NSMutableDictionary *mutableDict = [NSMutableDictionary dictionary];
    [mutableDict setValue:[NSNumber numberWithDouble:self.lat] forKey:kMOSouthwestLat];
    [mutableDict setValue:[NSNumber numberWithDouble:self.lng] forKey:kMOSouthwestLng];

    return [NSDictionary dictionaryWithDictionary:mutableDict];
}

- (NSString *)description
{
    return [NSString stringWithFormat:@"%@", [self dictionaryRepresentation]];
}

#pragma mark - Helper Method
- (id)objectOrNilForKey:(id)aKey fromDictionary:(NSDictionary *)dict
{
    id object = [dict objectForKey:aKey];
    return [object isEqual:[NSNull null]] ? nil : object;
}

#pragma mark - NSCoding Methods

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];

    self.lat = [aDecoder decodeDoubleForKey:kMOSouthwestLat];
    self.lng = [aDecoder decodeDoubleForKey:kMOSouthwestLng];
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder
{

    [aCoder encodeDouble:_lat forKey:kMOSouthwestLat];
    [aCoder encodeDouble:_lng forKey:kMOSouthwestLng];
}

- (id)copyWithZone:(NSZone *)zone
{
    MOSouthwest *copy = [[MOSouthwest alloc] init];

    if (copy) {

        copy.lat = self.lat;
        copy.lng = self.lng;
    }

    return copy;
}

@end


text:
function out_struct = CFF_read_EMdgmSdataInfo(fid)
%CFF_READ_EMDGMSDATAINFO  Read Data section of S datagram in kmall file
%
%   Information of repeated sensor data in one datagram.
%
%   Info about data from sensor. Part included if data from sensor appears
%   multiple times in a datagram.
%
%   Verified correct for kmall versions H,I
%
%   See also CFF_READ_KMALL_FROM_FILEINFO.

%   Authors: Alex Schimel (NGU, alexandre.schimel@ngu.no) and Yoann Ladroit
%   (NIWA, yoann.ladroit@niwa.co.nz)
%   2017-2021; Last revision: 27-07-2021

% Size in bytes of current struct.
out_struct.numBytesInfoPart = fread(fid,1,'uint16');

% Number of sensor samples added in datagram.
out_struct.numSamplesArray = fread(fid,1,'uint16');

% Length in bytes of one whole sample (decoded and raw data).
out_struct.numBytesPerSample = fread(fid,1,'uint16');

% Length in bytes of raw sensor data.
out_struct.numBytesRawSensorData = fread(fid,1,'uint16');

end


text:
// <copyright file="UserGramSchmidt.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2013 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>

using System;

namespace MathNet.Numerics.LinearAlgebra.Double.Factorization
{
    ///
    /// <para>A class which encapsulates the functionality of the QR decomposition Modified Gram-Schmidt Orthogonalization.</para>
    /// <para>Any real square matrix A may be decomposed as A = QR where Q is an orthogonal mxn matrix and R is an nxn upper triangular matrix.</para>
    ///
    /// <remarks>
    /// The computation of the QR decomposition is done at construction time by modified Gram-Schmidt Orthogonalization.
    /// </remarks>
    internal sealed class UserGramSchmidt : GramSchmidt
    {
        ///
        /// Initializes a new instance of the <see cref="UserGramSchmidt"/> class. This object creates an orthogonal matrix
        /// using the modified Gram-Schmidt method.
        ///
        /// <param name="matrix">The matrix to factor.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="matrix"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentException">If <paramref name="matrix"/> row count is less then column count</exception>
        /// <exception cref="ArgumentException">If <paramref name="matrix"/> is rank deficient</exception>
        public static UserGramSchmidt Create(Matrix<double> matrix)
        {
            if (matrix.RowCount < matrix.ColumnCount)
            {
                throw Matrix.DimensionsDontMatch<ArgumentException>(matrix);
            }

            var q = matrix.Clone();
            var r = Matrix<double>.Build.SameAs(matrix, matrix.ColumnCount, matrix.ColumnCount, fullyMutable: true);

            for (var k = 0; k < q.ColumnCount; k++)
            {
                var norm = q.Column(k).L2Norm();
                if (norm == 0.0)
                {
                    throw new ArgumentException("Matrix must not be rank deficient.");
                }

                r.At(k, k, norm);
                for (var i = 0; i < q.RowCount; i++)
                {
                    q.At(i, k, q.At(i, k) / norm);
                }

                for (var j = k + 1; j < q.ColumnCount; j++)
                {
                    var dot = q.Column(k).DotProduct(q.Column(j));
                    r.At(k, j, dot);
                    for (var i = 0; i < q.RowCount; i++)
                    {
                        var value = q.At(i, j) - (q.At(i, k) * dot);
                        q.At(i, j, value);
                    }
                }
            }

            return new UserGramSchmidt(q, r);
        }

        UserGramSchmidt(Matrix<double> q, Matrix<double> rFull)
            : base(q, rFull)
        {
        }

        ///
        /// Solves a system of linear equations, AX = B, with A QR factorized.
        ///
        /// <param name="input">The right hand side <see cref="Matrix{T}"/>, B.</param>
        /// <param name="result">The left hand side <see cref="Matrix{T}"/>, X.</param>
        public override void Solve(Matrix<double> input, Matrix<double> result)
        {
            // The solution X should have the same number of columns as B
            if (input.ColumnCount != result.ColumnCount)
            {
                throw new ArgumentException("Matrix column dimensions must agree.");
            }

            // The dimension compatibility conditions for X = A\B require the two matrices A and B to have the same number of rows
            if (Q.RowCount != input.RowCount)
            {
                throw new ArgumentException("Matrix row dimensions must agree.");
            }

            // The solution X row dimension is equal to the column dimension of A
            if (Q.ColumnCount != result.RowCount)
            {
                throw new ArgumentException("Matrix column dimensions must agree.");
            }

            var inputCopy = input.Clone();

            // Compute Y = transpose(Q)*B
            var column = new double[Q.RowCount];
            for (var j = 0; j < input.ColumnCount; j++)
            {
                for (var k = 0; k < Q.RowCount; k++)
                {
                    column[k] = inputCopy.At(k, j);
                }

                for (var i = 0; i < Q.ColumnCount; i++)
                {
                    double s = 0;
                    for (var k = 0; k < Q.RowCount; k++)
                    {
                        s += Q.At(k, i) * column[k];
                    }

                    inputCopy.At(i, j, s);
                }
            }

            // Solve R*X = Y;
            for (var k = Q.ColumnCount - 1; k >= 0; k--)
            {
                for (var j = 0; j < input.ColumnCount; j++)
                {
                    inputCopy.At(k, j, inputCopy.At(k, j) / FullR.At(k, k));
                }

                for (var i = 0; i < k; i++)
                {
                    for (var j = 0; j < input.ColumnCount; j++)
                    {
                        inputCopy.At(i, j, inputCopy.At(i, j) - (inputCopy.At(k, j) * FullR.At(i, k)));
                    }
                }
            }

            for (var i = 0; i < FullR.ColumnCount; i++)
            {
                for (var j = 0; j < input.ColumnCount; j++)
                {
                    result.At(i, j, inputCopy.At(i, j));
                }
            }
        }

        ///
        /// Solves a system of linear equations, Ax = b, with A QR factorized.
        ///
        /// <param name="input">The right hand side vector, b.</param>
        /// <param name="result">The left hand side <see cref="Matrix{T}"/>, x.</param>
        public override void Solve(Vector<double> input, Vector<double> result)
        {
            // Ax=b where A is an m x n matrix
            // Check that b is a column vector with m entries
            if (Q.RowCount != input.Count)
            {
                throw new ArgumentException("All vectors must have the same dimensionality.");
            }

            // Check that x is a column vector with n entries
            if (Q.ColumnCount != result.Count)
            {
                throw Matrix.DimensionsDontMatch<ArgumentException>(Q, result);
            }

            var inputCopy = input.Clone();

            // Compute Y = transpose(Q)*B
            var column = new double[Q.RowCount];
            for (var k = 0; k < Q.RowCount; k++)
            {
                column[k] = inputCopy[k];
            }

            for (var i = 0; i < Q.ColumnCount; i++)
            {
                double s = 0;
                for (var k = 0; k < Q.RowCount; k++)
                {
                    s += Q.At(k, i) * column[k];
                }

                inputCopy[i] = s;
            }

            // Solve R*X = Y;
            for (var k = Q.ColumnCount - 1; k >= 0; k--)
            {
                inputCopy[k] /= FullR.At(k, k);
                for (var i = 0; i < k; i++)
                {
                    inputCopy[i] -= inputCopy[k] * FullR.At(i, k);
                }
            }

            for (var i = 0; i < FullR.ColumnCount; i++)
            {
                result[i] = inputCopy[i];
            }
        }
    }
}


text:
Top-level document validity: Bad $regularExpression (options are number, not string)
--DESCRIPTION--
Generated by scripts/convert-bson-corpus-tests.php

DO NOT EDIT THIS FILE
--FILE--
<?php

require_once __DIR__ . '/../utils/tools.php';

throws(function() {
    fromJSON('{"x" : {"$regularExpression" : { "pattern": "a", "$options" : 0}}}');
}, 'MongoDB\Driver\Exception\UnexpectedValueException');

?>
===DONE===
<?php exit(0); ?>
--EXPECT--
OK: Got MongoDB\Driver\Exception\UnexpectedValueException
===DONE===


text:
import tornado.auth
import tornado.httpserver
import tornado.ioloop
import tornado.web
import yaml
from raven.contrib.tornado import AsyncSentryClient
from tornado.options import define, options

from core.models import session
from urls import handlers

# config
with open('app.yaml') as config_yaml:
    app_config = yaml.load(config_yaml)

# Options
define("port", default=8000, help="run on the given port", type=int)
define("domain", default='vagrant.intra.douban.com:8000')

class Application(tornado.web.Application):

    def __init__(self):
        settings = dict(debug=options.debug, autoreload=True)
        tornado.web.Application.__init__(self, handlers, **settings)
        self.db = session
        self.sentry_client = AsyncSentryClient(app_config['sentry'])

app = Application()

if __name__ == "__main__":
    tornado.options.parse_command_line()
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()


text:
class BASE_API TaskQueue : public Task {
 public:
  TaskQueue();
  ~TaskQueue();

  // Push the specified task onto the queue.  When the queue is run, the tasks
  // will be run in the order they are pushed.
  //
  // This method takes ownership of |task| and will delete task after it is run
  // (or when the TaskQueue is destroyed, if we never got a chance to run it).
  void Push(Task* task);

  // Remove all tasks from the queue.  The tasks are deleted.
  void Clear();

  // Returns true if this queue contains no tasks.
  bool IsEmpty() const;

  // Run all the tasks in the queue.  New tasks pushed onto the queue during
  // a run will be run next time |Run| is called.
  virtual void Run();

 private:
   // The list of tasks we are waiting to run.
   std::deque<Task*> queue_;
};

#endif  // BASE_TASK_QUEUE_H_


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

       Copyright 2009-2015 the original author or authors.

       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.

-->
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="org.apache.ibatis.submitted.resultmapwithassociationstest.Mapper">
  <resultMap id="personRM" type="org.apache.ibatis.submitted.resultmapwithassociationstest.Person" >
    <id property="id" column="id"/>
    <collection property="addresses" ofType="org.apache.ibatis.submitted.resultmapwithassociationstest.Address">
      <id property="id" column="address_id" />
    </collection>
  </resultMap>

  <select id="findAll" parameterType="map" resultMap="personRM">
    SELECT p.id, id_address, a.id as address_id
    FROM person p
    JOIN address a
    on a.id = p.id_address
  </select>

</mapper>


text:
<?php

define('DATABASE', 'tryout');
define('USERNAME', 'root');
define('PASSWORD', 'root');

/**
 * Parse Manually Session Data CodeIgniter to Array
 * @param String
 * @return Array
 */
if(! function_exists('sessionToArray')) {
	function sessionToArray($data) {
		if(strlen($data) == 0)
			return [];
		preg_match_all('/(^|;|\})([a-zA-Z0-9_]+)\|/i', $data, $matchesArray, PREG_OFFSET_CAPTURE);
	 	$returnArray = array();
		$lastOffset = null;
		$currentKey = '';
		foreach($matchesArray[2] as $value) {
			$offset = $value[1];
			if(!is_null($lastOffset)) {
				$valueText = substr($data, $lastOffset, $offset - $lastOffset);
				$returnArray[$currentKey] = unserialize($valueText);
			}
			$currentKey = $value[0];
			$lastOffset = $offset + strlen($currentKey) + 1;
		}
		$valueText = substr($data, $lastOffset);
		$returnArray[$currentKey] = unserialize($valueText);
		return $returnArray;
	}
}

$dsn = 'mysql:dbname='.DATABASE.';host=localhost';
try {
    $dbh = new PDO($dsn, USERNAME, PASSWORD);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}
// Get Cookie
// $session_id = $_COOKIE['_sessions'];
// $query = $dbh->prepare("SELECT data FROM `_sessions` WHERE id=:param");
// $query->bindParam(':param', $session_id);
// $query->execute();
// $result = $query->fetch();
// $session_data = sessionToArray($result['data']);
// if(!$session_data['is_logged_in']) {
// 	header('Location: '.$config['base_url']);
// }


text:
from __future__ import absolute_import
from envisage.plugins.remote_editor.enshell_client import *


text:
<!DOCTYPE html>

		<title>parser auto-require unit test</title>

parseOnLoad:true, async: true, auto-require unit test

This page tests that:

parseOnLoad: true parses the page on load

auto-require of modules

the parse happens before the ready() callback happens, including loading of auto-required modules

See console for test results.


text:
#ifndef _isdn_v110_h_
#define _isdn_v110_h_

/*
 * isdn_v110_encode will take raw data and encode it using V.110
 */
extern struct sk_buff *isdn_v110_encode(isdn_v110_stream *, struct sk_buff *);

/*
 * isdn_v110_decode receives V.110 coded data from the stream and rebuilds
 * frames from them. The source stream doesn't need to be framed.
 */
extern struct sk_buff *isdn_v110_decode(isdn_v110_stream *, struct sk_buff *);

extern int isdn_v110_stat_callback(int, isdn_ctrl *);
extern void isdn_v110_close(isdn_v110_stream * v);

#endif


text:
package com.opengamma.analytics.financial.interestrate.future.provider;

import com.opengamma.analytics.financial.interestrate.future.derivative.InterestRateFutureOptionPremiumSecurity;
import com.opengamma.analytics.financial.model.option.pricing.analytic.formula.BlackFunctionData;
import com.opengamma.analytics.financial.model.option.pricing.analytic.formula.BlackPriceFunction;
import com.opengamma.analytics.financial.model.option.pricing.analytic.formula.EuropeanVanillaOption;
import com.opengamma.analytics.financial.model.volatility.BlackFormulaRepository;
import com.opengamma.analytics.financial.provider.description.interestrate.BlackSTIRFuturesProviderInterface;
import com.opengamma.analytics.financial.provider.description.interestrate.ParameterProviderInterface;
import com.opengamma.util.ArgumentChecker;

/**
 * Method for the pricing of STIR future options with up-front premium. The pricing is done with a Black approach on the future rate
 * (1-price). The Black parameters are obtain from implied volatility providers at (expiration-delay-strike-rate) points. The delay is the
 * time difference between the underlying futures last trading date and the option expiration. The price of the underlying STIR futures is
 * computed by "discounting" (no convexity adjustment).
 */
public final class InterestRateFutureOptionPremiumSecurityBlackSTIRFuturesMethod extends FuturesSecurityBlackSTIRFuturesMethod {

  /**
   * Creates the method unique instance.
   */
  private static final InterestRateFutureOptionPremiumSecurityBlackSTIRFuturesMethod INSTANCE = new InterestRateFutureOptionPremiumSecurityBlackSTIRFuturesMethod();

  /**
   * Constructor.
   */
  private InterestRateFutureOptionPremiumSecurityBlackSTIRFuturesMethod() {
  }

  /**
   * Return the method unique instance.
   *
   * @return The instance.
   */
  public static InterestRateFutureOptionPremiumSecurityBlackSTIRFuturesMethod getInstance() {
    return INSTANCE;
  }

  /** The method used to compute the future price. It is a method without convexity adjustment. */
  private static final InterestRateFutureSecurityDiscountingMethod METHOD_FUTURE = InterestRateFutureSecurityDiscountingMethod
      .getInstance();
  /** The Black function used in the pricing. */
  private static final BlackPriceFunction BLACK_FUNCTION = new BlackPriceFunction();

  /**
   * Computes the option security price from future price.
   *
   * @param security
   *          The future option security.
   * @param blackData
   *          The Black volatility and multi-curves provider.
   * @param priceFuture
   *          The price of the underlying future.
   * @return The security price.
   */
  public double price(final InterestRateFutureOptionPremiumSecurity security, final BlackSTIRFuturesProviderInterface blackData,
      final double priceFuture) {
    ArgumentChecker.notNull(security, "Option security");
    ArgumentChecker.notNull(blackData, "Black data");
    final double rateStrike = 1.0 - security.getStrike();
    final EuropeanVanillaOption option = new EuropeanVanillaOption(rateStrike, security.getExpirationTime(), !security.isCall());
    final double rateFutures = 1 - priceFuture;
    final double delay = security.getUnderlyingFuture().getTradingLastTime() - security.getExpirationTime();
    final double volatility = blackData.getVolatility(security.getExpirationTime(), delay, security.getStrike(), priceFuture);
    final BlackFunctionData dataBlack = new BlackFunctionData(rateFutures, 1.0, volatility);
    final double priceSecurity = BLACK_FUNCTION.getPriceFunction(option).evaluate(dataBlack);
    return priceSecurity;
  }

  /**
   * Interpolates and returns the option's implied volatility The future price is computed without convexity adjustment.
   *
   * @param security
   *          The future option security.
   * @param blackData
   *          The curve and Black volatility data.
   * @return Lognormal Implied Volatility.
   */
  public double impliedVolatility(final InterestRateFutureOptionPremiumSecurity security,
      final BlackSTIRFuturesProviderInterface blackData) {
    ArgumentChecker.notNull(security, "Option security");
    ArgumentChecker.notNull(blackData, "Black data");
    final double priceFutures = METHOD_FUTURE.price(security.getUnderlyingFuture(), blackData);
    final double delay = security.getUnderlyingFuture().getTradingLastTime() - security.getExpirationTime();
    return blackData.getVolatility(security.getExpirationTime(), delay, security.getStrike(), priceFutures);
  }

  /**
   * Computes the underlying future security price. The future price is computed without convexity adjustment.
   *
   * @param security
   *          The future option security.
   * @param blackData
   *          The curve and Black volatility data.
   * @return The security price.
   */
  public double underlyingFuturesPrice(final InterestRateFutureOptionPremiumSecurity security, final ParameterProviderInterface blackData) {
    return METHOD_FUTURE.price(security.getUnderlyingFuture(), blackData.getMulticurveProvider());
  }

  /**
   * Computes the option security theoretical delta wrt the underlying futures price. The futures price is computed without convexity
   * adjustment. It is supposed that for a given strike the volatility does not change with the curves.
   *
   * @param security
   *          The future option security.
   * @param blackData
   *          The curve and Black volatility data.
   * @return The delta.
   */
  public double deltaUnderlyingPrice(final InterestRateFutureOptionPremiumSecurity security,
      final BlackSTIRFuturesProviderInterface blackData) {
    ArgumentChecker.notNull(security, "Option security");
    ArgumentChecker.notNull(blackData, "Black data");
    // Forward sweep
    final double priceFutures = METHOD_FUTURE.price(security.getUnderlyingFuture(), blackData);
    final double rateStrike = 1.0 - security.getStrike();
    final EuropeanVanillaOption option = new EuropeanVanillaOption(rateStrike, security.getExpirationTime(), !security.isCall());
    final double rateFutures = 1 - priceFutures;
    final double delay = security.getUnderlyingFuture().getTradingLastTime() - security.getExpirationTime();
    final double volatility = blackData.getVolatility(security.getExpirationTime(), delay, security.getStrike(), priceFutures);
    final BlackFunctionData dataBlack = new BlackFunctionData(rateFutures, 1.0, volatility);
    final double[] priceAdjoint = BLACK_FUNCTION.getPriceAdjoint(option, dataBlack);
    // Implementation note: the black delta is wrt the rateFutures; the function returns the delta with respect to the priceFutures
    return -priceAdjoint[1];
  }

  /**
   * Computes the option's value gamma, the second derivative of the security price wrt underlying futures rate. The future price is
   * computed without convexity adjustment.
   *
   * @param security
   *          The future option security.
   * @param blackData
   *          The curve and Black volatility data.
   * @return The security price.
   */
  public double gammaUnderlyingPrice(final InterestRateFutureOptionPremiumSecurity security,
      final BlackSTIRFuturesProviderInterface blackData) {
    ArgumentChecker.notNull(security, "Option security");
    ArgumentChecker.notNull(blackData, "Black data");
    // Forward sweep
    final double priceFuture = METHOD_FUTURE.price(security.getUnderlyingFuture(), blackData.getMulticurveProvider());
    final double strike = security.getStrike();
    final double rateStrike = 1.0 - strike;
    final EuropeanVanillaOption option = new EuropeanVanillaOption(rateStrike, security.getExpirationTime(), !security.isCall());
    final double forward = 1 - priceFuture;
    final double delay = security.getUnderlyingFuture().getTradingLastTime() - security.getExpirationTime();
    final double volatility = blackData.getVolatility(security.getExpirationTime(), delay, security.getStrike(), rateStrike);
    final BlackFunctionData dataBlack = new BlackFunctionData(forward, 1.0, volatility);
    final double[] firstDerivs = new double[3];
    final double[][] secondDerivs = new double[3][3];
    BLACK_FUNCTION.getPriceAdjoint2(option, dataBlack, firstDerivs, secondDerivs);
    return secondDerivs[0][0];
  }

  /**
   * Computes the option security vega. The future price is computed without convexity adjustment.
   *
   * @param security
   *          The future option security.
   * @param blackData
   *          The curve and Black volatility data.
   * @return Black lognormal vega.
   */
  public double vegaUnderlyingPrice(final InterestRateFutureOptionPremiumSecurity security,
      final BlackSTIRFuturesProviderInterface blackData) {
    // Forward sweep
    final double priceFuture = METHOD_FUTURE.price(security.getUnderlyingFuture(), blackData);
    final double strike = security.getStrike();
    final double rateStrike = 1.0 - strike;
    final EuropeanVanillaOption option = new EuropeanVanillaOption(rateStrike, security.getExpirationTime(), !security.isCall());
    final double forward = 1 - priceFuture;
    final double delay = security.getUnderlyingFuture().getTradingLastTime() - security.getExpirationTime();
    final double volatility = blackData.getVolatility(security.getExpirationTime(), delay, security.getStrike(), rateStrike);
    final BlackFunctionData dataBlack = new BlackFunctionData(forward, 1.0, volatility);
    final double[] priceAdjoint = BLACK_FUNCTION.getPriceAdjoint(option, dataBlack);
    return priceAdjoint[2];
  }

  /**
   * Computes the options theta.
   *
   * @param security
   *          the future option.
   * @param black
   *          the curve and black volatility data.
   * @return the theta.
   */
  public double thetaUnderlyingPrice(final InterestRateFutureOptionPremiumSecurity security,
      final BlackSTIRFuturesProviderInterface black) {
    ArgumentChecker.notNull(security, "security");
    ArgumentChecker.notNull(black, "black");
    final double priceFuture = METHOD_FUTURE.price(security.getUnderlyingFuture(), black);
    final double strike = security.getStrike();
    final double rateStrike = 1.0 - strike;
    final double forward = 1 - priceFuture;
    final double delay = security.getUnderlyingFuture().getTradingLastTime() - security.getExpirationTime();
    final double volatility = black.getVolatility(security.getExpirationTime(), delay, security.getStrike(), rateStrike);
    final double rate = -Math.log(black.getMulticurveProvider().getDiscountFactor(security.getCurrency(), security.getExpirationTime()))
        / security.getExpirationTime();
    return BlackFormulaRepository.theta(forward, rateStrike, security.getExpirationTime(), volatility, !security.isCall(), rate);
  }
}


text:
package jp.riken.kscope.language;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import jp.riken.kscope.information.InformationBlocks;

/**
 * 手続き呼び出しを表現するクラス。
 *
 * @author RIKEN
 *
 */
public class ProcedureUsage extends Block {
	/** シリアル番号 */
	private static final long serialVersionUID = 2385929813029019761L;
	/** サブルーチン、関数呼出名 */
    private String callName;
    /** サブルーチン、関数定義 */
    private transient Procedure callDefinition;
    /** 仮引数 */
    private List<Expression> arguments;
    /** 組込関数フラグ : true=組込関数 */
    private boolean intrinsic = false;
    /** 関数呼出フラグ : true=関数呼出 */
    private boolean isFunctionCall = false;

    /**
     *
     * コンストラクタ。
     *
     * @param mama
     *            親ブロック
     */
    ProcedureUsage(Block mama) {
        super(mama);
    }

    /**
     * コンストラクタ。
     *
     * @param mama
     *            親ブロック
     * @param subroutineName
     *            CALLサブルーチン名
     * @param argmnts
     *            引数リスト
     */
    public ProcedureUsage(Block mama, String subroutineName, List<Expression> argmnts) {
        super(mama);
        callName = subroutineName;
        arguments = argmnts;
    }

    /**
     * コンストラクタ。
     *
     * @param subroutineName
     *            CALLサブルーチン名
     * @param argmnts
     *            引数リスト
     */
    public ProcedureUsage(String subroutineName, List<Expression> argmnts) {
        super();
        callName = subroutineName;
        arguments = argmnts;
    }

    /**
     * ブロックタイプの取得。
     *
     * @return BlockType.PROCEDUREUSAGE
     */
    @Override
    public BlockType getBlockType() {
        return BlockType.PROCEDUREUSAGE;
    }

    @Override
    public String toString() {
        String info = "";
        // delete by @hira at 2013/03/01
        // if (this.getInformation() != null) {
        //    if (!(this.getInformation().getContent().equals(""))) {
        //        info = "[ ! ] ";
        //    }
        // }
        return (info + this.toStringBase());
    }

    @Override
    protected String toStringBase() {
        StringBuilder myString = new StringBuilder();
        String call = "call ";
        if (this.isFunctionCall) {
            call = "function call ";
        }
        myString.append(call + this.callName);
        if (this.arguments != null) {
            myString.append("(");
            for (Expression arg : arguments) {
                myString.append(arg.toString());
                myString.append(", ");
            }
            myString.replace(myString.length() - 2, myString.length(), ")");
        }
        return myString.toString();
    }

    /**
     * 呼び出している手続きの宣言をセットする。
     * @param proc 手続きの宣言
     */
    public void setCallDefinition(Procedure proc) {
        callDefinition = proc;
        if (proc != null) {
        	proc.addCallMember(this);
        }
    }

    /**
     * 組込み関数の呼出しであるとセットする。
     */
    public void setIntrinsic(){
        this.intrinsic = true;
    }

    /**
     * 呼び出し関数名の取得
     *
     * @return call_name 呼び出し関数名
     */
    public String getCallName() {
        return callName;
    }

    /**
     * 呼び出す手続の宣言を返す。
     *
     * @return 手続の宣言
     */
     public Procedure getCallDefinition() {
        return callDefinition;
    }

    /**
     * 実引数のリストを返す。無ければ空のリストを返す。
     *
     * @return 実引数のリスト
     */
    public List<Expression> getArguments() {
        if (this.arguments == null) {
            return new ArrayList<Expression>();
        }
        return arguments;
    }

    /**
     * 指定した名前の変数を実引数に含むか調べ、該当する添字の順番のsetを返す。
     *
     * @param varName
     *            変数の名前
     * @return 添字順番のset(値は0以上)。該当する変数を持たなければ空のsetを返す。
     */
    public Set<Integer> numberOfArg(String varName) {
        Set<Integer> nums = new HashSet<Integer>();
        List<Expression> args = this.getArguments();
        int i = 0;
        for (Expression arg : args) {
            if (arg.hasVariable(varName)) {
                nums.add(i);
            }
            i++;
        }
        return nums;
    }

    /**
     * 組込関数であるか取得する
     * @return		true=組込関数
     */
    public boolean isIntrinsic() {
        return intrinsic;
    }

    /**
     * 関数定義の文字列表現を取得する.
     * @return    関数定義の文字列表現
     */
    private String definitionToString() {
        if (this.callDefinition == null) {
            return "No Definition";
        } else {
            return this.callDefinition.toString();
        }
    }
    /**
     * 自身の宣言のHTML表現を返す。numArgに対応する引数をハイライトする。
     * @param numArg 引数の添字順番
     * @return 自身の宣言のHTML表現文字列。
     */
    public String toDefinitionHTMLString(int numArg) {
        StringBuilder html = new StringBuilder();
        html.append("" + this.definitionToString());
        if (this.arguments != null) {
            html.append("(");
            int count = 0;
            for (Expression arg : arguments) {
                if (count == numArg) {
                    // TODO 本来は、本メソッドの引数としてハイライト対象のStringを受け取り、そこだけを赤くするような処理があったほうが良い
                    html.append("");
                    html.append(arg.toString());
                    html.append("");
                } else {
                    html.append(arg.toString());
                }
                html.append(", ");
                count++;
            }
            html.replace(html.length() - 2, html.length(), ")");
        }
        html.append("");
        return html.toString();
    }

    /**
     * 自身のHTML表現を返す。numArgに対応する引数をハイライトする。
     *
     * @param numArg
     *            引数の添字順番
     * @param name
     *            引数の名前
     * @return 自身のHTML表現文字列。
     */
    public String toHTMLString(int numArg, String name) {
        StringBuilder html = new StringBuilder();
        html.append("" + "call " + this.callName);
        if (this.arguments != null) {
            html.append("(");
            int count = 0;
            for (Expression arg : arguments) {
                if (count == numArg) {
                    // TODO
                    // 本来は、本メソッドの引数としてハイライト対象のStringを受け取り、そこだけを赤くするような処理があったほうが良い
                    html.append("");
                    html.append(arg.toString());
                    html.append("");
                } else {
                    html.append(arg.toString());
                }
                html.append(", ");
                count++;
            }
            html.replace(html.length() - 2, html.length(), ")");
        }
        html.append("");
        return html.toString();
    }

    /**
     * 属するプログラム単位を返す。
     *
     * @return プログラム単位。得られなければnullを返す。
     */
    public Procedure getMyProcedure() {
        Block me = this;
        while (me != null) {
            me = me.get_mother();
            if (me instanceof ExecutableBody) {
                return ((ExecutableBody) me).getParent();
            }
        }
        return null;
    }

    /**
     * 指定された数字が指す順番の実引数に含まれる変数のセットを返す。
     *
     * @param numActualArg
     *            実引数の順番
     * @return 引数に含まれる変数名のセット。無ければ空のセットを返す。
     */
    public Set<String> getActualArgument(int numActualArg) {
        Set<String> varNames = new HashSet<String>();
        if (this.arguments != null) {
            Expression arg = this.arguments.get(numActualArg);
            if (arg != null) {
                Set<Variable> vars = arg.getAllVariables();
                for (Variable var: vars) {
                    varNames.add(var.getName());
                }
            }
        }
        return varNames;
    }

    /**
     * 指定された仮引数名とその順番に対応した実引数の順番を返す。
     *
     * @param dummyArg
     *            仮引数名
     * @param numDummyArg
     *            仮引数の順番
     * @return 実引数の順番。対応が見つからなければ-1を返す。
     */
    public int getNumOfActualArgument(String dummyArg, int numDummyArg) {
        if (this.arguments == null) {
            return -1;
        }
        int cnt = 0;
        for (Expression ex : this.arguments) {
            if (ex instanceof KeywordArgument) {
                KeywordArgument keywrd = (KeywordArgument) ex;
                if (keywrd.getKeyword().equalsIgnoreCase(dummyArg)) {
                    return cnt;
                }
            } else {
                if (cnt == numDummyArg) {
                    return cnt;
                }
            }
            cnt++;
        }
        return -1;
    }

    /**
     * 関数呼び出しであることを設定する。
     */
    public void setTypeIsFunction() {
        this.isFunctionCall = true;
    }

    /**
     * 付加情報ブロックコレクションを生成する。
     *
     * @return 付加情報ブロックコレクション
     */
    @Override
    public InformationBlocks createInformationBlocks() {
        InformationBlocks result = new InformationBlocks();
        result.addAll(super.createInformationBlocks());
        if (this.callDefinition != null) {
            // 自己参照の場合は外す
            if (!this.getNamespace().equals(this.callDefinition.getNamespace()))
            {
                result.addAll(this.callDefinition.createInformationBlocks());
            }
        }
        if (this.arguments != null) {
            for (Expression argument : this.arguments) {
                result.addAll(argument.createInformationBlocks());
            }
        }
        return result;
    }

    /**
     * idにマッチした情報ブロックを検索する。
     * @param id
     *          ID
     * @return 見つかった情報ブロック。見つからなかった場合はnullが返ります。
     */
    @Override
    public IInformation findInformationBlockBy(String id) {
        IInformation result = super.findInformationBlockBy(id);

        if (result == null && this.getID().equals(id)) {
            result = this;
        }

        if (result == null && this.callDefinition != null) {
            // 自己参照の場合は外す
            if (!this.getNamespace().equals(this.callDefinition.getNamespace()))
            {
                result = this.callDefinition.findInformationBlockBy(id);
            }
        }
        if (result == null && this.arguments != null) {
            for (Expression argument : this.arguments) {
                result = argument.findInformationBlockBy(id);
                if (result != null) { break; }
            }
        }

        return result;
    }

    /**
     * 同一ブロックであるかチェックする.
     * @param block		ブロック
	 * @return		true=一致
     */
    @Override
	public boolean equalsBlocks(Block block) {
		if (block == null) return false;
		if (!(block instanceof ProcedureUsage)) return false;
		if (!super.equalsBlocks(block)) return false;

		String thisname = this.callName;
		String destname = ((ProcedureUsage)block).callName;
		if (!thisname.equalsIgnoreCase(destname)) {
			return false;
		}
		if (this.arguments != null && ((ProcedureUsage)block).arguments != null) {
			if (this.arguments.size() == ((ProcedureUsage)block).arguments.size()) {
				for (int i=0; i<this.arguments.size(); i++) {
					Expression thisArg = this.arguments.get(i);
					Expression destArg = ((ProcedureUsage)block).arguments.get(i);
					if (thisArg == destArg) {
						continue;
					}
					else if (thisArg == null) {
						return false;
					}
					else if (!thisArg.equalsExpression(destArg)) {
						return false;
					}
				}
			}
		}
		else if (this.arguments != null || ((ProcedureUsage)block).arguments != null) {
			return false;
		}

		return true;
    }

	/**
	 * 同一ブロックを検索する
	 * @param block			IInformationブロック
	 * @return		同一ブロック
	 */
    @Override
	public IInformation[] searchInformationBlocks(IInformation block) {
		List<IInformation> list = new ArrayList<IInformation>();
		{
	    	IInformation[] infos = super.searchInformationBlocks(block);
	    	if (infos != null) {
	        	list.addAll(Arrays.asList(infos));
	        }
		}

        if (this.callDefinition != null) {
            // 自己参照の場合は外す
            if (!this.getNamespace().equals(this.callDefinition.getNamespace())) {
    	    	IInformation[] infos = this.callDefinition.searchInformationBlocks(block);
    	    	if (infos != null) {
    	        	list.addAll(Arrays.asList(infos));
    	        }
            }
        }
        if (this.arguments != null) {
            for (Expression argument : this.arguments) {
    	    	IInformation[] infos = argument.searchInformationBlocks(block);
    	    	if (infos != null) {
    	        	list.addAll(Arrays.asList(infos));
    	        }
            }
        }

        if (list.size() <= 0) {
        	return null;
        }

		return list.toArray(new IInformation[0]);
	}
}


text:
namespace tigre
{
    namespace gfx
    {
        class Color
        {
            public:

                Color();
                explicit Color(float red, float green, float blue, float alpha = 1.0f);

                float r, g, b, a;
        };

        namespace color
        {
            extern const Color White;
            extern const Color Black;
            extern const Color Red;
            extern const Color Green;
            extern const Color Blue;
            extern const Color Yellow;
        }
    }
}

#endif


text:
namespace Gu.State
{
    internal class IndexItem : PathItem
    {
        internal IndexItem(int? index)
        {
            this.Index = index;
        }

        internal int? Index { get; }
    }
}


text:
**USE THESE SCRIPTS AT YOUR OWN RISK!**
These scripts aren't very well tested and almost none of them are completely finished. They work to interface with the printer but it's all very manual.

##Overview and license
This is a basic set of utility scripts to interface with the New Matter Mod-T 3d printer on Linux. You are free to fork and contribute as you see fit.
This work falls under the MIT license. See the LICENSE file for more information.
I must also credit /u/modtdev on reddit for the work on getting the gcode sent to the Mod-T

###Depdencies

1. curl
2. *dfu-util
3. *python3
4. *python3-pyusb

##Usage

First, I recommend creating a udev rule for the Mod-T similar to the following:
/etc/udev/rules.d/51-modt.rules:
    SUBSYSTEM=="usb", ATTR{idVendor}=="2b75", ATTR{idProduct}=="0002", GROUP="users", MODE="0674"
SUBSYSTEM=="usb", ATTR{idVendor}=="2b75", ATTR{idProduct}=="0003", GROUP="users", MODE=0674"

In the above I have everyone in the `users` group enabled, however you can restrict access as needed.
This allows a regular user to run the scripts and still have them operate as intended.

From there most scripts are pretty straightforward. Simply flag them executable and run them. The `send_gcode.py`, `flash_firmware.sh`, and `fw_update.py` are the only scripts requiring arguments, each of them expect a single argument containing the path to an appropriate file for the function requested.

If you do choose to use these scripts to print things by sending gcode, monitor the output of the `send_gcode.py` script until you see `STATE_JOB_QUEUED` as the printer status. If you press the front panel button prior to seeing this state you will have a broken print job, which will not print correctly.


text:
class ReservationsController < ApplicationController
  before_action :set_reservation, only: [:show, :edit, :update, :destroy]

  # GET /reservations
  # GET /reservations.json
  def index
    @reservations = Reservation.all
  end

  # GET /reservations/1
  # GET /reservations/1.json
  def show
  end

  # GET /reservations/new
  def new
    @reservation = Reservation.new
  end

  # GET /reservations/1/edit
  def edit
  end

  # POST /reservations
  # POST /reservations.json
  def create
    @reservation = Reservation.new(reservation_params)

    respond_to do |format|
      if @reservation.save
        format.html { redirect_to @reservation, notice: 'Reservation was successfully created.' }
        format.json { render :show, status: :created, location: @reservation }
      else
        format.html { render :new }
        format.json { render json: @reservation.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /reservations/1
  # PATCH/PUT /reservations/1.json
  def update
    respond_to do |format|
      if @reservation.update(reservation_params)
        format.html { redirect_to @reservation, notice: 'Reservation was successfully updated.' }
        format.json { render :show, status: :ok, location: @reservation }
      else
        format.html { render :edit }
        format.json { render json: @reservation.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /reservations/1
  # DELETE /reservations/1.json
  def destroy
    @reservation.destroy
    respond_to do |format|
      format.html { redirect_to reservations_url, notice: 'Reservation was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_reservation
      @reservation = Reservation.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def reservation_params
      params.require(:reservation).permit(:customer_first_name, :customer_last_name, :customer_phone_number, :customer_email, :status, :date, :customers)
    end
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 <meta>

  <link href="../web.css" type="text/css" rel="stylesheet"></link>
  <link href="../pygmentize.css" type="text/css" rel="stylesheet"></link>
  <title>VLFeat - Tutorials - HIKM</title>

 </meta>

   <form action="http://www.vlfeat.org/search.html" method="get" id="cse-search-box" enctype="application/x-www-form-urlencoded">

     <input type="hidden" name="cx" value="003215582122030917471:oq23albfeam"></input>
     <input type="hidden" name="cof" value="FORID:11"></input>
     <input type="hidden" name="ie" value="UTF-8"></input>
     <input type="text" name="q" size="31"></input>
     <input type="submit" name="sa" value="Search"></input>

   </form>

VLFeat.org

   Tutorials - HIKM

Home

Download

Documentation

Tutorials

SIFT

DSIFT/PHOW

MSER

IKM

HIKM

AIB

Quick shift

SLIC

kd-tree

Distance transf.

Utils

Applications

VLFeat offers a hierarchical version of integer k-means, which
recursively applies vl_ikmeans to compute finer and finer
partitions. For more details see
Hierarchical Integer
  k-means API reference and the Integer
  k-means tutorial.

Usage

Tree structure

Elkan

Usage

First, we generate some random data to cluster in [0,255]^2:

data     = uint8(rand(2,10000) * 255) ;
datat    = uint8(rand(2,100000)* 255) ;

To cluster this data, we simply use vl_hikmeans:

K        = 3 ;
nleaves  = 100 ;
[tree,A] = vl_hikmeans(data,K,nleaves) ;

Here nleaves is the desired number of leaf
clusters. The algorithm terminates when there are at least
nleaves nodes, creating a tree with depth =
  floor(log(K nleaves))

To assign labels to the new data, we use vl_hikmeanspush:

AT       = vl_hikmeanspush(tree,datat) ;

<image src="../demo/hikmeans-tree.jpg"></image>
<image src="../demo/hikmeans-clusters.jpg"></image>

Hierarchical integer K-means.  Left: A depiction of the
recursive clusters. Each node is a cluster center. The root note is
not depicted (its center would be the mean of the dataset).  Right:
Clusters are represented as different colors (here are more than 100
clusters, but only three colors are used).

Tree structure

The output tree is a MATLAB structure representing the tree of
clusters:

> tree
tree =

          K: 3
      depth: 5
    centers: [2x3 int32]
        sub: [1x3 struct]

The field centers is the matrix of the cluster centers at the
root node.  If the depth of the tree is larger than 1, then the field
sub is a structure array with one entry for each cluster. Each
element is in turn a tree:

> tree.sub
ans =

1x3 struct array with fields:
    centers
    sub

with a field centers for its clusters and a field
sub for its children. When there are no children, this
field is equal to the empty matrix

> tree.sub(1).sub(1).sub(1).sub(1)

ans =

    centers: [2x3 int32]
        sub: []

Elkan

VLFeat supports two different implementations of k-means. While they
produce identical output, the Elkan method is sometimes faster.
The method parameters controls which method is used. Consider the case when K=10 and our data is now 128 dimensional (e.g. SIFT descriptors):

K=10;
nleaves = 1000;
data = uint8(rand(128,10000) * 255);
tic;
[tree,A] = vl_hikmeans(data,K,nleaves,'method', 'lloyd') ; % default
t_lloyd = toc
tic;
[tree,A] = vl_hikmeans(data,K,nleaves,'method', 'elkan') ;
t_elkan = toc

t_lloyd =

    8.0743

t_elkan =

    3.0427

   © 2007-12 Andrea Vedaldi and Brian Fulkerson


text:
import hashlib
import pprint

class IvStats:
    STAT_ATK_IV = 'atk_iv'
    STAT_DEF_IV = 'def_iv'
    STAT_STAM_IV = 'stam_iv'
    STAT_LEVEL = 'level'
    PERFECTION_PERCENTAGE = 'perfection'

    def __init__(self, level, atk_iv, def_iv, stam_iv, perfection):
        self._level = level
        self._atk_iv = atk_iv
        self._def_iv = def_iv
        self._stam_iv = stam_iv
        self._perfection = perfection

    def __hash__(self):
        """
        Hashes to a level agnostic value for use in equating the same base IVs across different powerups of the same
        Pokemon.
        """
        md5 = hashlib.md5()
        md5.update("a{atk_iv}d{def_iv}s{stam}".format(
            atk_iv=self._atk_iv,
            def_iv=self._def_iv,
            stam=self._stam_iv
        ).encode('ascii'))
        return int(md5.hexdigest(), 16)

    def as_dict(self):
        return {
            IvStats.STAT_ATK_IV: self._atk_iv,
            IvStats.STAT_STAM_IV: self._stam_iv,
            IvStats.STAT_DEF_IV: self._def_iv,
            IvStats.STAT_LEVEL: self._level,
            IvStats.PERFECTION_PERCENTAGE: self._perfection
        }

    def __eq__(self, other):
        """
        Uses to support set operations.
        """
        return hash(self) == hash(other)

    def __ne__(self, other):
        return not self.__eq__(other)

    def __str__(self):
        return pprint.pformat(self.as_dict())


text:
<?php

namespace Amostajo\LightweightMVC\Contracts;

/**
 * Interface contract for objects that can cast to json.
 *
 * @author Alejandro Mostajo
 * @license MIT
 * @package Amostajo\LightweightMVC
 */
interface JSONable
{
	/**
	 * Returns json string.
	 *
	 * @param string
	 */
	public function to_json();
}


text:
using System;
using System.Collections.Generic;
using KinderChat.ServiceBusShared.Entities;

namespace KinderChat.WorkerRole.SocketServer.Domain
{
    public interface IGroupChatsRepository
    {
        GroupChat GetChat(Guid id);

        void UpdateOrCreateGroup(GroupChat chat);

        List<Guid> GetGroupsForUser(long userId);

        void AddGroupToUser(long userId, Guid groupId);

        void RemoveGroupFromUser(long userId, Guid groupId);
    }
}


text:
<?php

namespace Artax;

class MultipartFormBodyIterator implements \Iterator, \Countable {

    private $fields;
    private $length;
    private $currentCache;
    private $position = 0;

    function __construct(array $fields, $length) {
        $this->fields = $fields;
        $this->length = $length;
    }

    function current() {
        if (isset($this->currentCache)) {
            $current = $this->currentCache;
        } elseif (current($this->fields) instanceof FileBody) {
            $current = $this->currentCache = current($this->fields)->current();
        } else {
            $current = $this->currentCache = current($this->fields);
        }

        return $current;
    }

    function key() {
        return key($this->fields);
    }

    function next() {
        $this->currentCache = NULL;
        if (current($this->fields) instanceof FormBody) {
            current($this->fields)->next();
        } else {
            next($this->fields);
        }
    }

    function valid() {
        return isset($this->fields[key($this->fields)]);
    }

    function rewind() {
        foreach ($this->fields as $field) {
            if ($field instanceof MultipartFormFile) {
                $field->rewind();
            }
        }

        reset($this->fields);

        $this->currentCache = NULL;
    }

    function count() {
        return $this->length;
    }
}


text:
  <meta charset="utf-8" />
  <title>Game of life</title>
  <link rel="stylesheet" href="css/index.css">


text:
Introdução
==========

Leia esta introdução antes de começar a trabalhar com Flask. Este texto
procura esclarecer a finalidade e os objetivos do projeto, e quando ele deve
ou não ser usado.

O que quer dizer "micro"?
-------------------------

"Micro" não significa que a sua aplicação web inteira tenha que se encaixar em
um único arquivo Python, embora isso seja totalmente possível. Também não quer
dizer que falte funcionalidade ao Flask. "Micro" em microframework significa
que o Flask procura manter o núcleo simples, mas extensível. O Flask não toma
muitas decisões por você, tipo, que banco de dados usar. Por outro lado, é
fácil mudar as coisas que já decidiu, tipo, o mecanismo de templates. Todo o
resto fica por sua conta decidir, de modo que você pode obter do Flask tudo o
que precisa e dispensar tudo o que não quer.

Por padrão, o Flask não inclui uma camada de abstração de banco de dados,
validação de formulário, ou qualquer outra coisa para a qual já existam
diferentes bibliotecas. Em vez disso, suporta extensões para adicionar uma
determinada funcionalidade à sua aplicação como se ela tivesse sido
implementada no Flask em si. Muitas extensões fornecem integração de banco de
dados, validação de formulários, manipulação de upload, diversas tecnologias
de autenticação abertas, entre outras coisas. O Flask pode ser "micro", mas
está pronto para uso em produção, preenchendo uma gama variada de
necessidades.

Configuração e convenções
-------------------------

O Flask tem vários valores de configuração, com defaults sensatos, e algumas
convenções. Por padrão, templates e arquivos estáticos são armazenados em
subdiretórios `templates` e `static` dentro da árvore-fonte do aplicativo
Python. Isso pode ser alterado, mas em geral não é necessário, especialmente
quando estiver apenas começando.

Crescendo com o Flask
---------------------

Depois que o Flask estiver instalado e funcionando, você vai encontrar à
disposição na comunidade diversas extensões para integrar seu projeto para
produção. A equipe central do Flask analisa as extensões e assegura que
extensões aprovadas permaneçam funcionais em lançamentos futuros.

À medida que a sua base de código vai crescendo, você pode ir escolhendo o
design mais apropriado ao seu projeto. O Flask continuará proporcionando uma
descomplicada camada de integração ao que Python tem de melhor a oferecer.
Você pode implementar padrões avançados em SQLAlchemy ou outra ferramenta de
banco de dados, introduzir persistência de dados não-relacionais quando for o
caso, e tirar proveito das ferramentas para WSGI, a interface web do Python,
que não são atreladas a nenhum framework específico.

O Flask tem muitos ganchos (*hooks* [#]_) para customizar seu comportamento.
Se você precisar de mais customização, saiba que a classe Flask foi construída
para ser estendida por herança. Se tiver interesse nisso, dê uma olhada no
capítulo :ref:`becomingbig`. Se tiver curiosidade sobre os princípios de
projeto do Flask, leia a seção :ref:`design`.

Continue lendo em :ref:`installation`, :ref:`quickstart`, ou
:ref:`advanced_foreword`.

.. rubric:: Notas da tradução

.. [#] *hook*, literalmente *gancho*, é um mecanismo usado em APIs
   extensíveis que permite ao programador criar uma função que será
   invocada pelo framework em determinado momento do processamento,
   por exemplo, uma função que será chamada sempre que o framework
   estiver pronto para gerar uma resposta HTTP. Leia mais na Wikipédia
   em português: hooking_.

.. _hooking: http://pt.wikipedia.org/wiki/Hooking


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

<title>org.apache.cassandra.utils.concurrent Class Hierarchy</title>
<meta name="date" content="2015-05-16">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package org.apache.cassandra.utils.concurrent

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

java.util.AbstractCollection<E> (implements java.util.Collection<E>)

org.apache.cassandra.utils.concurrent.Refs<T> (implements java.lang.AutoCloseable)

org.apache.cassandra.utils.concurrent.Accumulator<E> (implements java.lang.Iterable<T>)

org.apache.cassandra.utils.concurrent.AccumulatorTest

org.apache.cassandra.utils.concurrent.Locks

org.apache.cassandra.utils.concurrent.OpOrder

org.apache.cassandra.utils.concurrent.OpOrder.Barrier

org.apache.cassandra.utils.concurrent.OpOrder.Group (implements java.lang.AutoCloseable, java.lang.Comparable<T>)

org.apache.cassandra.utils.concurrent.Ref<T> (implements java.lang.AutoCloseable, org.apache.cassandra.utils.concurrent.RefCounted<T>)

org.apache.cassandra.utils.concurrent.RefCountedTest

org.apache.cassandra.utils.concurrent.SharedCloseableImpl (implements org.apache.cassandra.utils.concurrent.SharedCloseable)

org.apache.cassandra.utils.concurrent.WrappedSharedCloseable

org.apache.cassandra.utils.concurrent.SimpleCondition (implements java.util.concurrent.locks.Condition)

org.apache.cassandra.utils.concurrent.WaitQueue

org.apache.cassandra.utils.concurrent.WaitQueue.AbstractSignal (implements org.apache.cassandra.utils.concurrent.WaitQueue.Signal)

Interface Hierarchy

java.lang.AutoCloseable

org.apache.cassandra.utils.concurrent.SharedCloseable

org.apache.cassandra.utils.concurrent.RefCounted<T>

org.apache.cassandra.utils.concurrent.SelfRefCounted<T>

org.apache.cassandra.utils.concurrent.RefCounted.Tidy

org.apache.cassandra.utils.concurrent.WaitQueue.Signal

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
package vpcrouter

import (
	"github.com/sacloud/libsacloud/v2/sacloud"
	"github.com/sacloud/libsacloud/v2/sacloud/types"
)

// NICSettingHolder VPCルータのeth0の設定 SharedNICSettingまたはRouterNICSettingを指定する
type NICSettingHolder interface {
	connectedSwitch() *sacloud.ApplianceConnectedSwitch
	ipAddresses() []string
	interfaceSetting() *sacloud.VPCRouterInterfaceSetting
}

// StandardNICSetting VPCルータのeth0を共有セグメントに接続するためのSetting(スタンダードプラン)
type StandardNICSetting struct{}

func (s *StandardNICSetting) connectedSwitch() *sacloud.ApplianceConnectedSwitch {
	return &sacloud.ApplianceConnectedSwitch{Scope: types.Scopes.Shared}
}

func (s *StandardNICSetting) ipAddresses() []string {
	return nil
}

func (s *StandardNICSetting) interfaceSetting() *sacloud.VPCRouterInterfaceSetting {
	return nil
}

// PremiumNICSetting VPCルータのeth0をスイッチ+ルータに接続するためのSetting(プレミアム/ハイスペックプラン)
type PremiumNICSetting struct {
	SwitchID         types.ID
	IPAddresses      []string
	VirtualIPAddress string
	IPAliases        []string
}

func (s *PremiumNICSetting) connectedSwitch() *sacloud.ApplianceConnectedSwitch {
	return &sacloud.ApplianceConnectedSwitch{ID: s.SwitchID}
}

func (s *PremiumNICSetting) ipAddresses() []string {
	return s.IPAddresses
}

func (s *PremiumNICSetting) interfaceSetting() *sacloud.VPCRouterInterfaceSetting {
	return &sacloud.VPCRouterInterfaceSetting{
		IPAddress:        s.IPAddresses,
		VirtualIPAddress: s.VirtualIPAddress,
		IPAliases:        s.IPAliases,
		Index:            0,
	}
}

// AdditionalNICSettingHolder VPCルータのeth1-eth7の設定
type AdditionalNICSettingHolder interface {
	switchInfo() (switchID types.ID, index int)
	interfaceSetting() *sacloud.VPCRouterInterfaceSetting
}

// AdditionalStandardNICSetting VPCルータのeth1-eth7の設定(スタンダードプラン向け)
type AdditionalStandardNICSetting struct {
	SwitchID       types.ID
	IPAddress      string
	NetworkMaskLen int
	Index          int
}

func (s *AdditionalStandardNICSetting) switchInfo() (switchID types.ID, index int) {
	return s.SwitchID, s.Index
}

func (s *AdditionalStandardNICSetting) interfaceSetting() *sacloud.VPCRouterInterfaceSetting {
	return &sacloud.VPCRouterInterfaceSetting{
		IPAddress:      []string{s.IPAddress},
		NetworkMaskLen: s.NetworkMaskLen,
		Index:          s.Index,
	}
}

// AdditionalPremiumNICSetting VPCルータのeth1-eth7の設定(プレミアム/ハイスペックプラン向け)
type AdditionalPremiumNICSetting struct {
	SwitchID         types.ID
	IPAddresses      []string
	VirtualIPAddress string
	NetworkMaskLen   int
	Index            int
}

func (s *AdditionalPremiumNICSetting) switchInfo() (switchID types.ID, index int) {
	return s.SwitchID, s.Index
}

func (s *AdditionalPremiumNICSetting) interfaceSetting() *sacloud.VPCRouterInterfaceSetting {
	return &sacloud.VPCRouterInterfaceSetting{
		IPAddress:        s.IPAddresses,
		VirtualIPAddress: s.VirtualIPAddress,
		NetworkMaskLen:   s.NetworkMaskLen,
		Index:            s.Index,
	}
}