text:
<?php $this->load->view('fixos/cabecalho'); ?>

                            <a href="<?php echo base_url('candidatos'); ?>">Candidatos

<?php echo $candidato->get_nome_completo(); ?>

                        <button class="btn btn-style06" id="salvarCandidato">Salvar</button>

                        <a class="btn btn-style06" href="<?php echo base_url('candidatos/consultar/' . $candidato->get_id_paciente() ); ?>">Voltar

                            Informações

Última Modificação: <?php echo $candidato->get_data_atualizacao(); ?>

    <?php $this->load->view('fixos/mensagem'); ?>

        <?php  echo form_open('candidatos/editar_form/' . $candidato->get_id_paciente() ,
               array( 'id' => 'candidato_form', 'name' => 'candidato_form' ) ); ?>

                        Nome Completo*

                            <input type="text" name="nome_completo" class="form-control" value="<?php echo $candidato->get_nome_completo(); ?>" required>

                        Idade

                            <input type="number" name="idade" class="form-control" value="<?php echo $candidato->calcularIdade(); ?>" data-toggle="tooltip" data-placement="bottom" title="Idade é calculada de acordo com a data de nascimento." disabled>

                        Data de Nascimento*

                            <input type="text" name="data_nascimento" class="form-control" id="candidato_data_nasc" value="<?= (new DateTime( $candidato->get_data_nascimento() ))->format("d/m/Y"); ?>" required>

                        Sexo*

                            <select class="form-control" name="sexo" required>
                                <option value="m" <?php echo ( strtolower( $candidato->get_sexo() ) == 'm' ) ? 'selected' : ''; ?> >M</option>
                                <option value="f" <?php echo ( strtolower( $candidato->get_sexo() ) == 'f' ) ? 'selected' : ''; ?> >F</option>
                            </select>

                        Hipótese de Diagnóstico (HD)

                            <textarea name="hipotese_diagnostico" class="form-control" rows="2" style="resize: vertical; "><?php echo $candidato->get_hipotese_diagnostico(); ?></textarea>

                        Responsável*

                            <input type="text" name="nome_responsavel" class="form-control" value="<?php echo $candidato->get_nome_responsavel(); ?>" required>

                        Parentesco*

                            <input type="text" name="parentesco_resp" class="form-control" value="<?php echo $candidato->get_parentesco_resp(); ?>" required>

                        Telefone*

                            <input type="tel" name="telefone" class="form-control" value="<?php echo $candidato->get_telefone(); ?>" required>

                        Celular*

                            <input type="tel" name="celular" class="form-control" value="<?php echo $candidato->get_celular(); ?>" required>

                        Endereço*

                            <input type="text" name="endereco" class="form-control" value="<?php echo $candidato->get_endereco(); ?>" required>

                        Queixa Principal*

                            <input type="text" name="queixa_principal" class="form-control" value="<?php echo $candidato->get_queixa_principal(); ?>" required>

                        Defict Funcional

                            <input type="text" name="deficit_funcional" class="form-control" value="<?php echo $candidato->get_deficit_funcional(); ?>">

                        Solicitação de acompanhamento de FT Motora - Médico(a) Resonsável

                            <input type="text" name="medico_resp" class="form-control" value="<?php echo $candidato->get_medico_resp(); ?>">

                        Hospital de procedência

                            <input type="text" name="hospital_procedencia" class="form-control" value="<?php echo $candidato->get_hospital_procedencia(); ?>">

                        Tratamento prévios / cirurgias

                            <textarea name="tratamento_previo" class="form-control" rows="2" style="resize: vertical; "><?php echo $candidato->get_tratamento_previo(); ?></textarea>

                        ADNPM

                            <select class="form-control" name="adnpm">
                                <?php echo paciente_opcoes( $candidato->pegarOpcoesParaCamposDoPaciente('adnpm'), $candidato->get_adnpm() ); ?>
                            </select>

                        ADNPM Motivo

                            <input type="text" name="adnpm_motivo" class="form-control" value="<?php echo $candidato->get_adnpm_motivo(); ?>">

                        Síndrome de Down

                            <select class="form-control" name="sindrome_de_down">
                                <?php echo paciente_opcoes( $candidato->pegarOpcoesParaCamposDoPaciente('sindrome_de_down'), $candidato->get_sindrome_de_down() ); ?>
                            </select>

                        Mielomeningocele

                            <select class="form-control" name="mielo">
                                <?php echo paciente_opcoes( $candidato->pegarOpcoesParaCamposDoPaciente('mielo'), $candidato->get_mielo() ); ?>
                            </select>

                        Paralisia Braquial Congênita

                            <select class="form-control" name="paralisia_braquial">
                                <?php echo paciente_opcoes( $candidato->pegarOpcoesParaCamposDoPaciente('paralisia_braquial'), $candidato->get_paralisia_braquial() ); ?>
                            </select>

                        Outras Síndromes

                            <input type="text" name="outras_sindromes" class="form-control" value="<?php echo $candidato->get_outras_sindromes(); ?>">

                        Encefalopatia Crônica infantil não Progressiva

                            <select class="form-control" name="encefalopatia">
                                <?php echo paciente_opcoes( $candidato->pegarOpcoesParaCamposDoPaciente('encefalopatia'), $candidato->get_encefalopatia() ); ?>
                            </select>

                        Classificação Topográfica

                            <select class="form-control" name="class_topografia">
                                <?php echo paciente_opcoes( $candidato->pegarOpcoesParaCamposDoPaciente('class_topografia'), $candidato->get_class_topografia() ); ?>
                            </select>

                        Classificação clínica

                            <input type="text" name="class_clinica" class="form-control" value="<?php echo $candidato->get_class_clinica(); ?>">

                        Nivel

                            <select class="form-control" name="nivel">
                                <?php echo paciente_opcoes( $candidato->pegarOpcoesParaCamposDoPaciente('nivel'), $candidato->get_nivel() ); ?>
                            </select>

                        GMFCS nivel

                            <input type="text" name="gmfcs_nivel" class="form-control" value="<?php echo $candidato->get_gmfcs_nivel(); ?>">

                        CID<i class="fa fa-question-circle" style="cursor: pointer; font-size: 16px; margin-left: 5px; color: #646F80;" aria-hidden="true" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="<?= erro_msg(87); ?>">

                        	<input type="text" id="cid_search" name="cid" class="form-control" placeholder="Procure por um CID ou por uma descrição do CID" value="<?php echo $candidato->get_cid(); ?>">

                        História da Moléstia Atual/Pregressa: Intercorrência

                            <select class="form-control" name="historia_molestia">
                                <?php echo paciente_opcoes( $candidato->pegarOpcoesParaCamposDoPaciente('historia_molestia'), $candidato->get_historia_molestia() ); ?>
                            </select>

                        Observações

                            <textarea name="historia_molestia_obs" class="form-control" rows="10" style="resize: vertical; "><?php echo $candidato->get_historia_molestia_obs(); ?></textarea>

                        Patologias ou distúrbios associados

                            <textarea name="patol_disturbio_assoc" class="form-control" rows="5" style="resize: vertical; "><?php echo $candidato->get_patol_disturbio_assoc(); ?></textarea>

                        Medicamentos em uso / Motivo

                            <textarea name="medicamento_uso" class="form-control" rows="5" style="resize: vertical; "><?php echo $candidato->get_medicamento_uso(); ?></textarea>

                        Exames complementares

                            <textarea name="exames_complementares" class="form-control" rows="5" style="resize: vertical; "><?php echo $candidato->get_exames_complementares(); ?></textarea>

                        Órteses/Próteses e Adaptações

                            <textarea name="orteses_proteses_adaptacoes" class="form-control" rows="5" style="resize: vertical; "><?php echo $candidato->get_orteses_proteses_adaptacoes(); ?></textarea>

                        Características Sindrômicas

                            <textarea name="caracteristicas_sindromicas" class="form-control" rows="5" style="resize: vertical; "><?php echo $candidato->get_caracteristicas_sindromicas(); ?></textarea>

        </form>

<?php $this->load->view('fixos/rodape'); ?>


text:
package org.sterl;

import org.junit.Test;
import org.sterl.performancetest.TestRunner;

public class JunitRunner {

    @Test
    public void test() throws Exception {
        System.out.println(new TestRunner().runTests());
    }

}

redpajama_set_name: RedPajamaGithub


text:
//// [commentsClass.ts]

/** This is class c2 without constuctor*/
class c2 {
} // trailing comment1
var i2 = new c2();
var i2_c = c2;
class c3 {
    /** Constructor comment*/
    constructor() {
    } // trailing comment of constructor
} /* trailing comment 2 */
var i3 = new c3();
var i3_c = c3;
/** Class comment*/
class c4 {
    /** Constructor comment*/
    constructor() {
    } /* trailing comment of constructor 2*/
}
var i4 = new c4();
var i4_c = c4;
/** Class with statics*/
class c5 {
    static s1: number;
}
var i5 = new c5();
var i5_c = c5;

/// class with statics and constructor
class c6 { /// class with statics and constructor2
    /// s1 comment
    static s1: number; /// s1 comment2
    /// constructor comment
    constructor() { /// constructor comment2
    }
}
var i6 = new c6();
var i6_c = c6;

// class with statics and constructor
class c7 {
    // s1 comment
    static s1: number;
    // constructor comment
    constructor() {
    }
}
var i7 = new c7();
var i7_c = c7;

/** class with statics and constructor
 */
class c8 {
    /** s1 comment */
    static s1: number; /** s1 comment2 */
    /** constructor comment
    */
    constructor() {
        /** constructor comment2
        */
    }
}
var i8 = new c8();
var i8_c = c8;

class c9 {
    constructor() {
        /// This is some detached comment

        // should emit this leading comment of } too
    }
}

//// [commentsClass.js]
/** This is class c2 without constuctor*/
var c2 = (function () {
    function c2() {
    }
    return c2;
})(); // trailing comment1
var i2 = new c2();
var i2_c = c2;
var c3 = (function () {
    /** Constructor comment*/
    function c3() {
    } // trailing comment of constructor
    return c3;
})(); /* trailing comment 2 */
var i3 = new c3();
var i3_c = c3;
/** Class comment*/
var c4 = (function () {
    /** Constructor comment*/
    function c4() {
    } /* trailing comment of constructor 2*/
    return c4;
})();
var i4 = new c4();
var i4_c = c4;
/** Class with statics*/
var c5 = (function () {
    function c5() {
    }
    return c5;
})();
var i5 = new c5();
var i5_c = c5;
/// class with statics and constructor
var c6 = (function () {
    /// constructor comment
    function c6() {
    }
    return c6;
})();
var i6 = new c6();
var i6_c = c6;
// class with statics and constructor
var c7 = (function () {
    // constructor comment
    function c7() {
    }
    return c7;
})();
var i7 = new c7();
var i7_c = c7;
/** class with statics and constructor
 */
var c8 = (function () {
    /** constructor comment
    */
    function c8() {
        /** constructor comment2
        */
    }
    return c8;
})();
var i8 = new c8();
var i8_c = c8;
var c9 = (function () {
    function c9() {
        /// This is some detached comment
        // should emit this leading comment of } too
    }
    return c9;
})();

//// [commentsClass.d.ts]
/** This is class c2 without constuctor*/
declare class c2 {
}
declare var i2: c2;
declare var i2_c: typeof c2;
declare class c3 {
    /** Constructor comment*/
    constructor();
}
declare var i3: c3;
declare var i3_c: typeof c3;
/** Class comment*/
declare class c4 {
    /** Constructor comment*/
    constructor();
}
declare var i4: c4;
declare var i4_c: typeof c4;
/** Class with statics*/
declare class c5 {
    static s1: number;
}
declare var i5: c5;
declare var i5_c: typeof c5;
declare class c6 {
    static s1: number;
    constructor();
}
declare var i6: c6;
declare var i6_c: typeof c6;
declare class c7 {
    static s1: number;
    constructor();
}
declare var i7: c7;
declare var i7_c: typeof c7;
/** class with statics and constructor
 */
declare class c8 {
    /** s1 comment */
    static s1: number;
    /** constructor comment
    */
    constructor();
}
declare var i8: c8;
declare var i8_c: typeof c8;
declare class c9 {
    constructor();
}


text:
time_in_words
=============

Describe Periods of Time in Words


text:
package org.thriftee.core.restlet;

import org.w3c.dom.Node;

public interface DomSerializable {

  public <T extends Node> T writeToDom(T node);

}


text:
import Ember from "ember";
const { computed, Component } = Ember;
const { readOnly, sort } = computed;

export default Component.extend({
  /**
   * mixinDetails controller passed through the template
   *
   * @property mixinDetails
   * @type {Ember.Controller}
   */
  mixinDetails: null,

  objectId: readOnly('mixinDetails.model.objectId'),

  isExpanded: computed('model.expand', 'model.properties.length', function() {
    return this.get('model.expand') && this.get('model.properties.length') > 0;
  }),

  /**
   * Used by the `sort` computed macro.
   *
   * @property sortProperties
   * @type {Array<String>}
   */
  sortProperties: ['name'],

  /**
   * Sort the properties by name to make them easier to find in the object inspector.
   *
   * @property sortedProperties
   * @type {Array<Object>}
   */
  sortedProperties: sort('model.properties', 'sortProperties'),

  actions: {
    calculate({ name }) {
      let objectId = this.get('objectId');
      let mixinIndex = this.get('mixinDetails.model.mixins').indexOf(this.get('model'));

      this.get('port').send('objectInspector:calculate', {
        objectId,
        mixinIndex,
        property: name
      });
    },

    sendToConsole({ name }) {
      let objectId = this.get('objectId');

      this.get('port').send('objectInspector:sendToConsole', {
        objectId,
        property: name
      });
    },

    toggleExpanded() {
      this.toggleProperty('isExpanded');
    },

    digDeeper({ name }) {
      let objectId = this.get('objectId');

      this.get('port').send('objectInspector:digDeeper', {
        objectId,
        property: name
      });
    },

    saveProperty(property, value, dataType) {
      let mixinIndex = this.get('mixinDetails.model.mixins').indexOf(this.get('model'));

      this.get('port').send('objectInspector:saveProperty', {
        objectId: this.get('objectId'),
        property,
        value,
        mixinIndex,
        dataType
      });
    }
  }
});


text:
/**
 * CaGridiSalmonServiceAddressing.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.2RC2 Apr 28, 2006 (12:42:00 EDT) WSDL2Java emitter.
 */

package org.cagrid.CaGridiSalmon.stubs.service;

public interface CaGridiSalmonServiceAddressing extends org.cagrid.CaGridiSalmon.stubs.service.CaGridiSalmonService {
    public org.cagrid.CaGridiSalmon.stubs.CaGridiSalmonPortType getCaGridiSalmonPortTypePort(org.apache.axis.message.addressing.EndpointReferenceType reference) throws javax.xml.rpc.ServiceException;

}


text:
var test = require("tape");
var Cookies = require("js-cookie");
var fauxJax = require("faux-jax");

const before = test;

before('before', (t) => {
  ahoy.reset();
  Cookies.set('ahoy_track', true);

  t.end();
})

test('Defines ahoy', (t) => {
  t.plan(1);

  t.notEqual(window.ahoy, undefined, 'Ahoy should be globally available');
});

test('Initialization and visit creation', (t) => {
  t.plan(8);

  t.notEqual(Cookies.get('ahoy_track'), undefined, 'Should have ahoy_track cookie');
  t.equal(Cookies.get('ahoy_visit'), undefined, 'Should not have ahoy_visit cookie');
  t.equal(Cookies.get('ahoy_visitor'), undefined, 'Should not have ahoy_visitor cookie');

  fauxJax.install();
  fauxJax.once('request', function(request) {
    t.equal(request.requestMethod, 'POST', 'Should use POST method');
    t.equal(request.requestURL, '/ahoy/visits', 'Should POST to correct URL');
    t.equal(request.requestHeaders['X-CSRF-Token'],
            'test-token-abcdef123456',
            'Should set CSRF header');

    request.respond(200, { 'Content-Type': 'application/json' }, '{}');
    fauxJax.restore();
  });

  ahoy.start();

  t.notEqual(Cookies.get('ahoy_visit'), undefined, 'Should have ahoy_visit cookie');
  t.notEqual(Cookies.get('ahoy_visitor'), undefined, 'Should have ahoy_visitor cookie');
});

test('Ready callback', (t) => {
  t.plan(1);

  fauxJax.install();
  fauxJax.once('request', function(request) {
    request.respond(200, { 'Content-Type': 'application/json' }, '{}');
    fauxJax.restore();
  });

  let value = false;
  ahoy.ready(() => {
    value = true;
    t.equal(value, true, 'Value should be true');
  });

  ahoy.start();
});

test('Manual tracking', (t) => {
  t.plan(5);

  fauxJax.install();
  fauxJax.once('request', function(request) {
    const event = JSON.parse(request.requestBody).events[0];

    t.equal(request.requestMethod, 'POST', 'Should use POST method');
    t.equal(request.requestURL, '/ahoy/events', 'Should POST to correct URL');
    t.equal(request.requestHeaders['X-CSRF-Token'],
            'test-token-abcdef123456',
            'Should set CSRF header');
    t.equal(event.name, 'Test Request', 'Should set event name property');
    t.deepEqual(event.properties, { foo: 'bar' }, 'Should set event properties property');

    request.respond(200, {}, '{}');
    fauxJax.restore();
  });

  ahoy.track('Test Request', { foo: 'bar' });
});

test('View tracking', (t) => {
  t.plan(3);

  fauxJax.install();
  fauxJax.once('request', function(request) {
    const event = JSON.parse(request.requestBody).events[0];
    console.log(event);

    t.equal(request.requestMethod, 'POST', 'Should use POST method');
    t.equal(request.requestURL, '/ahoy/events', 'Should POST to correct URL');
    t.equal(event.name, '$view', 'Should set event name property');

    request.respond(200, {}, '{}');
    fauxJax.restore();
  });

  ahoy.trackView();
});

test('Click tracking', (t) => {
  t.plan(6);

  fauxJax.install();
  fauxJax.once('request', function(request) {
    const event = JSON.parse(request.requestBody).events[0];
    const properties = event.properties

    t.equal(request.requestMethod, 'POST', 'Should use POST method');
    t.equal(request.requestURL, '/ahoy/events', 'Should POST to correct URL');
    t.equal(event.name, '$click', 'Should set event name property');
    t.equal(properties.id, 'ahoy-test-link', 'Should set event id property');
    t.equal(properties.section, 'Header', 'Should set event section property');
    t.equal(properties.text, 'Home', 'Should set event text property');

    request.respond(200, {}, '{}');
    fauxJax.restore();
  });

  ahoy.trackClicks();
  document.getElementById('ahoy-test-link').click();
});


text:
sudo apt-get update -y
sudo apt-get install -y git nodejs npm

# Clone and build source.
git clone https://github.com/github/fetch.git
cd fetch
sudo npm install
# Disabling tests, as it's trying to launch the chrome browser which is not supported on power.
# sudo npm test


text:
package jp.azw.kancolleague;

import java.util.Optional;

import org.eclipse.jetty.client.api.ProxyConfiguration;
import org.eclipse.jetty.proxy.ConnectHandler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

public class Context{
	private Server server;
	private int port;
	private KCProxyServlet servlet;
	private ServerConnector connector;
	private KCDataReceiver dataReceiver = KCDataReceiver.instance();
	private Optional<ProxyConfiguration> proxyConfiguration = Optional.empty();
	private boolean allAccess = false;

	private Context () {

	}

	private Context create() {
		connector = new ServerConnector(server = new Server());
		connector.setPort(port);
		server.addConnector(connector);

		HandlerCollection handlers = new HandlerCollection();
		server.setHandler(handlers);

		// proxy servlet
		ServletContextHandler context = new ServletContextHandler(handlers, "/", ServletContextHandler.SESSIONS);
		context.addServlet(new ServletHolder(servlet = KCProxyServlet.instance(dataReceiver)), "/*");

		// proxy handler (CONNECT method)
		// for HTTPS
		handlers.addHandler(new ConnectHandler());

		return this;
	}

	public Context start() throws Exception {
		if (server == null) {
			create();
		}

		server.start();

		return this;
	}

	public Context stop() throws Exception {
		if (server != null) {
			server.stop();
			server.join();
			server = null;
		}

		return this;
	}

	/**
	 * インターネット側 (艦これ側) のプロキシを設定する。解除するときは  {@link #unsetProxy()} で。
	 * {@link start()} またち {@link restart()} するまで変更は適用されない。
	 *
	 * @param host null か 空 ("") の場合は "localhost"
	 * @param port
	 * @return このインスタンス自身
	 */
	public Context setProxy(String host, int port) {
		if (host == null || host.isEmpty()) {
			host = "localhost";
		}
		proxyConfiguration = Optional.of(new ProxyConfiguration(host, port));
		return refleshServletSetting();
	}

	/**
	 * インターネット側 (艦これ側) のプロキシを解除する。
	 * {@link start()} またち {@link restart()} するまで変更は適用されない。
	 *
	 * @return
	 */
	public Context unsetProxy() {
		proxyConfiguration = Optional.empty();
		return refleshServletSetting();
	}

	/**
	 * 受信側 (ローカル側、ブラウザ側) のポート番号をセットする。
	 * {@link start()} またち {@link restart()} するまで変更は適用されない。
	 *
	 * @return このインスタンス自身
	 * @return
	 */
	public Context setPort(int port) {
		this.port = port;
		if (connector != null) {
			connector.setPort(port);
		}
		return this;
	}

	/**
	 * {@link #stop()} してから {@link start()} する。
	 *
	 * @return このインスタンス自身
	 * @throws Exception
	 */
	public Context restart() throws Exception {
		return stop().start();
	}

	public int getPort() {
		return port;
	}

	public KCDataReceiver getDataReceiver() {
		return dataReceiver;
	}

	public static Context instance(int port) {
		return new Context().setPort(port).create();
	}

	private Context refleshServletSetting() {
		if (servlet != null) {
			servlet.setDataReceiver(dataReceiver).setProxy(proxyConfiguration).setAllAccess(allAccess);
			try {
				stop().create().start();
			} catch (Exception e) {
			}
		}
		return this;
	}
}


text:
import unittest

from cachetools import MRUCache

from . import CacheTestMixin

class MRUCacheTest(unittest.TestCase, CacheTestMixin):

    Cache = MRUCache

    def test_evict__writes_only(self):
        cache = MRUCache(maxsize=2)

        cache[1] = 1
        cache[2] = 2
        cache[3] = 3  # Evicts 1 because nothing's been used yet

        assert len(cache) == 2
        assert 1 not in cache, "Wrong key was evicted. Should have been '1'."
        assert 2 in cache
        assert 3 in cache

    def test_evict__with_access(self):
        cache = MRUCache(maxsize=2)

        cache[1] = 1
        cache[2] = 2
        cache[1]
        cache[2]
        cache[3] = 3  # Evicts 2
        assert 2 not in cache, "Wrong key was evicted. Should have been '2'."
        assert 1 in cache
        assert 3 in cache

    def test_evict__with_delete(self):
        cache = MRUCache(maxsize=2)

        cache[1] = 1
        cache[2] = 2
        del cache[2]
        cache[3] = 3  # Doesn't evict anything because we just deleted 2

        assert 2 not in cache
        assert 1 in cache

        cache[4] = 4  # Should evict 1 as we just accessed it with __contains__
        assert 1 not in cache
        assert 3 in cache
        assert 4 in cache


text:
<?php

namespace FrontBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Usuaris
 *
 * @ORM\Table(name="usuaris")
 * @ORM\Entity
 */
class Usuaris implements UserInterface
{
    /**
     * @var string
     *
     * @ORM\Column(name="user", type="string", length=255, nullable=false)
     */
    private $user;

    /**
     *@Assert\NotBlank()
     *@Assert\Length(max=4096)
     */
    private $plainpassword;

    /**
     * @var string
     *
     * @ORM\Column(name="password", type="string", length=255, nullable=false)
     */
    private $password;

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * Set user
     *
     * @param string $user
     *
     * @return Usuaris
     */
    public function setUser($user)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * Get user
     *
     * @return string
     */
    public function getUser()
    {
        return $this->user;
    }

    /**
     * Set password
     *
     * @param string $password
     *
     * @return Usuaris
     */
    public function setPassword($password)
    {
        $this->password = $password;

        return $this;
    }

    /**
     * Get password
     *
     * @return string
     */
    public function getPassword()
    {
        return $this->password;
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }
    /**
     * @var string
     */
    private $roles;

    /**
     * Set roles
     *
     * @param string $roles
     *
     * @return Usuaris
     */
    public function setRoles($roles)
    {
        $this->roles = $roles;

        return $this;
    }

    /**
     * Get roles
     *
     * @return string
     */
    public function getRoles()
    {
        return $this->roles;
    }

    public function getSalt()
    {
        //The bcrypt algorithm doesn't require a separate salt.
        //You *may* need a real salt if you choose a different encoder.
        return null;
    }

    public function getRoles()
    {
        return array('ROLE_ADMIN');
    }

    public function eraseCredentials()
    {
        return null;
    }
}


text:
package net.ripe.db.whois.api.acl;

import net.ripe.db.whois.api.AbstractRestClientTest;
import net.ripe.db.whois.api.httpserver.Audience;
import net.ripe.db.whois.common.IntegrationTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import javax.ws.rs.BadRequestException;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import java.util.List;

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

@Category(IntegrationTest.class)
public class AclMirrorServiceTestIntegration extends AbstractRestClientTest {
    private static final Audience AUDIENCE = Audience.INTERNAL;
    private static final String MIRRORS_PATH = "api/acl/mirrors";

    @Before
    public void setUp() throws Exception {
        databaseHelper.insertAclMirror("0/0");
        databaseHelper.insertAclMirror("10.0.0.2/32");
        databaseHelper.insertAclMirror("::0/0");
        databaseHelper.insertApiKey("DB-WHOIS-testapikey", "/api/acl", "acl api key");
        setApiKey("DB-WHOIS-testapikey");
    }

    @Test
    public void mirrors() {
        databaseHelper.insertAclMirror("10.0.0.0/32");
        databaseHelper.insertAclMirror("10.0.0.1/32");

        List<Mirror> mirrors = getMirrors();

        assertThat(mirrors, hasSize(5));
    }

    @Test
    public void getMirror_non_existing() {
        try {
            createResource(AUDIENCE, MIRRORS_PATH, "10.0.0.0/32")
                    .request(MediaType.APPLICATION_JSON)
                    .get(Mirror.class);
        } catch (NotFoundException ignored) {
            // expected
        }
    }

    @Test
    public void getMirror_existing() {
        databaseHelper.insertAclMirror("10.0.0.0/32");

        Mirror mirror = createResource(AUDIENCE, MIRRORS_PATH, "10.0.0.0/32")
                .request(MediaType.APPLICATION_JSON)
                .get(Mirror.class);

        assertThat(mirror.getPrefix(), is("10.0.0.0/32"));
    }

    @Test
    public void getMirror_invalid() {
        try {
            createResource(AUDIENCE, MIRRORS_PATH, "10")
                    .request(MediaType.APPLICATION_JSON)
                    .get(Mirror.class);
        } catch (BadRequestException e) {
            assertThat(e.getResponse().readEntity(String.class), is("'10' is not an IP string literal."));
        }
    }

    @Test
    public void createMirror() {
        Mirror mirror = createResource(AUDIENCE, MIRRORS_PATH)
                .request(MediaType.APPLICATION_JSON)
                .post(Entity.entity(new Mirror("10.0.0.0/32", "comment"), MediaType.APPLICATION_JSON), Mirror.class);

        assertThat(mirror.getPrefix(), is("10.0.0.0/32"));
        assertThat(mirror.getComment(), is("comment"));

        List<Mirror> mirrors = getMirrors();
        assertThat(mirrors, hasSize(4));
    }

    @Test
    public void createMirror_invalid() {
        try {
            createResource(AUDIENCE, MIRRORS_PATH)
                    .request(MediaType.APPLICATION_JSON)
                    .post(Entity.entity(new Mirror("10", "comment"), MediaType.APPLICATION_JSON));

        } catch (Exception e) {
            System.out.println(e.getClass());
//            assertThat(e.getResponse().readEntity(String.class), is("'10' is not an IP string literal."));
        }
    }

    @Test
    public void updateMirror() {
        Mirror mirror = createResource(AUDIENCE, MIRRORS_PATH)
                .request(MediaType.APPLICATION_JSON_TYPE)
                .post(Entity.entity(new Mirror("10.0.0.2/32", "changed comment"), MediaType.APPLICATION_JSON), Mirror.class);

        assertThat(mirror.getPrefix(), is("10.0.0.2/32"));
        assertThat(mirror.getComment(), is("changed comment"));
        assertThat(getMirrors(), hasSize(3));
    }

    @Test
    public void deleteMirror() throws Exception {
        final Mirror mirror = createResource(AUDIENCE, MIRRORS_PATH, "10.0.0.2/32")
                .request(MediaType.APPLICATION_JSON_TYPE)
                .delete(Mirror.class);

        assertThat(mirror.getPrefix(), is("10.0.0.2/32"));
        assertThat(getMirrors(), hasSize(2));

    }

    @SuppressWarnings("unchecked")
    private List<Mirror> getMirrors() {
        return createResource(AUDIENCE, MIRRORS_PATH)
                .request(MediaType.APPLICATION_JSON_TYPE)
                .get(new GenericType<List<Mirror>>() {});
    }
}


text:
module Ziya::Charts
  class Line < Base
    def initialize( license=nil, title=nil, chart_id=nil)
      super( license, title, chart_id )
      @type = "line"
    end
  end
end


text:
export default function srtTimecodeParser(aupTimecode){
  const shifts = 1000;
  const roundToMillisecond = (Math.round( parseFloat(aupTimecode) * shifts) / shifts).toFixed(3);

  const decimalPart = Math.floor(aupTimecode);
  const fractionalPart = parseInt(roundToMillisecond.toString().split(".")[1]);

  const HHMMSS = secondToHHMMSS(decimalPart);
  let millisecond = '';
  if(fractionalPart<100 && fractionalPart>=10){
    millisecond = '0'+fractionalPart.toString();
  }else if(fractionalPart<10){
    millisecond = '00'+fractionalPart.toString();
  }else {
    millisecond = fractionalPart.toString();
  }

  return HHMMSS+','+ millisecond;
}

/**credits to powtac
* http://stackoverflow.com/questions/6312993/javascript-seconds-to-time-string-with-format-hhmmss
*/
function secondToHHMMSS(second){
  let hours = Math.floor(second / 3600);
  let minutes = Math.floor((second - (hours * 3600)) / 60);
  let seconds = second - (hours * 3600) - (minutes * 60);
  if (hours   < 10) { hours = "0" + hours; }
  if (minutes < 10) { minutes = "0" + minutes; }
  if (seconds < 10) { seconds = "0" + seconds; }
  return hours+':'+minutes+':'+seconds;
}


text:
Calendar._DN = new Array
("Nedjelja",
 "Ponedjeljak",
 "Utorak",
 "Srijeda",
 "Cetvrtak",
 "Petak",
 "Subota",
 "Nedjelja");

// Please note that the following array of short day names (and the same goes
// for short month names, _SMN) isn't absolutely necessary.  We give it here
// for exemplification on how one can customize the short day names, but if
// they are simply the first N letters of the full name you can simply say:
//
//   Calendar._SDN_len = N; // short day name length
//   Calendar._SMN_len = N; // short month name length
//
// If N = 3 then this is not needed either since we assume a value of 3 if not
// present, to be compatible with translation files that were written before
// this feature.

// short day names
Calendar._SDN = new Array
("Ned",
 "Pon",
 "Uto",
 "Sri",
 "Cet",
 "Pet",
 "Sub",
 "Ned");

// First day of the week. "0" means display Sunday first, "1" means display
// Monday first, etc.
Calendar._FD = 0;

// full month names
Calendar._MN = new Array
("Sijecanj",
 "Veljaca",
 "Ožujak",
 "Travanj",
 "Svibanj",
 "Lipanj",
 "Srpanj",
 "Kolovoz",
 "Rujan",
 "Listopad",
 "Studeni",
 "Prosinac");

// short month names
Calendar._SMN = new Array
("Sij",
 "Velj",
 "Ožu",
 "Tra",
 "Svi",
 "Lip",
 "Srp",
 "Kol",
 "Ruj",
 "List",
 "Stu",
 "Pro");

// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "About the calendar";

Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" + // don't translate this this ;-)
"For latest version visit: http://www.dynarch.com/projects/calendar/\n" +
"Distributed under GNU LGPL.  See http://gnu.org/licenses/lgpl.html for details." +
"\n\n" +
"Date selection:\n" +
"- Use the \xab, \xbb buttons to select year\n" +
"- Use the " + String.fromCharCode(0x2039) + ", " + String.fromCharCode(0x203a) + " buttons to select month\n" +
"- Hold mouse button on any of the above buttons for faster selection.";
Calendar._TT["ABOUT_TIME"] = "\n\n" +
"Time selection:\n" +
"- Click on any of the time parts to increase it\n" +
"- or Shift-click to decrease it\n" +
"- or click and drag for faster selection.";

Calendar._TT["PREV_YEAR"] = "Prethodna godina (hold for menu)";
Calendar._TT["PREV_MONTH"] = "Prethodni mjesec (hold for menu)";
Calendar._TT["GO_TODAY"] = "Na današnji dan";
Calendar._TT["NEXT_MONTH"] = "Naredni mjesec (hold for menu)";
Calendar._TT["NEXT_YEAR"] = "Naredna godina (hold for menu)";
Calendar._TT["SEL_DATE"] = "Odaberite datum";
Calendar._TT["DRAG_TO_MOVE"] = "Drag to move";
Calendar._TT["PART_TODAY"] = " (Danas)";

// the following is to inform that "%s" is to be the first day of week
// %s will be replaced with the day name.
Calendar._TT["DAY_FIRST"] = "Prikaži %s prvo";

// This may be locale-dependent.  It specifies the week-end days, as an array
// of comma-separated numbers.  The numbers are from 0 to 6: 0 means Sunday, 1
// means Monday, etc.
Calendar._TT["WEEKEND"] = "0,6";

Calendar._TT["CLOSE"] = "Zatvori";
Calendar._TT["TODAY"] = "Danas";
Calendar._TT["TIME_PART"] = "(Shift-)Click or drag to change value";

// date formats
Calendar._TT["DEF_DATE_FORMAT"] = "%Y-%m-%d";
Calendar._TT["TT_DATE_FORMAT"] = "%a, %b %e";

Calendar._TT["WK"] = "wk";
Calendar._TT["TIME"] = "Vrijeme:";


text:
require "spec_helper"

describe PostsController do
  it "exists! (and RSpec works)" do
    # nop
  end
end


text:
//*********************************License***************************************
//===============================================================================
//The MIT License (MIT)

//Copyright (c) 2014 FRC_Scouting_V2

//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:

//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.

//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//SOFTWARE.
//===============================================================================

using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;

namespace UsefulSnippets
{
    /// <summary>
    ///     Methods to inact security measures
    /// </summary>
    public class Security
    {
        /// <summary>
        ///     Encrypts a string with AES256 encryption
        /// </summary>
        /// <param name="plainText"></param>
        /// <returns></returns>
        public static string EncryptString(string plainText)
        {
            string encryptedText;
            const string key = ("abcdefghijklmnopqrstuvwxyz123456");
            const string IV = ("1234567890123456");
            byte[] plainTextBytes = Encoding.ASCII.GetBytes(plainText);
            var aes = new AesCryptoServiceProvider
            {
                BlockSize = 128,
                KeySize = 256,
                Key = Encoding.ASCII.GetBytes(key),
                IV = Encoding.ASCII.GetBytes(IV),
                Padding = PaddingMode.PKCS7,
                Mode = CipherMode.CBC
            };
            ICryptoTransform crypto = aes.CreateEncryptor(aes.Key, aes.IV);
            byte[] encrypted = crypto.TransformFinalBlock(plainTextBytes, 0, plainTextBytes.Length);
            encryptedText = Convert.ToBase64String(encrypted);
            return encryptedText;
        }

        /// <summary>
        ///     Decrypts a cipher-text that has been encrypted with AES256 Encryption
        /// </summary>
        /// <param name="encryptedText"></param>
        /// <returns></returns>
        public static string DeCryptString(string encryptedText)
        {
            string plainText;
            const string key = ("abcdefghijklmnopqrstuvwxyz123456");
            const string IV = ("1234567890123456");
            byte[] encryptedBytes = Convert.FromBase64String(encryptedText);
            var aes = new AesCryptoServiceProvider
            {
                BlockSize = 128,
                KeySize = 256,
                Key = Encoding.ASCII.GetBytes(key),
                IV = Encoding.ASCII.GetBytes(IV),
                Padding = PaddingMode.PKCS7,
                Mode = CipherMode.CBC
            };
            ICryptoTransform crypto = aes.CreateDecryptor(aes.Key, aes.IV);
            byte[] plainTextBytes = crypto.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
            plainText = Encoding.ASCII.GetString(plainTextBytes);
            return plainText;
        }

        /// <summary>
        ///     Returns a pseudo random number between a range
        /// </summary>
        /// <param name="startingNum"></param>
        /// <param name="endingNum"></param>
        /// <returns></returns>
        public static int GetSecureRandomNum(int startingNum, int endingNum)
        {
            int difference = endingNum - startingNum;
            var bytes = new byte[16];
            var r = new RNGCryptoServiceProvider();

            r.GetBytes(bytes);
            int number = (int) ((decimal) bytes[0]/256*difference) + startingNum;

            return number;
        }

        /// <summary>
        ///     Returns a random password based on the password type selected and the password length selected
        /// </summary>
        /// <param name="passwordType"></param>
        /// <param name="passwordLength"></param>
        /// <returns></returns>
        public static string MakeRandomPassword(int passwordType, int passwordLength)
        {
            //Password Types
            //0 - No Type Selected
            //1 - Numbers
            //2 - Letters (Uppercase and Lowercase)
            //3 - Numbers and Letters (Uppercase and Lowercase)
            //4 - All Characters (Numbers, Letters, and Special Characters)

            //Variables
            var gen = new Random();
            string passwordToString = ("");
            char[] numbers = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};
            char[] letters =
            {
                'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
                's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
                'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
            };
            char[] lettersAndNumbers =
            {
                'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
                'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
                'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6',
                '7', '8', '9', '0'
            };
            char[] allCharacters =
            {
                'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
                'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
                'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7',
                '8', '9', '0', '!', '@', '#', '$', '%', '^', '&', '*', '<', '>', '?'
            };
            var passwordList = new List<char>();
            int randomNumber = 0;

            if (passwordType == 0)
            {
                Notifications.ErrorOccured("No password type selected!");
            }
            else
            {
                if (passwordType == 1)
                {
                    for (int i = 0; i < passwordLength; i++)
                    {
                        randomNumber = gen.Next(10);
                        passwordList.Add(numbers[randomNumber]);
                    }
                    passwordToString = string.Join("", passwordList.ToArray());
                }
                else
                {
                    if (passwordType == 2)
                    {
                        for (int i = 0; i < passwordLength; i++)
                        {
                            randomNumber = gen.Next(52);
                            passwordList.Add(letters[randomNumber]);
                        }
                        passwordToString = string.Join("", passwordList.ToArray());
                    }
                    else
                    {
                        if (passwordType == 3)
                        {
                            for (int i = 0; i < passwordLength; i++)
                            {
                                randomNumber = gen.Next(62);
                                passwordList.Add(lettersAndNumbers[randomNumber]);
                            }
                            passwordToString = string.Join("", passwordList.ToArray());
                        }
                        else
                        {
                            if (passwordType == 4)
                            {
                                for (int i = 0; i < passwordLength; i++)
                                {
                                    randomNumber = gen.Next(73);
                                    passwordList.Add(allCharacters[randomNumber]);
                                }
                                passwordToString = string.Join("", passwordList.ToArray());
                            }
                        }
                    }
                }
            }
            return passwordToString;
        }
    }
}


text:
package com.ezextended.registry;

import net.minecraft.block.Block;
import net.minecraft.client.renderer.ItemModelMesher;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

import com.ezextended.ref.RefStrings;

/** Interface to help with block registration */
public interface IRegistryBlock extends IRegistryBase {

	/** Gets the block's item class to use when registering */
	public default Class<? extends ItemBlock> getItemClass() {
		return ItemBlock.class;
	}

	/** Gets additional arguments to pass through to the ItemBlock constructor */
	public default Object[] getItemClassArgs() {
		return new Object[0];
	}

	@Override
	public default String getShorthandName() {
		return ((Block)this).getUnlocalizedName().substring(5);
	}

	@SideOnly(Side.CLIENT)
	@Override
	public default void registerRender(ItemModelMesher mesher) {
		mesher.register(Item.getItemFromBlock((Block)this), 0, new ModelResourceLocation(RefStrings.MODID + ":" + this.getShorthandName(), "inventory"));
	}

}


text:
<!DOCTYPE html>
<meta charset="utf-8">
<title>AnimationTiming Test: multiple calls to requestAnimationFrame with the same callback</title>
<link rel="author" title="Intel" href="http://www.intel.com">
<link rel="help" href="https://html.spec.whatwg.org/multipage/#dom-window-requestanimationframe">


text:
package jetbrains.jetpad.model.property;

import jetbrains.jetpad.model.event.EventHandler;

public class PropertyEventHandlers {
  public static class CountingHandler<ItemT> implements EventHandler<PropertyChangeEvent<ItemT>> {
    private int counter = 0;

    @Override
    public void onEvent(PropertyChangeEvent<ItemT> event) {
      counter += 1;
    }

    public int getCounter() {
      return counter;
    }
  }

  public static class RecordingHandler<ItemT> implements EventHandler<PropertyChangeEvent<ItemT>> {
    private ItemT oldValue, newValue;

    @Override
    public void onEvent(PropertyChangeEvent<ItemT> event) {
      oldValue = event.getOldValue();
      newValue = event.getNewValue();
    }

    public ItemT getOldValue() {
      return oldValue;
    }

    public ItemT getNewValue() {
      return newValue;
    }
  }
}


text:
package edu.northwestern.bioinformatics.studycalendar.osgi.commands;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.felix.shell.Command;

import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Properties;

/**
 * @author Rhett Sutphin
 */
public class SystemPropertyCommand implements Command {
    private SystemPropertyAccessor accessor;

    public SystemPropertyCommand() {
        this(new DefaultAccessor());
    }

    public SystemPropertyCommand(SystemPropertyAccessor accessor) {
        this.accessor = accessor;
    }

    public String getName() {
        return "sysprop";
    }

    public String getUsage() {
        return "sysprop [property.name]";
    }

    public String getShortDescription() {
        return "display the current value for one or all system properties.";
    }

    @SuppressWarnings({ "unchecked" })
    public void execute(String command, PrintStream out, PrintStream err) {
        String[] parts = command.split("\\s+");
        if (parts.length == 1) {
            List<String> propertyNames = new ArrayList<String>((Collection) accessor.getAll().keySet());
            Collections.sort(propertyNames);
            for (String name : propertyNames) {
                printProperty(out, name, accessor.getProperty(name));
            }
        } else {
            String name = parts[1];
            String value = accessor.getProperty(name);

            if (value != null) {
                printProperty(out, name, value);
            } else {
                err.println(String.format("'%s' is not set", name));
            }
        }
    }

    private void printProperty(PrintStream out, String name, String value) {
        out.println(String.format("%s=\"%s\"", name, StringEscapeUtils.escapeJava(value)));
    }

    // This is indirected for testing
    public interface SystemPropertyAccessor {
        String getProperty(String propertyName);
        Properties getAll();
    }

    private static class DefaultAccessor implements SystemPropertyAccessor {
        public String getProperty(String propertyName) {
            return System.getProperty(propertyName);
        }

        public Properties getAll() {
            return System.getProperties();
        }
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mém. Cl. Sci. Math. Inst. Natl. France 12:77, t. 4. 1812

#### Original name
null

### Remarks
null


text:
package com.maddyhome.idea.copyright.language.databinding.psi;

import com.intellij.psi.tree.IElementType;
import com.maddyhome.idea.copyright.language.SimpleLanguage;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

/**
 * Created by mike on 9/6/15.
 */
public class DbTokenType extends IElementType {
  public DbTokenType(@NotNull @NonNls String debugName) {
    super(debugName, SimpleLanguage.INSTANCE);
  }

  @Override
  public String toString() {
    return "DbTokenType." + super.toString();
  }
}


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)

// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.

// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_GEOMETRY_STRATEGIES_SPHERICAL_DISTANCE_CROSS_TRACK_HPP
#define BOOST_GEOMETRY_STRATEGIES_SPHERICAL_DISTANCE_CROSS_TRACK_HPP

#include <boost/config.hpp>
#include <boost/concept_check.hpp>
#include <boost/mpl/if.hpp>
#include <boost/type_traits.hpp>

#include <boost/geometry/core/cs.hpp>
#include <boost/geometry/core/access.hpp>
#include <boost/geometry/core/radian_access.hpp>

#include <boost/geometry/strategies/distance.hpp>
#include <boost/geometry/strategies/concepts/distance_concept.hpp>
#include <boost/geometry/strategies/spherical/distance_haversine.hpp>

#include <boost/geometry/util/promote_floating_point.hpp>
#include <boost/geometry/util/math.hpp>

#ifdef BOOST_GEOMETRY_DEBUG_CROSS_TRACK
#  include <boost/geometry/io/dsv/write.hpp>
#endif

namespace pdalboost {} namespace boost = pdalboost; namespace pdalboost { namespace geometry
{

namespace strategy { namespace distance
{

/*!
\brief Strategy functor for distance point to segment calculation
\ingroup strategies
\details Class which calculates the distance of a point to a segment, for points on a sphere or globe
\see http://williams.best.vwh.net/avform.htm
\tparam CalculationType \tparam_calculation
\tparam Strategy underlying point-point distance strategy, defaults to haversine

\qbk{
[heading See also]
[link geometry.reference.algorithms.distance.distance_3_with_strategy distance (with strategy)]
}

*/
template
<
    typename CalculationType = void,
    typename Strategy = haversine<double, CalculationType>
>
class cross_track
{
public :
    template <typename Point, typename PointOfSegment>
    struct return_type
        : promote_floating_point
          <
              typename select_calculation_type
                  <
                      Point,
                      PointOfSegment,
                      CalculationType
                  >::type
          >
    {};

    inline cross_track()
    {}

    explicit inline cross_track(typename Strategy::radius_type const& r)
        : m_strategy(r)
    {}

    inline cross_track(Strategy const& s)
        : m_strategy(s)
    {}

    // It might be useful in the future
    // to overload constructor with strategy info.
    // crosstrack(...) {}

    template <typename Point, typename PointOfSegment>
    inline typename return_type<Point, PointOfSegment>::type
    apply(Point const& p, PointOfSegment const& sp1, PointOfSegment const& sp2) const
    {

#if !defined(BOOST_MSVC)
        BOOST_CONCEPT_ASSERT
            (
                (concept::PointDistanceStrategy<Strategy, Point, PointOfSegment>)
            );
#endif

        typedef typename return_type<Point, PointOfSegment>::type return_type;

        // http://williams.best.vwh.net/avform.htm#XTE
        return_type d1 = m_strategy.apply(sp1, p);
        return_type d3 = m_strategy.apply(sp1, sp2);

        if (geometry::math::equals(d3, 0.0))
        {
            // "Degenerate" segment, return either d1 or d2
            return d1;
        }

        return_type d2 = m_strategy.apply(sp2, p);

        return_type crs_AD = course(sp1, p);
        return_type crs_AB = course(sp1, sp2);
        return_type crs_BA = crs_AB - geometry::math::pi<return_type>();
        return_type crs_BD = course(sp2, p);
        return_type d_crs1 = crs_AD - crs_AB;
        return_type d_crs2 = crs_BD - crs_BA;

        // d1, d2, d3 are in principle not needed, only the sign matters
        return_type projection1 = cos( d_crs1 ) * d1 / d3;
        return_type projection2 = cos( d_crs2 ) * d2 / d3;

#ifdef BOOST_GEOMETRY_DEBUG_CROSS_TRACK
        std::cout << "Course " << dsv(sp1) << " to " << dsv(p) << " " << crs_AD * geometry::math::r2d << std::endl;
        std::cout << "Course " << dsv(sp1) << " to " << dsv(sp2) << " " << crs_AB * geometry::math::r2d << std::endl;
        std::cout << "Course " << dsv(sp2) << " to " << dsv(p) << " " << crs_BD * geometry::math::r2d << std::endl;
        std::cout << "Projection AD-AB " << projection1 << " : " << d_crs1 * geometry::math::r2d << std::endl;
        std::cout << "Projection BD-BA " << projection2 << " : " << d_crs2 * geometry::math::r2d << std::endl;
#endif

        if(projection1 > 0.0 && projection2 > 0.0)
        {
            return_type XTD = radius() * geometry::math::abs( asin( sin( d1 / radius() ) * sin( d_crs1 ) ));

 #ifdef BOOST_GEOMETRY_DEBUG_CROSS_TRACK
            std::cout << "Projection ON the segment" << std::endl;
            std::cout << "XTD: " << XTD << " d1: " <<  d1  << " d2: " <<  d2  << std::endl;
#endif

            // Return shortest distance, projected point on segment sp1-sp2
            return return_type(XTD);
        }
        else
        {
#ifdef BOOST_GEOMETRY_DEBUG_CROSS_TRACK
            std::cout << "Projection OUTSIDE the segment" << std::endl;
#endif

            // Return shortest distance, project either on point sp1 or sp2
            return return_type( (std::min)( d1 , d2 ) );
        }
    }

    inline typename Strategy::radius_type radius() const
    { return m_strategy.radius(); }

private :

    Strategy m_strategy;

    /// Calculate course (bearing) between two points. Might be moved to a "course formula" ...
    template <typename Point1, typename Point2>
    inline typename return_type<Point1, Point2>::type
    course(Point1 const& p1, Point2 const& p2) const
    {
        typedef typename return_type<Point1, Point2>::type return_type;

        // http://williams.best.vwh.net/avform.htm#Crs
        return_type dlon = get_as_radian<0>(p2) - get_as_radian<0>(p1);
        return_type cos_p2lat = cos(get_as_radian<1>(p2));

        // "An alternative formula, not requiring the pre-computation of d"
        return atan2(sin(dlon) * cos_p2lat,
            cos(get_as_radian<1>(p1)) * sin(get_as_radian<1>(p2))
            - sin(get_as_radian<1>(p1)) * cos_p2lat * cos(dlon));
    }

};

#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS
namespace services
{

template <typename CalculationType, typename Strategy>
struct tag<cross_track<CalculationType, Strategy> >
{
    typedef strategy_tag_distance_point_segment type;
};

template <typename CalculationType, typename Strategy, typename P, typename PS>
struct return_type<cross_track<CalculationType, Strategy>, P, PS>
    : cross_track<CalculationType, Strategy>::template return_type<P, PS>
{};

template <typename CalculationType, typename Strategy>
struct comparable_type<cross_track<CalculationType, Strategy> >
{
    // There is no shortcut, so the strategy itself is its comparable type
    typedef cross_track<CalculationType, Strategy>  type;
};

template
<
    typename CalculationType,
    typename Strategy
>
struct get_comparable<cross_track<CalculationType, Strategy> >
{
    typedef typename comparable_type
        <
            cross_track<CalculationType, Strategy>
        >::type comparable_type;
public :
    static inline comparable_type apply(cross_track<CalculationType, Strategy> const& strategy)
    {
        return comparable_type(strategy.radius());
    }
};

template
<
    typename CalculationType,
    typename Strategy,
    typename P, typename PS
>
struct result_from_distance<cross_track<CalculationType, Strategy>, P, PS>
{
private :
    typedef typename cross_track<CalculationType, Strategy>::template return_type<P, PS> return_type;
public :
    template <typename T>
    static inline return_type apply(cross_track<CalculationType, Strategy> const& , T const& distance)
    {
        return distance;
    }
};

template
<
    typename CalculationType,
    typename Strategy
>
struct strategy_point_point<cross_track<CalculationType, Strategy> >
{
    typedef Strategy type;
};

/*

TODO:  spherical polar coordinate system requires "get_as_radian_equatorial<>"

template <typename Point, typename PointOfSegment, typename Strategy>
struct default_strategy
    <
        segment_tag, Point, PointOfSegment,
        spherical_polar_tag, spherical_polar_tag,
        Strategy
    >
{
    typedef cross_track
        <
            void,
            typename pdalboost::mpl::if_
                <
                    pdalboost::is_void<Strategy>,
                    typename default_strategy
                        <
                            point_tag, Point, PointOfSegment,
                            spherical_polar_tag, spherical_polar_tag
                        >::type,
                    Strategy
                >::type
        > type;
};
*/

template <typename Point, typename PointOfSegment, typename Strategy>
struct default_strategy
    <
        segment_tag, Point, PointOfSegment,
        spherical_equatorial_tag, spherical_equatorial_tag,
        Strategy
    >
{
    typedef cross_track
        <
            void,
            typename pdalboost::mpl::if_
                <
                    pdalboost::is_void<Strategy>,
                    typename default_strategy
                        <
                            point_tag, Point, PointOfSegment,
                            spherical_equatorial_tag, spherical_equatorial_tag
                        >::type,
                    Strategy
                >::type
        > type;
};

} // namespace services
#endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS

}} // namespace strategy::distance

#ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS

#endif

}} // namespace pdalboost::geometry

#endif // BOOST_GEOMETRY_STRATEGIES_SPHERICAL_DISTANCE_CROSS_TRACK_HPP


text:
package com.jaf.examples.redis.redisson.pool;

import static org.assertj.core.api.Assertions.assertThat;

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

import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
import org.redisson.core.RScoredSortedSet;

/**
 * TODO
 *
 * @author liaozhicheng.cn@163.com
 * @date 2016年3月12日
 * @since 1.0
 */
public class SortedSetTypeTests extends RedissonTestBase{

    @Test
    public void testAddAll() {
        RScoredSortedSet<String> set = redisson.getScoredSortedSet("testAddAll");

        Map<String, Double> objects = new HashMap<String, Double>();
        objects.put("1", 0.1);
        objects.put("2", 0.2);
        objects.put("3", 0.3);
        assertThat(set.addAll(objects)).isEqualTo(3);
    }

    @Test
    public void testPollLast() {
        RScoredSortedSet<String> set = redisson.getScoredSortedSet("testPollLast");
        Assert.assertNull(set.pollLast());

        set.add(0.1, "a");
        set.add(0.2, "b");
        set.add(0.3, "c");

        Assert.assertEquals("c", set.pollLast());
        MatcherAssert.assertThat(set, Matchers.contains("a", "b"));
    }

    @Test
    public void testRemoveRangeByScore() {
        RScoredSortedSet<String> set = redisson.getScoredSortedSet("testRemoveRangeByScore");
        set.add(0.1, "a");
        set.add(0.2, "b");
        set.add(0.3, "c");
        set.add(0.4, "d");
        set.add(0.5, "e");
        set.add(0.6, "f");
        set.add(0.7, "g");

        Assert.assertEquals(2, set.removeRangeByScore(0.1, false, 0.3, true));
        MatcherAssert.assertThat(set, Matchers.contains("a", "d", "e", "f", "g"));
    }

}


text:
package in.twizmwaz.cardinal.module.modules.filter.parsers;

import in.twizmwaz.cardinal.module.modules.filter.FilterParser;
import org.jdom2.Element;

public class ClassFilterParser extends FilterParser {

    private String classModule;

    public ClassFilterParser(final Element element) {
        super(element);
        classModule = element.getText();
    }

    public String getClassModule() {
        return classModule;
    }
}


text:
package io.oilfox.backend.api.shared.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Created by ben on 26/01/16.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ApiDocDescription {
    String value();
}


text:
var FriendCollection = Backbone.Collection.extend({
    model: function (attrs, options) {
        return new FriendModel(attrs, options);
    },
    create: function (attrs, options) {
        var friendModel = null,
            self = this;
        if (options && options.wait) {
            friendModel = new this.model(attrs, options);
            if (friendModel && friendModel.isValid()) {
                friendModel.save().done(function () {
                    self.add(friendModel);
                });
            }
        } else {
            return Backbone.Collection.prototype.create.call(this, attrs.options);
        }
    },
    fetch: function (options) {
        var self = this;
        options = options || {};
        var success = options.success || function () {
                return true;
            },
            error = options.error || function () {
                return true;
            };
        DataLayer.getAllFriends().done(function (friends) {
            self.add(friends, {
                validate: true
            });
            success(self.models);
        }).fail(function (message) {
            error(message);
        });
    }
});


text:
package com.github.rjeschke.neetutils.concurrent;

interface RequeueWatcherCallback<A, B>
{
    void requeue(B worker, A job);
}


text:
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_PUBSUBLITE_INTERNAL_SERVICE_H
#define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_PUBSUBLITE_INTERNAL_SERVICE_H

#include "google/cloud/future.h"
#include "google/cloud/status.h"

namespace google {
namespace cloud {
namespace pubsublite_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN

/**
 * A `Service` is anything that can start, run for a while, possibly have other
 * operations invoked on it, possibly with an error, and then can shutdown.
 *
 * Examples include resumable streaming RPCs of different types, and
 * compositions of these streaming RPCs.
 */
class Service {
 protected:
  Service() = default;

 public:
  virtual ~Service() = default;
  Service(Service const&) = delete;
  Service& operator=(Service const&) = delete;
  Service(Service&&) = delete;
  Service& operator=(Service&&) = delete;

  /**
   * Starts the lifecycle of the object.
   *
   * The future returned by this function is satisfied when the object
   * encounters an error during one of its operations or when `Shutdown` is
   * called on it. The value the future is satisfied with details what happened
   * to the object, i.e., `Shutdown` was called, encountered a permanent error,
   * etc.
   *
   * Must be called before any other method and may only be called once.
   *
   * @note The above restriction applies to all additional member functions
   * present in derived classes, if any.
   */
  virtual future<Status> Start() = 0;

  /**
   * This causes the object to reach its shutdown state if not already in it.
   *
   * This will cause any outstanding futures to fail. This may be
   * called while an asynchronous operation of an object of this class is
   * outstanding. Internally, the class will manage waiting on futures of any
   * dependencies. If the class has a present internal outstanding future, this
   * call will satisfy the returned future only after the internal operation(s)
   * finish.
   *
   * Must be called before destroying this object if `Start` was called and may
   * only be called once.
   */
  virtual future<void> Shutdown() = 0;
};

GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace pubsublite_internal
}  // namespace cloud
}  // namespace google

#endif  // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_PUBSUBLITE_INTERNAL_SERVICE_H


text:
namespace base {
namespace internal {

Sequence::Transaction::Transaction(Sequence* sequence)
    : TaskSource::Transaction(sequence) {}

Sequence::Transaction::Transaction(Sequence::Transaction&& other) = default;

Sequence::Transaction::~Transaction() = default;

bool Sequence::Transaction::WillPushTask() const {
  // If the sequence is empty before a Task is inserted into it and the pool is
  // not running any task from this sequence, it should be queued.
  // Otherwise, one of these must be true:
  // - The Sequence is already queued, or,
  // - A thread is running a Task from the Sequence. It is expected to reenqueue
  //   the Sequence once it's done running the Task.
  return sequence()->queue_.empty() && !sequence()->has_worker_;
}

void Sequence::Transaction::PushTask(Task task) {
  // Use CHECK instead of DCHECK to crash earlier. See http://crbug.com/711167
  // for details.
  CHECK(task.task);
  DCHECK(task.queue_time.is_null());

  bool should_be_queued = WillPushTask();
  task.queue_time = TimeTicks::Now();

  task.task = sequence()->traits_.shutdown_behavior() ==
                      TaskShutdownBehavior::BLOCK_SHUTDOWN
                  ? MakeCriticalClosure(task.posted_from.ToString(),
                                        std::move(task.task))
                  : std::move(task.task);

  sequence()->queue_.push(std::move(task));

  // AddRef() matched by manual Release() when the sequence has no more tasks
  // to run (in DidProcessTask() or Clear()).
  if (should_be_queued && sequence()->task_runner())
    sequence()->task_runner()->AddRef();
}

TaskSource::RunStatus Sequence::WillRunTask() {
  // There should never be a second call to WillRunTask() before DidProcessTask
  // since the RunStatus is always marked a saturated.
  DCHECK(!has_worker_);

  // It's ok to access |has_worker_| outside of a Transaction since
  // WillRunTask() is externally synchronized, always called in sequence with
  // TakeTask() and DidProcessTask() and only called if |!queue_.empty()|, which
  // means it won't race with WillPushTask()/PushTask().
  has_worker_ = true;
  return RunStatus::kAllowedSaturated;
}

size_t Sequence::GetRemainingConcurrency() const {
  return 1;
}

Task Sequence::TakeTask(TaskSource::Transaction* transaction) {
  CheckedAutoLockMaybe auto_lock(transaction ? nullptr : &lock_);

  DCHECK(has_worker_);
  DCHECK(!queue_.empty());
  DCHECK(queue_.front().task);

  auto next_task = std::move(queue_.front());
  queue_.pop();
  return next_task;
}

bool Sequence::DidProcessTask(TaskSource::Transaction* transaction) {
  CheckedAutoLockMaybe auto_lock(transaction ? nullptr : &lock_);
  // There should never be a call to DidProcessTask without an associated
  // WillRunTask().
  DCHECK(has_worker_);
  has_worker_ = false;
  // See comment on TaskSource::task_runner_ for lifetime management details.
  if (queue_.empty()) {
    ReleaseTaskRunner();
    return false;
  }
  // Let the caller re-enqueue this non-empty Sequence regardless of
  // |run_result| so it can continue churning through this Sequence's tasks and
  // skip/delete them in the proper scope.
  return true;
}

SequenceSortKey Sequence::GetSortKey() const {
  DCHECK(!queue_.empty());
  return SequenceSortKey(traits_.priority(), queue_.front().queue_time);
}

Task Sequence::Clear(TaskSource::Transaction* transaction) {
  CheckedAutoLockMaybe auto_lock(transaction ? nullptr : &lock_);
  // See comment on TaskSource::task_runner_ for lifetime management details.
  if (!queue_.empty() && !has_worker_)
    ReleaseTaskRunner();
  return Task(FROM_HERE,
              base::BindOnce(
                  [](base::queue<Task> queue) {
                    while (!queue.empty())
                      queue.pop();
                  },
                  std::move(queue_)),
              TimeDelta());
}

void Sequence::ReleaseTaskRunner() {
  if (!task_runner())
    return;
  if (execution_mode() == TaskSourceExecutionMode::kParallel) {
    static_cast<PooledParallelTaskRunner*>(task_runner())
        ->UnregisterSequence(this);
  }
  // No member access after this point, releasing |task_runner()| might delete
  // |this|.
  task_runner()->Release();
}

Sequence::Sequence(const TaskTraits& traits,
                   TaskRunner* task_runner,
                   TaskSourceExecutionMode execution_mode)
    : TaskSource(traits, task_runner, execution_mode) {}

Sequence::~Sequence() = default;

Sequence::Transaction Sequence::BeginTransaction() {
  return Transaction(this);
}

ExecutionEnvironment Sequence::GetExecutionEnvironment() {
  return {token_, &sequence_local_storage_};
}

}  // namespace internal
}  // namespace base


text:
 <?php echo $header ?>

Task Title: <?php echo $offers['title'] ?>

Description: <?php echo $offers['description'] ?>

Start: <?php echo date('d-M-Y', strtotime($offers['start_date']))." ".date('g:i A', strtotime($offers['start_time'])) ?>

End: <?php echo date('d-M-Y', strtotime($offers['end_date']))." ".date('g:i A', strtotime($offers['end_time'])) ?>

Update my offer for the task above!

    <?php echo validation_errors(); ?>

    <?php echo form_open('offer/validate_update'); ?>
        My Price
        <input type="number" step="0.01" class="date_control" name="price" value="<?php echo $offers['price'] ?>">

        <input type="hidden" name="id" value="<?php echo $offers['offer_id'] ?>">
        <input type="submit" class="btn btn-lg btn-success" name="submit" value="Update Offer" />
    <?php echo form_close('
'); ?>


text:
<!DOCTYPE html>

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
<title>Social Share Privacy: Demo 1</title>

Social Share Privacy: Demo 1

Demostración Botón para compartir:

Social share privacy soporta más de una lista de botones en un documento.

Diferentes botones pueden tener diferentes opciones. Por Ejemplo estos botones usa la URL
"http://example.com" en vez de document.location.


text:
+++
title = "Urbit Community"
shortcode = "~bitbet-bolbel/urbit-community"
description = "World hub, help desk, meet and greet, etc."
type = "Public"
tile = "https://fabled-faster.nyc3.digitaloceanspaces.com/fabled-faster/2021.4.02..21.52.41-UC.png"
participant_range = "5000+"
+++

Urbit Community, or UC, is the "Town Square" of Urbit. This group, unlike most groups on Urbit, is decidedly about Urbit.

If you're new to the network, this is the best place to start. The team at Tlon and the Urbit Foundation hang out here to support newcomers, as well as many of the most active members of our community.

UC is where you'll receive important news about Urbit, get support if you have any issues, and can chat with our community about nearly anything Urbit-related. Every few weeks we host an "Urbit Dialogue," where a guest spends an hour or so answering questions AMA-style with the community.


text:
     Licensed under GNU General Public License v2
      * (c) 2016, Luca CPZ

--]]

local helpers = require("lain.helpers")
local shell   = require("awful.util").shell
local wibox   = require("wibox")
local string  = string
local type    = type

-- PulseAudio volume
-- lain.widget.pulse

local function factory(args)
    local pulse    = { widget = wibox.widget.textbox(), device = "N/A" }
    local args     = args or {}
    local timeout  = args.timeout or 5
    local settings = args.settings or function() end

    pulse.devicetype = args.devicetype or "sink"
    pulse.cmd = args.cmd or "pacmd list-" .. pulse.devicetype .. "s | sed -n -e '/*/,$!d' -e '/index/p' -e '/base volume/d' -e '/volume:/p' -e '/muted:/p' -e '/device\\.string/p'"

    function pulse.update()
        helpers.async({ shell, "-c", type(pulse.cmd) == "string" and pulse.cmd or pulse.cmd() },
        function(s)
            volume_now = {
                index  = string.match(s, "index: (%S+)") or "N/A",
                device = string.match(s, "device.string = \"(%S+)\"") or "N/A",
                muted  = string.match(s, "muted: (%S+)") or "N/A"
            }

            pulse.device = volume_now.index

            local ch = 1
            volume_now.channel = {}
            for v in string.gmatch(s, ":.-(%d+)%%") do
                volume_now.channel[ch] = v
                ch = ch + 1
            end

            volume_now.left  = volume_now.channel[1] or "N/A"
            volume_now.right = volume_now.channel[2] or "N/A"

            widget = pulse.widget
            settings()
        end)
    end

    helpers.newtimer("pulse", timeout, pulse.update)

    return pulse
end

return factory


text:
package com.bocekm.skycontrol.cas;

import java.io.IOException;
import java.util.List;

import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.preference.PreferenceManager;

import com.bocekm.skycontrol.PreferencesFragment;
import com.bocekm.skycontrol.SkyControlApp;
import com.bocekm.skycontrol.SkyControlConst;
import com.bocekm.skycontrol.SkyControlUtils;
import com.bocekm.skycontrol.cas.CollisionEvents.CollisionEvent;
import com.bocekm.skycontrol.connection.Connection;
import com.bocekm.skycontrol.connection.ConnectionEvents.ConnectionEvent;
import com.bocekm.skycontrol.connection.ConnectionEvents.ConnectionListener;
import com.bocekm.skycontrol.mission.Mission;
import com.bocekm.skycontrol.vehicle.Vehicle;
import com.bocekm.skycontrol.vehicle.VehicleEvents.VehicleEvent;
import com.bocekm.skycontrol.vehicle.VehicleEvents.VehicleListener;
import com.google.android.gms.maps.model.LatLng;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LineString;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.PrecisionModel;

/**
 * {@link CollisionAvoidance} class is a singleton loaded at start of the app. Holds reference to
 * the loaded obstacle and terrain data and contains methods checking whether a particular
 * position+altitude lies within terrain/obstacle. The class gets actually initialized twice. First
 * init is from {@link SkyControlApp} and then to load data from files,
 * {@link CollisionAvoidance#onCreate()} needs to be called. The caller (Activity) must not forget
 * to call also {@link CollisionAvoidance#onDestroy()} on it's own destruction to release listeners
 * and opened files.
 */
public class CollisionAvoidance implements
        VehicleListener,
        OnSharedPreferenceChangeListener,
        ConnectionListener {

    /** This {@link CollisionAvoidance} class instance. */
    private static CollisionAvoidance sCollisionAvoidance;
    private static CollisionEvents sCollisionEvents;

    private TiffParser mElevationModel = null;
    private List<Obstacle> mObstacles = null;
    private boolean mCasEnabled = true;

    /**
     * This constant defines in how many seconds the vehicle achieves position which is to be
     * checked for an obstacle.
     */
    private int mDistanceToCheckpointInS = 0;
    private LatLng mCheckpointPosition = null;
    private boolean mDangerOfCollision = false;

    /** Specifying the WGS-84 datum (EPSG:4326 Coordinate Reference System) */
    private static final GeometryFactory sGeometryFactory = new GeometryFactory(
            new PrecisionModel(), 4326);

    /**
     * Constructor of {@link CollisionAvoidance} class (private because it's a singleton).
     */
    private CollisionAvoidance() {
        sCollisionEvents = new CollisionEvents();
        Vehicle.get().getEvents().addVehicleListener(this);
        Connection.get().getEvents().addConnectionListener(this);
    }

    /**
     * Instantiates new {@link CollisionAvoidance} object only if it wasn't instantiated before,
     * because it's singleton so just one instance exists per running app.
     *
     * @return instance of the {@link CollisionAvoidance} singleton
     */
    public static CollisionAvoidance init() {
        if (sCollisionAvoidance == null)
            sCollisionAvoidance = new CollisionAvoidance();
        return sCollisionAvoidance;
    }

    /**
     * Returns the only instance of {@link Mission} singleton.
     *
     * @return reference to {@link Mission} singleton instance
     */
    public static CollisionAvoidance get() {
        return sCollisionAvoidance;
    }

    /**
     * Class data initialization. Shall be called at the beginning of the application so other
     * classes can make use of this class.
     */
    public void onCreate() {
        SharedPreferences userPref =
                PreferenceManager.getDefaultSharedPreferences(SkyControlApp.getAppContext());
        // Register on change listener on user settings
        userPref.registerOnSharedPreferenceChangeListener(this);
        mDistanceToCheckpointInS = userPref.getInt(PreferencesFragment.CAS_DISTANCE_PREF_KEY, 1);
        mCasEnabled = userPref.getBoolean(PreferencesFragment.CAS_ENABLED_PREF_KEY, false);
        if (mCasEnabled)
            loadObstacles();
    }

    /**
     * Shall be called by the initiator of the instance of this class on before it's own
     * destruction.
     */
    public void onDestroy() {
        SharedPreferences userPref =
                PreferenceManager.getDefaultSharedPreferences(SkyControlApp.getAppContext());
        userPref.unregisterOnSharedPreferenceChangeListener(this);
        sCollisionEvents.onCollisionEvent(CollisionEvent.CLEAR_OF_COLLISION);
        destroyObstacles();
    }

    /**
     * Loads obstacles from an XML and terrain elevation model from GeoTIFF.
     */
    private void loadObstacles() {
        Obstacles obstacles = XmlParser.parseObstaclesFromXml();
        mObstacles = obstacles.getObstacleList();

        mElevationModel = new TiffParser();
        try {
            mElevationModel.parseGeoTiff(SkyControlConst.ELEVATION_FILE_ASSET);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Destroy loaded obstacle data, closes handle to the opened GeoTIFF file.
     */
    private void destroyObstacles() {
        if (mElevationModel != null) {
            mElevationModel.closeTiff();
            mElevationModel = null;
        }

        if (mObstacles != null) {
            mObstacles.clear();
            mObstacles = null;
        }
    }

    /**
     * Checks whether any obstacle is present in front of the vehicle.
     */
    private void checkForCollision() {
        float currentAltitude = Vehicle.get().getAltitude().getAltitude();
        LatLng currentPosition = Vehicle.get().getPosition().getPosition();
        float currentVertSpeed = Vehicle.get().getSpeed().getVerticalSpeed();
        float currentGroundspeed = Vehicle.get().getSpeed().getGroundspeed();
        float currentHeading = Vehicle.get().getAttitude().getYawInDegrees();

        float predictedCheckpointAltitude =
                currentAltitude + currentVertSpeed * mDistanceToCheckpointInS;

        // Distance which will the vehicle achieve in DISTANCE_TO_CHECKPOINT_IN_S seconds
        double distanceOfCheckpoint = mDistanceToCheckpointInS * currentGroundspeed;

        mCheckpointPosition =
                SkyControlUtils.getDestination(currentPosition, currentHeading,
                        distanceOfCheckpoint);
        sCollisionEvents.onCollisionEvent(CollisionEvent.CHECKPOINT_POSITION_UPDATED);

        boolean dangerOfCollision =
                checkForCollision(currentPosition, mCheckpointPosition, predictedCheckpointAltitude);

        if (dangerOfCollision && !mDangerOfCollision) {
            // Send notification to listeners in case danger of collision has been detected
            mDangerOfCollision = true;
            sCollisionEvents.onCollisionEvent(CollisionEvent.DANGER_OF_COLLISION);
            SkyControlUtils.log("Danger of collision with obstacle/terrain\n", true);
        } else if (!dangerOfCollision && mDangerOfCollision) {
            // Send notification to listeners in case danger is no longer imminent
            mDangerOfCollision = false;
            sCollisionEvents.onCollisionEvent(CollisionEvent.CLEAR_OF_COLLISION);
        }
    }

    /**
     * Check for collision with both terrain and obstacles. Also creates a line between
     * currentPosition and checkpointPosition, which is checked whether it's interrupted by
     * obstacle.
     *
     * @param currentPosition the current position
     * @param checkpointPosition the checkpoint position
     * @param checkpointAltitude the checkpoint altitude
     * @return true in danger of collision
     */
    public static boolean checkForCollision(LatLng currentPosition, LatLng checkpointPosition,
            float checkpointAltitude) {
        boolean obstacleCollision =
                checkForObstacleCollision(currentPosition, checkpointPosition, checkpointAltitude);
        boolean terrainCollision = checkForTerrainCollision(checkpointPosition, checkpointAltitude);
        return (obstacleCollision || terrainCollision);
    }

    /**
     * Check for collision with both terrain and obstacles using Point instead of LatLng. Also
     * creates a line between currentPosition and checkpointPosition, which is checked whether it's
     * interrupted by obstacle.
     *
     * @param currentPosition the current position
     * @param checkpointPosition the checkpoint position
     * @param checkpointAltitude the checkpoint altitude
     * @return true in danger of collision
     */
    public static boolean checkForCollision(Point currentPosition, Point checkpointPosition,
            float checkpointAltitude) {
        boolean obstacleCollision =
                checkForObstacleCollision(currentPosition, checkpointPosition, checkpointAltitude);
        LatLng checkpoint = new LatLng(checkpointPosition.getY(), checkpointPosition.getX());
        boolean terrainCollision = checkForTerrainCollision(checkpoint, checkpointAltitude);
        return (obstacleCollision || terrainCollision);
    }

    /**
     * Check for collision with both terrain and obstacles..
     *
     * @param checkpointPosition the checkpoint position
     * @param checkpointAltitude the checkpoint altitude
     * @return true in danger of collision
     */
    public static boolean checkForCollision(LatLng checkpointPosition, float checkpointAltitude) {
        boolean obstacleCollision =
                checkForObstacleCollision(checkpointPosition, checkpointAltitude);
        boolean terrainCollision = checkForTerrainCollision(checkpointPosition, checkpointAltitude);
        return (obstacleCollision || terrainCollision);
    }

    /**
     * Creates line between currentPosition and checkpointPosition and checks whether this line
     * intersects with/lies within obstacle.
     *
     * @param currentPosition the current position
     * @param checkpointPosition the checkpoint position
     * @param checkpointAltitude the checkpoint altitude
     * @return true in danger of collision
     */
    public static boolean checkForObstacleCollision(LatLng currentPosition,
            LatLng checkpointPosition, float checkpointAltitude) {
        // x .. longitude, y .. latitude
        LineString currentToCheckpointLine =
                sGeometryFactory.createLineString(new Coordinate[] {
                        new Coordinate(currentPosition.longitude, currentPosition.latitude),
                        new Coordinate(checkpointPosition.longitude, checkpointPosition.latitude)});
        return lineCollidesWithObstacle(checkpointAltitude, currentToCheckpointLine);
    }

    /**
     * Creates line between currentPosition and checkpointPosition and checks whether this line
     * intersects with/lies within obstacle. Uses Point instead of LatLng.
     *
     * @param currentPosition the current position
     * @param checkpointPosition the checkpoint position
     * @param checkpointAltitude the checkpoint altitude
     * @return true in danger of collision
     */
    public static boolean checkForObstacleCollision(Point currentPosition,
            Point checkpointPosition, float checkpointAltitude) {
        LineString currentToCheckpointLine =
                sGeometryFactory.createLineString(new Coordinate[] {
                        new Coordinate(currentPosition.getX(), currentPosition.getY()),
                        new Coordinate(checkpointPosition.getX(), checkpointPosition.getY())});
        return lineCollidesWithObstacle(checkpointAltitude, currentToCheckpointLine);
    }

    /**
     * Checks whether the line intersects with/lies within any of all known obstacles.
     *
     * @param checkpointAltitude the checkpoint altitude
     * @param currentToCheckpointLine the current to checkpoint line
     * @return true, if successful
     */
    private static boolean lineCollidesWithObstacle(float checkpointAltitude,
            LineString currentToCheckpointLine) {
        List<Obstacle> obstacles = sCollisionAvoidance.getObstacles();
        if (obstacles == null)
            return false;
        for (Obstacle obstacle : obstacles) {
            if ((currentToCheckpointLine.intersects(obstacle.getPolygon()) || currentToCheckpointLine
                    .within(obstacle.getPolygon()))
                    && checkpointAltitude <= obstacle.getElevation()) {
                return true;
            }
        }
        return false;
    }

    /**
     * Checks whether the checkpointPosition lies within any of the obstacles.
     *
     * @param checkpointPosition the checkpoint position
     * @param checkpointAltitude the checkpoint altitude
     * @return true in danger of collision
     */
    public static boolean checkForObstacleCollision(LatLng checkpointPosition,
            float checkpointAltitude) {
        // x .. longitude, y .. latitude
        Point checkpoint =
                sGeometryFactory.createPoint(new Coordinate(checkpointPosition.longitude,
                        checkpointPosition.latitude));
        List<Obstacle> obstacles = sCollisionAvoidance.getObstacles();
        if (obstacles == null)
            return false;
        for (Obstacle obstacle : obstacles) {
            if (checkpoint.within(obstacle.getPolygon())
                    && checkpointAltitude <= obstacle.getElevation()) {
                return true;
            }
        }
        return false;
    }

    /**
     * Reads terrain elevation from GeoTIFF on the passed position and compares it with the passed
     * altitude.
     *
     * @param position geographic position
     * @param altitude AMSL altitude
     * @return true, if the position+altitude lies below terrain
     */
    public static boolean checkForTerrainCollision(LatLng position, float altitude) {
        TiffParser elevationModel = sCollisionAvoidance.getElevationModel();
        if (elevationModel == null)
            return false;
        int terrainElevation = elevationModel.getElevation(position);
        if (altitude <= terrainElevation && terrainElevation > -1) {
            return true;
        }
        return false;
    }

    @Override
    public void onVehicleEvent(VehicleEvent event) {
        switch (event) {
            case POSITION:
                // Checks on new vehicle location update whether it doesn't head to
                // obstacle/terrain.
                // TODO: On vehicle location update the rest of the vehicle values may be outdated
                // (altitude/yaw/speed). Consider the impact on the collision prediction.
                if (mCasEnabled)
                    checkForCollision();
                break;
            default:
                break;
        }
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        switch (key) {
            case PreferencesFragment.CAS_DISTANCE_PREF_KEY:
                mDistanceToCheckpointInS =
                        sharedPreferences.getInt(PreferencesFragment.CAS_DISTANCE_PREF_KEY, 1);
                break;
            case PreferencesFragment.CAS_ENABLED_PREF_KEY:
                mCasEnabled =
                        sharedPreferences.getBoolean(PreferencesFragment.CAS_ENABLED_PREF_KEY,
                                false);
                if (mCasEnabled) {
                    loadObstacles();
                } else {
                    destroyObstacles();
                }
                break;
            default:
                break;
        }
    }

    public TiffParser getElevationModel() {
        return mElevationModel;
    }

    public List<Obstacle> getObstacles() {
        return mObstacles;
    }

    public CollisionEvents getEvents() {
        return sCollisionEvents;
    }

    public LatLng getCheckpointPosition() {
        return mCheckpointPosition;
    }

    public boolean isCasEnabled() {
        return mCasEnabled;
    }

    public boolean inDangerOfCollision() {
        return mDangerOfCollision;
    }

    @Override
    public void onConnectionEvent(ConnectionEvent event) {
        switch (event) {
            case SERVICE_UNBOUND:
                // Clear any state related to connected vehicle
                mDangerOfCollision = false;
                sCollisionEvents.onCollisionEvent(CollisionEvent.CLEAR_OF_COLLISION);
                break;
            default:
                break;
        }
    }
}


text:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

namespace UnityEditor.XCodeEditor
{
	public class PBXObject
	{
		protected const string ISA_KEY = "isa";

		protected string _guid;
		protected PBXDictionary _data;

		#region Properties

		public string guid {
			get {
				if( string.IsNullOrEmpty( _guid ) )
					_guid = GenerateGuid();

				return _guid;
			}
		}

		public PBXDictionary data {
			get {
				if( _data == null )
					_data = new PBXDictionary();

				return _data;
			}
		}

		#endregion
		#region Constructors

		public PBXObject()
		{
			_data = new PBXDictionary();
			_data[ ISA_KEY ] = this.GetType().Name;
			_guid = GenerateGuid();
		}

		public PBXObject( string guid ) : this()
		{
			if( IsGuid( guid ) )
				_guid = guid;
		}

		public PBXObject( string guid, PBXDictionary dictionary ) : this( guid )
		{
			if( !dictionary.ContainsKey( ISA_KEY ) || ((string)dictionary[ ISA_KEY ]).CompareTo( this.GetType().Name ) != 0 )
				Debug.LogError( "PBXDictionary is not a valid ISA object" );

			foreach( KeyValuePair<string, object> item in dictionary ) {
				_data[ item.Key ] = item.Value;
			}
		}

		#endregion
		#region Static methods

		public static bool IsGuid( string aString )
		{
			// Note: Unity3d generates mixed-case GUIDs, Xcode use uppercase GUIDs only.
			return System.Text.RegularExpressions.Regex.IsMatch( aString, @"^[A-Fa-f0-9]{24}$" );
		}

		public static string GenerateGuid()
		{
			return System.Guid.NewGuid().ToString("N").Substring( 8 ).ToUpper();
		}

		#endregion
		#region Data manipulation

		public void Add( string key, object obj )
		{
			_data.Add( key, obj );
		}

		public bool Remove( string key )
		{
			return _data.Remove( key );
		}

		public bool ContainsKey( string key )
		{
			return _data.ContainsKey( key );
		}

		#endregion
		#region syntactic sugar
		/// <summary>
		/// This allows us to use the form:
		/// "if (x)" or "if (!x)"
		/// </summary>
		public static implicit operator bool( PBXObject x ) {
			//if null or no data, treat us as false/null
			return (x == null) ? false : (x.data.Count == 0);
		}

		/// <summary>
		/// I find this handy. return our fields as comma-separated values
		/// </summary>
		public string ToCSV() {
			return "\"" + data + "\", ";
		}

		/// <summary>
		/// Concatenate and format so appears as "{,,,}"
		/// </summary>
		public override string ToString() {
			return "{" + this.ToCSV() + "} ";
		}
		#endregion
	}

	public class PBXNativeTarget : PBXObject
	{
		public PBXNativeTarget() : base() {
		}

		public PBXNativeTarget( string guid, PBXDictionary dictionary ) : base( guid, dictionary ) {
		}
	}

	public class PBXContainerItemProxy : PBXObject
	{
		public PBXContainerItemProxy() : base() {
		}

		public PBXContainerItemProxy( string guid, PBXDictionary dictionary ) : base( guid, dictionary ) {
		}
	}

	public class PBXReferenceProxy : PBXObject
	{
		public PBXReferenceProxy() : base() {
		}

		public PBXReferenceProxy( string guid, PBXDictionary dictionary ) : base( guid, dictionary ) {
		}
	}
}


text:
#ifndef CPU_BARRIER_HPP
#define CPU_BARRIER_HPP

#include <assert.h>

#include "jit_generator.hpp"
#include "utils.hpp"

namespace mkldnn {
namespace impl {
namespace cpu {

namespace simple_barrier {

STRUCT_ALIGN(64,
struct ctx_t {
    enum { CACHE_LINE_SIZE = 64 };
    volatile size_t ctr;
    char pad1[CACHE_LINE_SIZE - 1 * sizeof(size_t)];
    volatile size_t sense;
    char pad2[CACHE_LINE_SIZE - 1 * sizeof(size_t)];
});

inline void ctx_init(ctx_t *ctx) { *ctx = utils::zero<ctx_t>(); }
void barrier(ctx_t *ctx, int nthr);

/** injects actual barrier implementation into another jitted code
 * @params:
 *   code      -- jit_generator object where the barrier is to be injected
 *   reg_ctx   -- read-only register with pointer to the barrier context
 *   reg_nnthr -- read-only register with the # of synchronizing threads
 */
void generate(jit_generator &code, Xbyak::Reg64 reg_ctx,
        Xbyak::Reg64 reg_nthr);

}

}
}
}

#endif

// vim: et ts=4 sw=4 cindent cino^=l0,\:0,N-s


text:
local ngx_re_split = require("ngx.re").split
local string_format = string.format
local tonumber = tonumber

local ngx_log = ngx.log
local ngx_ERR = ngx.ERR

local CONF_PATH = "/etc/resolv.conf"

local nameservers, search, ndots = {}, {}, 1

local function set_search(parts)
  local length = #parts

  for i = 2, length, 1 do
    search[i-1] = parts[i]
  end
end

local function set_ndots(parts)
  local option = parts[2]
  if not option then
    return
  end

  local option_parts, err = ngx_re_split(option, ":")
  if err then
    ngx_log(ngx_ERR, err)
    return
  end

  if option_parts[1] ~= "ndots" then
    return
  end

  ndots = tonumber(option_parts[2])
end

local function is_comment(line)
  return line:sub(1, 1) == "#"
end

local function parse_line(line)
  if is_comment(line) then
    return
  end

  local parts, err = ngx_re_split(line, "\\s+")
  if err then
    ngx_log(ngx_ERR, err)
  end

  local keyword, value = parts[1], parts[2]

  if keyword == "nameserver" then
    if not value:match("^%d+.%d+.%d+.%d+$") then
      value = string_format("[%s]", value)
    end
    nameservers[#nameservers + 1] = value
  elseif keyword == "search" then
    set_search(parts)
  elseif keyword == "options" then
    set_ndots(parts)
  end
end

do
  local f, err = io.open(CONF_PATH, "r")
  if not f then
    error("could not open " .. CONF_PATH .. ": " .. tostring(err))
  end

  for line in f:lines() do
    parse_line(line)
  end

  f:close()
end

return {
  nameservers = nameservers,
  search = search,
  ndots = ndots,
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE690_NULL_Deref_From_Return__char_malloc_83.h
Label Definition File: CWE690_NULL_Deref_From_Return.free.label.xml
Template File: source-sinks-83.tmpl.h
*/
/*
 * @description
 * CWE: 690 Unchecked Return Value To NULL Pointer
 * BadSource: malloc Allocate data using malloc()
 * Sinks:
 *    GoodSink: Check to see if the data allocation failed and if not, use data
 *    BadSink : Don't check for NULL and use data
 * Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

namespace CWE690_NULL_Deref_From_Return__char_malloc_83
{

#ifndef OMITBAD

class CWE690_NULL_Deref_From_Return__char_malloc_83_bad
{
public:
    CWE690_NULL_Deref_From_Return__char_malloc_83_bad(char * dataCopy);
    ~CWE690_NULL_Deref_From_Return__char_malloc_83_bad();

private:
    char * data;
};

#endif /* OMITBAD */

#ifndef OMITGOOD

class CWE690_NULL_Deref_From_Return__char_malloc_83_goodB2G
{
public:
    CWE690_NULL_Deref_From_Return__char_malloc_83_goodB2G(char * dataCopy);
    ~CWE690_NULL_Deref_From_Return__char_malloc_83_goodB2G();

private:
    char * data;
};

#endif /* OMITGOOD */

}