text:
(function() {
  'use strict';
  angular.module('historico-saude.state.login.controller', [])
    .controller('LoginController', Login);

  function Login($scope, $state, $http, apiUrl, $ionicPopup, $rootScope, $timeout, Filhos, $ionicScrollDelegate) {
    $scope.email = "pai@pai.com";
    $scope.senha = "123456";

    $scope.shownGroupPai = false;
    $scope.shownGroupMae = false;
    $scope.estados = ['AC', 'AL', 'AP', 'AM', 'BA', 'CE', 'DF', 'ES', 'GO', 'MA', 'MT', 'MS', 'MG', 'PA', 'PB', 'PR', 'PE', 'PI', 'RJ', 'RN', 'RS', 'RO', 'RR', 'SC', 'SP', 'SE', 'TO'];
    $scope.pai = {uf: $scope.estados[0], sexo: 1, dataNascimento: new Date()};
    $scope.mae = {uf: $scope.estados[0], sexo: 0, dataNascimento: new Date()};
    //mock PAI
    $scope.pai.nome = 'Pai';
    $scope.pai.email = 'pai@pai.com';
    $scope.pai.endereco = 'Endereco';
    $scope.pai.numero = '123';
    $scope.pai.bairro = 'Bai';
    $scope.pai.cidade = 'ABC';
    $scope.pai.telefone = '1234';
    //mock MAE
    $scope.mae.nome = 'Mae';
    $scope.mae.email = 'mae@mae.com';
    $scope.mae.endereco = 'Endereco';
    $scope.mae.numero = '123';
    $scope.mae.bairro = 'Bai';
    $scope.mae.cidade = 'ABC';
    $scope.mae.telefone = '1234';

    $scope.login = function() {
      console.log({email: $scope.email, senha: $scope.senha});
      $http.post(apiUrl + '/usuario/login', {email: $scope.email, senha: $scope.senha})
        .success(function(data, status){
          if (data) {
            $rootScope.user = data;
            carregarFilhos();
            $state.go('app.dashboard');
          } else {
            $ionicPopup.alert({
              title: 'Oops! :(',
              template: 'Email ou senha não conferem!'
            });
          }
        })
        .error(function(data, status, headers, config){
          console.log('error', status, data);
        });
    };

    $scope.signUpUI = function() {
      $state.go('signup');
    };

    $scope.loginUI = function() {
      $state.go('login');
    };

    $scope.signUp = function() {
      console.log($scope.user);
      $http.post(apiUrl + '/usuario', $scope.user)
        .success(function(data, status){
          console.log('Usuário', data);
          $rootScope.user = data;
          $scope.pai.usuario = data;
          $scope.mae.usuario = data;
          cadastraPessoa($scope.pai);
          cadastraPessoa($scope.mae);
        })
        .error(function(data, status, headers, config){
          console.log('error', status, data);
        });
      $timeout(function() {
        $state.go('app.filho');
      }, 400);
    };

    $scope.callbackDataNascimentoPai = function (val) {
      if(typeof(val)!=='undefined'){
        $scope.pai.dataNascimento = val;
      }
    };

    $scope.callbackDataNascimentoMae = function (val) {
      if(typeof(val)!=='undefined'){
        $scope.mae.dataNascimento = val;
      }
    };

    function cadastraPessoa(pessoa) {
      $http.post(apiUrl + '/pessoa', pessoa)
        .success(function(data, status){
          console.log('Pessoa', data);
        })
        .error(function(data, status, headers, config){
          console.log('error', status, data);
        });
    };

    function carregarFilhos() {
      $http.post(apiUrl + '/usuario/filhos', {user: $rootScope.user.id})
        .success(function(data, status){
          console.log(data);
          Filhos.set(data);
        })
        .error(function(data, status, headers, config){
          console.log('error', status, data);
        });
    };

    $scope.toggleGroup = function(group) {
      if (group == 'pai') {
        $scope.shownGroupPai = !$scope.shownGroupPai;
      } else {
        $scope.shownGroupMae = !$scope.shownGroupMae;
      }
      $ionicScrollDelegate.resize();
    };
  }
})();


text:
<?php

declare(strict_types=1);

namespace Nelmio\Alice\FixtureBuilder\Denormalizer\Fixture\SpecificationBagDenormalizer\Value;

use Nelmio\Alice\Definition\Fixture\FakeFixture;
use Nelmio\Alice\Definition\Fixture\SimpleFixture;
use Nelmio\Alice\Definition\Flag\DummyFlag;
use Nelmio\Alice\Definition\Flag\UniqueFlag;
use Nelmio\Alice\Definition\FlagBag;
use Nelmio\Alice\Definition\SpecificationBagFactory;
use Nelmio\Alice\Definition\Value\ArrayValue;
use Nelmio\Alice\Definition\Value\DynamicArrayValue;
use Nelmio\Alice\Definition\Value\FakeValue;
use Nelmio\Alice\Definition\Value\UniqueValue;
use Nelmio\Alice\FixtureBuilder\Denormalizer\Fixture\SpecificationBagDenormalizer\ValueDenormalizerInterface;
use Nelmio\Alice\Throwable\Exception\FixtureBuilder\Denormalizer\InvalidScopeException;
use PHPUnit\Framework\TestCase;
use Prophecy\Argument;
use Prophecy\PhpUnit\ProphecyTrait;
use ReflectionClass;
use stdClass;

/**
 * @covers \Nelmio\Alice\FixtureBuilder\Denormalizer\Fixture\SpecificationBagDenormalizer\Value\UniqueValueDenormalizer
 */
class UniqueValueDenormalizerTest extends TestCase
{
    use ProphecyTrait;

    public function testIsAValueDenormalizer(): void
    {
        static::assertTrue(is_a(UniqueValueDenormalizer::class, ValueDenormalizerInterface::class, true));
    }

    public function testIsNotClonable(): void
    {
        static::assertFalse((new ReflectionClass(UniqueValueDenormalizer::class))->isCloneable());
    }

    public function testReturnsParsedValueIfNoUniqueFlagsHasBeenFound(): void
    {
        $fixture = new FakeFixture();
        $flags = new FlagBag('');
        $value = 'foo';

        $decoratedDenormalizerProphecy = $this->prophesize(ValueDenormalizerInterface::class);
        $decoratedDenormalizerProphecy
            ->denormalize($fixture, $flags, $value)
            ->willReturn($expected = 'denormalized_value')
        ;
        /** @var ValueDenormalizerInterface $decoratedDenormalizer */
        $decoratedDenormalizer = $decoratedDenormalizerProphecy->reveal();

        $denormalizer = new UniqueValueDenormalizer($decoratedDenormalizer);
        $actual = $denormalizer->denormalize($fixture, $flags, $value);

        static::assertEquals($expected, $actual);

        $decoratedDenormalizerProphecy->denormalize(Argument::cetera())->shouldHaveBeenCalledTimes(1);
    }

    public function testReturnsUniqueValueIfUniqueFlagsFound(): void
    {
        $fixture = new SimpleFixture('dummy_id', 'Dummy', SpecificationBagFactory::create());
        $flags = (new FlagBag(''))->withFlag(new UniqueFlag());
        $value = 'foo';

        $decoratedDenormalizerProphecy = $this->prophesize(ValueDenormalizerInterface::class);
        $decoratedDenormalizerProphecy
            ->denormalize($fixture, $flags, $value)
            ->willReturn('denormalized_value')
        ;
        /** @var ValueDenormalizerInterface $decoratedDenormalizer */
        $decoratedDenormalizer = $decoratedDenormalizerProphecy->reveal();

        $denormalizer = new UniqueValueDenormalizer($decoratedDenormalizer);
        $result = $denormalizer->denormalize($fixture, $flags, $value);

        static::assertInstanceOf(UniqueValue::class, $result);
        static::assertStringStartsWith('Dummy#', $result->getId());
        static::assertEquals('denormalized_value', $result->getValue());

        $decoratedDenormalizerProphecy->denormalize(Argument::cetera())->shouldHaveBeenCalledTimes(1);
    }

    public function testIfParsedValueIsDynamicArrayThenUniqueFlagAppliesToItsElementInstead(): void
    {
        $fixture = new SimpleFixture('dummy_id', 'Dummy', SpecificationBagFactory::create());
        $value = 'string value';
        $denormalizedValue = new DynamicArrayValue(10, 'parsed_value');
        $flags = (new FlagBag(''))->withFlag(new UniqueFlag());

        $decoratedDenormalizerProphecy = $this->prophesize(ValueDenormalizerInterface::class);
        $decoratedDenormalizerProphecy
            ->denormalize($fixture, $flags, $value)
            ->willReturn($denormalizedValue)
        ;
        /** @var ValueDenormalizerInterface $decoratedDenormalizer */
        $decoratedDenormalizer = $decoratedDenormalizerProphecy->reveal();

        $denormalizer = new UniqueValueDenormalizer($decoratedDenormalizer);
        $result = $denormalizer->denormalize($fixture, $flags, $value);

        static::assertInstanceOf(DynamicArrayValue::class, $result);
        /** @var DynamicArrayValue $result */
        static::assertEquals(10, $result->getQuantifier());
        static::assertInstanceOf(UniqueValue::class, $result->getElement());
        // @phpstan-ignore-next-line
        static::assertStringStartsWith('Dummy#', $result->getElement()->getId());
        static::assertEquals('parsed_value', $result->getElement()->getValue());
    }

    public function testThrowsAnExceptionIsATemporaryFixtureWithAUniqueValue(): void
    {
        $fixture = new SimpleFixture(uniqid('temporary_id'), 'Dummy', SpecificationBagFactory::create());
        $value = 'string value';
        $denormalizedValue = new FakeValue();
        $flags = (new FlagBag(''))->withFlag(new UniqueFlag());

        $decoratedDenormalizerProphecy = $this->prophesize(ValueDenormalizerInterface::class);
        $decoratedDenormalizerProphecy
            ->denormalize($fixture, $flags, $value)
            ->willReturn($denormalizedValue)
        ;
        /** @var ValueDenormalizerInterface $decoratedDenormalizer */
        $decoratedDenormalizer = $decoratedDenormalizerProphecy->reveal();

        $denormalizer = new UniqueValueDenormalizer($decoratedDenormalizer);

        $this->expectException(InvalidScopeException::class);
        $this->expectExceptionMessage('Cannot bind a unique value scope to a temporary fixture.');

        $denormalizer->denormalize($fixture, $flags, $value);
    }

    public function testIfParsedValueIsArrayValueThenUniqueFlagAppliesToItsElementInstead(): void
    {
        $fixture = new SimpleFixture('dummy_id', 'Dummy', SpecificationBagFactory::create());
        $value = 'string value';
        $denormalizedValue = new ArrayValue(['foo', 'bar']);
        $flags = (new FlagBag(''))->withFlag(new UniqueFlag());

        $decoratedDenormalizerProphecy = $this->prophesize(ValueDenormalizerInterface::class);
        $decoratedDenormalizerProphecy
            ->denormalize($fixture, $flags, $value)
            ->willReturn($denormalizedValue)
        ;
        /** @var ValueDenormalizerInterface $decoratedDenormalizer */
        $decoratedDenormalizer = $decoratedDenormalizerProphecy->reveal();

        $denormalizer = new UniqueValueDenormalizer($decoratedDenormalizer);
        $result = $denormalizer->denormalize($fixture, $flags, $value);

        static::assertInstanceOf(ArrayValue::class, $result);
        /** @var ArrayValue $result */
        static::assertInstanceOf(UniqueValue::class, $result->getValue()[0]);
        static::assertStringStartsWith('Dummy#', $result->getValue()[0]->getId());
        static::assertEquals('foo', $result->getValue()[0]->getValue());

        static::assertInstanceOf(UniqueValue::class, $result->getValue()[1]);
        static::assertStringStartsWith('Dummy#', $result->getValue()[1]->getId());
        static::assertEquals('bar', $result->getValue()[1]->getValue());
    }

    public function provideValues()
    {
        $unparsedValues = [
            'null' => null,
            'int' => 0,
            'float' => .5,
            'bool' => true,
            'array' => [],
            'object' => new stdClass(),
        ];

        $flagBags = [
            'null' => null,
            'empty' => new FlagBag(''),
            'with random flag' => (new FlagBag(''))->withFlag(new DummyFlag()),
        ];

        foreach ($flagBags as $flagName => $flags) {
            foreach ($unparsedValues as $unparsedValueName => $unparsedValue) {
                yield $unparsedValueName.'/'.$flagName => [$unparsedValue, false, $flags];
            }

            yield 'string value /'.$flagName => ['1', true, $flags];
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using namespace Valkyrie::Scene;

Camera::Camera() : m_camera_component_ptr(nullptr) {

}

Camera::~Camera() {

}

void Camera::start() {
	Object::start();
}

void Camera::update() {
	Object::update();
	m_camera_component_ptr->update();
}

ValkyrieComponent::ComponentPtr Camera::getComponentPtr(const std::string& component_name) {
	if (component_name == ValkyrieComponent::Camera::getCameraComponentName())
		return m_camera_component_ptr;
	return Object::getComponentPtr(component_name);
}


text:
#region License

#endregion

using System.IO;
using NUnit.Framework;
using Revise.Files.CHR;

namespace Revise.Files.Tests {
    /// <summary>
    /// Provides testing for the <see cref="CharacterFile"/> class.
    /// </summary>
    [TestFixture]
    public class CharacterFileTests {
        private const string TEST_FILE = "Files/LIST_NPC.CHR";

        /// <summary>
        /// Tests the load method.
        /// </summary>
        [Test]
        public void TestLoadMethod() {
            Stream stream = File.OpenRead(TEST_FILE);

            stream.Seek(0, SeekOrigin.End);
            long fileSize = stream.Position;
            stream.Seek(0, SeekOrigin.Begin);

            CharacterFile characterFile = new CharacterFile();
            characterFile.Load(stream);

            long streamPosition = stream.Position;
            stream.Close();

            Assert.AreEqual(fileSize, streamPosition, "Not all of the file was read");
        }

        /// <summary>
        /// Tests the save method.
        /// </summary>
        [Test]
        public void TestSaveMethod() {
            CharacterFile characterFile = new CharacterFile();
            characterFile.Load(TEST_FILE);

            MemoryStream savedStream = new MemoryStream();
            characterFile.Save(savedStream);

            savedStream.Seek(0, SeekOrigin.Begin);

            CharacterFile savedCharacterFile = new CharacterFile();
            savedCharacterFile.Load(savedStream);

            savedStream.Close();

            Assert.AreEqual(characterFile.SkeletonFiles.Count, savedCharacterFile.SkeletonFiles.Count, "Skeleton file counts do not match");

            for (int i = 0; i < characterFile.SkeletonFiles.Count; i++) {
                Assert.AreEqual(characterFile.SkeletonFiles[i], savedCharacterFile.SkeletonFiles[i], "Skeleton file names do not match");
            }

            Assert.AreEqual(characterFile.MotionFiles.Count, savedCharacterFile.MotionFiles.Count, "Motion file counts do not match");

            for (int i = 0; i < characterFile.MotionFiles.Count; i++) {
                Assert.AreEqual(characterFile.MotionFiles[i], savedCharacterFile.MotionFiles[i], "Motion file names do not match");
            }

            Assert.AreEqual(characterFile.EffectFiles.Count, savedCharacterFile.EffectFiles.Count, "Effect file counts do not match");

            for (int i = 0; i < characterFile.EffectFiles.Count; i++) {
                Assert.AreEqual(characterFile.EffectFiles[i], savedCharacterFile.EffectFiles[i], "Effect file names do not match");
            }

            Assert.AreEqual(characterFile.Characters.Count, savedCharacterFile.Characters.Count, "Character counts do not match");

            for (int i = 0; i < characterFile.Characters.Count; i++) {
                Assert.AreEqual(characterFile.Characters[i].IsEnabled, savedCharacterFile.Characters[i].IsEnabled, "Character enabled values do not match");

                if (characterFile.Characters[i].IsEnabled) {
                    Assert.AreEqual(characterFile.Characters[i].ID, savedCharacterFile.Characters[i].ID, "Character ID values do not match");
                    Assert.AreEqual(characterFile.Characters[i].Name, savedCharacterFile.Characters[i].Name, "Character name values do not match");

                    Assert.AreEqual(characterFile.Characters[i].Objects.Count, savedCharacterFile.Characters[i].Objects.Count, "Character object counts do not match");

                    for (int j = 0; j < characterFile.Characters[i].Objects.Count; j++) {
                        Assert.AreEqual(characterFile.Characters[i].Objects[j].Object, savedCharacterFile.Characters[i].Objects[j].Object, "Character object values do not match");
                    }

                    Assert.AreEqual(characterFile.Characters[i].Animations.Count, savedCharacterFile.Characters[i].Animations.Count, "Character animation counts do not match");

                    for (int j = 0; j < characterFile.Characters[i].Animations.Count; j++) {
                        Assert.AreEqual(characterFile.Characters[i].Animations[j].Type, savedCharacterFile.Characters[i].Animations[j].Type, "Character animation type values do not match");
                        Assert.AreEqual(characterFile.Characters[i].Animations[j].Animation, savedCharacterFile.Characters[i].Animations[j].Animation, "Character animation values do not match");
                    }

                    Assert.AreEqual(characterFile.Characters[i].Effects.Count, savedCharacterFile.Characters[i].Effects.Count, "Character effect counts do not match");

                    for (int j = 0; j < characterFile.Characters[i].Effects.Count; j++) {
                        Assert.AreEqual(characterFile.Characters[i].Effects[j].Bone, savedCharacterFile.Characters[i].Effects[j].Bone, "Character effect bone values do not match");
                        Assert.AreEqual(characterFile.Characters[i].Effects[j].Effect, savedCharacterFile.Characters[i].Effects[j].Effect, "Character effect values do not match");
                    }
                }
            }
        }
    }
}


text:
import sys, os
import numpy as np

from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer

def load_dataset(if_data_shake):

    if sys.version_info[0] == 2:
        from urllib import urlretrieve
    else:
        from urllib.request import urlretrieve

    def download(filename, source='http://yann.lecun.com/exdb/mnist/'):
        print("Downloading %s" % filename)
        urlretrieve(source + filename, 'mnist/' + filename)

    import gzip

    def load_mnist_images(filename):
        if not os.path.exists('mnist/' + filename):
            download(filename)
        with gzip.open('mnist/' + filename, 'rb') as f:
            data = np.frombuffer(f.read(), np.uint8, offset=16)
        data = data.reshape(-1, 784)
        return data / np.float32(256)

    def load_mnist_labels(filename):
        if not os.path.exists('mnist/' + filename):
            download(filename)
        with gzip.open('mnist/' + filename, 'rb') as f:
            data = np.frombuffer(f.read(), np.uint8, offset=8)
        return data

    if if_data_shake==0:
        # We can now download and read the training and test set images and labels.
        X_train = load_mnist_images('train-images-idx3-ubyte.gz')
        y_train = load_mnist_labels('train-labels-idx1-ubyte.gz')
        X_test = load_mnist_images('t10k-images-idx3-ubyte.gz')
        y_test = load_mnist_labels('t10k-labels-idx1-ubyte.gz')

        # We reserve the last 10000 training examples for validation.
        X_train, X_val = X_train[:-10000], X_train[-10000:]
        y_train, y_val = y_train[:-10000], y_train[-10000:]

    else:
        X_train = load_mnist_images('train-images-idx3-ubyte.gz')
        y_train = load_mnist_labels('train-labels-idx1-ubyte.gz')
        X_test = load_mnist_images('t10k-images-idx3-ubyte.gz')
        y_test = load_mnist_labels('t10k-labels-idx1-ubyte.gz')

        # We reserve the last 10000 training examples for validation.
        X_train, X_val = X_train[:-10000], X_train[-10000:]
        y_train, y_val = y_train[:-10000], y_train[-10000:]

        X_train.flags.writeable = True
        y_train.flags.writeable = True

        for i in range(50000):
            y_train[i] = i%2
            if i%2 ==0:
                dd = -10
            else:
                dd = 10
            mm = np.ones(784)
            X_train[i] = mm*dd

    return X_train, y_train, X_val, y_val, X_test, y_test

def load_cifar(f):
    import cPickle
    fo = open(f, 'rb')
    d = cPickle.load(fo)
    fo.close()

    X_train, y_train = d['data'], np.array(d['labels'], dtype=np.int32)

    X_train = X_train.reshape(-1, 3, 32, 32)

    X_train, X_val = X_train[:-1000], X_train[-1000:]
    y_train, y_val = y_train[:-1000], y_train[-1000:]

    X_train, X_test = X_train[:-1000], X_train[-1000:]
    y_train, y_test = y_train[:-1000], y_train[-1000:]

    return X_train, y_train, X_val, y_val, X_test, y_test

def load_20news():
    newsgroups_train = fetch_20newsgroups(subset='train', remove=('headers', 'footers', 'quotes'))
    newsgroups_test = fetch_20newsgroups(subset='test', remove=('headers', 'footers', 'quotes'))

    vectorizer = TfidfVectorizer()

    X_train = vectorizer.fit_transform(newsgroups_train.data)
    X_test = vectorizer.transform(newsgroups_test.data)

    y_train = newsgroups_train.target
    y_test = newsgroups_test.target

    X_train, X_val = X_train[:-1000], X_train[-1000:]
    y_train, y_val = y_train[:-1000], y_train[-1000:]

    return X_train, y_train, X_val, y_val, X_test, y_test


text:
<?php
namespace Dizda\CloudBackupBundle\Database;

use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Process\Process;

/**
 * Class BaseDatabase.
 *
 * @author  Jonathan Dizdarevic <dizda@dizda.fr>
 */
abstract class BaseDatabase implements DatabaseInterface
{
    const DB_PATH = '';

    protected $dataPath;
    protected $filesystem;
    protected $timeout;

    /**
     * Get SF2 Filesystem.
     *
     * @param string $basePath
     */
    public function __construct($basePath)
    {
        $this->dataPath = $basePath.static::DB_PATH.'/';
        $this->filesystem = new Filesystem();
        $this->timeout = 300;
    }

    /**
     * Handle process error on fails.
     *
     * @param string $command
     *
     * @throws \RuntimeException
     */
    protected function execute($command)
    {
        $process = new Process($command, null, null, null, $this->timeout);
        $process->run();

        if (!$process->isSuccessful()) {
            throw new \RuntimeException($process->getErrorOutput());
        }
    }

    /**
     * Prepare path for dump file.
     */
    protected function preparePath()
    {
        $this->filesystem->mkdir($this->dataPath);
    }

    /**
     * @param int $timeout
     *
     * @return $this
     */
    public function setTimeout($timeout)
    {
        $this->timeout = $timeout;

        return $this;
    }
}


text:
package ai.subut.kurjun.metadata.common.snap;

import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

public class DefaultFrameworkTest
{
    private DefaultFramework defaultFramework;

    @Before
    public void setUp() throws Exception
    {
        defaultFramework = new DefaultFramework();

        defaultFramework.setName( "name" );
    }

    @Test
    public void getName() throws Exception
    {
        assertNotNull( defaultFramework.getName() );
    }
}


text:
#include "energy.hpp"

namespace sirius {
double ewald_energy(const Simulation_context& ctx, const Gvec& gvec, const Unit_cell& unit_cell)
{
    double alpha{ctx.ewald_lambda()};
    double ewald_g{0};

    #pragma omp parallel for reduction(+ : ewald_g)
    for (int igloc = 0; igloc < gvec.count(); igloc++) {
        int ig = gvec.offset() + igloc;
        if (!ig) {
            continue;
        }

        double g2 = std::pow(gvec.gvec_len(ig), 2);

        double_complex rho(0, 0);

        for (int ia = 0; ia < unit_cell.num_atoms(); ia++) {
            rho += ctx.gvec_phase_factor(gvec.gvec(ig), ia) * static_cast<double>(unit_cell.atom(ia).zn());
        }

        ewald_g += std::pow(std::abs(rho), 2) * std::exp(-g2 / 4 / alpha) / g2;
    }

    ctx.comm().allreduce(&ewald_g, 1);
    if (gvec.reduced()) {
        ewald_g *= 2;
    }
    /* remaining G=0 contribution */
    ewald_g -= std::pow(unit_cell.num_electrons(), 2) / alpha / 4;
    ewald_g *= (twopi / unit_cell.omega());

    /* remove self-interaction */
    for (int ia = 0; ia < unit_cell.num_atoms(); ia++) {
        ewald_g -= std::sqrt(alpha / pi) * std::pow(unit_cell.atom(ia).zn(), 2);
    }

    double ewald_r{0};
    #pragma omp parallel for reduction(+ : ewald_r)
    for (int ia = 0; ia < unit_cell.num_atoms(); ia++) {
        for (int i = 1; i < unit_cell.num_nearest_neighbours(ia); i++) {
            int ja   = unit_cell.nearest_neighbour(i, ia).atom_id;
            double d = unit_cell.nearest_neighbour(i, ia).distance;
            ewald_r += 0.5 * unit_cell.atom(ia).zn() * unit_cell.atom(ja).zn() * std::erfc(std::sqrt(alpha) * d) / d;
        }
    }

    return (ewald_g + ewald_r);
}

double energy_vxc(Density const& density, Potential const& potential)
{
    return potential.energy_vxc(density);
}

double energy_exc(Density const& density, Potential const& potential)
{
    return potential.energy_exc(density);
}

double energy_vha(Potential const& potential)
{
    return potential.energy_vha();
}

double energy_bxc(const Density& density, const Potential& potential, int num_mag_dims)
{
    double ebxc{0};
    for (int j = 0; j < num_mag_dims; j++) {
        ebxc += sirius::inner(density.magnetization(j), potential.effective_magnetic_field(j));
    }
    return ebxc;
}

double energy_enuc(Simulation_context const& ctx, Potential const& potential)
{
    auto& unit_cell = ctx.unit_cell();
    double enuc{0};
    if (ctx.full_potential()) {
        for (int ialoc = 0; ialoc < unit_cell.spl_num_atoms().local_size(); ialoc++) {
            int ia = unit_cell.spl_num_atoms(ialoc);
            int zn = unit_cell.atom(ia).zn();
            enuc -= 0.5 * zn * potential.vh_el(ia);
        }
        ctx.comm().allreduce(&enuc, 1);
    }
    return enuc;
}

double energy_vloc(Density const& density, Potential const& potential)
{
    return sirius::inner(potential.local_potential(), density.rho());
}

double core_eval_sum(Unit_cell const& unit_cell)
{
    double sum{0};
    for (int ic = 0; ic < unit_cell.num_atom_symmetry_classes(); ic++) {
        sum += unit_cell.atom_symmetry_class(ic).core_eval_sum() * unit_cell.atom_symmetry_class(ic).num_atoms();
    }
    return sum;
}

double eval_sum(Unit_cell const& unit_cell, K_point_set const& kset)
{
    return core_eval_sum(unit_cell) + kset.valence_eval_sum();
}

double energy_veff(Density const& density, Potential const& potential)
{
    return sirius::inner(density.rho(), potential.effective_potential());
}

double energy_kin(Simulation_context const& ctx, K_point_set const& kset, Density const& density,
                  Potential const& potential)
{
    return eval_sum(ctx.unit_cell(), kset) - energy_veff(density, potential) -
           energy_bxc(density, potential, ctx.num_mag_dims());
}

double total_energy(Simulation_context const& ctx, K_point_set const& kset, Density const& density,
                    Potential const& potential, double ewald_energy)
{
    double tot_en{0};

    switch (ctx.electronic_structure_method()) {
        case electronic_structure_method_t::full_potential_lapwlo: {
            tot_en = (energy_kin(ctx, kset, density, potential) + energy_exc(density, potential) +
                      0.5 * energy_vha(potential) + energy_enuc(ctx, potential));
            break;
        }

        case electronic_structure_method_t::pseudopotential: {
            tot_en = (kset.valence_eval_sum() - energy_vxc(density, potential) -
                      energy_bxc(density, potential, ctx.num_mag_dims()) - potential.PAW_one_elec_energy()) -
                      0.5 * energy_vha(potential) + energy_exc(density, potential) + potential.PAW_total_energy() +
                      ewald_energy;
            break;
        }
    }

    if (ctx.hubbard_correction()) {
        tot_en += potential.U().hubbard_energy();
    }

    return tot_en;
}

} // namespace sirius


text:
package com.hazelcast.client.impl.protocol.codec.builtin;

import com.hazelcast.cache.CacheEventType;
import com.hazelcast.cache.impl.CacheEventDataImpl;
import com.hazelcast.config.BitmapIndexOptions;
import com.hazelcast.config.BitmapIndexOptions.UniqueKeyTransformation;
import com.hazelcast.config.CacheSimpleEntryListenerConfig;
import com.hazelcast.config.EventJournalConfig;
import com.hazelcast.config.HotRestartConfig;
import com.hazelcast.config.IndexConfig;
import com.hazelcast.config.IndexType;
import com.hazelcast.config.MerkleTreeConfig;
import com.hazelcast.config.NearCachePreloaderConfig;
import com.hazelcast.core.HazelcastException;
import com.hazelcast.instance.EndpointQualifier;
import com.hazelcast.instance.ProtocolType;
import com.hazelcast.internal.management.dto.ClientBwListEntryDTO;
import com.hazelcast.map.impl.SimpleEntryView;
import com.hazelcast.map.impl.querycache.event.DefaultQueryCacheEventData;
import com.hazelcast.cluster.Address;
import com.hazelcast.internal.serialization.Data;
import com.hazelcast.sql.SqlColumnMetadata;
import com.hazelcast.sql.SqlColumnType;

import java.net.UnknownHostException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hazelcast.config.CacheSimpleConfig.ExpiryPolicyFactoryConfig.TimedExpiryPolicyFactoryConfig;
import static com.hazelcast.config.CacheSimpleConfig.ExpiryPolicyFactoryConfig.TimedExpiryPolicyFactoryConfig.ExpiryPolicyType;
import static com.hazelcast.config.CacheSimpleConfig.ExpiryPolicyFactoryConfig.DurationConfig;

@SuppressWarnings("checkstyle:ClassDataAbstractionCoupling")
public final class CustomTypeFactory {

    private CustomTypeFactory() {
    }

    public static Address createAddress(String host, int port) {
        try {
            return new Address(host, port);
        } catch (UnknownHostException e) {
            throw new HazelcastException(e);
        }
    }

    public static CacheEventDataImpl createCacheEventData(String name, int cacheEventType, Data dataKey,
                                                          Data dataValue, Data dataOldValue, boolean oldValueAvailable) {
        return new CacheEventDataImpl(name, CacheEventType.getByType(cacheEventType), dataKey, dataValue,
                dataOldValue, oldValueAvailable);
    }

    public static TimedExpiryPolicyFactoryConfig createTimedExpiryPolicyFactoryConfig(int expiryPolicyType,
                                                                                DurationConfig durationConfig) {
        return new TimedExpiryPolicyFactoryConfig(ExpiryPolicyType.getById(expiryPolicyType), durationConfig);
    }

    public static CacheSimpleEntryListenerConfig createCacheSimpleEntryListenerConfig(boolean oldValueRequired,
                                                                                boolean synchronous,
                                                                                String cacheEntryListenerFactory,
                                                                                String cacheEntryEventFilterFactory) {
        CacheSimpleEntryListenerConfig config = new CacheSimpleEntryListenerConfig();
        config.setOldValueRequired(oldValueRequired);
        config.setSynchronous(synchronous);
        config.setCacheEntryListenerFactory(cacheEntryListenerFactory);
        config.setCacheEntryEventFilterFactory(cacheEntryEventFilterFactory);
        return config;
    }

    public static EventJournalConfig createEventJournalConfig(boolean enabled, int capacity, int timeToLiveSeconds) {
        EventJournalConfig config = new EventJournalConfig();
        config.setEnabled(enabled);
        config.setCapacity(capacity);
        config.setTimeToLiveSeconds(timeToLiveSeconds);
        return config;
    }

    public static HotRestartConfig createHotRestartConfig(boolean enabled, boolean fsync) {
        HotRestartConfig config = new HotRestartConfig();
        config.setEnabled(enabled);
        config.setFsync(fsync);
        return config;
    }

    public static MerkleTreeConfig createMerkleTreeConfig(boolean enabled, int depth) {
        MerkleTreeConfig config = new MerkleTreeConfig();
        config.setEnabled(enabled);
        config.setDepth(depth);
        return config;
    }

    public static NearCachePreloaderConfig createNearCachePreloaderConfig(boolean enabled, String directory,
                                                                          int storeInitialDelaySeconds,
                                                                          int storeIntervalSeconds) {
        NearCachePreloaderConfig config = new NearCachePreloaderConfig();
        config.setEnabled(enabled);
        config.setDirectory(directory);
        config.setStoreInitialDelaySeconds(storeInitialDelaySeconds);
        config.setStoreIntervalSeconds(storeIntervalSeconds);
        return config;
    }

    public static SimpleEntryView<Data, Data> createSimpleEntryView(Data key, Data value, long cost, long creationTime,
                                                        long expirationTime, long hits, long lastAccessTime,
                                                        long lastStoredTime, long lastUpdateTime, long version,
                                                        long ttl, long maxIdle) {
        SimpleEntryView<Data, Data> entryView = new SimpleEntryView<>();
        entryView.setKey(key);
        entryView.setValue(value);
        entryView.setCost(cost);
        entryView.setCreationTime(creationTime);
        entryView.setExpirationTime(expirationTime);
        entryView.setHits(hits);
        entryView.setLastAccessTime(lastAccessTime);
        entryView.setLastStoredTime(lastStoredTime);
        entryView.setLastUpdateTime(lastUpdateTime);
        entryView.setVersion(version);
        entryView.setTtl(ttl);
        entryView.setMaxIdle(maxIdle);
        return entryView;
    }

    public static DefaultQueryCacheEventData createQueryCacheEventData(Data dataKey, Data dataNewValue, long sequence,
                                                                int eventType, int partitionId) {
        DefaultQueryCacheEventData eventData = new DefaultQueryCacheEventData();
        eventData.setDataKey(dataKey);
        eventData.setDataNewValue(dataNewValue);
        eventData.setSequence(sequence);
        eventData.setEventType(eventType);
        eventData.setPartitionId(partitionId);
        return eventData;
    }

    public static DurationConfig createDurationConfig(long durationAmount, int timeUnitId) {
        TimeUnit timeUnit;
        if (timeUnitId == 0) {
            timeUnit = TimeUnit.NANOSECONDS;
        } else if (timeUnitId == 1) {
            timeUnit = TimeUnit.MICROSECONDS;
        } else if (timeUnitId == 2) {
            timeUnit = TimeUnit.MILLISECONDS;
        } else if (timeUnitId == 3) {
            timeUnit = TimeUnit.SECONDS;
        } else if (timeUnitId == 4) {
            timeUnit = TimeUnit.MINUTES;
        } else if (timeUnitId == 5) {
            timeUnit = TimeUnit.HOURS;
        } else if (timeUnitId == 6) {
            timeUnit = TimeUnit.DAYS;
        } else {
            timeUnit = null;
        }
        return new DurationConfig(durationAmount, timeUnit);
    }

    public static IndexConfig createIndexConfig(String name, int type, List<String> attributes,
                                                BitmapIndexOptions bitmapIndexOptions) {
        IndexType type0 = IndexType.getById(type);

        return new IndexConfig()
                .setName(name)
                .setType(type0)
                .setAttributes(attributes)
                .setBitmapIndexOptions(bitmapIndexOptions);
    }

    public static BitmapIndexOptions createBitmapIndexOptions(String uniqueKey, int uniqueKeyTransformation) {
        UniqueKeyTransformation resolvedUniqueKeyTransformation = UniqueKeyTransformation.fromId(uniqueKeyTransformation);
        return new BitmapIndexOptions().setUniqueKey(uniqueKey).setUniqueKeyTransformation(resolvedUniqueKeyTransformation);
    }

    public static ClientBwListEntryDTO createClientBwListEntry(int type, String value) {
        ClientBwListEntryDTO.Type entryType = ClientBwListEntryDTO.Type.getById(type);
        if (entryType == null) {
            throw new HazelcastException("Unexpected client B/W list entry type = [" + type + "]");
        }
        return new ClientBwListEntryDTO(entryType, value);
    }

    public static EndpointQualifier createEndpointQualifier(int type, String identifier) {
        ProtocolType protocolType = ProtocolType.getById(type);
        if (protocolType == null) {
            throw new HazelcastException("Unexpected protocol type = [" + type + "]");
        }
        return EndpointQualifier.resolve(protocolType, identifier);
    }

    public static SqlColumnMetadata createSqlColumnMetadata(String name, int type, boolean isNullableExists, boolean nullability) {
        SqlColumnType sqlColumnType = SqlColumnType.getById(type);

        if (sqlColumnType == null) {
            throw new HazelcastException("Unexpected SQL column type = [" + type + "]");
        }

        if (isNullableExists) {
            return new SqlColumnMetadata(name, sqlColumnType, nullability);
        }

        return new SqlColumnMetadata(name, sqlColumnType, true);
    }
}


text:
package kiwi.service.config;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import javax.faces.context.FacesContext;
import javax.persistence.spi.PersistenceUnitTransactionType;
import javax.servlet.http.HttpServletRequest;

import kiwi.api.config.ConfigurationServiceLocal;
import kiwi.api.config.ConfigurationServiceRemote;
import kiwi.api.event.KiWiEvents;
import kiwi.api.extension.KiWiApplication;
import kiwi.model.Constants;
import kiwi.model.user.User;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.MapConfiguration;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.hibernate.ejb.Ejb3Configuration;
import org.hibernate.ejb.packaging.PersistenceMetadata;
import org.hibernate.ejb.packaging.PersistenceXmlLoader;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Create;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Startup;
import org.jboss.seam.annotations.Synchronized;
import org.jboss.seam.annotations.intercept.BypassInterceptors;
import org.jboss.seam.contexts.Contexts;
import org.jboss.seam.core.Conversation;
import org.jboss.seam.core.Events;
import org.jboss.seam.log.Log;
import org.jboss.seam.web.ServletContexts;

/**
 * @author Sebastian Schaffert
 *
 */
@Name("configurationService")
@Scope(ScopeType.APPLICATION)
@AutoCreate
@Synchronized
@Startup(depends="org.jboss.seam.core.applicationContext")
public class ConfigurationServiceImpl implements ConfigurationServiceLocal, ConfigurationServiceRemote {

    private static final double VERSION = 0.9;

    // default configuration (components names)
    private static final String[] savelets_source = {
        "kiwi.service.render.savelet.ExtractLinksSavelet",
        "kiwi.service.render.savelet.HtmlCleanerSavelet"
    };

    private static final String[] savelets_text = {
        "kiwi.service.render.savelet.NavigationalLinksSavelet",
        "kiwi.service.render.savelet.RdfaSavelet",
        "kiwi.service.render.savelet.FragmentsSavelet",
        "kiwi.service.render.savelet.ComponentSavelet"
    };

    private static final String[] renderlets_html_xom = {
        "kiwi.service.render.renderlet.ComponentRenderlet",
		"kiwi.service.render.renderlet.ComponentDisplayRenderlet",
        "kiwi.service.render.renderlet.RdfaRenderlet",
        "kiwi.service.render.renderlet.HtmlLinkRenderlet",
        "kiwi.service.render.renderlet.HtmlRdfaRenderlet",
        "kiwi.service.render.renderlet.HtmlFragmentRenderlet",
        "kiwi.service.render.renderlet.ImageLinkRenderlet",
        "kiwi.service.render.renderlet.QueryRenderlet"
    };

    private static final String[] renderlets_editor_xom = {
        "kiwi.service.render.renderlet.ComponentRenderlet",
        "kiwi.service.render.renderlet.RdfaRenderlet",
        "kiwi.service.render.renderlet.EditorLinkRenderlet"
    };

    private static final String[] renderlets_annotation_xom = {
        "kiwi.service.render.renderlet.HtmlLinkRenderlet",
        "kiwi.service.render.renderlet.AnnotationLinksRenderlet"
    };

    @Logger
    private Log log;

 	private String configFile;

 	private Configuration config;
 	private HashMap<String,Configuration> userConfigurations;

 	public static boolean needsSetup      = false;
 	public static boolean setupInProgress = false;
 	public static boolean configurationInProgress = false;

 	// indicates whether we are in testing mode
 	public static boolean testing = false;

    /**
     * Transforms a given path from relative path to an absolute
     * path. More precisely if the given path
     * argument does not start with / then the given path is
     * considered relative path and it is prefixed with the
     * current running directory.

     * If the path starts with / then the same string is
     * returned.
     *
     * @param path the path to analyze.
     * @return a absolute path, if the given path
     *         argument starts with / character or the same
     *         String if it starts.
     */
    private String getPath(String path) {

        if (new File(path).isAbsolute()) {
            return path;
        }

        final String prefix = System.getProperty("user.dir");
        final StringBuffer result = new StringBuffer(prefix);
        result.append(File.separator);
        result.append(path);

        return result.toString();
    }

	@Create
	public void initialise() {
		log.info("KiWi ConfigurationService starting up ...");
		ConfigurationServiceImpl.configurationInProgress = true;

		HashMap<String,String> persistenceProperties = initPersistenceConfiguration();

		// initialise Apache Commons Configuration using a XML-file-based configuration
		if(persistenceProperties.get("kiwi.config") != null) {
			configFile = persistenceProperties.get("kiwi.config");
		} else if(persistenceProperties.get("kiwi.work.dir") != null) {
			configFile = persistenceProperties.get("kiwi.work.dir") + File.separator + "system-config.properties";
		}
		try {
			File f = new File(configFile);
			if(!f.exists()) {
				f.createNewFile();
			}
			config = new PropertiesConfiguration(f);
		} catch (Exception e) {
			log.error("error while initialising configuration: #0; creating memory-only configuration",e.getMessage());
			log.error(e);
			config = new MapConfiguration(new HashMap());
		}

		// copy over persistence.xml configuration
		for(String key : persistenceProperties.keySet()) {
			config.setProperty(key, persistenceProperties.get(key));
		}

		userConfigurations = new HashMap<String, Configuration>();

		if(persistenceProperties.get("kiwi.work.dir") != null) {
			File f = new File(persistenceProperties.get("kiwi.work.dir") + File.separator + "config");
			f.mkdirs();
		}

		if (config.containsKey("kiwi.solr.home")) {
		    // in this way the solr can use relative and absolute
            // path.
            final String solrHomeConf = getConfiguration("kiwi.solr.home");
            final String realPath = getPath(solrHomeConf);
            System.setProperty("solr.solr.home", realPath);
		} else {
			System.setProperty("solr.solr.home", getWorkDir() + "/solr");
		}

		System.setProperty("solr.data.dir",System.getProperty("solr.solr.home")+"/data");

//		if(version.getStringValue() == null || !version.getStringValue().equals(VERSION)) {

		// if the setup configuration is not yet set, this indicates that the system needs
		// setup; we set the appropriate flag in the application context; this flag is processed
		// by CheckSetupFilter and redirects to the setup process
		if(!config.containsKey("kiwi.setup")) {
			ConfigurationServiceImpl.needsSetup = true;
		}

		if (!config.containsKey("kiwi.version") || VERSION > config.getDouble("kiwi.version")) {
			log.info("no configuration found; initialising with default values ...");

			// initialise configuration
			setDoubleConfiguration("kiwi.version",VERSION);

			initWiklet("savelets.source", savelets_source);
			initWiklet("savelets.text", savelets_text);
			initWiklet("savelets.media", new String[0]);

			initWiklet("renderlets.html.source", new String[0]);
			initWiklet("renderlets.html.xom", renderlets_html_xom);

			initWiklet("renderlets.editor.source", new String[0]);
			initWiklet("renderlets.editor.xom", renderlets_editor_xom);

			initWiklet("renderlets.annotation.source", new String[0]);
			initWiklet("renderlets.annotation.xom", renderlets_annotation_xom);

			initWiklet("renderlets.media", new String[0]);

			//entityManager.flush();
		}

		setConfiguration(Constants.CFG_RELATIVE_PATH,"seam/resource/services");

		Events.instance().raiseAsynchronousEvent(KiWiEvents.CONFIGURATIONSERVICE_INIT,"init");
		Events.instance().raiseAsynchronousEvent(KiWiEvents.CONFIGURATIONSERVICE_CREATE_ADMIN,"init");
		// load the default stored procedures
		Events.instance().raiseAsynchronousEvent("loadDefaultStoredprocedures");
	}

	private void initWiklet(String configurationName, String[] componentNames) {
		List<String> componentNamesConfig = new LinkedList<String>();

        for(String cmp_name : componentNames) {
            componentNamesConfig.add(cmp_name);
        }
        setConfiguration(configurationName,componentNamesConfig);

    }

    private HashMap<String,String> initPersistenceConfiguration() {
        log.info("KiWi Configuration Service: looking up Hibernate configuration...");

        HashMap<String,String> result = new HashMap<String, String>();

        final Ejb3Configuration cfg = new Ejb3Configuration();
        try {
            final Enumeration<URL> xmls = Thread.currentThread()
            .getContextClassLoader()
            .getResources( "META-INF/persistence.xml" );
            if ( ! xmls.hasMoreElements() ) {
                log.info( "Could not find any META-INF/persistence.xml file in the classpath");
            }
            while ( xmls.hasMoreElements() ) {
                final URL url = xmls.nextElement();
                log.info( "Analysing persistence.xml: #0", url );
                try {
                    final List<PersistenceMetadata> metadataFiles = PersistenceXmlLoader.deploy(
                            url,
                            new HashMap(),
                            cfg.getHibernateConfiguration().getEntityResolver(),
                            PersistenceUnitTransactionType.RESOURCE_LOCAL );
                    for ( final PersistenceMetadata metadata : metadataFiles ) {

                        for(final Object key : metadata.getProps().keySet()) {
                            if("kiwi".equalsIgnoreCase(key.toString().substring(0, 4))) {
                                log.info( "#0 = #1", key, metadata.getProps().get(key) );
                                result.put(key.toString(), metadata.getProps().get(key).toString());
                            }
                        }
                    }
                } catch(Exception ex) {
                    log.error("error reading #0: is this a valid persistence configuration?",url.toString());
                }
            }
        } catch(final Exception ex) {
            log.error("could not read persistence.xml",ex);
        }
        return result;
    }

    @BypassInterceptors
	public String getSetupPage() {
		return getConfiguration("setupPage_1", getBaseUri()+"/content/SetupPage");
	}

	/* (non-Javadoc)
	 * @see kiwi.api.kspace.ConfigurationService#getStartPage()
	 */
    @BypassInterceptors
	public String getStartPage() {
		return getConfiguration("startpage", getBaseUri()+"/content/FrontPage");
	}

    /**
     * Get the base URI out of the current request. The base URI
     * is used e.g. to generate URIs of internal content items
     *
     * @see kiwi.api.config.ConfigurationService#getBaseUri()
     */
	@BypassInterceptors
	public String getBaseUri() {

		String baseUri = (String) Contexts.getSessionContext().get("baseUri");

		if(baseUri == null) {
			final ServletContexts servletContexts = ServletContexts.getInstance();
			final HttpServletRequest request = servletContexts.getRequest();

			if(request != null && request.getScheme() != null && request.getServerName() != null) {
				baseUri = request.getScheme() + "://" + request.getServerName();
				if(!(
		             (request.getScheme()=="http" && request.getServerPort()==80) ||
		             (request.getScheme()=="https" && request.getServerPort()==443)
		             )){
		            baseUri += (":" + request.getServerPort());
				}
			    baseUri+= request.getContextPath();
			} else {
				return "http://localhost";
			}
			Contexts.getSessionContext().set("baseUri", baseUri);
		}
		return baseUri;
	}

	private String serverUri;

	@BypassInterceptors
	public String getServerUri() {
		if(serverUri == null) {
			final ServletContexts servletContexts = ServletContexts.getInstance();
			final HttpServletRequest request = servletContexts.getRequest();

			if(request != null) {
				serverUri = request.getScheme() + "://" + request.getServerName();
				if(!(
		             (request.getScheme()=="http" && request.getServerPort()==80) ||
		             (request.getScheme()=="https" && request.getServerPort()==443)
		             )){
		            serverUri += (":" + request.getServerPort());
				}
				serverUri += "/";
			} else {
				return "http://localhost/";
			}
		}

	    return serverUri;
	}

	/* (non-Javadoc)
	 * @see kiwi.api.config.ConfigurationService#isConfigurationSet(java.lang.String)
	 */
	@Override
    @BypassInterceptors
	public boolean isConfigurationSet(String key) {
		return config.containsKey(key);
	}

	/**
	 *
	 *
	 */
	@Override
    @BypassInterceptors
	public String getConfiguration(String key) {
		return config.getString(key);
	}

	@Override
    @BypassInterceptors
	public String getConfiguration(String key, String defaultValue) {
		return config.getString(key, defaultValue);
	}

	@Override
    @BypassInterceptors
	public double getDoubleConfiguration(String key) {
		return config.getDouble(key, 0.0);
    }

	@Override
    @BypassInterceptors
	public double getDoubleConfiguration(String key, double defaultValue) {
		return config.getDouble(key, defaultValue);
    }

	/* (non-Javadoc)
	 * @see kiwi.api.config.ConfigurationService#setDoubleConfiguration(java.lang.String, double)
	 */
	@Override
    @BypassInterceptors
	public void setDoubleConfiguration(String key, double value) {
		config.setProperty(key, value);
		save();
		Events.instance().raiseEvent("configurationChanged");
	}

	@Override
    @BypassInterceptors
	public int getIntConfiguration(String key) {
		return config.getInt(key, 0);
    }

	@Override
    @BypassInterceptors
	public int getIntConfiguration(String key, int defaultValue) {
		return config.getInt(key, defaultValue);
    }

	/* (non-Javadoc)
	 * @see kiwi.api.config.ConfigurationService#setIntConfiguration(java.lang.String, int)
	 */
	@Override
	public void setIntConfiguration(String key, int value) {
		config.setProperty(key, value);
		save();
		Events.instance().raiseEvent("configurationChanged");
	}

	@Override
    @BypassInterceptors
	public boolean getBooleanConfiguration(String key) {
		return config.getBoolean(key, true);
    }

	@Override
    @BypassInterceptors
	public boolean getBooleanConfiguration(String key, boolean defaultValue) {
		return config.getBoolean(key, defaultValue);
    }

	/* (non-Javadoc)
	 * @see kiwi.api.config.ConfigurationService#setIntConfiguration(java.lang.String, int)
	 */
	@Override
	public void setBooleanConfiguration(String key, boolean value) {
		config.setProperty(key, value);
		save();
		Events.instance().raiseEvent("configurationChanged");
	}

	/* (non-Javadoc)
	 * @see kiwi.api.config.ConfigurationService#getListConfiguration(java.lang.String)
	 */
	@Override
    @BypassInterceptors
	public List<String> getListConfiguration(String key) {
		return config.getList(key,Collections.EMPTY_LIST);
	}

	/* (non-Javadoc)
	 * @see kiwi.api.config.ConfigurationService#getListConfiguration(java.lang.String, java.util.List)
	 */
	@Override
    @BypassInterceptors
	public List<String> getListConfiguration(String key, List<String> defaultValue) {
		return config.getList(key, defaultValue);
	}

	/* (non-Javadoc)
	 * @see kiwi.api.config.ConfigurationService#setListConfiguration(java.lang.String, java.util.List)
	 */
	@Override
	public void setListConfiguration(String key, List<String> value) {
		config.setProperty(key, value);
		save();
		Events.instance().raiseEvent("configurationChanged");
	}

	public void removeConfiguration(String key) {
		config.clearProperty(key);
	}

	public void setConfiguration(String key, String value) {
		config.setProperty(key, value);
		save();
		Events.instance().raiseEvent("configurationChanged");
	}

	@Override
	public void setConfiguration(String key, List<String> values) {
		config.setProperty(key,values);
		save();
		Events.instance().raiseEvent("configurationChanged");
	}

	public Configuration getUserConfiguration(User user) {
		Configuration userConfig = userConfigurations.get(user.getLogin());
		if(userConfig == null) {

			String userConfigFile = getConfiguration("kiwi.work.dir") + File.separator + "config" + File.separator + user.getLogin() + ".conf.xml";

			try {
				File f = new File(userConfigFile);
				if(f.exists()) {
					f.createNewFile();
				}
				userConfig = new PropertiesConfiguration(f);
			} catch(Exception ex) {
				log.error("could not create user configuration in file #0: #1",userConfigFile,ex.getMessage());
				userConfig = new MapConfiguration(new HashMap());
			}
			userConfigurations.put(user.getLogin(),userConfig);
		}
		return userConfig;
	}

	/* (non-Javadoc)
	 * @see kiwi.api.config.ConfigurationService#isUserConfigurationSet(kiwi.model.user.User, java.lang.String)
	 */
	@Override
	public boolean isUserConfigurationSet(User user, String key) {
		return getUserConfiguration(user).containsKey(key);
	}

	@Override
	public String getUserConfiguration(User user, String key, String defaultValue) {
		return getUserConfiguration(user).getString(key, defaultValue);
	}

	@Override
	public String getUserConfiguration(User user, String key) {
		return getUserConfiguration(user).getString(key);
	}

	/* (non-Javadoc)
	 * @see kiwi.api.config.ConfigurationService#getUserListConfiguration(kiwi.model.user.User, java.lang.String)
	 */
	@Override
	public List getUserListConfiguration(User user, String key) {
		return getUserListConfiguration(user, key, Collections.EMPTY_LIST);
	}

	/* (non-Javadoc)
	 * @see kiwi.api.config.ConfigurationService#getUserListConfiguration(kiwi.model.user.User, java.lang.String, java.util.List)
	 */
	@Override
	public List getUserListConfiguration(User user, String key, List defaultValue) {
		return getUserConfiguration(user).getList(key, defaultValue);
	}

	@Override
	public void removeUserConfiguration(User user, String key) {
		getUserConfiguration(user).clearProperty(key);
	}

	@Override
	public void setUserListConfiguration(User user, String key, List<String> values) {
		getUserConfiguration(user).setProperty(key, values);
	}

	@Override
	public void setUserConfiguration(User user, String key, String value) {
		getUserConfiguration(user).setProperty(key, value);
	}

//	@Override
//	public void setUserRSAConfiguration(User user, String key, String value) {
//		UserConfiguration conf = getUserConfiguration(user,key);
//		if(conf == null) {
//			conf = new UserConfiguration(user,key);
//		}
//		conf.setEncryptedKey(value);
//		setUserConfiguration(conf);
//	}

	/**
     * The work directory of the Sesame 2 native store. Sesame will create its own subdirectory
     * beneath this directory called "triples" and store the native database there.
     */
    @BypassInterceptors
	public String getWorkDir() {
		final String value = getConfiguration("kiwi.work.dir");
		return value!=null?value:"/tmp/kiwi";
	}

	@Override
	@BypassInterceptors
	public String getApplicationPrefix(KiWiApplication app) {
		return "kiwi.app."+app.getIdentifier()+".";
	}

	/**
     * redirect to the IDP server,
     * which should then redirect to the FoafSslAuthenticationServlet
     */
    public void redirectToIDP() {

        /**
         * end conversation
         */
        Conversation.instance().end(true);

        try {
            FacesContext.getCurrentInstance().getExternalContext()
                .redirect(getBaseUri()+"/seam/resource/idp?authreqissuer="+
                        getBaseUri()+"/seam/resource/foafSsl");
        } catch (IOException e) {
            log.error("Redirect was not possible: #0 ", e.getMessage());
            e.printStackTrace();
        }
    }

    public void save() {
    	if(config instanceof PropertiesConfiguration) {
    		try {
				((PropertiesConfiguration)config).save();
			} catch (ConfigurationException e) {
				log.error("could not save system configuration: #0",e.getMessage());
			}
    	}
    }

    public void save(User user) {
    	Configuration userConfig = getUserConfiguration(user);

    	if(userConfig instanceof PropertiesConfiguration) {
    		try {
				((PropertiesConfiguration)userConfig).save();
			} catch (ConfigurationException e) {
				log.error("could not save user configuration for user #0: #1",user.getLogin(),e.getMessage());
			}
    	}
    }
}


text:
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <assert.h>
#include "linked_list.h"

LINKED_LIST_CONTAINER* initialize_empty_linked_list(int type_id) {
     LINKED_LIST_CONTAINER *new_list = (LINKED_LIST_CONTAINER *) malloc(sizeof(LINKED_LIST_CONTAINER));
     memset(new_list, 0, sizeof(LINKED_LIST_CONTAINER));
     new_list->head = NULL;
     new_list->tail = NULL;
     new_list->length = 0;
     new_list->type_id = type_id;
     assert(new_list->head == new_list->tail);
     return new_list;
}

void free_linked_list_element(NODE *node) {
     assert(node != NULL);
     if (node->free) {
          free(node->value);
     }
     free(node);
}

void linked_list_map(LINKED_LIST_CONTAINER *container, void(*callback) (NODE *node)) {
     unsigned int num_elements_left = container->length;
     NODE *node = container->head;
     NODE *next_node = NULL;
     if (NULL == node) {
          return;
     }
     while (num_elements_left > 0) {
          next_node = node->next;
          if (NULL == next_node) {
               break;
          }
          callback(node);

          node = next_node;
          num_elements_left--;
     }
     return;
}

void* linked_list_popleft(LINKED_LIST_CONTAINER* container, size_t *node_size) {
     unsigned int num_elements_left = container->length;
     if (num_elements_left == 0) {
          return NULL;
     }
     NODE *node = container->head;
     NODE *next_node = NULL;
     if (node == NULL) {
          return NULL;
     }
     next_node = node->next;
     if (next_node != NULL) {
          next_node->prev = NULL;
     }

     container->head = next_node;
     if (container->tail == node) {
          container->tail = next_node;
     }
     container->length = num_elements_left - 1;
     *node_size = node->value_size;
     return node->value;
}

/*
* Add to the buffer with a two pass scan provided by callback, which returns true or false
*/

LINKED_LIST_CONTAINER* linked_list_select(LINKED_LIST_CONTAINER *container, bool(*callback)(NODE *)) {
     LINKED_LIST_CONTAINER* retval = (LINKED_LIST_CONTAINER *) malloc(sizeof(LINKED_LIST_CONTAINER));
     memset(retval, 0, sizeof(LINKED_LIST_CONTAINER));
     retval->length = 0;
     retval->head = NULL;
     retval->tail = NULL;

     NODE *node = container->head;
     NODE *new_node = NULL;

     while (NULL != node) {
          if (callback(node)) {
               new_node = (NODE *)malloc(sizeof(NODE));
               memcpy(new_node, node, sizeof(NODE));
               new_node->value = (void *) malloc(node->value_size);
               memcpy(new_node->value, node->value, node->value_size);

               if (NULL == retval->head) {
                    new_node->prev = NULL;
                    new_node->next = NULL;
                    retval->head = new_node;
                    retval->tail = new_node;
               } else {
                    new_node->prev = retval->tail;
                    new_node->next = NULL;
                    retval->tail->next = new_node;
                    retval->tail = new_node;
               }
               retval->length++;
          }
          node = node->next;
     }
     return retval;
}

void linked_list_free(LINKED_LIST_CONTAINER *container) {
     linked_list_map(container, &free_linked_list_element);
     free(container);
}

void linked_list_append(
          LINKED_LIST_CONTAINER *container,
          void *value, size_t value_size, bool free_value,
          bool direction_tail) {
     DEBUG_PRINTF(("(linked_list_append) Num elements %d\n", container->length));

     NODE *node = (NODE *)malloc(sizeof(NODE));
     memset(node, 0, sizeof(NODE));
     node->value = value;
     node->value_size = value_size;
     node->free = free_value;
     node->next = NULL;
     node->prev = NULL;

     if (NULL == container->head) {
          DEBUG_PRINTF(("(linked_list_append) Head assigned.\n"));
          container->head = node;
     }
     if (NULL == container->tail) {
          DEBUG_PRINTF(("(linked_list_append) Tail assigned. %p\n", node));
          container->tail = node;
     }

     if (container->length) {
          if (direction_tail) {
               /* ensure the new tail considers the previous tail it's prev
               and the next element NULL
               */
               node->prev = container->tail;
               node->next = NULL;
               /* Ensure the current tail (before we change it) considers the new node it's successor */
               DEBUG_PRINTF(("(linked_list_append) Current Tail Memory Address: %p\n", container->tail));
               container->tail->next = node;

               /* Ensure the tail is set to the new node */
               container->tail = node;
          } else {
               /* ensure the new head considers the previous head it's prev
               and the next element NULL
               */
               node->prev = NULL;
               node->next = container->head;
               /* Ensure the current head (before we change it) considers the new node it's successor */
               container->head->prev = node;

               /* Ensure the head is set to the new node */
               container->head = node;
          }
     }
     container->length += 1;
     return;
}

ARRAY* linked_list_to_array(LINKED_LIST_CONTAINER *container) {
     unsigned int num_elements_left = container->length;
     unsigned int i = 0;
     ARRAY *result = (ARRAY *) malloc(sizeof(ARRAY));
     memset(result, 0, sizeof(ARRAY));
     if (container->length == 0) {
          return result;
     }

     assert(container->length <= MAXIMUM_CONTAINER_LENGTH);
     NODE *node = container->head;
     NODE *new_node;
     NODE *nodes = (NODE *) malloc(sizeof(NODE) * (container->length));
     result->nodes = nodes;
     result->length = container->length;

     while (i < num_elements_left) {
          memcpy(&(nodes[i]), node, sizeof(NODE));
          new_node = &nodes[i];
          new_node->free = node->free;
          new_node->value = (void *) malloc(node->value_size);
          memcpy(new_node->value, node->value, node->value_size);
          node = node->next;
          i++;
     }
     return result;
}


text:
from pudzu.charts import *

df = pd.read_csv("datasets/flagsgyw.csv")
groups = list(remove_duplicates(df.group))
array = [[dict(r) for _,r in df.iterrows() if r.group == g] for g in groups]
data = pd.DataFrame(array, index=list(remove_duplicates(df.group)))

FONT = calibri or sans
fg, bg="black", "#EEEEEE"
default_img = "https://s-media-cache-ak0.pinimg.com/736x/0d/36/e7/0d36e7a476b06333d9fe9960572b66b9.jpg"

N = 1

def process(d):
    if not d or d["name"] == "_": return None
    description = get_non(d, 'description')
    description = "({})".format(description) if description else " "
    flag = Image.from_url_with_cache(get_non(d, 'image', default_img)).to_rgba()
    flag = flag.resize_fixed_aspect(height=N*198) if flag.width / flag.height < 1.3 else flag.resize((N*318,N*198))
    flag = flag.pad(0 if "coat" in d['group'] else (N,0,0,0) if "Maratha" in str(d['name']) else N, "grey")
    return Image.from_column([
      Image.from_text_bounded(d['name'].replace(r"\n","\n"), (N*320 if "Switzerland" not in description else N*200,N*200), N*32, partial(FONT, bold=True), beard_line=True, align="center", fg=fg),
      Image.from_text_bounded(description, (N*320 if "Switzerland" not in description else N*200,N*200), N*24, partial(FONT, italics=True), align="center", fg=fg),
      flag
      ], padding=N*2, bg=bg, equal_widths=True)

title = Image.from_text(f"Green, White and Yellow flags".upper(), FONT(N*80, bold=True), fg=fg, bg=bg).pad(N*40, bg)

grid = grid_chart(data, process, padding=(N*10,N*20), fg=fg, bg=bg, yalign=(0.5,1,0.5), row_label=lambda r: None if data.index[r].startswith("_") else Image.from_text("{}".format(data.index[r].replace(r"\n","\n")).upper(), FONT(N*32, bold=True), align="center", line_spacing=N*3))
img = Image.from_column([title, grid, Rectangle((0,N*50))], bg=bg)
img.place(Image.from_text("/u/Udzu", FONT(N*24), fg=fg, bg=bg, padding=5).pad((N*1,N*1,0,0), fg), align=1, padding=N*5, copy=False)
img.save("output/flagsgyw.png")


text:
angular.module("ngTools").directive('markdown', function()
{
    var converter = new Showdown.converter();

    return {
        restrict: 'E',
        require: '?ngModel',
        link:  function(scope, element, attrs, model)
        {
            // Check for extensions
            var extAttr = attrs['extensions'];
            var callPrettyPrint = false;
            if(extAttr)
            {
                var extensions = [];

                // Convert the comma separated string into a list.
                extAttr.split(',').forEach(function(val)
                {
                    // Strip any whitespace from the beginning or end.
                    extensions.push(val.replace(/^\s+|\s+$/g, ''));
                });

                if(extensions.indexOf('prettify') >= 0)
                {
                    callPrettyPrint = true;
                } // end if

                // Create a new converter.
                converter = new Showdown.converter({extensions: extensions});
            } // end if

            // Check for option to strip whitespace
            var stripWS = attrs['strip'];
            stripWS = String(stripWS).toLowerCase() == 'true';

            // Check for option to translate line breaks
            var lineBreaks = attrs['lineBreaks'];
            lineBreaks = String(lineBreaks).toLowerCase() == 'true';

            var render = function()
            {
                var htmlText = "";
                var val = "";

                // Check to see if we're using a model.
                if(attrs['ngModel'])
                {
                    if (model.$modelValue)
                    {
                        val = model.$modelValue;
                    } // end if
                }
                else
                {
                    val = element.text();
                } // end if

                if(stripWS)
                {
                    val = val.replace(/^[ /t]+/g, '').replace(/\n[ /t]+/g, '\n');
                } // end stripWS

                if (lineBreaks) {
                    val = val.replace(/
/g, '\n');
                } // end lineBreaks

                // Compile the markdown, and set it.
                htmlText = converter.makeHtml(val);
                element.html(htmlText);

                if(callPrettyPrint)
                {
                    prettyPrint();
                } // end if
            };

            if(attrs['ngModel'])
            {
                scope.$watch(attrs['ngModel'], render);
            } // end if

            render();
        } // end link
    }
}); // end markdown directive


text:
@interface OANameStringMatcher : NSObject<OAStringMatcher>

- (instancetype)initWithLastWord:(NSString *)lastWordTrim mode:(StringMatcherMode)mode;

- (BOOL)matchesMap:(NSArray<NSString *>  *)map;

@end


text:
package com.baraccasoftware.securenotes.app;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * Created by angelo on 25/02/14.
 */
public class InfoFragment extends Fragment {

    TextView code;
    InfoActivity mActivity;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mActivity = (InfoActivity) activity;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_info, container, false);

        code = (TextView) rootView.findViewById(R.id.textView_code);
        code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               startBroserActivity(code.getText().toString());
            }
        });
        return rootView;
    }
    private void startBroserActivity(String url){
        String mUrl = "https://"+url;
        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(mUrl));
        startActivity(browserIntent);
    }
}