text:
<?php

class CI_regras_agendamento extends CI_controller {

	public function __construct()
	{
		parent::__construct();

		$this->load->model('M_geral');
		$this->load->model('M_configuracoes');
		$this->load->model('M_regras');
		$this->load->model('M_Regras_SB');
		$this->load->model('M_relcontextointeresse');
		$this->load->model('M_usuarios');
		$this->load->model('M_perfisusuarios');
		$this->load->model('M_contextosinteresse');
		$this->load->model('M_sensores');
		$this->load->model('M_topico');

		$this->M_geral->verificaSessao();
		if ($this->session->userdata('usuario_id') != 0 && $this->session->userdata('usuario_id') != ""){
			$this->dados['isLoged'] = true;
			$this->dados['usuario_logado'] = $this->session->userdata('nome');
		}else
			$this->dados['isLoged'] = false;
		$this->dados['title'] = "Gerenciador de Servidor de Contexto";
		$this->dados["caminho"] = $this->uri->segment(1)."/".$this->uri->segment(2);
	}

	function index() {
		$this->pesquisa();
	}

	function select() {
		$registros = $this->M_regras->pesquisar()->result_array();
	    echo json_encode($registros);
	}

	function pesquisa($nr_pagina=20 ){

		if(isset($_GET["msg"])) {
			$this->dados["msg"] = $_GET["msg"];
		}

		$this->dados["metodo"] = "pesquisa";

		$perfilusuario_id = $this->session->userdata('perfilusuario_id');
		if ($this->M_perfisusuarios->isAdm($perfilusuario_id) == 't') // É um superuser?
			$this->dados["linhas"]       = $this->M_regras->pesquisar('', array('r.tipo' => 4), $nr_pagina, $this->uri->segment(5), 'asc', FALSE,2);
		else
			$this->dados["linhas"]       = $this->M_regras->pesquisar('', array('r.tipo' => 4,'p.usuario_id' => $this->session->userdata('usuario_id')), $nr_pagina, $this->uri->segment(5), 'asc', TRUE,2);

		$this->dados["nr_pagina"]      = $nr_pagina;
		$this->dados["total"]          = $this->M_regras->numeroLinhasTotais('',array('tipo'=>4));
		$this->dados["tituloPesquisa"] = "Regras Cadastradas";
		$pag['base_url']               = base_url.$this->dados["caminho"]."/".$this->dados["metodo"]."/".$nr_pagina."/";
		$pag['total_rows']             = $this->dados["total"];
		$pag['uri_segment']	           = 5;
		$pag['per_page']               = $this->dados["nr_pagina"];
		$this->pagination->initialize($pag);
		$this->load->view('inc/topo',$this->dados);
		$this->load->view('inc/menu');
		$this->load->view('inc/topoPesquisa');
		$this->load->view('cadastros/regras_sb/pesquisa');
		$this->load->view('inc/rodape');
	}

	function cadastro(){
		$this->dados["regras"] = $this->M_regras->pesquisar();
		$perfilusuario_id = $this->session->userdata('perfilusuario_id');
		if ($this->M_perfisusuarios->isAdm($perfilusuario_id) == 't'){
			$this->dados["contextointeresse"] = $this->M_contextosinteresse->pesquisar($select='', $where=array(), $limit=100, $offset=0, $ordem='asc');
			$this->dados["sensores"] = $this->M_sensores->pesquisar($select='', $where=array(), $limit=1000, $offset=0, $ordem='asc', $perm=FALSE);
		}
		else{
			$this->dados["contextointeresse"] = $this->M_contextosinteresse->pesquisar('', array('p.usuario_id' => $this->session->userdata('usuario_id')), 100, 0, 'asc', TRUE);
			$this->dados["sensores"] = $this->M_sensores->pesquisar($select='', $where=array(), $limit=1000, $offset=0, $ordem='asc', $perm=FALSE);
		}

		if(!isset($this->dados["editable"])){
			$this->dados["editable"] = "false";
		}

		$this->load->view('inc/topo',$this->dados);
		$this->load->view('inc/menu');
		// $this->load->view('cadastros/regras/cadastro');
		$this->load->view('cadastros/regras_sb/cadastro');
		$this->load->view('inc/rodape');
	}
	function gravar() {

		$json      = json_decode($_POST["rule"]);
		$get_information  = array('sensor' => $_POST["id_sensor"],
		'status' => $_POST["status"]);

		if(isset($_POST["id_rule"])and $_POST["id_rule"] != ""){ // se id estiver setado, é uma edição

			$this->M_Regras_SB->setRegraId($_POST["id_rule"]);
			$id_rule_edge = $this->distributed_rule($_POST["id_rule"],$_POST["id_sensor"],$get_information,$json); //metodo para enviar regra ao servidor de borda
			if($id_rule_edge == null) { //se for null, possível perda de comunicação ou problema no servidor de borda
					$id_rule_edge_off = $this->M_Regras_SB->getRegraIdBorda($_POST["id_rule"]); //seta a variavel com um valor já existente
					$this->M_Regras_SB->setRegraIdBorda($id_rule_edge_off);
			}
			else{ // caso contrário, pega o id referente na borda
				$this->M_Regras_SB->setRegraIdBorda($id_rule_edge);
			}
		}
		else {
			$id_rule_edge = $this->distributed_rule('',$_POST["id_sensor"],$get_information,$json);
			$this->M_Regras_SB->setRegraIdBorda($id_rule_edge);
		}

		$this->M_Regras_SB->setRegraNome($_POST["rules_name"]);
		$this->M_Regras_SB->setRegraStatus($_POST["status"]);
		$this->M_Regras_SB->setRegraArquivoPy($_POST["rule"]);
		$this->M_Regras_SB->setRegraTipo(4);
		$this->M_Regras_SB->setSensor(intval($_POST["id_sensor"]));

		if ($this->M_Regras_SB->salvar() == "inc") {
			$this->dados["msg"] = "Dados registrados com sucesso!";
		}	elseif ($id_rule_edge == null) {
			$this->dados["msg"] = "Não foi possível registrar dados no servidor de borda. Tente mais tarde";
		}	else {
			$this->dados["msg"] = "Dados alterados com sucesso!";
		}
		echo  $this->dados["msg"];
	}

	function get_rules() {

		if(isset($_POST["sensor_id"])) {
			$response = $this->M_regras->selecionar($_POST["sensor_id"])->result_array();
			$response = $response[0]['arquivo_py'];
		} else {
			$response = "algo de errado";
		}
		echo json_encode($response);
	}

	public function distributed_rule($id_regra_context='',$id_sensor='',$array=array(),$rules) {
		$request         = "POST";
		$get_url         = $this->M_sensores->get_acesso_borda(array('sensor_id' =>$id_sensor))->result_array();
		$url             = $get_url[0]["url"];
		$token           = $get_url[0]["token"];
		$id_sensor_borda = $this->M_sensores->get_borda_id($id_sensor);
		$array           = array_merge($array,array('sensor'=>$id_sensor_borda, 'minute'=> $rules->minutes,'hour'=> $rules->hours,'day'=> $rules->days,'month'=> $rules->months,'year'=> "*",'second'=>$rules->second,'event'=>$rules->event));
		$url_rule        = $url."schedules/";

		if($id_regra_context != '') {
			$request           = "PUT";
			$array["id_regra"] = $this->M_Regras_SB->getRegraIdBorda($id_regra_context);
			$url_rule          = $url_rule.$array["id_regra"]."/"; // concatenar com id_regra_borda
			$ch                = curl_init($url_rule);
			$data_string       = json_encode($array,JSON_FORCE_OBJECT);
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
		}	else {
			$ch          = curl_init($url_rule);
			$data_string = json_encode($array,JSON_FORCE_OBJECT);
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
		}

		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
				'Authorization: token '.$token,
				'Content-Type: application/json',
				'Content-Length: ' . strlen($data_string))
		);

		$result = curl_exec($ch);
		$info   = curl_getinfo($ch);
		curl_close($ch);
		if ($info['http_code'] > 199 || $info['http_code'] <= 299)
		  return json_decode($result)->id;
	  else
			return null;
	}

	function get_rules_names() {
		if (isset($_POST["id_sensor"])) {
			$response = $this->M_Regras_SB->get_rules($_POST["id_sensor"])->result_array();
		} else {
			$response = "algo de errado";
		}
		echo json_encode($response);
	}

	function excluir($id="") {

		if ($id=="") {
			$id_regra_contexto = $_POST["item"];
			if (isset($_POST["item"])) {
				$this->M_regras->setRegraId($_POST["item"]);
			}
		} else {
			$id_regra_contexto = $id;
			$this->M_regras->setRegraId($id);
		}
		$id_regra_borda    = $this->M_Regras_SB->getRegraIdBorda($id_regra_contexto);

		$id_sensor         = $this->M_Regras_SB->selecionar($id_regra_contexto)->result_array();
		$get_url           = $this->M_sensores->get_acesso_borda(array('sensor_id' =>$id_sensor[0]["sensor_id"]))->result_array();
		$url               = $get_url[0]["url"];
		$token             = $get_url[0]["token"];
		$url_rule          = $url."schedules/".$id_regra_borda."/";
		$ch                = curl_init($url_rule);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
				'Authorization: token '.$token,
				'Content-Type: application/json')
		);
		$this->M_regras->excluir();
		$result = curl_exec($ch);
		curl_close($ch);
		if ($result == null) {
			$this->dados["msg"] = "Registro(s) excluído(s) com sucesso!";
		} else {
			$this->dados["msg"] = "Não foi possível excluir registro na borda, tentativa será realizada automaticamente!";
		}
		// $this->pesquisa();

	}

  function editar($valor = "") {

		if(isset($_POST["item"])) {
			$this->dados["registro"] = $this->M_regras->selecionar($_POST["item"]);
			$registro                = $this->dados["registro"]->result_array();
			$this->dados["sensor"]   = $this->M_Regras_SB->get_sensor_id($registro[0]['regra_id']);
			$this->dados["editable"] = "true";
	} else if (isset($_GET["item"])) {

			$this->dados["registro"] = $this->M_regras->selecionar($_GET["item"]);
			$registro                = $this->dados["registro"]->result_array();
			$this->dados["sensor"]   = $this->M_Regras_SB->get_sensor_id($registro[0]['regra_id']);
			$this->dados["editable"] = "true";
	}
	else if ($valor != "") {
			$this->dados["registro"] = $this->M_regras->selecionar($valor);
			$registro                = $this->dados["registro"]->result_array();
			$this->dados["sensor"]   = $this->M_Regras_SB->get_sensor_id($registro[0]['regra_id']);
			$this->dados["editable"] = "true";
	}
		$this->cadastro();
	}

	function ativar($id="") {

		if ($id=="") {
			if (isset($_POST["item"])) {
				$this->M_regras->setRegraId($_POST["item"]);
				$this->M_regras->setRegraStatus('true');
				$this->M_regras->altStatus();
			}
		} else {
			$this->M_regras->setRegraId($id);
			$this->M_regras->setRegraStatus('true');
			$this->M_regras->altStatus();
		}

		$this->dados["msg"] = "Regra ativada com sucesso!";
		$this->pesquisa();
	}

	function desativar($id="") {

		if ($id=="") {
			if (isset($_POST["item"])) {
				$this->M_regras->setRegraId($_POST["item"]);
				$this->M_regras->setRegraStatus('false');
				$this->M_regras->altStatus();
			}
		} else {
			$this->M_regras->setRegraId($id);
			$this->M_regras->setRegraStatus('false');
			$this->M_regras->altStatus();
		}

		$this->dados["msg"] = "Regra desativada com sucesso!";
		$this->pesquisa();
	}

	function getSensorByRci($id=""){

		if ($id=="") {
			if (isset($_POST["contextointeresse"])) {
				$sensores = $this->M_relcontextointeresse->getByCi($_POST["contextointeresse"]);
			}
		} else {
			$sensores = $this->M_relcontextointeresse->getByCi($id);
		}

	    echo json_encode($sensores);
	}
}

?>


text:
<?xml version="1.0" encoding="UTF-8"?><data jsxid="jsxroot">
	<record group="object" include="master.xml"/>
	<record group="position" include="master.xml"/>

	<record group="1" jsxid="linechart" jsxtext="LineChart">
		<record docdefault="overlay (jsx3.chart.LineChart.TYPE_OVERLAY)" docgetter="getType" docsetter="setType" eval="0" jsxexecute="objJSX.setType(vntValue);objJSX.repaint();" jsxid="type" jsxmask="jsxselect" jsxtext="Type" jsxtip="Sets the type of line chart." nullable="0">
			<enum jsxid="jsx3.chart.LineChart.TYPE_OVERLAY" jsxtext="overlay"/>
			<enum jsxid="jsx3.chart.LineChart.TYPE_STACKED" jsxtext="stacked"/>
			<enum jsxid="jsx3.chart.LineChart.TYPE_STACKED100" jsxtext="stacked 100%"/>
		</record>
	</record>

	<record group="blockx" include="master.xml"/>
	<record group="background" include="master.xml"/>
	<record group="chart" include="master.xml"/>
	<record group="interaction_menuonly" include="master.xml"/>
</data>

redpajama_set_name: RedPajamaGithub


text:
===============================
 Python Service Locator v 0.1.3
===============================

- The service locator pattern is a very simple but useful pattern that helps you remove glue code from application code.
- Decoupling the wiring of dependencies (glue code) can reduce your lines of code significantly and encourages loose coupling.
- This allows you to depend on abstractions rather than on concretions, it makes adding additional
  functionality to your application much easier.
- Configuration xml files are not pythonic and are often overcomplicated, class decorators are used instead.
- Very simple, under 100 lines of code.
- Test suite, got it.

Usage
-----

::

    pip install service-locator

Usage
-----

Please see test/integration/test.py for a sample project. Suppose you have an abstract service class that looks like this:

.. code-block:: python

    #mime_recognizer_service.py
    class MIMERecognizerService(object):
        def recognizes_extension(self, extension):
            pass

        def get_MIME_type(self):
            pass

Register a service like this:

.. code-block:: python

    #pdf_recognizer.py
    from servicelocator.service_discoverer import discover_services

    @service_provider(MIMERecognizerService)
    class PDFRecognizer(MIMERecognizerService):
        def recognizes_extension(self, extension):
            return extension == ".pdf"

        def get_MIME_type(self):
            return "application/pdf"

You can register as many services and service providers as you like. When you retrieve all MIMERecognizerServices using the
lookup_all function, one of the results in the list will be a PDFRecognizer() instance.

In order for the service discovery process to find the PDFRecognizer, you need to place it in a services folder. Your
directory structure might look something like this (__init__.py's removed for demo purposes):

::

    -root/
        -main.py
        -mime_recognizers/
           -mime_recognizer_service.py
           -services/
               -pdf_recognizer.py
        -file_openers/
           -file_opener_service.py
           -services/
               -pdf_opener.py

You discover services like this:

.. code-block:: python

    from servicelocator.service_discoverer import discover_services

     discover_services()

And that's it. The discover_services will walk the project directory tree and import all python modules inside services folders.

To retrieve service providers for a service, use the lookup functions like this:

.. code-block:: python

    from servicelocator.lookup import global_lookup

    MIMERecognizers = global_lookup.lookup_all(MIMERecognizerService)

This will get all concrete implementations of the MIMERecognizerService but the we do not need to know about the
existence of any of these concrete implementations. Adding extra functionality is as simple as dropping a file inside a
services directory, no additional code is necessary. This makes adding new service providers in a loosely coupled way very easy .

And if you know there is only one implementation of the service:

.. code-block:: python

    from servicelocator.lookup import global_lookup

    MIMERecognizer = global_lookup.lookup(MIMERecognizerService)


text:
#include "soundio_private.h"
#include "util.h"
#include "os.h"
#include "config.h"

#include <string.h>
#include <assert.h>
#include <stdio.h>

static const enum SoundIoBackend available_backends[] = {
#ifdef SOUNDIO_HAVE_JACK
    SoundIoBackendJack,
#endif
#ifdef SOUNDIO_HAVE_PULSEAUDIO
    SoundIoBackendPulseAudio,
#endif
#ifdef SOUNDIO_HAVE_ALSA
    SoundIoBackendAlsa,
#endif
#ifdef SOUNDIO_HAVE_COREAUDIO
    SoundIoBackendCoreAudio,
#endif
#ifdef SOUNDIO_HAVE_WASAPI
    SoundIoBackendWasapi,
#endif
    SoundIoBackendDummy,
};

typedef int (*backend_init_t)(struct SoundIoPrivate *);
static backend_init_t backend_init_fns[] = {
    NULL, // None backend

#ifdef SOUNDIO_HAVE_JACK
    &soundio_jack_init,
#else
    NULL,
#endif

#ifdef SOUNDIO_HAVE_PULSEAUDIO
    &soundio_pulseaudio_init,
#else
    NULL,
#endif

#ifdef SOUNDIO_HAVE_ALSA
    &soundio_alsa_init,
#else
    NULL,
#endif

#ifdef SOUNDIO_HAVE_COREAUDIO
    &soundio_coreaudio_init,
#else
    NULL,
#endif

#ifdef SOUNDIO_HAVE_WASAPI
    soundio_wasapi_init,
#else
    NULL,
#endif

    &soundio_dummy_init,
};

SOUNDIO_MAKE_LIST_DEF(struct SoundIoDevice*, SoundIoListDevicePtr, SOUNDIO_LIST_NOT_STATIC)
SOUNDIO_MAKE_LIST_DEF(struct SoundIoSampleRateRange, SoundIoListSampleRateRange, SOUNDIO_LIST_NOT_STATIC)

const char *soundio_strerror(int error) {
    switch ((enum SoundIoError)error) {
        case SoundIoErrorNone: return "(no error)";
        case SoundIoErrorNoMem: return "out of memory";
        case SoundIoErrorInitAudioBackend: return "unable to initialize audio backend";
        case SoundIoErrorSystemResources: return "system resource not available";
        case SoundIoErrorOpeningDevice: return "unable to open device";
        case SoundIoErrorNoSuchDevice: return "no such device";
        case SoundIoErrorInvalid: return "invalid value";
        case SoundIoErrorBackendUnavailable: return "backend unavailable";
        case SoundIoErrorStreaming: return "unrecoverable streaming failure";
        case SoundIoErrorIncompatibleDevice: return "incompatible device";
        case SoundIoErrorNoSuchClient: return "no such client";
        case SoundIoErrorIncompatibleBackend: return "incompatible backend";
        case SoundIoErrorBackendDisconnected: return "backend disconnected";
        case SoundIoErrorInterrupted: return "interrupted; try again";
        case SoundIoErrorUnderflow: return "buffer underflow";
        case SoundIoErrorEncodingString: return "failed to encode string";
    }
    return "(invalid error)";
}

int soundio_get_bytes_per_sample(enum SoundIoFormat format) {
    switch (format) {
    case SoundIoFormatU8:         return 1;
    case SoundIoFormatS8:         return 1;
    case SoundIoFormatS16LE:      return 2;
    case SoundIoFormatS16BE:      return 2;
    case SoundIoFormatU16LE:      return 2;
    case SoundIoFormatU16BE:      return 2;
    case SoundIoFormatS24LE:      return 4;
    case SoundIoFormatS24BE:      return 4;
    case SoundIoFormatU24LE:      return 4;
    case SoundIoFormatU24BE:      return 4;
    case SoundIoFormatS32LE:      return 4;
    case SoundIoFormatS32BE:      return 4;
    case SoundIoFormatU32LE:      return 4;
    case SoundIoFormatU32BE:      return 4;
    case SoundIoFormatFloat32LE:  return 4;
    case SoundIoFormatFloat32BE:  return 4;
    case SoundIoFormatFloat64LE:  return 8;
    case SoundIoFormatFloat64BE:  return 8;

    case SoundIoFormatInvalid:    return -1;
    }
    return -1;
}

const char * soundio_format_string(enum SoundIoFormat format) {
    switch (format) {
    case SoundIoFormatS8:         return "signed 8-bit";
    case SoundIoFormatU8:         return "unsigned 8-bit";
    case SoundIoFormatS16LE:      return "signed 16-bit LE";
    case SoundIoFormatS16BE:      return "signed 16-bit BE";
    case SoundIoFormatU16LE:      return "unsigned 16-bit LE";
    case SoundIoFormatU16BE:      return "unsigned 16-bit LE";
    case SoundIoFormatS24LE:      return "signed 24-bit LE";
    case SoundIoFormatS24BE:      return "signed 24-bit BE";
    case SoundIoFormatU24LE:      return "unsigned 24-bit LE";
    case SoundIoFormatU24BE:      return "unsigned 24-bit BE";
    case SoundIoFormatS32LE:      return "signed 32-bit LE";
    case SoundIoFormatS32BE:      return "signed 32-bit BE";
    case SoundIoFormatU32LE:      return "unsigned 32-bit LE";
    case SoundIoFormatU32BE:      return "unsigned 32-bit BE";
    case SoundIoFormatFloat32LE:  return "float 32-bit LE";
    case SoundIoFormatFloat32BE:  return "float 32-bit BE";
    case SoundIoFormatFloat64LE:  return "float 64-bit LE";
    case SoundIoFormatFloat64BE:  return "float 64-bit BE";

    case SoundIoFormatInvalid:
        return "(invalid sample format)";
    }
    return "(invalid sample format)";
}

const char *soundio_backend_name(enum SoundIoBackend backend) {
    switch (backend) {
        case SoundIoBackendNone: return "(none)";
        case SoundIoBackendJack: return "JACK";
        case SoundIoBackendPulseAudio: return "PulseAudio";
        case SoundIoBackendAlsa: return "ALSA";
        case SoundIoBackendCoreAudio: return "CoreAudio";
        case SoundIoBackendWasapi: return "WASAPI";
        case SoundIoBackendDummy: return "Dummy";
    }
    return "(invalid backend)";
}

void soundio_destroy(struct SoundIo *soundio) {
    struct SoundIoPrivate *si = (struct SoundIoPrivate *)soundio;

    soundio_disconnect(soundio);

    free(si);
}

static void do_nothing_cb(struct SoundIo *soundio) { }
static void default_msg_callback(const char *msg) { }

static void default_backend_disconnect_cb(struct SoundIo *soundio, int err) {
    soundio_panic("libsoundio: backend disconnected: %s", soundio_strerror(err));
}

static struct SoundIoAtomicFlag rtprio_seen = SOUNDIO_ATOMIC_FLAG_INIT;
static void default_emit_rtprio_warning(void) {
    if (!SOUNDIO_ATOMIC_FLAG_TEST_AND_SET(rtprio_seen)) {
        fprintf(stderr, "warning: unable to set high priority thread: Operation not permitted\n");
        fprintf(stderr, "See "
            "https://github.com/andrewrk/genesis/wiki/warning:-unable-to-set-high-priority-thread:-Operation-not-permitted\n");
    }
}

struct SoundIo *soundio_create(void) {
    int err;
    if ((err = soundio_os_init()))
        return NULL;
    struct SoundIoPrivate *si = ALLOCATE(struct SoundIoPrivate, 1);
    if (!si)
        return NULL;
    struct SoundIo *soundio = &si->pub;
    soundio->on_devices_change = do_nothing_cb;
    soundio->on_backend_disconnect = default_backend_disconnect_cb;
    soundio->on_events_signal = do_nothing_cb;
    soundio->app_name = "SoundIo";
    soundio->emit_rtprio_warning = default_emit_rtprio_warning;
    soundio->jack_info_callback = default_msg_callback;
    soundio->jack_error_callback = default_msg_callback;
    return soundio;
}

int soundio_connect(struct SoundIo *soundio) {
    int err = 0;

    for (int i = 0; i < ARRAY_LENGTH(available_backends); i += 1) {
        enum SoundIoBackend backend = available_backends[i];
        err = soundio_connect_backend(soundio, backend);
        if (!err)
            return 0;
        if (err != SoundIoErrorInitAudioBackend)
            return err;
    }

    return err;
}

int soundio_connect_backend(struct SoundIo *soundio, enum SoundIoBackend backend) {
    struct SoundIoPrivate *si = (struct SoundIoPrivate *)soundio;

    if (soundio->current_backend)
        return SoundIoErrorInvalid;

    if (backend <= 0 || backend > SoundIoBackendDummy)
        return SoundIoErrorInvalid;

    int (*fn)(struct SoundIoPrivate *) = backend_init_fns[backend];

    if (!fn)
        return SoundIoErrorBackendUnavailable;

    int err;
    if ((err = backend_init_fns[backend](si))) {
        soundio_disconnect(soundio);
        return err;
    }
    soundio->current_backend = backend;

    return 0;
}

void soundio_disconnect(struct SoundIo *soundio) {
    struct SoundIoPrivate *si = (struct SoundIoPrivate *)soundio;

    if (!si)
        return;

    if (si->destroy)
        si->destroy(si);
    memset(&si->backend_data, 0, sizeof(union SoundIoBackendData));

    soundio->current_backend = SoundIoBackendNone;

    soundio_destroy_devices_info(si->safe_devices_info);
    si->safe_devices_info = NULL;

    si->destroy = NULL;
    si->flush_events = NULL;
    si->wait_events = NULL;
    si->wakeup = NULL;
    si->force_device_scan = NULL;

    si->outstream_open = NULL;
    si->outstream_destroy = NULL;
    si->outstream_start = NULL;
    si->outstream_begin_write = NULL;
    si->outstream_end_write = NULL;
    si->outstream_clear_buffer = NULL;
    si->outstream_pause = NULL;
    si->outstream_get_latency = NULL;
    si->outstream_set_volume = NULL;

    si->instream_open = NULL;
    si->instream_destroy = NULL;
    si->instream_start = NULL;
    si->instream_begin_read = NULL;
    si->instream_end_read = NULL;
    si->instream_pause = NULL;
    si->instream_get_latency = NULL;
}

void soundio_flush_events(struct SoundIo *soundio) {
    assert(soundio->current_backend != SoundIoBackendNone);
    struct SoundIoPrivate *si = (struct SoundIoPrivate *)soundio;
    si->flush_events(si);
}

int soundio_input_device_count(struct SoundIo *soundio) {
    struct SoundIoPrivate *si = (struct SoundIoPrivate *)soundio;

    assert(si->safe_devices_info);
    if (!si->safe_devices_info)
        return -1;

    assert(soundio->current_backend != SoundIoBackendNone);
    if (soundio->current_backend == SoundIoBackendNone)
        return -1;

    return si->safe_devices_info->input_devices.length;
}

int soundio_output_device_count(struct SoundIo *soundio) {
    struct SoundIoPrivate *si = (struct SoundIoPrivate *)soundio;

    assert(si->safe_devices_info);
    if (!si->safe_devices_info)
        return -1;

    assert(soundio->current_backend != SoundIoBackendNone);
    if (soundio->current_backend == SoundIoBackendNone)
        return -1;

    return si->safe_devices_info->output_devices.length;
}

int soundio_default_input_device_index(struct SoundIo *soundio) {
    struct SoundIoPrivate *si = (struct SoundIoPrivate *)soundio;

    assert(si->safe_devices_info);
    if (!si->safe_devices_info)
        return -1;

    assert(soundio->current_backend != SoundIoBackendNone);
    if (soundio->current_backend == SoundIoBackendNone)
        return -1;

    return si->safe_devices_info->default_input_index;
}

int soundio_default_output_device_index(struct SoundIo *soundio) {
    struct SoundIoPrivate *si = (struct SoundIoPrivate *)soundio;

    assert(si->safe_devices_info);
    if (!si->safe_devices_info)
        return -1;

    assert(soundio->current_backend != SoundIoBackendNone);
    if (soundio->current_backend == SoundIoBackendNone)
        return -1;

    return si->safe_devices_info->default_output_index;
}

struct SoundIoDevice *soundio_get_input_device(struct SoundIo *soundio, int index) {
    struct SoundIoPrivate *si = (struct SoundIoPrivate *)soundio;

    assert(soundio->current_backend != SoundIoBackendNone);
    if (soundio->current_backend == SoundIoBackendNone)
        return NULL;

    assert(si->safe_devices_info);
    if (!si->safe_devices_info)
        return NULL;

    assert(index >= 0);
    assert(index < si->safe_devices_info->input_devices.length);
    if (index < 0 || index >= si->safe_devices_info->input_devices.length)
        return NULL;

    struct SoundIoDevice *device = SoundIoListDevicePtr_val_at(&si->safe_devices_info->input_devices, index);
    soundio_device_ref(device);
    return device;
}

struct SoundIoDevice *soundio_get_output_device(struct SoundIo *soundio, int index) {
    struct SoundIoPrivate *si = (struct SoundIoPrivate *)soundio;

    assert(soundio->current_backend != SoundIoBackendNone);
    if (soundio->current_backend == SoundIoBackendNone)
        return NULL;

    assert(si->safe_devices_info);
    if (!si->safe_devices_info)
        return NULL;

    assert(index >= 0);
    assert(index < si->safe_devices_info->output_devices.length);
    if (index < 0 || index >= si->safe_devices_info->output_devices.length)
        return NULL;

    struct SoundIoDevice *device = SoundIoListDevicePtr_val_at(&si->safe_devices_info->output_devices, index);
    soundio_device_ref(device);
    return device;
}

void soundio_device_unref(struct SoundIoDevice *device) {
    if (!device)
        return;

    device->ref_count -= 1;
    assert(device->ref_count >= 0);

    if (device->ref_count == 0) {
        struct SoundIoDevicePrivate *dev = (struct SoundIoDevicePrivate *)device;
        if (dev->destruct)
            dev->destruct(dev);

        free(device->id);
        free(device->name);

        if (device->sample_rates != &dev->prealloc_sample_rate_range &&
            device->sample_rates != dev->sample_rates.items)
        {
            free(device->sample_rates);
        }
        SoundIoListSampleRateRange_deinit(&dev->sample_rates);

        if (device->formats != &dev->prealloc_format)
            free(device->formats);

        if (device->layouts != &device->current_layout)
            free(device->layouts);

        free(dev);
    }
}

void soundio_device_ref(struct SoundIoDevice *device) {
    assert(device);
    device->ref_count += 1;
}

void soundio_wait_events(struct SoundIo *soundio) {
    struct SoundIoPrivate *si = (struct SoundIoPrivate *)soundio;
    si->wait_events(si);
}

void soundio_wakeup(struct SoundIo *soundio) {
    struct SoundIoPrivate *si = (struct SoundIoPrivate *)soundio;
    si->wakeup(si);
}

void soundio_force_device_scan(struct SoundIo *soundio) {
    struct SoundIoPrivate *si = (struct SoundIoPrivate *)soundio;
    si->force_device_scan(si);
}

int soundio_outstream_begin_write(struct SoundIoOutStream *outstream,
        struct SoundIoChannelArea **areas, int *frame_count)
{
    struct SoundIo *soundio = outstream->device->soundio;
    struct SoundIoPrivate *si = (struct SoundIoPrivate *)soundio;
    struct SoundIoOutStreamPrivate *os = (struct SoundIoOutStreamPrivate *)outstream;
    if (*frame_count <= 0)
        return SoundIoErrorInvalid;
    return si->outstream_begin_write(si, os, areas, frame_count);
}

int soundio_outstream_end_write(struct SoundIoOutStream *outstream) {
    struct SoundIo *soundio = outstream->device->soundio;
    struct SoundIoPrivate *si = (struct SoundIoPrivate *)soundio;
    struct SoundIoOutStreamPrivate *os = (struct SoundIoOutStreamPrivate *)outstream;
    return si->outstream_end_write(si, os);
}

static void default_outstream_error_callback(struct SoundIoOutStream *os, int err) {
    soundio_panic("libsoundio: %s", soundio_strerror(err));
}

static void default_underflow_callback(struct SoundIoOutStream *outstream) { }

struct SoundIoOutStream *soundio_outstream_create(struct SoundIoDevice *device) {
    struct SoundIoOutStreamPrivate *os = ALLOCATE(struct SoundIoOutStreamPrivate, 1);
    struct SoundIoOutStream *outstream = &os->pub;

    if (!os)
        return NULL;
    if (!device)
        return NULL;

    outstream->device = device;
    soundio_device_ref(device);

    outstream->error_callback = default_outstream_error_callback;
    outstream->underflow_callback = default_underflow_callback;

    return outstream;
}

int soundio_outstream_open(struct SoundIoOutStream *outstream) {
    struct SoundIoDevice *device = outstream->device;

    if (device->aim != SoundIoDeviceAimOutput)
        return SoundIoErrorInvalid;

    if (device->probe_error)
        return device->probe_error;

    if (outstream->layout.channel_count > SOUNDIO_MAX_CHANNELS)
        return SoundIoErrorInvalid;

    if (outstream->format == SoundIoFormatInvalid) {
        outstream->format = soundio_device_supports_format(device, SoundIoFormatFloat32NE) ?
            SoundIoFormatFloat32NE : device->formats[0];
    }

    if (outstream->format <= SoundIoFormatInvalid)
        return SoundIoErrorInvalid;

    if (!outstream->layout.channel_count) {
        const struct SoundIoChannelLayout *stereo = soundio_channel_layout_get_builtin(SoundIoChannelLayoutIdStereo);
        outstream->layout = soundio_device_supports_layout(device, stereo) ? *stereo : device->layouts[0];
    }

    if (!outstream->sample_rate)
        outstream->sample_rate = soundio_device_nearest_sample_rate(device, 48000);

    struct SoundIoOutStreamPrivate *os = (struct SoundIoOutStreamPrivate *)outstream;
    outstream->bytes_per_frame = soundio_get_bytes_per_frame(outstream->format, outstream->layout.channel_count);
    outstream->bytes_per_sample = soundio_get_bytes_per_sample(outstream->format);

    struct SoundIo *soundio = device->soundio;
    struct SoundIoPrivate *si = (struct SoundIoPrivate *)soundio;
    return si->outstream_open(si, os);
}

void soundio_outstream_destroy(struct SoundIoOutStream *outstream) {
    if (!outstream)
        return;

    struct SoundIoOutStreamPrivate *os = (struct SoundIoOutStreamPrivate *)outstream;
    struct SoundIo *soundio = outstream->device->soundio;
    struct SoundIoPrivate *si = (struct SoundIoPrivate *)soundio;

    if (si->outstream_destroy)
        si->outstream_destroy(si, os);

    soundio_device_unref(outstream->device);
    free(os);
}

int soundio_outstream_start(struct SoundIoOutStream *outstream) {
    struct SoundIo *soundio = outstream->device->soundio;
    struct SoundIoPrivate *si = (struct SoundIoPrivate *)soundio;
    struct SoundIoOutStreamPrivate *os = (struct SoundIoOutStreamPrivate *)outstream;
    return si->outstream_start(si, os);
}

int soundio_outstream_pause(struct SoundIoOutStream *outstream, bool pause) {
    struct SoundIo *soundio = outstream->device->soundio;
    struct SoundIoPrivate *si = (struct SoundIoPrivate *)soundio;
    struct SoundIoOutStreamPrivate *os = (struct SoundIoOutStreamPrivate *)outstream;
    return si->outstream_pause(si, os, pause);
}

int soundio_outstream_clear_buffer(struct SoundIoOutStream *outstream) {
    struct SoundIo *soundio = outstream->device->soundio;
    struct SoundIoPrivate *si = (struct SoundIoPrivate *)soundio;
    struct SoundIoOutStreamPrivate *os = (struct SoundIoOutStreamPrivate *)outstream;
    return si->outstream_clear_buffer(si, os);
}

int soundio_outstream_get_latency(struct SoundIoOutStream *outstream, double *out_latency) {
    struct SoundIo *soundio = outstream->device->soundio;
    struct SoundIoPrivate *si = (struct SoundIoPrivate *)soundio;
    struct SoundIoOutStreamPrivate *os = (struct SoundIoOutStreamPrivate *)outstream;
    return si->outstream_get_latency(si, os, out_latency);
}

int soundio_outstream_set_volume(struct SoundIoOutStream *outstream, double volume) {
    struct SoundIo *soundio = outstream->device->soundio;
    struct SoundIoPrivate *si = (struct SoundIoPrivate *)soundio;
    struct SoundIoOutStreamPrivate *os = (struct SoundIoOutStreamPrivate *)outstream;
    return si->outstream_set_volume(si, os, volume);
}

static void default_instream_error_callback(struct SoundIoInStream *is, int err) {
    soundio_panic("libsoundio: %s", soundio_strerror(err));
}

static void default_overflow_callback(struct SoundIoInStream *instream) { }

struct SoundIoInStream *soundio_instream_create(struct SoundIoDevice *device) {
    struct SoundIoInStreamPrivate *is = ALLOCATE(struct SoundIoInStreamPrivate, 1);
    struct SoundIoInStream *instream = &is->pub;

    if (!is)
        return NULL;
    if (!device)
        return NULL;

    instream->device = device;
    soundio_device_ref(device);

    instream->error_callback = default_instream_error_callback;
    instream->overflow_callback = default_overflow_callback;

    return instream;
}

int soundio_instream_open(struct SoundIoInStream *instream) {
    struct SoundIoDevice *device = instream->device;
    if (device->aim != SoundIoDeviceAimInput)
        return SoundIoErrorInvalid;

    if (instream->format <= SoundIoFormatInvalid)
        return SoundIoErrorInvalid;

    if (instream->layout.channel_count > SOUNDIO_MAX_CHANNELS)
        return SoundIoErrorInvalid;

    if (device->probe_error)
        return device->probe_error;

    if (instream->format == SoundIoFormatInvalid) {
        instream->format = soundio_device_supports_format(device, SoundIoFormatFloat32NE) ?
            SoundIoFormatFloat32NE : device->formats[0];
    }

    if (!instream->layout.channel_count) {
        const struct SoundIoChannelLayout *stereo = soundio_channel_layout_get_builtin(SoundIoChannelLayoutIdStereo);
        instream->layout = soundio_device_supports_layout(device, stereo) ? *stereo : device->layouts[0];
    }

    if (!instream->sample_rate)
        instream->sample_rate = soundio_device_nearest_sample_rate(device, 48000);

    instream->bytes_per_frame = soundio_get_bytes_per_frame(instream->format, instream->layout.channel_count);
    instream->bytes_per_sample = soundio_get_bytes_per_sample(instream->format);
    struct SoundIo *soundio = device->soundio;
    struct SoundIoPrivate *si = (struct SoundIoPrivate *)soundio;
    struct SoundIoInStreamPrivate *is = (struct SoundIoInStreamPrivate *)instream;
    return si->instream_open(si, is);
}

int soundio_instream_start(struct SoundIoInStream *instream) {
    struct SoundIo *soundio = instream->device->soundio;
    struct SoundIoPrivate *si = (struct SoundIoPrivate *)soundio;
    struct SoundIoInStreamPrivate *is = (struct SoundIoInStreamPrivate *)instream;
    return si->instream_start(si, is);
}

void soundio_instream_destroy(struct SoundIoInStream *instream) {
    if (!instream)
        return;

    struct SoundIoInStreamPrivate *is = (struct SoundIoInStreamPrivate *)instream;
    struct SoundIo *soundio = instream->device->soundio;
    struct SoundIoPrivate *si = (struct SoundIoPrivate *)soundio;

    if (si->instream_destroy)
        si->instream_destroy(si, is);

    soundio_device_unref(instream->device);
    free(is);
}

int soundio_instream_pause(struct SoundIoInStream *instream, bool pause) {
    struct SoundIo *soundio = instream->device->soundio;
    struct SoundIoPrivate *si = (struct SoundIoPrivate *)soundio;
    struct SoundIoInStreamPrivate *is = (struct SoundIoInStreamPrivate *)instream;
    return si->instream_pause(si, is, pause);
}

int soundio_instream_begin_read(struct SoundIoInStream *instream,
        struct SoundIoChannelArea **areas, int *frame_count)
{
    struct SoundIo *soundio = instream->device->soundio;
    struct SoundIoPrivate *si = (struct SoundIoPrivate *)soundio;
    struct SoundIoInStreamPrivate *is = (struct SoundIoInStreamPrivate *)instream;
    return si->instream_begin_read(si, is, areas, frame_count);
}

int soundio_instream_end_read(struct SoundIoInStream *instream) {
    struct SoundIo *soundio = instream->device->soundio;
    struct SoundIoPrivate *si = (struct SoundIoPrivate *)soundio;
    struct SoundIoInStreamPrivate *is = (struct SoundIoInStreamPrivate *)instream;
    return si->instream_end_read(si, is);
}

int soundio_instream_get_latency(struct SoundIoInStream *instream, double *out_latency) {
    struct SoundIo *soundio = instream->device->soundio;
    struct SoundIoPrivate *si = (struct SoundIoPrivate *)soundio;
    struct SoundIoInStreamPrivate *is = (struct SoundIoInStreamPrivate *)instream;
    return si->instream_get_latency(si, is, out_latency);
}

void soundio_destroy_devices_info(struct SoundIoDevicesInfo *devices_info) {
    if (!devices_info)
        return;

    for (int i = 0; i < devices_info->input_devices.length; i += 1)
        soundio_device_unref(SoundIoListDevicePtr_val_at(&devices_info->input_devices, i));
    for (int i = 0; i < devices_info->output_devices.length; i += 1)
        soundio_device_unref(SoundIoListDevicePtr_val_at(&devices_info->output_devices, i));

    SoundIoListDevicePtr_deinit(&devices_info->input_devices);
    SoundIoListDevicePtr_deinit(&devices_info->output_devices);

    free(devices_info);
}

bool soundio_have_backend(enum SoundIoBackend backend) {
    assert(backend > 0);
    assert(backend <= SoundIoBackendDummy);
    return backend_init_fns[backend];
}

int soundio_backend_count(struct SoundIo *soundio) {
    return ARRAY_LENGTH(available_backends);
}

enum SoundIoBackend soundio_get_backend(struct SoundIo *soundio, int index) {
    return available_backends[index];
}

static bool layout_contains(const struct SoundIoChannelLayout *available_layouts, int available_layouts_count,
        const struct SoundIoChannelLayout *target_layout)
{
    for (int i = 0; i < available_layouts_count; i += 1) {
        const struct SoundIoChannelLayout *available_layout = &available_layouts[i];
        if (soundio_channel_layout_equal(target_layout, available_layout))
            return true;
    }
    return false;
}

const struct SoundIoChannelLayout *soundio_best_matching_channel_layout(
        const struct SoundIoChannelLayout *preferred_layouts, int preferred_layouts_count,
        const struct SoundIoChannelLayout *available_layouts, int available_layouts_count)
{
    for (int i = 0; i < preferred_layouts_count; i += 1) {
        const struct SoundIoChannelLayout *preferred_layout = &preferred_layouts[i];
        if (layout_contains(available_layouts, available_layouts_count, preferred_layout))
            return preferred_layout;
    }
    return NULL;
}

static int compare_layouts(const void *a, const void *b) {
    const struct SoundIoChannelLayout *layout_a = (const struct SoundIoChannelLayout *)a;
    const struct SoundIoChannelLayout *layout_b = (const struct SoundIoChannelLayout *)b;
    if (layout_a->channel_count > layout_b->channel_count)
        return -1;
    else if (layout_a->channel_count < layout_b->channel_count)
        return 1;
    else
        return 0;
}

void soundio_sort_channel_layouts(struct SoundIoChannelLayout *layouts, int layouts_count) {
    if (!layouts)
        return;

    qsort(layouts, layouts_count, sizeof(struct SoundIoChannelLayout), compare_layouts);
}

void soundio_device_sort_channel_layouts(struct SoundIoDevice *device) {
    soundio_sort_channel_layouts(device->layouts, device->layout_count);
}

bool soundio_device_supports_format(struct SoundIoDevice *device, enum SoundIoFormat format) {
    for (int i = 0; i < device->format_count; i += 1) {
        if (device->formats[i] == format)
            return true;
    }
    return false;
}

bool soundio_device_supports_layout(struct SoundIoDevice *device,
        const struct SoundIoChannelLayout *layout)
{
    for (int i = 0; i < device->layout_count; i += 1) {
        if (soundio_channel_layout_equal(&device->layouts[i], layout))
            return true;
    }
    return false;
}

bool soundio_device_supports_sample_rate(struct SoundIoDevice *device, int sample_rate) {
    for (int i = 0; i < device->sample_rate_count; i += 1) {
        struct SoundIoSampleRateRange *range = &device->sample_rates[i];
        if (sample_rate >= range->min && sample_rate <= range->max)
            return true;
    }
    return false;
}

static int abs_diff_int(int a, int b) {
    int x = a - b;
    return (x >= 0) ? x : -x;
}

int soundio_device_nearest_sample_rate(struct SoundIoDevice *device, int sample_rate) {
    int best_rate = -1;
    int best_delta = -1;
    for (int i = 0; i < device->sample_rate_count; i += 1) {
        struct SoundIoSampleRateRange *range = &device->sample_rates[i];
        int candidate_rate = soundio_int_clamp(range->min, sample_rate, range->max);
        if (candidate_rate == sample_rate)
            return candidate_rate;

        int delta = abs_diff_int(candidate_rate, sample_rate);
        bool best_rate_too_small = best_rate < sample_rate;
        bool candidate_rate_too_small = candidate_rate < sample_rate;
        if (best_rate == -1 ||
            (best_rate_too_small && !candidate_rate_too_small) ||
            ((best_rate_too_small || !candidate_rate_too_small) && delta < best_delta))
        {
            best_rate = candidate_rate;
            best_delta = delta;
        }
    }
    return best_rate;
}

bool soundio_device_equal(
        const struct SoundIoDevice *a,
        const struct SoundIoDevice *b)
{
    return a->is_raw == b->is_raw && a->aim == b->aim && strcmp(a->id, b->id) == 0;
}

const char *soundio_version_string(void) {
    return SOUNDIO_VERSION_STRING;
}

int soundio_version_major(void) {
    return SOUNDIO_VERSION_MAJOR;
}

int soundio_version_minor(void) {
    return SOUNDIO_VERSION_MINOR;
}

int soundio_version_patch(void) {
    return SOUNDIO_VERSION_PATCH;
}


text:
namespace Azure.ResourceManager.Insights.Models
{
    /// <summary> The type of the diagnostic settings category. </summary>
    public enum CategoryType
    {
        /// <summary> Metrics. </summary>
        Metrics,
        /// <summary> Logs. </summary>
        Logs
    }
}


text:
    <button type="button" class="navbar-toggle">
      Toggle navigation

    </button>

      {% if site.navbar-pf-navbar-brand-icon %}{% endif %}

        <button class="btn btn-link nav-item-iconic">

        </button>

    {% if page.contextselector %}
    {% include widgets/framework/context-selector.html %}
    {% endif %}

        <button class="btn btn-link nav-item-iconic">

        </button>

        <button class="btn btn-link dropdown-toggle nav-item-iconic" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">

        </button>

Help

About

        <button class="btn btn-link dropdown-toggle nav-item-iconic" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">

            Brian Johnson

        </button>

Preferences

Logout

  {% include widgets/notification-drawer.html %}


text:
<?php
/**
 * Template Name: Header-slider
 */
?>

<?php while (have_posts()) : the_post(); ?>
 <?php the_content(); ?>
<?php endwhile; ?>


text:
try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO
import csv
import requests

from pyzipcodeapi.options import OPTIONS

BASE_URL = 'https://www.zipcodeapi.com/rest/{api_key}/{option}.{format}/'
FORMAT = ['json', 'xml', 'csv']

class ZipCodeApiRequest(object):
    def __init__(self, base_url, option, output_format):
        """
        :param base_url:
        :param option:
        :param output_format:
        """
        self.base_url = base_url
        self.option = option
        self.output_format = output_format
        self.requests = requests

    def filter(self, **kwargs):
        """
        :param kwargs:
        :return:
        """
        try:
            if kwargs['units'] not in self.option['units']:
                raise ValueError(
                    "%s unit is not available. ZipCodeApi's units for the option '%s' should be in %s" %
                    (str(kwargs['units']), str(self.option['name']), str(', '.join(self.option['units'])))
                )
        except KeyError:
            pass
        url = self.base_url + self.option['url'].format(**kwargs)
        return self.make_request(url)

    def make_request(self, url):
        """
        :param url:
        :return:
        """
        r = self.requests.get(url)
        return self.request_output(r)

    def request_output(self, request):
        """
        :param request:
        :return:
        """
        if self.output_format == 'json':
            return request.json()
        elif self.output_format == 'csv':
            f = StringIO(request.text)
            reader = csv.DictReader(f, delimiter=',')
            return reader
        return request.text

class ZipCodeApi(object):
    def __init__(self, api_key):
        """
        :param api_key:
        """
        self.api_key = api_key

    def get(self, option, output_format='json'):
        """
        :param option:
        :param output_format:
        :return:
        """
        if option not in OPTIONS:
            raise KeyError(
                'Option {0} is not valid'.format(option) +
                "ZipCodeApi's option should be in %s" % str(', '.join(OPTIONS.keys()))
            )
        if output_format not in FORMAT:
            raise ValueError(
                "%s format is not available. ZipCodeApi's format should be in %s" %
                (str(output_format), str(', '.join(FORMAT)))
            )
        base_url = BASE_URL.format(api_key=self.api_key, option=option, format=output_format)
        return ZipCodeApiRequest(base_url, OPTIONS[option], output_format)


text:
using System;

using Zenject.ReflectionBaking.Mono.Cecil.PE;

namespace Zenject.ReflectionBaking.Mono.Cecil.Metadata {

	sealed class UserStringHeap : StringHeap {

		public UserStringHeap (Section section, uint start, uint size)
			: base (section, start, size)
		{
		}

		protected override string ReadStringAt (uint index)
		{
			byte [] data = Section.Data;
			int start = (int) (index + Offset);

			uint length = (uint) (data.ReadCompressedUInt32 (ref start) & ~1);
			if (length < 1)
				return string.Empty;

			var chars = new char [length / 2];

			for (int i = start, j = 0; i < start + length; i += 2)
				chars [j++] = (char) (data [i] | (data [i + 1] << 8));

			return new string (chars);
		}
	}
}


text:
var templates = require('../../templates'),
	util = require('util'),
	BaseView = require('./Base'),
	FindModel = require('../models/Find');

function FindView(router) {

	var findModel = new FindModel(),
		self = this,
		options = {
			el: document.getElementById('find'),
			template: templates['find'],
			data: findModel
		};

	BaseView.call(this, options);

	this.on('create', function() {
		$('.ui.accordion').accordion({
			onOpen: function() {
				console.log('here');
				findModel.pick();
			},
			onClose: function() {
				console.log('here2');
				findModel.resetPick();
			}
		});

		var modalElement = $('#notAuthedModal'),
			confirmModalElement = $('#areYouSureModal');

		this._ractive.observe({
			name: findModel.fetchConfig,
			appName: findModel.pick,
			appVersion: findModel.pick,
			envName: findModel.pick,
			config: function() {
				$('.optionsPopup').popup();
			}
		}, { defer: true });

		self._ractive.on('edit', function(event) {
			if (findModel.canWrite()) {
				router.go('/add', { data: event.context });
			}
			else {
				modalElement.modal('show');
			}

		});

		self._ractive.on('remove', function(event) {
			if (findModel.canWrite()) {
				confirmModalElement.modal('setting', 'onApprove', function() {
					findModel.remove(event.context.id);
				}).modal('show');
			}
			else {
				modalElement.modal('show');
			}
		});

	});

}

util.inherits(FindView, BaseView);

module.exports = FindView;


text:
@class ZZDataRow;

// --------------------------------------------------

@interface NSMutableArray (ZZRowSortByIndexPath)

- (void)zz_sortByInexPath;
- (ZZDataRow *)zz_containsCell:(UITableViewCell *)cell;
@end

// --------------------------------------------------

@interface ZZDataRow : NSObject

@property (nonatomic) BOOL hidden;
@property (nonatomic, weak) UITableViewCell *cell;
@property (nonatomic) NSIndexPath *indexPath;
@property (nonatomic, weak) ZZDataRow *previous;
@property (nonatomic, weak) ZZDataRow *next;
@property (nonatomic) CGFloat height;
- (void)resetIndexPath;
@end

// --------------------------------------------------

@interface ZZDataSection : NSObject

@property (nonatomic) NSMutableArray<ZZDataRow *> *rows;
@property (nonatomic) NSMutableArray<ZZDataRow *> *deleteRows;
@property (nonatomic) NSMutableArray<ZZDataRow *> *insertRows;

- (void)makeLink; // 使用双向链表结构记录每个ZZDataRow对象的前一个和后一个对象
- (void)zz_deleteRows;
- (void)zz_insertRows;
- (NSArray *)allCells;
@end

// --------------------------------------------------

@interface ZZDataTable : NSObject

- (instancetype)initWithTableView:(UITableView *)tableView;

@property (nonatomic) NSMutableArray<ZZDataSection *> *sections;
@property (nonatomic) NSMutableArray<ZZDataRow *> *deleteRows;
@property (nonatomic) NSMutableArray<ZZDataRow *> *didDeleteRows;
@property (nonatomic) NSMutableArray<ZZDataRow *> *insertRows;

- (void)deleteCells:(NSArray *)cells;
- (void)insertCells:(NSArray *)cells;
- (NSArray<NSIndexPath *> *)deleteIndexPaths;
- (NSArray<NSIndexPath *> *)insertIndexPaths;

@end


text:
package org.gradoop.flink.model.impl.operators.intersection;

import org.gradoop.flink.model.impl.epgm.GraphCollection;
import org.gradoop.flink.model.impl.operators.base.BinaryCollectionOperatorsTestBase;
import org.gradoop.flink.util.FlinkAsciiGraphLoader;
import org.junit.Test;

public class ReduceIntersectionTest extends BinaryCollectionOperatorsTestBase {

  @Test
  public void testOverlappingCollections() throws Exception {
    FlinkAsciiGraphLoader loader = getSocialNetworkLoader();

    GraphCollection col02 = loader.getGraphCollectionByVariables("g0", "g2");

    GraphCollection col12 = loader.getGraphCollectionByVariables("g1", "g2");

    GraphCollection expectation = loader.getGraphCollectionByVariables("g2");

    GraphCollection result = col02.intersect(col12);
    checkAssertions(expectation, result, "");

    result = col02.intersectWithSmallResult(col12);
    checkAssertions(expectation, result, "small");
  }

  @Test
  public void testNonOverlappingCollections() throws Exception {
    FlinkAsciiGraphLoader loader = getSocialNetworkLoader();

    GraphCollection col01 = loader.getGraphCollectionByVariables("g0", "g1");

    GraphCollection col23 = loader.getGraphCollectionByVariables("g2", "g3");

    GraphCollection expectation = getConfig().getGraphCollectionFactory().createEmptyCollection();

    GraphCollection result = col01.intersect(col23);

    checkAssertions(expectation, result, "non");

    result = col01.intersectWithSmallResult(col23);
    checkAssertions(expectation, result, "small non");
  }

  @Test
  public void testTotalOverlappingCollections() throws Exception {
    FlinkAsciiGraphLoader loader = getSocialNetworkLoader();

    GraphCollection expectation = loader
      .getGraphCollectionByVariables("g0", "g1");

    GraphCollection result = expectation.intersect(expectation);
    checkAssertions(expectation, result, "total");

    result = expectation.intersectWithSmallResult(expectation);
    checkAssertions(expectation, result, "small total");
  }
}


text:
#ifndef GFX_TYPES_H
#define GFX_TYPES_H

#include "prtypes.h"
#include "nsAtomicRefcnt.h"

/**
 * Currently needs to be 'double' for Cairo compatibility. Could
 * become 'float', perhaps, in some configurations.
 */
typedef double gfxFloat;

#if defined(IMPL_THEBES)
# define THEBES_API NS_EXPORT
#else
# define THEBES_API NS_IMPORT
#endif

/**
 * gfx errors
 */

/* nsIDeviceContextSpec.h defines a set of printer errors  */
#define NS_ERROR_GFX_GENERAL_BASE (50)

/* Font cmap is strangely structured - avoid this font! */
#define NS_ERROR_GFX_CMAP_MALFORMED          \
  NS_ERROR_GENERATE_FAILURE(NS_ERROR_MODULE_GFX,NS_ERROR_GFX_GENERAL_BASE+1)

/**
 * Priority of a line break opportunity.
 *
 * eNoBreak       The line has no break opportunities
 * eWordWrapBreak The line has a break opportunity only within a word. With
 *                word-wrap: break-word we will break at this point only if
 *                there are no other break opportunities in the line.
 * eNormalBreak   The line has a break opportunity determined by the standard
 *                line-breaking algorithm.
 *
 * Future expansion: split eNormalBreak into multiple priorities, e.g.
 *                    punctuation break and whitespace break (bug 389710).
 *                   As and when we implement it, text-wrap: unrestricted will
 *                    mean that priorities are ignored and all line-break
 *                    opportunities are equal.
 *
 * @see gfxTextRun::BreakAndMeasureText
 * @see nsLineLayout::NotifyOptionalBreakPosition
 */
enum gfxBreakPriority {
    eNoBreak       = 0,
    eWordWrapBreak,
    eNormalBreak
};

#define THEBES_INLINE_DECL_THREADSAFE_REFCOUNTING(_class)                     \
public:                                                                       \
    nsrefcnt AddRef(void) {                                                   \
        NS_PRECONDITION(PRInt32(mRefCnt) >= 0, "illegal refcnt");             \
        nsrefcnt count = NS_AtomicIncrementRefcnt(mRefCnt);                   \
        NS_LOG_ADDREF(this, count, #_class, sizeof(*this));                   \
        return count;                                                         \
    }                                                                         \
    nsrefcnt Release(void) {                                                  \
        NS_PRECONDITION(0 != mRefCnt, "dup release");                         \
        nsrefcnt count = NS_AtomicDecrementRefcnt(mRefCnt);                   \
        NS_LOG_RELEASE(this, count, #_class);                                 \
        if (count == 0) {                                                     \
            mRefCnt = 1; /* stabilize */                                      \
            delete this;                                                      \
            return 0;                                                         \
        }                                                                     \
        return count;                                                         \
    }                                                                         \
protected:                                                                    \
    nsAutoRefCnt mRefCnt;                                                     \
public:

#endif /* GFX_TYPES_H */


text:
package fr.paris.lutece.util.pool.service;

import fr.paris.lutece.portal.service.util.AppException;

import org.apache.commons.collections.CollectionUtils;
import org.apache.logging.log4j.Logger;

import java.io.PrintWriter;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

/**
 * This class manages a database connection pool.

 * Connections are wrapped by a {@link LuteceConnection} to avoid explicit calls to {@link Connection#close()}. Connections are released to this pool when
 * {@link Connection#close()} is called, and are not actually closed until {@link #release()} call.
 *
 * @see LuteceConnection
 */
public class ConnectionPool implements DataSource
{
    private static final String DEFAULT_CHECK_VALID_CONNECTION_SQL = "SELECT 1";
    private String _strUrl;
    private String _strUser;
    private String _strPassword;
    private int _nMaxConns;
    private int _nTimeOut;
    private Logger _logger;
    private int _nCheckedOut;
    private List<Connection> _freeConnections = new ArrayList<>( );
    private String _strCheckValidConnectionSql; // Added in v1.4
    private PrintWriter _logWriter;

    /**
     * Constructor.
     *
     * @param strName
     *            Nom du pool
     * @param strUrl
     *            JDBC Data source URL
     * @param strUser
     *            SQL User
     * @param strPassword
     *            SQL Password
     * @param nMaxConns
     *            Max connections
     * @param nInitConns
     *            Initials connections
     * @param nTimeOut
     *            Timeout to get a connection
     * @param logger
     *            the Logger object
     * @param strCheckValidConnectionSql
     *            The SQL syntax used for check connexion validatation
     */
    public ConnectionPool( String strName, String strUrl, String strUser, String strPassword, int nMaxConns, int nInitConns, int nTimeOut, Logger logger,
            String strCheckValidConnectionSql )
    {
        _strUrl = strUrl;
        _strUser = strUser;
        _strPassword = strPassword;
        _nMaxConns = nMaxConns;
        _nTimeOut = ( nTimeOut > 0 ) ? nTimeOut : 5;
        _logger = logger;
        initPool( nInitConns );
        _logger.info( "New pool created : {}", strName );

        _strCheckValidConnectionSql = ( ( strCheckValidConnectionSql != null ) && !strCheckValidConnectionSql.equals( "" ) ) ? strCheckValidConnectionSql
                : DEFAULT_CHECK_VALID_CONNECTION_SQL;

        String lf = System.getProperty( "line.separator" );
        _logger.debug( "{} url={}{} user= {}{} password= {}{} initconns= {}{} maxConns={}{} logintimeout={}", lf, strUrl, lf, _strUser, lf, _strPassword, lf,
                nInitConns, lf, _nMaxConns, lf, _nTimeOut );
        _logger.debug( ( ) -> getStats( ) );
    }

    /**
     * Initializes the pool
     *
     * @param initConns
     *            Number of connections to create at the initialisation
     */
    private void initPool( int initConns )
    {
        for ( int i = 0; i < initConns; i++ )
        {
            try
            {
                Connection pc = newConnection( );
                _freeConnections.add( pc );
            }
            catch( SQLException e )
            {
                throw new AppException( "SQL Error executing command : " + e.toString( ), e );
            }
        }
    }

    /**
     * Returns a connection from the pool.
     *
     * @return An open connection
     * @throws SQLException
     *             The SQL exception
     */
    @Override
    public Connection getConnection( ) throws SQLException
    {
        _logger.debug( "Request for connection received" );

        try
        {
            return getConnection( _nTimeOut * 1000L );
        }
        catch( SQLException e )
        {
            _logger.error( "Exception getting connection", e );
            throw e;
        }
    }

    /**
     * Returns a connection from the pool.
     *
     * @param timeout
     *            The maximum time to wait for a connection
     * @return An open connection
     * @throws SQLException
     *             The SQL exception
     */
    private synchronized Connection getConnection( long timeout ) throws SQLException
    {
        // Get a pooled Connection from the cache or a new one.
        // Wait if all are checked out and the max limit has
        // been reached.
        long startTime = System.currentTimeMillis( );
        long remaining = timeout;
        Connection conn = null;

        while ( ( conn = getPooledConnection( ) ) == null )
        {
            try
            {
                _logger.debug( "Waiting for connection. Timeout= {}", remaining );

                wait( remaining );
            }
            catch( InterruptedException e )
            {
                _logger.debug( "A connection has been released by another thread.", e );
            }

            remaining = timeout - ( System.currentTimeMillis( ) - startTime );

            if ( remaining <= 0 )
            {
                // Timeout has expired
                _logger.debug( "Time-out while waiting for connection" );
                throw new SQLException( "getConnection() timed-out" );
            }
        }

        // Check if the Connection is still OK
        if ( !isConnectionOK( conn ) )
        {
            // It was bad. Try again with the remaining timeout
            _logger.error( "Removed selected bad connection from pool" );

            return getConnection( remaining );
        }

        _nCheckedOut++;
        _logger.debug( "Delivered connection from pool" );
        _logger.debug( getStats( ) );

        return conn;
    }

    /**
     * Checks a connection to see if it's still alive
     *
     * @param conn
     *            The connection to check
     * @return true if the connection is OK, otherwise false.
     */
    private boolean isConnectionOK( Connection conn )
    {
        Statement testStmt = null;

        try
        {
            if ( !conn.isClosed( ) )
            {
                // Try to createStatement to see if it's really alive
                testStmt = conn.createStatement( );
                testStmt.executeQuery( _strCheckValidConnectionSql );
                testStmt.close( );
            }
            else
            {
                return false;
            }
        }
        catch( SQLException e )
        {
            if ( testStmt != null )
            {
                try
                {
                    testStmt.close( );
                }
                catch( SQLException se )
                {
                    throw new AppException( "ConnectionService : SQL Error executing command : " + se.toString( ) );
                }
            }

            _logger.error( "Pooled Connection was not okay", e );

            return false;
        }

        return true;
    }

    /**
     * Gets a connection from the pool
     *
     * @return An opened connection
     * @throws SQLException
     *             The exception
     */
    private Connection getPooledConnection( ) throws SQLException
    {
        Connection conn = null;

        if ( CollectionUtils.isNotEmpty( _freeConnections ) )
        {
            // Pick the first Connection in the Vector
            // to get round-robin usage
            conn = _freeConnections.get( 0 );
            _freeConnections.remove( 0 );
        }
        else
            if ( ( _nMaxConns == 0 ) || ( _nCheckedOut < _nMaxConns ) )
            {
                conn = newConnection( );
            }

        return conn;
    }

    /**
     * Creates a new connection.

     * The connection is wrapped by {@link LuteceConnection}
     *
     * @return The new created connection
     * @throws SQLException
     *             The SQL exception
     */
    private Connection newConnection( ) throws SQLException
    {
        Connection conn;

        if ( _strUser == null )
        {
            conn = DriverManager.getConnection( _strUrl );
        }
        else
        {
            conn = DriverManager.getConnection( _strUrl, _strUser, _strPassword );
        }

        // wrap connection so this connection pool is used when conn.close() is called
        conn = LuteceConnectionFactory.newInstance( this, conn );
        _logger.info( "New connection created. Connections count is : " + ( getConnectionCount( ) + 1 ) );
        return conn;
    }

    /**
     * Returns a connection to pool.
     *
     * @param conn
     *            The released connection to return to pool
     */
    public synchronized void freeConnection( Connection conn )
    {
        // Put the connection at the end of the Vector
        _freeConnections.add( conn );
        _nCheckedOut--;
        notifyAll( );
        _logger.debug( "Returned connection to pool" );
        _logger.debug( ( ) -> getStats( ) );
    }

    /**
     * Releases the pool by closing all its connections.
     */
    public synchronized void release( )
    {
        for ( Connection connection : _freeConnections )
        {
            try
            {
                if ( connection instanceof LuteceConnection )
                {
                    ( (LuteceConnection) connection ).closeConnection( );
                }
                else
                {
                    connection.close( );
                }

                _logger.debug( "Closed connection" );
            }
            catch( SQLException e )
            {
                _logger.error( "Couldn't close connection", e );
            }
        }

        _freeConnections.clear( );
    }

    /**
     * Returns stats on pool's connections
     *
     * @return Stats as String.
     */
    private String getStats( )
    {
        return "Total connections: " + getConnectionCount( ) + " Available: " + getFreeConnectionCount( ) + " Checked-out: " + getBusyConnectionCount( );
    }

    /**
     * Returns the number of connections opened by the pool (available or busy)
     *
     * @return A connection count
     */
    public int getConnectionCount( )
    {
        return getFreeConnectionCount( ) + getBusyConnectionCount( );
    }

    /**
     * Returns the number of free connections of the pool (available or busy)
     *
     * @return A connection count
     */
    public int getFreeConnectionCount( )
    {
        return _freeConnections.size( );
    }

    /**
     * Returns the number of busy connections of the pool (available or busy)
     *
     * @return A connection count
     */
    public int getBusyConnectionCount( )
    {
        return _nCheckedOut;
    }

    /**
     * Returns the maximum number of connections of the pool
     *
     * @return A connection count
     */
    public int getMaxConnectionCount( )
    {
        return _nMaxConns;
    }

    /**
     * Returns the connection of the pool.
     *
     * @param username
     *            the username
     * @param password
     *            the password
     * @return A connection
     * @throws SQLException
     *             the sQL exception
     */
    @Override
    public Connection getConnection( String username, String password ) throws SQLException
    {
        return getConnection( );
    }

    /**
     * Get the log.
     *
     * @return A log writer
     * @throws SQLException
     *             the sQL exception
     */
    @Override
    public PrintWriter getLogWriter( ) throws SQLException
    {
        _logger.debug( "ConnectionPool : DataSource getLogWriter called" );

        return _logWriter;
    }

    /**
     * Set the log.
     *
     * @param out
     *            the new log writer
     * @throws SQLException
     *             the sQL exception
     */
    @Override
    public void setLogWriter( PrintWriter out ) throws SQLException
    {
        _logger.debug( "ConnectionPool : DataSource setLogWriter called" );
        _logWriter = out;
    }

    /**
     * Set Login Timeout.
     *
     * @param seconds
     *            the new login timeout
     * @throws SQLException
     *             the sQL exception
     */
    @Override
    public void setLoginTimeout( int seconds ) throws SQLException
    {
        // Do nothing
    }

    /**
     * Get loging timeout.
     *
     * @return A time out
     * @throws SQLException
     *             the sQL exception
     */
    @Override
    public int getLoginTimeout( ) throws SQLException
    {
        return _nTimeOut;
    }

    /**
     * Get the unwrap.
     *
     * @param <T>
     *            the generic type
     * @param iface
     *            the iface
     * @return null
     * @throws SQLException
     *             the sQL exception
     */
    @Override
    public <T> T unwrap( Class<T> iface ) throws SQLException
    {
        return null;
    }

    /**
     * Get the wrapper.
     *
     * @param iface
     *            the iface
     * @return false
     * @throws SQLException
     *             the sQL exception
     */
    @Override
    public boolean isWrapperFor( Class<?> iface ) throws SQLException
    {
        return false;
    }

    /**
     * Implementation of JDBC 4.1's getParentLogger method (Java 7)
     *
     * @return the parent logger
     */
    public java.util.logging.Logger getParentLogger( )
    {
        return java.util.logging.Logger.getLogger( java.util.logging.Logger.GLOBAL_LOGGER_NAME );
    }
}


text:
class CHost;
class CHostEngine;

enum
{
	MSG_GRID_COL_ID = 0,
	MSG_GRID_COL_START_TIME,
	MSG_GRID_COL_REMAINED,
	MSG_GRID_COL_HOPS,
};

// CListCtrlMessages

class CListCtrlMessages : public CMFCListCtrl
{
	DECLARE_DYNAMIC(CListCtrlMessages)

public:
	CListCtrlMessages();
	virtual ~CListCtrlMessages();
	void Init(CHost * pHost, CHostEngine * pEngine);
	void ShowAllMsgs();

	CHost * m_pHost;
	CHostEngine * m_pEngine;

protected:
	DECLARE_MESSAGE_MAP()
};


text:
# ************************************************************
# Sequel Pro SQL dump
# Version 4096
#
# http://www.sequelpro.com/
# http://code.google.com/p/sequel-pro/
#
# Host: 127.0.0.1 (MySQL 5.5.38-0ubuntu0.14.04.1)
# Database: cake2_watermark
# Generation Time: 2014-11-30 04:22:21 +0000
# ************************************************************

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

# Dump of table attachments
# ------------------------------------------------------------

DROP TABLE IF EXISTS `attachments`;

CREATE TABLE `attachments` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `model` varchar(20) NOT NULL,
  `foreign_key` int(11) NOT NULL,
  `name` varchar(32) NOT NULL,
  `attachment` varchar(255) NOT NULL,
  `dir` varchar(255) DEFAULT NULL,
  `type` varchar(255) DEFAULT NULL,
  `size` int(11) DEFAULT '0',
  `active` tinyint(1) DEFAULT '1',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

# Dump of table photos
# ------------------------------------------------------------

DROP TABLE IF EXISTS `photos`;

CREATE TABLE `photos` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `watermark` text,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;


text:
package com.intellij.codeInsight.template.impl;

import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.editor.Editor;
import com.intellij.psi.PsiFile;

/**
 * @author yole
 */
public interface TemplatePreprocessor {
  ExtensionPointName<TemplatePreprocessor> EP_NAME = ExtensionPointName.create("com.intellij.liveTemplatePreprocessor");

  void preprocessTemplate(final Editor editor, final PsiFile file, int caretOffset, final String textToInsert, final String templateText);
}


text:
from django.test import SimpleTestCase
from django.utils.topological_sort import (
    CyclicDependencyError, stable_topological_sort, topological_sort_as_sets,
)

class TopologicalSortTests(SimpleTestCase):

    def test_basic(self):
        dependency_graph = {
            1: {2, 3},
            2: set(),
            3: set(),
            4: {5, 6},
            5: set(),
            6: {5},
        }
        self.assertEqual(list(topological_sort_as_sets(dependency_graph)), [{2, 3, 5}, {1, 6}, {4}])
        self.assertEqual(stable_topological_sort([1, 2, 3, 4, 5, 6], dependency_graph), [2, 3, 5, 1, 6, 4])

    def test_cyclic_dependency(self):
        msg = 'Cyclic dependency in graph: '
        with self.assertRaisesMessage(CyclicDependencyError, msg):
            list(topological_sort_as_sets({1: {2}, 2: {1}}))


text:
**) A random collection [ IPython nb ] (http://nbviewer.ipython.org/github/rasbt/python_reference/blob/master/python_patterns/patterns.ipynb)

**) Time saving Python tips [ Python-3 snippets ] ( http://fadymak.com/pages/useful_python_snippets.html )

**) Getting started with [ IPython Notebook ] ( https://nbviewer.jupyter.org/github/ipython/ipython/blob/4.0.x/examples/Notebook/Index.ipynb )

**) Searching interesting [ Jupyter Notebooks ] (https://nbviewer.jupyter.org/)

**) A nice introduction to [ Bayesian for Hackers ] (https://nbviewer.jupyter.org/github/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/blob/master/Chapter1_Introduction/Chapter1.ipynb)

**) Kickstarting [Numpy, Scipy, Sympy, Matplotlib] ( http://nbviewer.jupyter.org/github/jrjohansson/scientific-python-lectures/blob/master/Lecture-0-Scientific-Computing-with-Python.ipynb )

**) Mining social web [Twitter, FB, G+] ( https://nbviewer.jupyter.org/github/ptwobrussell/Mining-the-Social-Web-2nd-Edition/blob/master/ipynb/Chapter%201%20-%20Mining%20Twitter.ipynb )

Last-But-Not-The-Least: [ Python sub-reddit ] ( https://www.reddit.com/r/Python/ )

PyCoders Hangout Place [ so-chatroom ] ( http://chat.stackoverflow.com/rooms/6/python )
Gitter Chatroom  [![Join the chat at https://gitter.im/saarpy/Python-snippets](https://badges.gitter.im/saarpy/Python-snippets.svg)](https://gitter.im/saarpy/Python-snippets?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)


text:
[![CircleCI](https://circleci.com/gh/Shopify/slate-tools.svg?style=svg&circle-token=0b8147527ef88134b4238064a563ceaaae98f06a)](https://circleci.com/gh/Shopify/slate-tools)

Tooling for Shopify themes using [Slate](https://github.com/Shopify/slate).

Best used in conjunction with the [Slate CLI](https://www.npmjs.com/package/t-kelly-slate) package.

## Installation
```bash
$ npm install t-kelly-slate-tools
```

## Documentation

For full API documentation checkout the [API docs](https://shopify.github.io/slate/).

## Contributing
For help on setting up the repo locally, building, testing, and contributing
please see [CONTRIBUTING.md](https://github.com/Shopify/slate-tools/blob/master/CONTRIBUTING.md).

## Code of Conduct
All developers who wish to contribute through code or issues, take a look at the
[CODE_OF_CONDUCT.md](https://github.com/Shopify/slate-tools/blob/master/CODE_OF_CONDUCT.md).

## License

MIT, see [LICENSE.md](http://github.com/Shopify/slate-tools/blob/master/LICENSE.md) for details.

<img src="https://cdn.shopify.com/shopify-marketing_assets/builds/19.0.0/shopify-full-color-black.svg" width="200" />

Some other enhancement


text:
package org.apache.accumulo.tserver.memory;

import org.apache.accumulo.core.dataImpl.KeyExtent;
import org.apache.accumulo.tserver.tablet.Tablet;

public class TabletMemoryReport implements Cloneable {

  private final Tablet tablet;
  private final long lastCommitTime;
  private final long memTableSize;
  private final long minorCompactingMemTableSize;

  public TabletMemoryReport(Tablet tablet, long lastCommitTime, long memTableSize,
      long minorCompactingMemTableSize) {
    this.tablet = tablet;
    this.lastCommitTime = lastCommitTime;
    this.memTableSize = memTableSize;
    this.minorCompactingMemTableSize = minorCompactingMemTableSize;
  }

  public KeyExtent getExtent() {
    return tablet.getExtent();
  }

  public Tablet getTablet() {
    return tablet;
  }

  public long getLastCommitTime() {
    return lastCommitTime;
  }

  public long getMemTableSize() {
    return memTableSize;
  }

  public long getMinorCompactingMemTableSize() {
    return minorCompactingMemTableSize;
  }

  @Override
  public TabletMemoryReport clone() throws CloneNotSupportedException {
    return (TabletMemoryReport) super.clone();
  }
}


text:
import pickle
import leveldb

from wikiref.semadata import SemanticNodeSet
from wikiref.settings import LDB_ARRAY_DELIM

class YagoClassDict(object):
    """
    Maps: <yago_label> -> [<yago_node>]
    """

    def __init__(self, data_root):
        self.data_root = data_root
        self.ldb = leveldb.LevelDB(data_root)

    def get(self, term, default=None):
        try:
            return SemanticNodeSet(lemmas=[term], nodes=self.ldb.Get(term).split(LDB_ARRAY_DELIM))
        except KeyError:
            return default

    def __getitem__(self, key):
        return self.get(key)

    def __repr__(self):
        return "<YagoDict(data=%s)>" % self.data_root

class YagoClassSearch(object):
    """
    Map: <word> -> [<yago_node>]
    """

    def __init__(self, data_root):
        self.data_root = data_root
        self.ldb = leveldb.LevelDB(data_root)

    def get(self, lemma_or_lemmas, default=None):
        if isinstance(lemma_or_lemmas, list) or isinstance(lemma_or_lemmas, tuple):
            return self.search(lemma_or_lemmas, default=default)
        else:
            return self.search([lemma_or_lemmas], default=default)

    def search(self, lemmas, default=None):
        node_sets = []
        for lemma in lemmas:
            try:
                lemma_nodes = self.ldb.Get(lemma).split(LDB_ARRAY_DELIM)
            except KeyError:
                return default
            node_sets.append(lemma_nodes)
        conjunction = set(node_sets[0])
        for i in xrange(1, len(node_sets)):
            node_set = node_sets[i]
            conjunction.intersection_update(node_set)
        if len(conjunction) == 0:
            return default
        return SemanticNodeSet(lemmas=lemmas, nodes=conjunction)

    def __getitem__(self, key):
        return self.get(key)

    def __repr__(self):
        return "<YagoSearchDict(data=%s)>" % self.data_root

class YagoTaxonomy(object):
    """
    Map: <child_node> -> [<parent_node>]
    """

    def __init__(self, data_root):
        self.data_root = data_root
        self.ldb = leveldb.LevelDB(data_root)

    def get_parent(self, node, default=None):
        try:
            if isinstance(node, list):
                node = node
            value = self.ldb.Get(node).split(LDB_ARRAY_DELIM)[0]
            return value
        except KeyError:
            return default

    def __getitem__(self, key):
        return self.get_parent(key)

    def __repr__(self):
        return "<YagoTaxonomyDict(data=%s)>" % self.data_root

class YagoTypes(object):

    def __init__(self, data_root):
        self.data_root = data_root
        self.ldb = leveldb.LevelDB(data_root)

    def get_parent(self, node, default=[]):
        try:
            return self.ldb.Get(node).split(LDB_ARRAY_DELIM)
        except KeyError:
            return default

    def __getitem__(self, key):
        return self.get_parent(key)

    def __repr__(self):
        return "<YagoTransitiveDict(data=%s)>" % self.data_root

# class YagoPreferredSearch(object):

#     def __init__(self, data_root):
#         self.data_root = data_root
#         self.ldb = leveldb.LevelDB(data_root)

#     def get(self, lemma_or_lemmas, default=None):
#         if isinstance(lemma_or_lemmas, list) or isinstance(lemma_or_lemmas, tuple):
#             return self.search(lemma_or_lemmas, default=default)
#         else:
#             return self.search([lemma_or_lemmas], default=default)

#     def search(self, lemmas, default=None):
#         node_sets = []
#         for lemma in lemmas:
#             try:
#                 lemma_nodes = set(self.ldb.Get(lemma).split(DELIM))
#             except KeyError:
#                 return default
#             node_sets.append(lemma_nodes)
#         conjunction = node_sets[0]
#         for i in xrange(1, len(node_sets)):
#             node_set = node_sets[i]
#             conjunction.intersection_update(node_set)
#         if len(conjunction) == 0:
#             return default
#         return SemanticNodeSet(lemmas=lemmas, nodes=conjunction)

#     def __getitem__(self, key):
#         return self.get(key)

#     def __repr__(self):
#         return "<YagoSearchDict(data=%s)>" % self.data_root


text:
package org.apache.cassandra.db;

import java.io.DataInputStream;
import java.io.IOError;
import java.io.IOException;

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

import org.apache.cassandra.io.util.FastByteArrayInputStream;
import org.apache.cassandra.net.IVerbHandler;
import org.apache.cassandra.net.Message;
import org.apache.cassandra.net.MessagingService;

public class TruncateVerbHandler implements IVerbHandler
{
    private static Logger logger = LoggerFactory.getLogger(TruncateVerbHandler.class);

    public void doVerb(Message message, String id)
    {
        byte[] bytes = message.getMessageBody();
        FastByteArrayInputStream buffer = new FastByteArrayInputStream(bytes);

        try
        {
            Truncation t = Truncation.serializer().deserialize(new DataInputStream(buffer), message.getVersion());
            logger.debug("Applying {}", t);

            try
            {
                ColumnFamilyStore cfs = Table.open(t.keyspace).getColumnFamilyStore(t.columnFamily);
                cfs.truncate().get();
            }
            catch (Exception e)
            {
                logger.error("Error in truncation", e);
                respondError(t, message);
            }
            logger.debug("Truncate operation succeeded at this host");

            TruncateResponse response = new TruncateResponse(t.keyspace, t.columnFamily, true);
            Message responseMessage = TruncateResponse.makeTruncateResponseMessage(message, response);
            logger.debug("{} applied.  Sending response to {}@{} ", new Object[]{ t, id, message.getFrom()});
            MessagingService.instance().sendReply(responseMessage, id, message.getFrom());
        }
        catch (IOException e)
        {
            throw new IOError(e);
        }
    }

    private static void respondError(Truncation t, Message truncateRequestMessage) throws IOException
    {
        TruncateResponse response = new TruncateResponse(t.keyspace, t.columnFamily, false);
        Message responseMessage = TruncateResponse.makeTruncateResponseMessage(truncateRequestMessage, response);
        MessagingService.instance().sendOneWay(responseMessage, truncateRequestMessage.getFrom());
    }
}


text:
namespace Atomic
{

class XMLElement;

/// PList value types.
enum PListValueType
{
    PLVT_NONE = 0,
    PLVT_INT,
    PLVT_BOOL,
    PLVT_FLOAT,
    PLVT_STRING,
    PLVT_VALUEMAP,
    PLVT_VALUEVECTOR,
};

class PListValue;

/// PList value map.
typedef HashMap<String, PListValue> PListValueMap;

/// Vector of PList value.
typedef Vector<PListValue> PListValueVector;

/// PList value.
class ATOMIC_API PListValue
{
public:
    // Construct.
    PListValue();
    // Construct from int.
    PListValue(int value);
    // Construct from boolean.
    PListValue(bool value);
    // Construct from float.
    PListValue(float value);
    // Construct from string.
    PListValue(const String& value);
    // Construct from value map.
    PListValue(PListValueMap& valueMap);
    // Construct from value vector.
    PListValue(PListValueVector& valueVector);
    // Construct from another value.
    PListValue(const PListValue& value);
    /// Destruct.
    ~PListValue();

    /// Assign operator.
    PListValue& operator =(const PListValue& rhs);

    /// Return true if is valid.
    operator bool() const { return type_ != PLVT_NONE; }

    /// Set int.
    void SetInt(int value);
    /// Set boolean.
    void SetBool(bool value);
    /// Set float.
    void SetFloat(float value);
    /// Set string.
    void SetString(const String& value);
    /// Set value map.
    void SetValueMap(const PListValueMap& valueMap);
    /// Set value vector.
    void SetValueVector(const PListValueVector& valueVector);

    /// Return type.
    PListValueType GetType() const { return type_; }

    /// Return int.
    int GetInt() const;
    /// Return boolean.
    bool GetBool() const;
    /// Return float.
    float GetFloat() const;
    /// Return string.
    const String& GetString() const;
    /// Return IntRect, for string type.
    IntRect GetIntRect() const;
    /// Return IntVector2, for string type.
    IntVector2 GetIntVector2() const;
    /// Return value map.
    const PListValueMap& GetValueMap() const;
    /// Return value vector.
    const PListValueVector& GetValueVector() const;

    /// Convert to value map (internal use only).
    PListValueMap& ConvertToValueMap();
    /// Convert to value vector (internal use only).
    PListValueVector& ConvertToValueVector();

private:
    /// Reset.
    void Reset();

    /// Type.
    PListValueType type_;
    /// Values.
    union
    {
        int int_;
        bool bool_;
        float float_;
        String* string_;
        PListValueMap* valueMap_;
        PListValueVector* valueVector_;
    };
};

/// Property list (plist).
class ATOMIC_API PListFile : public Resource
{
    OBJECT(PListFile);

public:
    /// Construct.
    PListFile(Context* context);
    /// Destruct.
    virtual ~PListFile();
    /// Register object factory.
    static void RegisterObject(Context* context);

    /// Load resource from stream. May be called from a worker thread. Return true if successful.
    virtual bool BeginLoad(Deserializer& source);

    /// Return root.
    const PListValueMap& GetRoot() const { return root_; }

private:
    /// Load dictionary.
    bool LoadDict(PListValueMap& dict, const XMLElement& dictElem);
    /// Load array.
    bool LoadArray(PListValueVector& array, const XMLElement& arrayElem);
    /// Load value.
    bool LoadValue(PListValue& value, const XMLElement& valueElem);

    /// Root dictionary.
    PListValueMap root_;
};

}


text:
#include <lfant/FrameBuffer.h>

// Internal
#include <lfant/Console.h>
#include <lfant/Thread.h>
#include <lfant/Renderer.h>
#include <lfant/Camera.h>
#include <lfant/Scene.h>
#include <lfant/Transform.h>
#include <lfant/Input.h>
#include "lfant/Window.h"

// External
#if !ANDROID
#include <GL/glew.h>
#else
//#include <EGL/egl.h>
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <GLES2/gl2platform.h>
#endif

namespace lfant {

FrameBuffer* FrameBuffer::current = nullptr;

FrameBuffer::FrameBuffer(Game* game) :
	game(game)
{
}

FrameBuffer::~FrameBuffer()
{
}

void FrameBuffer::Clear()
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}

void FrameBuffer::Init()
{
	glGenFramebuffers(1, &id);
	glBindFramebuffer(GL_FRAMEBUFFER, id);

//	GetGame()->Log(glGetError());

	drawBuffers.clear();
	Texture* tex = nullptr;
	if(textures.size() > 0)
	{
		for(uint i = 0; i < textures.size(); ++i)
		{
			tex = textures[i];
		//	tex->scaleFilter = Texture::ScaleFilter::Linear;
			tex->wrapMode = Texture::WrapMode::Clamp;
		//	tex->mode = GL_TEXTURE_2D_MULTISAMPLE;
			tex->size = uvec2(rect.width, rect.height);
			tex->SetIndex(startIndex+i);
			tex->InitData(0);

			uint32 attachment = startIndex+GL_COLOR_ATTACHMENT0+i;
			GetGame()->Log("Setting up textures for FrameBuffer, tex ", i, " gets attachment ", attachment, ". GL_COLOR_ATTACHMENT0 = ", GL_COLOR_ATTACHMENT0);

			tex->Bind();
			glFramebufferTexture2D(GL_FRAMEBUFFER, attachment, tex->GetMode(), tex->GetId(), 0);

			drawBuffers.push_back(attachment);
		}
	}

	if(hasDepth)
	{
	/*	glGenRenderbuffers(1, &depthBuffer);
		glBindRenderbuffer(GL_RENDERBUFFER, depthBuffer);
		glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, rect.width, rect.height);
		glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, depthBuffer);
	*/
		if(depthTexture)
		{
		//	depthTexture->SetFormat(Texture::Format::Depth32F_Stencil8, Texture::Format::Depth);
			depthTexture->SetFormat(Texture::Format::Depth32F, Texture::Format::Depth);
			depthTexture->wrapMode = Texture::WrapMode::Clamp;
			depthTexture->dataType = Texture::DataType::Float;
			depthTexture->size = uvec2(rect.width, rect.height);
			depthTexture->SetIndex(startIndex+textures.size());
			depthTexture->InitData(0);

			depthTexture->Bind();
			glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, depthTexture->GetMode(), depthTexture->GetId(), 0);

			GetGame()->Log(glGetError());
		}
	}

	DrawBuffers();

	BeginRender();

	Unbind();
}

void FrameBuffer::Deinit()
{
	posBuffer.Destroy();
	shader.reset();

	for(auto& tex : textures)
	{
		tex->Destroy();
	}
	textures.clear();

	depthTexture->Destroy();
	depthTexture.reset();

	glDeleteFramebuffers(1, &id);
}

Game* FrameBuffer::GetGame() const
{
	return game;
}

void FrameBuffer::AddTexture(string name, Texture::Format form1, Texture::Format form2)
{
	Texture* tex = new Texture;
	tex->path = name;
	tex->SetFormat(form1, form2);
	textures.push_back(tex);
}

void FrameBuffer::AddDepthTexture(string name, Texture::Format form1, Texture::Format form2)
{
	if(!depthTexture)
	{
		depthTexture = new Texture;
	}
	depthTexture->path = name;
	hasDepth = true;
}

void FrameBuffer::GetTextures(Shader* sh) const
{
	if(textures.size() > 0)
	{
		sh->Bind();
		for(uint i = 0; i < textures.size(); ++i)
		{
			textures[i]->Bind();
			sh->SetUniform(textures[i]->path, textures[i]);
		}
		textures[0]->Unbind();
		sh->Unbind();
	}
}

Texture* FrameBuffer::GetTexture(string name) const
{
	if(name == depthTexture->path)
	{
		return depthTexture;
	}
	for(uint i = 0; i < textures.size(); ++i)
	{
		if(textures[i]->path == name)
		{
			return textures[i];
		}
	}
	return nullptr;
}

void FrameBuffer::BindTextures(Shader* sh)
{
	if(!sh)
	{
		for(uint i = 0; i < textures.size(); ++i)
		{
			textures[i]->Bind();
		}
	}
	else
	{
		for(uint i = 0; i < textures.size(); ++i)
		{
			sh->SetUniform(textures[i]->path, textures[i]);
		}
	}
}

FrameBuffer* FrameBuffer::GetCurrent()
{
	return FrameBuffer::current;
}

void FrameBuffer::Bind()
{
	glBindFramebuffer(GL_FRAMEBUFFER, id);
	FrameBuffer::current = this;
}

void FrameBuffer::Unbind()
{
	glBindFramebuffer(GL_FRAMEBUFFER, 0);
	FrameBuffer::current = nullptr;
}

void FrameBuffer::BindRead()
{
#if !LFANT_GLES
	glBindFramebuffer(GL_READ_FRAMEBUFFER, id);
#else
	glBindFramebuffer(GL_FRAMEBUFFER, id);
#endif
	FrameBuffer::current = this;
}

void FrameBuffer::UnbindRead()
{
#if !LFANT_GLES
	glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
#else
	glBindFramebuffer(GL_FRAMEBUFFER, 0);
#endif
	FrameBuffer::current = nullptr;
}

void FrameBuffer::DrawBuffers()
{
	glDrawBuffer(GL_NONE);
//	glBindFramebuffer(GL_DRAW_FRAMEBUFFER, id);
#if !LFANT_GLES
	glDrawBuffers(drawBuffers.size(), &drawBuffers[0]);
#endif
	if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
	{
		GetGame()->Log("Framebuffer failed to draw.");
	}
//	glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
}

void FrameBuffer::DrawBuffer(int idx)
{
	glDrawBuffer(drawBuffers[idx]);
}

uint32 FrameBuffer::GetAttachment(uint32 idx)
{
	return GL_COLOR_ATTACHMENT0 + idx;
}

void FrameBuffer::ResizeViewport()
{
	glViewport(rect.x, rect.y, rect.width, rect.height);
}

void FrameBuffer::Resize()
{

}

void FrameBuffer::BeginRender()
{
//	GLuint VertexArrayID;
//	glGenVertexArrays(1, &VertexArrayID);
//	glBindVertexArray(VertexArrayID);

//	shader = new Shader;
//	shader->LoadFile("shaders/FrameBuffer.vert", "shaders/FrameBuffer.frag");
	shader = Shader::LoadFile("shaders/FrameBuffer.vert", "shaders/FrameBuffer.frag");

	for(uint i = 0; i < textures.size(); ++i)
	{
		shader->AddUniform(textures[i]->path);
	}
	if(!depthTexture->path.empty())
	{
		shader->AddUniform(depthTexture->path);
	}

	shader->AddUniform("cameraRange");
	shader->AddUniform("focalDepth");
	shader->AddUniform("focalLength");
	shader->AddUniform("fstop");
	shader->AddUniform("focus");
	shader->AddUniform("textureSize");
	shader->AddUniform("useDof");
	shader->AddUniform("ambientLight");

	posBuffer.push_back(vec2(-1, -1));
	posBuffer.push_back(vec2(1, -1));
	posBuffer.push_back(vec2(-1, 1));

	posBuffer.push_back(vec2(-1, 1));
	posBuffer.push_back(vec2(1, -1));
	posBuffer.push_back(vec2(1, 1));

	Geometry::CreateBuffer(posBuffer, GL_ARRAY_BUFFER);

	GetGame()->Log(glGetError());
}

void FrameBuffer::Render()
{
	shader->Bind();

//	GetGame()->Log(glGetError());

//	shader->SetUniform("cameraPosition", game->scene->mainCamera->owner->transform->GetWorldPosition());
//	shader->SetUniform("cameraDof", vec2(game->scene->mainCamera->dof - game->scene->mainCamera->dofWidth, game->scene->mainCamera->dof + game->scene->mainCamera->dofWidth));
	if(GetGame()->scene->mainCamera)
	{
		shader->SetUniform("focalDepth", GetGame()->scene->mainCamera->focalDepth);
		shader->SetUniform("focalLength", GetGame()->scene->mainCamera->focalLength);
		shader->SetUniform("fstop", GetGame()->scene->mainCamera->aperture);
		shader->SetUniform("focus", GetGame()->scene->mainCamera->focus);
		shader->SetUniform("cameraRange", vec2_cast<vec2>(GetGame()->scene->mainCamera->GetViewRange()));
		shader->SetUniform("useDof", GetGame()->scene->mainCamera->useDof);
	}
	shader->SetUniform("textureSize", (vec2)GetGame()->window->GetSize());
	shader->SetUniform("ambientLight", GetGame()->renderer->ambientLight);
//	GetGame()->Log(glGetError());

	for(uint32 i = 0; i < textures.size(); ++i)
	{
		if(shader->GetUniform(textures[i]->path) != -1)
		{
		//	shader->SetUniform(textures[i]->path, textures[i]->GetIndex());
			shader->SetUniform(textures[i]->path, textures[i]);
		}
	}
	if(depthTexture) shader->SetUniform(depthTexture->path, depthTexture);

	glEnableVertexAttribArray(0);
	glBindBuffer(GL_ARRAY_BUFFER, posBuffer.id);
	glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, (void*)0);

	glDrawArrays(GL_TRIANGLES, 0, posBuffer.size());

//	GetGame()->Log(glGetError());

//	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glDisableVertexAttribArray(0);

/*	for(uint i = 0; i < textures.size(); ++i)
	{
		textures[i]->Unbind();
	}

	shader->Unbind();*/
}

void FrameBuffer::EndRender()
{
}

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Endothiella robiniae Chona & Munjal

### Remarks
null


text:
'use strict';

var $ = require('jquery');
var AmpersandView = require('ampersand-view');
var CardView = require('./card-view');
var template = require('./templates/list.hbs');

//Initialize touchswipe on jquery
var $ = require('jquery');
require('touchswipe')($);

module.exports = AmpersandView.extend({
  autoRender: true,
  template: template,

  initialize: function() {
    this.listenTo(this.collection, 'sync', this.renderCards);
    this.listenTo(this.collection, 'change:selectedNode', this.showSelected);

    var _this = this;
    window.addEventListener('orientationchange', function() {
      _this.enableSwipe(true);
    }, false);
  },

  render: function() {
    this.renderWithTemplate();

    $(this.el).swipe({
      swipe:function(event, direction, distance, duration, fingerCount) {
        if (direction === 'left') {
          app.mapNodes.selectNextNode();
        } else if (direction === 'right') {
          app.mapNodes.selectPreviousNode();
        }
      },
    });

    this.triggerDetails(false);

    return this;
  },

  renderCards: function() {
    $(this.el).empty();
    this.collectionView = this.renderCollection(this.collection,
                                                  CardView, this.el);
  },

  triggerDetails: function(showDetails) {
    if (showDetails) {
      this.enableSwipe(true);
      this.el.classList.add('cards--full');
    } else {
      this.enableSwipe(false);
      this.el.classList.remove('cards--full');
      $(this.el).find('li').css('left', 0);
    }
  },

  enableSwipe: function(flag) {
    if (flag && !window.matchMedia('(min-width:860px)').matches) {
      $(this.el).swipe('enable');
    } else {
      $(this.el).swipe('disable');
    }
  },

  showSelected: function() {
    var selectedIndex;
    var selectedNode = this.collection.selectedNode;
    this.collectionView.views.forEach(function(view, index) {
      if (selectedNode === view.model) {
        view.showAsSelected(true);
        selectedIndex = index;
      } else {
        view.showAsSelected(false);
      }
    });

    if (!window.matchMedia('(min-width:860px)').matches) {
      $(this.el).find('li').css('left', -85 * selectedIndex + '%');
    } else {
      //TODO: find correct scrolling algorithm, only scroll when necessary
    }
  }
});