text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Puccinia tagana Maire

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
package com.justjames.beertour.beer;

import java.util.Collection;

import javax.transaction.Transactional;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.justjames.beertour.Brewception;
import com.justjames.beertour.beer.Beer;
import com.justjames.beertour.beer.BeerSvc;
import com.justjames.beertour.security.LoginSvc;
import com.justjames.beertour.security.NotAuthorizedException;
import com.justjames.beertour.security.Role;
import com.justjames.beertour.security.UserRealm;
import com.justjames.beertour.shiro.AbstractShiroTest;
import com.justjames.beertour.user.User;
import com.justjames.beertour.user.UserSvc;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class BeerSvcTest extends AbstractShiroTest {

		@Autowired BeerSvc beerSvc;
		@Autowired UserRealm userRealm;
		@Autowired UserSvc userSvc;
		@Autowired LoginSvc loginSvc;
		SecurityManager securityManager = null;

		@Before
		public void setUp() {
			if (securityManager == null) {
				securityManager =  new DefaultSecurityManager(userRealm);
				setSecurityManager(securityManager);
			}
		}

		@After
		public void tearDownSubject() {
			Subject subject = SecurityUtils.getSubject();
			subject.logout();
			clearSubject();
		}

		public User addTestUser(String name,Role role) {
			User user = new User();
			user.setEmail( String.format("%s@just-james.com", name));
			user.setName(name);
			user.setPassword("1234");
			user.setRole(role);
			user = userSvc.addUser(user);
			loginSvc.login(user.getEmail(), user.getPassword());
			return user;
		}

		/* In order to sell beer
		 * I want to see the list of all the beers I have
		 * so that I can see what beers are available.
		 */
		@Test
		public void listBeers() {
			Collection<Beer> allBeers = beerSvc.getAll();
			Assert.assertNotNull(allBeers);
		}

		/* In order to sell beer
		 * I want to add a new beer
		 * so that it will be available to customers.
		 */
		@Test
		@Transactional
		public void addBeer() {
			addTestUser("addBeer",Role.ADMIN);
			Beer newBeer = new Beer();
			newBeer.setName("Jimmy Light");
			newBeer.setBrewery("Jimmy Brewing");
			newBeer.setCountry("US");
			Beer savedBeer = beerSvc.add(newBeer);
			Assert.assertNotNull(savedBeer);
			Assert.assertTrue(savedBeer.getId() > 0);
		}

		@Test
		@Transactional
		public void updateExistingBeerAsAdmin() {
			addTestUser("updateExistingBeerAsAdmin",Role.ADMIN);
			Collection<Beer> allBeers = beerSvc.getAll();
			Beer beer = allBeers.iterator().next();
			BeerUpdateTO beerTO = new BeerUpdateTO();
			beerTO.setId(beer.getId());
			beerTO.setName(beer.getName());
			beerTO.setBrewery(beer.getBrewery());
			beerTO.setOutOfStock(true);
			Beer updatedBeer = beerSvc.update(beerTO);
			Assert.assertTrue(updatedBeer.isOutOfStock());
		}

		@Test(expected=NotAuthorizedException.class)
		@Transactional
		public void updateExistingBeerAsCustomer() {
			addTestUser("updateExistingBeerAsCustomer",Role.CUSTOMER);
			Collection<Beer> allBeers = beerSvc.getAll();
			Beer beer = allBeers.iterator().next();
			BeerUpdateTO beerTO = new BeerUpdateTO();
			beerTO.setId(beer.getId());
			beer.setOutOfStock(true);
			beerSvc.update(beerTO);
		}

		@Test(expected=Brewception.class)
		@Transactional
		public void updateInvalidBeerAsAdmin() {
			addTestUser("updateInvalidBeerAsAdmin",Role.ADMIN);
			BeerUpdateTO newBeer = new BeerUpdateTO();
			newBeer.setId(-1);
			beerSvc.update(newBeer);
		}

}


text:
package com.dx168.patchserver.manager.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by tong on 16/10/31.
 */
@Service
public class FacadeService {
    private static final Logger LOG = LoggerFactory.getLogger(FacadeService.class);

    @Value("${tm-facade-url}")
    private String facadrUrl;

    public void clearCache() {
        String url = (facadrUrl.endsWith("/") ? facadrUrl : facadrUrl + "/") + "api/clearCache";
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setRequestMethod("GET");
            conn.connect();

            byte[] buffer = org.apache.commons.io.IOUtils.toByteArray(conn.getInputStream());
            LOG.info("clearCache res: " + new String(buffer));
        } catch (Exception e) {
            LOG.error("通知facade清空缓存失败: " + e.getMessage());
        }
    }
}


text:
package sias.model.service;

import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import sias.model.ConnectionManager;
import sias.model.base.service.BaseFormaIngressoService;
import sias.model.dao.FormaIngressoDAO;
import sias.model.pojo.FormaIngresso;

public class FormaIngressoService implements BaseFormaIngressoService {

    @Override
    public void create(FormaIngresso pojo) throws Exception {
        Connection conn = ConnectionManager.getInstance().getConnection();
        try {
            FormaIngressoDAO dao = new FormaIngressoDAO();
            dao.create(pojo, conn);
            conn.commit();
            conn.close();
        } catch (Exception e) {
            conn.rollback();
            conn.close();
            throw e;
        }
    }

    @Override
    public FormaIngresso readById(Long id) throws Exception {
        Connection conn = ConnectionManager.getInstance().getConnection();
        FormaIngresso formaIngresso = null;
        try {
            FormaIngressoDAO dao = new FormaIngressoDAO();
            formaIngresso = dao.readById(id, conn);
            conn.commit();
            conn.close();
        } catch (Exception e) {
            conn.rollback();
            conn.close();
            throw e;
        }
        return formaIngresso;
    }

    @Override
    public List<FormaIngresso> readByCriteria(Map<String, Object> criteria) throws Exception {
        Connection conn = ConnectionManager.getInstance().getConnection();
        List<FormaIngresso> lista = null;
        try {
            FormaIngressoDAO dao = new FormaIngressoDAO();
            lista = dao.readByCriteria(criteria, conn);
            conn.commit();
            conn.close();
        } catch (Exception e) {
            conn.rollback();
            conn.close();
            throw e;
        }
        return lista;
    }

    @Override
    public void update(FormaIngresso pojo) throws Exception {
        Connection conn = ConnectionManager.getInstance().getConnection();
        try {
            FormaIngressoDAO dao = new FormaIngressoDAO();
            dao.update(pojo, conn);
            conn.commit();
            conn.close();
        } catch (Exception e) {
            conn.rollback();
            conn.close();
            throw e;
        }
    }

    @Override
    public void delete(Long id) throws Exception {
        Connection conn = ConnectionManager.getInstance().getConnection();
        try {
            FormaIngressoDAO dao = new FormaIngressoDAO();
            dao.delete(id, conn);
            conn.commit();
            conn.close();
        } catch (Exception e) {
            conn.rollback();
            conn.close();
            throw e;
        }
    }

    @Override
    public Map<String, String> validateForCreate(Map<String, Object> properties) throws Exception {
        Map<String, String> errors = new HashMap<String, String>();
        if (properties != null) {
            String codigo = (String) properties.get("codigo");
            if (codigo == null || codigo.isEmpty()) {
                errors.put("codigo", "*");
            }
            String descricao = (String) properties.get("descricao");
            if (descricao == null || descricao.isEmpty()) {
                errors.put("descricao", "*");
            }
            String ativo = (String) properties.get("ativo");
            if (ativo == null || ativo.isEmpty()) {
                errors.put("ativo", "*");
            }
        }
        return errors;
    }

    @Override
    public Map<String, String> validateForUpdate(Map<String, Object> properties) throws Exception {
        return this.validateForCreate(properties);
    }

}


text:
<?php

namespace Richpolis\CategoriasGaleriaBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

use Richpolis\CategoriasGaleriaBundle\Repository\CategoriasRepository;

class GaleriasLinkVideoType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('titulo','hidden')
            ->add('thumbnail','hidden')
            ->add('posicion','hidden')
            ->add('archivo','text',array('label'=>'Link youtube o vimeo'))
            ->add('categoria','entity', array(
                'class' => 'CategoriasGaleriaBundle:Categorias',
                'query_builder' => function(CategoriasRepository $er) {
                        return $er->createQueryBuilder('u')
                                ->orderBy('u.id', 'ASC');
                },
                'property'  => 'categoria',
                'label'     => 'Categoria',
                'multiple'  => false
            ))
            ->add('tipoArchivo','hidden')

            ->add('isActive',null,array('label'=>'Activo?','required'=>false))

        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Richpolis\CategoriasGaleriaBundle\Entity\Galerias'
        ));
    }

    public function getName()
    {
        return 'richpolis_categoriasgaleriabundle_galeriaslinkvideotype';
    }
}


text:
<?php if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

class Auth extends Nip_Model
{

    /**
     * Model for Authentication
     */
    public $model = "User";

    protected $user;

    public function __construct($options = array())
    {
        parent::__construct($options);

        $this->load->model("User");
    }

    public function check()
    {
        if ($this->session->userdata('user_id')) {
            return true;
        }
        return false;
    }

    public function login($data = array())
    {

        $result = $this->{$this->model}->first($data);
        $primary = $this->{$this->model}->getPrimary();

        if ($result) {
            $this->session->set_userdata('user_id', $result->{$primary});
            $this->session->set_userdata('role_id', $result->role_id);

            return true;
        }

        return false;
    }

    public function logout()
    {
        $this->session->unset_userdata('user_id');
        $this->session->unset_userdata('role_id');

        return true;
    }

    public function user()
    {
        if ($this->check()) {

            if (empty($this->user)) {

                $user_id = $this->session->userdata('user_id');

                $user = $this->{$this->model}->first($user_id);
                $this->user = $user;

                return $user;
            } else {

                return $this->user;
            }
        }

        return null;
    }

    public function primary()
    {
        $user = $this->user();

        if ($user) {
            $primary = $user->getPrimary();

            return $user->{$primary};
        }

        return false;
    }

    public function role()
    {
        $user = $this->user();

        if ($user) {
            return $user->role_id;
        }

        return false;
    }
}


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

#include "Nebula.h"

#include "RaftManager.h"
#include "FedReplicaManager.h"
#include "ZoneServer.h"
#include "Client.h"

#include <cstdlib>

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
const time_t RaftManager::timer_period_ms = 50;

static void set_timeout(long long ms, struct timespec& timeout)
{
    std::lldiv_t d;

    d = std::div(ms, (long long) 1000);

    timeout.tv_sec  = d.quot;
    timeout.tv_nsec = d.rem * 1000000;
}

static unsigned int get_zone_servers(std::map<int, std::string>& _s);

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
/* RaftManager component life-cycle functions                                 */
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

RaftManager::RaftManager(int id, const VectorAttribute * leader_hook_mad,
        const VectorAttribute * follower_hook_mad, time_t log_purge,
        long long bcast, long long elect, time_t xmlrpc,
        const string& remotes_location):server_id(id), term(0), num_servers(0),
        commit(0), leader_hook(0), follower_hook(0)
{
    Nebula& nd    = Nebula::instance();
    LogDB * logdb = nd.get_logdb();

    std::string raft_xml, cmd, arg;

	pthread_mutex_init(&mutex, 0);

	am.addListener(this);

    // -------------------------------------------------------------------------
    // Initialize Raft variables:
    //   - state
    //   - servers
    //   - votedfor
    //   - term
    // -------------------------------------------------------------------------

    if ( logdb->get_raft_state(raft_xml) != 0 )
    {
        std::ostringstream bsr;

        bsr << "bootstrap state";

        logdb->insert_log_record(-1, -1, bsr, 0, -1);

        raft_state.replace("TERM", 0);
        raft_state.replace("VOTEDFOR", -1);

        raft_state.to_xml(raft_xml);

        logdb->update_raft_state(raft_xml);

        votedfor = -1;
        term     = 0;
    }
    else
    {
        raft_state.from_xml(raft_xml);

        raft_state.get("TERM", term);
        raft_state.get("VOTEDFOR", votedfor);
    }

    leader_id = -1;

    num_servers = get_zone_servers(servers);

	if ( server_id == -1 )
	{
        NebulaLog::log("ONE", Log::INFO, "oned started in solo mode.");
		state = SOLO;
	}
	else
	{
        NebulaLog::log("RCM", Log::INFO, "oned started in follower mode");
		state = FOLLOWER;
	}

    // -------------------------------------------------------------------------
    // Initialize Raft timers
    // -------------------------------------------------------------------------

    purge_period_ms   = log_purge * 1000;
    xmlrpc_timeout_ms = xmlrpc;

    set_timeout(bcast, broadcast_timeout);
    set_timeout(elect, election_timeout);

    // 5 seconds warm-up to start election
    clock_gettime(CLOCK_REALTIME, &last_heartbeat);
    last_heartbeat.tv_sec += 5;

    // -------------------------------------------------------------------------
    // Initialize Hooks
    // -------------------------------------------------------------------------

    if ( leader_hook_mad != 0 )
    {
        cmd = leader_hook_mad->vector_value("COMMAND");
        arg = leader_hook_mad->vector_value("ARGUMENTS");

        if ( cmd.empty() )
        {
            ostringstream oss;

            oss << "Empty COMMAND attribute in RAFT_LEADER_HOOK. Hook "
                << "not registered!";

            NebulaLog::log("ONE", Log::WARNING, oss);
        }
        else
        {
            if (cmd[0] != '/')
            {
                ostringstream cmd_os;
                cmd_os << remotes_location << "/hooks/" << cmd;
                cmd = cmd_os.str();
            }

            leader_hook = new RaftLeaderHook(cmd, arg);
        }
    }

    if ( follower_hook_mad != 0 )
    {
        cmd = follower_hook_mad->vector_value("COMMAND");
        arg = follower_hook_mad->vector_value("ARGUMENTS");

        if ( cmd.empty() )
        {
            ostringstream oss;

            oss << "Empty COMMAND attribute in RAFT_FOLLOWER_HOOK. Hook "
                << "not registered!";

            NebulaLog::log("ONE", Log::WARNING, oss);
        }
        else
        {
            if (cmd[0] != '/')
            {
                ostringstream cmd_os;
                cmd_os << remotes_location << "/hooks/" << cmd;
                cmd = cmd_os.str();
            }

            follower_hook = new RaftFollowerHook(cmd, arg);
        }
    }

    if ( state == FOLLOWER && follower_hook != 0 )
    {
        follower_hook->do_hook(0);
    }
};

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

extern "C" void * raft_manager_loop(void *arg)
{
    RaftManager * raftm;
    struct timespec timeout;

    if ( arg == 0 )
    {
        return 0;
    }

    raftm = static_cast<RaftManager *>(arg);

    timeout.tv_sec  = 0;
    timeout.tv_nsec = raftm->timer_period_ms * 1000000;

    NebulaLog::log("RCM",Log::INFO,"Raft Consensus Manager started.");

    if ( raftm->is_solo() )
    {
        raftm->am.loop();

    }
    else
    {
        raftm->am.loop(timeout);
    }

    NebulaLog::log("RCM",Log::INFO,"Raft Consensus Manager stopped.");

    return 0;
}

/* -------------------------------------------------------------------------- */

int RaftManager::start()
{
    int               rc;
    pthread_attr_t    pattr;

    pthread_attr_init (&pattr);
    pthread_attr_setdetachstate (&pattr, PTHREAD_CREATE_JOINABLE);

    NebulaLog::log("RCM",Log::INFO,"Starting Raft Consensus Manager...");

    rc = pthread_create(&raft_thread, &pattr, raft_manager_loop,(void *) this);

    return rc;
}

/* -------------------------------------------------------------------------- */

void RaftManager::finalize_action(const ActionRequest& ar)
{
    NebulaLog::log("RCM", Log::INFO, "Raft Consensus Manager...");
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
/* Server management interface                                                */
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

static unsigned int get_zone_servers(std::map<int, std::string>& _serv)
{
    Nebula& nd       = Nebula::instance();
    ZonePool * zpool = nd.get_zonepool();

    int zone_id = nd.get_zone_id();

    return zpool->get_zone_servers(zone_id, _serv);
}

int RaftManager::get_leader_endpoint(std::string& endpoint)
{
    int rc;

    pthread_mutex_lock(&mutex);

    if ( leader_id == -1 )
    {
        rc = -1;
    }
    else
    {
        std::map<int, std::string>::iterator it;

        it = servers.find(leader_id);

        if ( it == servers.end() )
        {
            rc = -1;
        }
        else
        {
            endpoint = it->second;
            rc = 0;
        }
    }

    pthread_mutex_unlock(&mutex);

    return rc;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void RaftManager::add_server(int follower_id, const std::string& endpoint)
{
    std::ostringstream oss;

	LogDB * logdb = Nebula::instance().get_logdb();

	unsigned int log_index, log_term;

    logdb->get_last_record_index(log_index, log_term);

	pthread_mutex_lock(&mutex);

    if ( state != LEADER )
    {
        pthread_mutex_unlock(&mutex);
        return;
    }

    num_servers++;
    servers.insert(std::make_pair(follower_id, endpoint));

	next.insert(std::make_pair(follower_id, log_index + 1));

	match.insert(std::make_pair(follower_id, 0));

    oss << "Starting replication and heartbeat threads for follower: "
        << follower_id;

    NebulaLog::log("RCM", Log::INFO, oss);

	replica_manager.add_replica_thread(follower_id);

	heartbeat_manager.add_replica_thread(follower_id);

	pthread_mutex_unlock(&mutex);
};

/* -------------------------------------------------------------------------- */

void RaftManager::delete_server(int follower_id)
{
    std::ostringstream oss;
    std::map<int, std::string> _servers;

	pthread_mutex_lock(&mutex);

    if ( state != LEADER )
    {
        pthread_mutex_unlock(&mutex);
        return;
    }

    num_servers--;
    servers.erase(follower_id);

	next.erase(follower_id);

	match.erase(follower_id);

    oss << "Stopping replication and heartbeat threads for follower: "
        << follower_id;

    NebulaLog::log("RCM", Log::INFO, oss);

	replica_manager.delete_replica_thread(follower_id);

	heartbeat_manager.delete_replica_thread(follower_id);

	pthread_mutex_unlock(&mutex);
};

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
/* State transitions & and callbacks                                          */
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void RaftManager::leader()
{
    Nebula& nd    = Nebula::instance();

    LogDB * logdb     = nd.get_logdb();
    AclManager * aclm = nd.get_aclm();

    FedReplicaManager * frm = nd.get_frm();

    std::map<int, std::string>::iterator it;
    std::vector<int> _follower_ids;

    int index, _applied;

    std::map<int, std::string> _servers;

    std::ostringstream oss;

    std::string raft_state_xml;

    logdb->setup_index(_applied, index);

    pthread_mutex_lock(&mutex);

    if ( state != CANDIDATE )
    {
        pthread_mutex_unlock(&mutex);
        return;
    }

    oss << "Becoming leader of zone. Last log record: " << index << " last "
        << "applied record: " << _applied;

    NebulaLog::log("RCM", Log::INFO, oss);

    next.clear();
    match.clear();

    requests.clear();

    if ( leader_hook != 0 )
    {
        leader_hook->do_hook(0);
    }

    state = LEADER;

    commit   = _applied;
    votedfor = -1;

    leader_id = server_id;

    raft_state.replace("VOTEDFOR", votedfor);

    raft_state.to_xml(raft_state_xml);

    for (it = servers.begin(); it != servers.end() ; ++it )
    {
        if ( it->first == server_id )
        {
            continue;
        }

        next.insert(std::make_pair(it->first, index + 1));

        match.insert(std::make_pair(it->first, 0));

        _follower_ids.push_back(it->first);
    }

    replica_manager.start_replica_threads(_follower_ids);
    heartbeat_manager.start_replica_threads(_follower_ids);

    pthread_mutex_unlock(&mutex);

    aclm->reload_rules();

    if ( nd.is_federation_master() )
    {
        frm->start_replica_threads();
    }

    logdb->update_raft_state(raft_state_xml);

    NebulaLog::log("RCM", Log::INFO, "oned is now the leader of zone");
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void RaftManager::follower(unsigned int _term)
{
    int lapplied, lindex;

    Nebula& nd    = Nebula::instance();
    LogDB * logdb = nd.get_logdb();

    FedReplicaManager * frm = nd.get_frm();

    std::string raft_state_xml;

    logdb->setup_index(lapplied, lindex);

    pthread_mutex_lock(&mutex);

    if ( state == LEADER && follower_hook != 0 )
    {
        follower_hook->do_hook(0);
    }

    replica_manager.stop_replica_threads();
    heartbeat_manager.stop_replica_threads();

    state = FOLLOWER;

    term     = _term;
    votedfor = -1;

    commit   = lapplied;

    leader_id = -1;

    raft_state.replace("VOTEDFOR", votedfor);
    raft_state.replace("TERM", term);

    raft_state.to_xml(raft_state_xml);

    NebulaLog::log("RCM", Log::INFO, "oned is set to follower mode");

    std::map<int, ReplicaRequest *>::iterator it;

    for ( it = requests.begin() ; it != requests.end() ; ++it )
    {
        it->second->result = false;
        it->second->timeout= false;
        it->second->message= "oned is now follower";

        it->second->notify();
    }

    next.clear();
    match.clear();

    requests.clear();

    pthread_mutex_unlock(&mutex);

    if ( nd.is_federation_master() )
    {
        frm->stop_replica_threads();
    }

    logdb->update_raft_state(raft_state_xml);
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void RaftManager::replicate_log(ReplicaRequest * request)
{
    pthread_mutex_lock(&mutex);

    if ( state != LEADER )
    {
        pthread_mutex_unlock(&mutex);
        return;
    }

    if ( num_servers <= 1 )
    {
        request->notify();

        request->result  = true;
        request->timeout = false;

        commit = request->index();
    }
    else
    {
        request->to_commit(num_servers / 2 );

        requests.insert(std::make_pair(request->index(), request));
    }

    if ( num_servers > 1 )
    {
        replica_manager.replicate();
    }

    pthread_mutex_unlock(&mutex);
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void RaftManager::replicate_success(int follower_id)
{
    std::map<int, ReplicaRequest *>::iterator it;

    std::map<int, unsigned int>::iterator next_it;
    std::map<int, unsigned int>::iterator match_it;

    Nebula& nd    = Nebula::instance();
    LogDB * logdb = nd.get_logdb();

	unsigned int db_last_index, db_last_term;

    logdb->get_last_record_index(db_last_index, db_last_term);

    pthread_mutex_lock(&mutex);

    next_it  = next.find(follower_id);
    match_it = match.find(follower_id);

    if ( next_it == next.end() || match_it == match.end() )
    {
        pthread_mutex_unlock(&mutex);
        return;
    }

    unsigned int replicated_index = next_it->second;

    match_it->second = replicated_index;
    next_it->second  = replicated_index + 1;

    it = requests.find(replicated_index);

    if ( it != requests.end() )
    {
        it->second->inc_replicas();

        if ( it->second->to_commit() == 0 )
        {
            requests.erase(it);

            commit = replicated_index;
        }
    }

    if ((db_last_index > replicated_index) && (state == LEADER))
    {
        replica_manager.replicate(follower_id);
    }

    pthread_mutex_unlock(&mutex);
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void RaftManager::replicate_failure(int follower_id)
{
    std::map<int, unsigned int>::iterator next_it;

    pthread_mutex_lock(&mutex);

    next_it = next.find(follower_id);

    if ( next_it != next.end() )
    {
        if ( next_it->second > 0 )
        {
            next_it->second = next_it->second - 1;
        }
    }

    if ( state == LEADER )
    {
        replica_manager.replicate(follower_id);
    }

    pthread_mutex_unlock(&mutex);
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
/* Raft state interface                                                       */
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void RaftManager::update_last_heartbeat(int _leader_id)
{
    pthread_mutex_lock(&mutex);

    leader_id = _leader_id;

	clock_gettime(CLOCK_REALTIME, &last_heartbeat);

    pthread_mutex_unlock(&mutex);
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

unsigned int RaftManager::update_commit(unsigned int leader_commit,
        unsigned int index)
{
    unsigned int _commit;

    pthread_mutex_lock(&mutex);

    if ( leader_commit > commit )
    {
        if ( index < leader_commit )
        {
            commit = index;
        }
        else
        {
            commit = leader_commit;
        }
    }

    _commit = commit;

    pthread_mutex_unlock(&mutex);

    return _commit;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int RaftManager::update_votedfor(int _votedfor)
{
    Nebula& nd    = Nebula::instance();
    LogDB * logdb = nd.get_logdb();

    std::string raft_state_xml;

    pthread_mutex_lock(&mutex);

    if ( votedfor != -1 && votedfor != _votedfor )
    {
        pthread_mutex_unlock(&mutex);

        return -1;
    }

    votedfor = _votedfor;

    raft_state.replace("VOTEDFOR", votedfor);

    raft_state.to_xml(raft_state_xml);

    pthread_mutex_unlock(&mutex);

    logdb->update_raft_state(raft_state_xml);

    return 0;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void RaftManager::timer_action(const ActionRequest& ar)
{
    static int mark_tics  = 0;
    static int purge_tics = 0;

    mark_tics++;
    purge_tics++;

    // Thread heartbeat
    if ( (mark_tics * timer_period_ms) >= 600000 )
    {
        NebulaLog::log("RCM",Log::INFO,"--Mark--");
        mark_tics = 0;
    }

    // Database housekeeping
    if ( (purge_tics * timer_period_ms) >= purge_period_ms )
    {
        Nebula& nd    = Nebula::instance();
        LogDB * logdb = nd.get_logdb();

        NebulaLog::log("RCM", Log::INFO, "Purging obsolete LogDB records");

        logdb->purge_log();

        purge_tics = 0;
    }

	// Leadership
	struct timespec the_time;

	clock_gettime(CLOCK_REALTIME, &the_time);

	pthread_mutex_lock(&mutex);

	if ( state == LEADER ) // Send the heartbeat
	{
		time_t sec  = last_heartbeat.tv_sec + broadcast_timeout.tv_sec;
		long   nsec = last_heartbeat.tv_nsec + broadcast_timeout.tv_nsec;

		if ((sec < the_time.tv_sec) || (sec == the_time.tv_sec &&
				nsec <= the_time.tv_nsec))
		{
			heartbeat_manager.replicate();

            clock_gettime(CLOCK_REALTIME, &last_heartbeat);

            pthread_mutex_unlock(&mutex);
		}
        else
        {
            pthread_mutex_unlock(&mutex);
        }

	}
	else if ( state == FOLLOWER )
	{
		time_t sec  = last_heartbeat.tv_sec + election_timeout.tv_sec;
		long   nsec = last_heartbeat.tv_nsec + election_timeout.tv_nsec;

		if ((sec < the_time.tv_sec) || (sec == the_time.tv_sec &&
				nsec <= the_time.tv_nsec))
		{
			NebulaLog::log("RRM", Log::ERROR, "Failed to get heartbeat from "
				"leader. Starting election proccess");

            state = CANDIDATE;

            pthread_mutex_unlock(&mutex);

            request_vote();
		}
        else
        {
            pthread_mutex_unlock(&mutex);
        }
	}
	else
	{
		pthread_mutex_unlock(&mutex);
	}

    return;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
/* XML-RPC interface to talk to followers                                     */
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void RaftManager::request_vote()
{
    unsigned int lindex, lterm, fterm, _term;
    int _server_id;

    std::map<int, std::string> _servers;
    std::map<int, std::string>::iterator it;

    std::ostringstream oss;

    unsigned int granted_votes;
    unsigned int votes2go;

    Nebula& nd    = Nebula::instance();
    LogDB * logdb = nd.get_logdb();

    int rc;

    std::string error;
    std::string raft_state_xml;

    struct timespec etimeout;
    long long ms;

    bool success;

    unsigned int _num_servers = get_zone_servers(_servers);

    do
    {
        /* ------------------------------------------------------------------ */
        /* Initialize election variables                                      */
        /* ------------------------------------------------------------------ */
        pthread_mutex_lock(&mutex);

        if ( state != CANDIDATE )
        {
            pthread_mutex_unlock(&mutex);
            break;
        }

        servers     = _servers;
        num_servers = _num_servers;

        term     = term + 1;
        votedfor = server_id;

        leader_id = -1;

        raft_state.replace("TERM", term);
        raft_state.replace("VOTEDFOR", votedfor);

        raft_state.to_xml(raft_state_xml);

        votes2go      = num_servers / 2;
        granted_votes = 0;

        _term      = term;
        _server_id = server_id;

        pthread_mutex_unlock(&mutex);

        logdb->update_raft_state(raft_state_xml);

        logdb->get_last_record_index(lindex, lterm);

        /* ------------------------------------------------------------------ */
        /* Request vote on all the followers                                  */
        /* ------------------------------------------------------------------ */
        for (it = _servers.begin(); it != _servers.end() ; ++it, oss.str("") )
        {
            int id = it->first;

            if ( id == _server_id )
            {
                continue;
            }

            rc = xmlrpc_request_vote(id, lindex, lterm, success, fterm, error);

            if ( rc == -1 )
            {
                NebulaLog::log("RCM", Log::INFO, error);
            }
            else if ( success == false )
            {
                oss << "Vote not granted from follower " << id << ": " << error;

                NebulaLog::log("RCM", Log::INFO, oss);

                if ( fterm > _term )
                {
                    oss.str("");
                    oss << "Follower " << id << " is in term " << fterm
                        << " current term is "<< _term
                        << ". Turning into follower";

                    NebulaLog::log("RCM", Log::INFO, oss);

                    follower(fterm);

                    return;
                }
            }
            else if ( success == true )
            {
                granted_votes++;

                oss << "Got vote from follower " << id << ". Total votes: "
                    << granted_votes;

                NebulaLog::log("RCM", Log::INFO, oss);
            }

            if ( granted_votes >= votes2go )
            {
                NebulaLog::log("RCM", Log::INFO, "Got majority of votes");
                break;
            }
        }

        /* ------------------------------------------------------------------ */
        /* Become leader if we have enough votes                              */
        /* ------------------------------------------------------------------ */
        if ( granted_votes >= votes2go )
        {
            leader();
            return;
        }

        /* ------------------------------------------------------------------ */
        /* Timeout for a new election process (blocking timer thread)         */
        /* ------------------------------------------------------------------ */
        pthread_mutex_lock(&mutex);

        votedfor = -1;

        raft_state.replace("VOTEDFOR", votedfor);

        raft_state.to_xml(raft_state_xml);

        pthread_mutex_unlock(&mutex);

        logdb->update_raft_state(raft_state_xml);

        srand(_server_id);

        ms = rand() % 500 + election_timeout.tv_sec * 1000
            + election_timeout.tv_nsec / 1000000;

        set_timeout(ms, etimeout);

        nanosleep(&etimeout, 0);

    } while ( true );
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int RaftManager::xmlrpc_replicate_log(int follower_id, LogDBRecord * lr,
		bool& success, unsigned int& fterm, std::string& error)
{
	int _server_id;
	int _commit;
	int _term;

    static const std::string replica_method = "one.zone.replicate";

    std::string secret;
    std::string follower_edp;

    std::map<int, std::string>::iterator it;

	int xml_rc = 0;

	pthread_mutex_lock(&mutex);

    it = servers.find(follower_id);

    if ( it == servers.end() )
    {
        error = "Cannot find follower end point";
        pthread_mutex_unlock(&mutex);

        return -1;
    }

    follower_edp = it->second;

	_commit    = commit;
    _term      = term;
	_server_id = server_id;

	pthread_mutex_unlock(&mutex);

    // -------------------------------------------------------------------------
    // Get parameters to call append entries on follower
    // -------------------------------------------------------------------------
    if ( Client::read_oneauth(secret, error) == -1 )
    {
        NebulaLog::log("RRM", Log::ERROR, error);
        return -1;
    }

    xmlrpc_c::value result;
    xmlrpc_c::paramList replica_params;

    replica_params.add(xmlrpc_c::value_string(secret));
    replica_params.add(xmlrpc_c::value_int(_server_id));
    replica_params.add(xmlrpc_c::value_int(_commit));
    replica_params.add(xmlrpc_c::value_int(_term));
    replica_params.add(xmlrpc_c::value_int(lr->index));
    replica_params.add(xmlrpc_c::value_int(lr->term));
    replica_params.add(xmlrpc_c::value_int(lr->prev_index));
    replica_params.add(xmlrpc_c::value_int(lr->prev_term));
    replica_params.add(xmlrpc_c::value_int(lr->fed_index));
    replica_params.add(xmlrpc_c::value_string(lr->sql));

    // -------------------------------------------------------------------------
    // Do the XML-RPC call
    // -------------------------------------------------------------------------
    xml_rc = Client::call(follower_edp, replica_method, replica_params,
            xmlrpc_timeout_ms, &result, error);

    if ( xml_rc == 0 )
    {
        vector<xmlrpc_c::value> values;

        values  = xmlrpc_c::value_array(result).vectorValueValue();
        success = xmlrpc_c::value_boolean(values[0]);

        if ( success ) //values[2] = error code (string)
        {
            fterm = xmlrpc_c::value_int(values[1]);
        }
        else
        {
            error = xmlrpc_c::value_string(values[1]);
            fterm = xmlrpc_c::value_int(values[3]);
        }
    }
    else
    {
        std::ostringstream ess;

        ess << "Error replicating log entry " << lr->index << " on follower "
            << follower_id << ": " << error;

        error = ess.str();
    }

    return xml_rc;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int RaftManager::xmlrpc_request_vote(int follower_id, unsigned int lindex,
        unsigned int lterm, bool& success, unsigned int& fterm,
        std::string& error)
{
	int _server_id;
	int _term;

    static const std::string replica_method = "one.zone.voterequest";

    std::string secret;
    std::string follower_edp;

    std::map<int, std::string>::iterator it;

	int xml_rc = 0;

	pthread_mutex_lock(&mutex);

    it = servers.find(follower_id);

    if ( it == servers.end() )
    {
        error = "Cannot find follower end point";
        pthread_mutex_unlock(&mutex);

        return -1;
    }

    follower_edp = it->second;

	_term      = term;
	_server_id = server_id;

	pthread_mutex_unlock(&mutex);

    // -------------------------------------------------------------------------
    // Get parameters to call append entries on follower
    // -------------------------------------------------------------------------
    if ( Client::read_oneauth(secret, error) == -1 )
    {
        NebulaLog::log("RRM", Log::ERROR, error);
        return -1;
    }

    xmlrpc_c::value result;
    xmlrpc_c::paramList replica_params;

    replica_params.add(xmlrpc_c::value_string(secret));
    replica_params.add(xmlrpc_c::value_int(_term));
    replica_params.add(xmlrpc_c::value_int(_server_id));
    replica_params.add(xmlrpc_c::value_int(lindex));
    replica_params.add(xmlrpc_c::value_int(lterm));

    // -------------------------------------------------------------------------
    // Do the XML-RPC call
    // -------------------------------------------------------------------------
    xml_rc = Client::call(follower_edp, replica_method, replica_params,
        xmlrpc_timeout_ms, &result, error);

    if ( xml_rc == 0 )
    {
        vector<xmlrpc_c::value> values;

        values  = xmlrpc_c::value_array(result).vectorValueValue();
        success = xmlrpc_c::value_boolean(values[0]);

        if ( success ) //values[2] = error code (string)
        {
            fterm = xmlrpc_c::value_int(values[1]);
        }
        else
        {
            error = xmlrpc_c::value_string(values[1]);
            fterm = xmlrpc_c::value_int(values[3]);
        }
    }
    else
    {
        std::ostringstream ess;

        ess << "Error requesting vote from follower "<< follower_id << ":"
            << error;

        error = ess.str();
    }

    return xml_rc;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

std::string& RaftManager::to_xml(std::string& raft_xml)
{
    Nebula& nd    = Nebula::instance();
    LogDB * logdb = nd.get_logdb();

    unsigned int lindex, lterm;

    std::ostringstream oss;

    logdb->get_last_record_index(lindex, lterm);

	pthread_mutex_lock(&mutex);

    oss << "<RAFT>"
        << "<SERVER_ID>" << server_id << "</SERVER_ID>"
        << "<STATE>"     << state << "</STATE>"
        << "<TERM>"      << term << "</TERM>"
        << "<VOTEDFOR>"  << votedfor << "</VOTEDFOR>"
        << "<COMMIT>"    << commit << "</COMMIT>";

	if ( state == SOLO )
	{
        oss << "<LOG_INDEX>-1</LOG_INDEX>"
            << "<LOG_TERM>-1</LOG_TERM>";
	}
    else
    {
        oss << "<LOG_INDEX>" << lindex << "</LOG_INDEX>"
            << "<LOG_TERM>"  << lterm  << "</LOG_TERM>";
    }

    if ( nd.is_federation_enabled() )
    {
        oss << "<FEDLOG_INDEX>" << logdb->last_federated() << "</FEDLOG_INDEX>";
    }
    else
    {
        oss << "<FEDLOG_INDEX>-1</FEDLOG_INDEX>";
    }

    oss << "</RAFT>";

	pthread_mutex_unlock(&mutex);

    raft_xml = oss.str();

    return raft_xml;
}


text:
package com.evolveum.midpoint.web.component.data;

import com.evolveum.midpoint.gui.api.component.BasePanel;
import com.evolveum.midpoint.web.component.AjaxButton;
import com.evolveum.midpoint.web.component.data.column.DoubleButtonColumn;
import com.evolveum.midpoint.web.component.data.column.SingleButtonColumn;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.StringResourceModel;

/**
 *  @author shood
 *  @author mederly
 */
public class SingleButtonPanel<T> extends BasePanel<T> {

    private static final String ID_BUTTON = "button";

    private String caption;

    public SingleButtonPanel(String id, IModel<T> model){
        super(id, model);
        initLayout();
    }

    private void initLayout(){
        AjaxButton button = new AjaxButton(ID_BUTTON, createButtonStringResource(getCaption())) {

            @Override
            public void onClick(AjaxRequestTarget target) {
                clickPerformed(target, SingleButtonPanel.this.getModel());
            }

            @Override
            public boolean isEnabled(){
                return SingleButtonPanel.this.isEnabled(SingleButtonPanel.this.getModel());
            }

            @Override
            public boolean isVisible() {
                return SingleButtonPanel.this.isVisible(SingleButtonPanel.this.getModel());
            }
        };
        button.add(new AttributeAppender("class", getButtonCssClass()));

        add(button);
    }

    private String getButtonCssClass(){
        StringBuilder sb = new StringBuilder();
        sb.append(SingleButtonColumn.BUTTON_BASE_CLASS).append(" ");
        sb.append(getButtonCssColorClass()).append(" ").append(getButtonCssSizeClass());
        return sb.toString();
    }

    public String getButtonCssSizeClass(){
        return DoubleButtonColumn.ButtonSizeClass.DEFAULT.toString();
    }

    public String getButtonCssColorClass(){
        return DoubleButtonColumn.ButtonColorClass.DEFAULT.toString();
    }

    public String getCaption(){
        return caption;
    }

    private StringResourceModel createButtonStringResource(String caption) {
        if (caption == null){
            return createStringResource("SingleButtonPanel.button.default");
        } else {
            return createStringResource(caption);
        }
    }

    public void clickPerformed(AjaxRequestTarget target, IModel<T> model){}

    public boolean isEnabled(IModel<T> model){
        return true;
    }

    public boolean isVisible(IModel<T> model){
        return true;
    }

    public AjaxButton getButton() {
        return (AjaxButton) get(ID_BUTTON);
    }
}


text:
var BENCHMARK_PARSE = true
var { default: IntlMF } = require('intl-messageformat')
var MessageFormat2 = require('messageformat')
var MessageFormat = require('../packages/message-format')
var formatMessage = require('format-message') // cannot be relative or else transform misses it
var { parse: intlParse } = require('intl-messageformat-parser')
var parse = require('../packages/format-message-parse')
var parse2 = require('messageformat-parser').parse
var Benchmark = require('benchmark')
var pattern
var args
var intlMF
var mf
var mf2

formatMessage.setup({ missingTranslation: 'ignore' })

function benchmark (name, cases) {
  var suiteOptions = {
    onStart: function () {
      console.log(this.name)
    },
    onCycle: function (event) {
      console.log(' ', String(event.target))
    },
    onComplete: function () {
      console.log('Fastest is ' + this.filter('fastest').map('name').join(' or '))
      console.log()
    }
  }

  var suite = new Benchmark.Suite(name, suiteOptions)
  Object.keys(cases).forEach(function (name) {
    suite.add(name, cases[name])
  })
  suite.run()
}

pattern = 'Simple string with nothing special'
formatMessage(pattern, args, 'en') // prime cache
intlMF = new IntlMF(pattern, 'en').format
mf2 = new MessageFormat2('en').compile(pattern)
mf = new MessageFormat(pattern, 'en').format
BENCHMARK_PARSE && benchmark(
  'Parse simple message', {
    'intl-messageformat-parser': function () { return intlParse(pattern) },
    'messageformat-parser': function () { return parse2(pattern) },
    'format-message-parse': function () { return parse(pattern) }
  }
)
benchmark(
  'Format simple message', {
    'intl-messageformat (reuse object)': function () { return intlMF(args) },
    'messageformat (reuse object)': function () { return mf2(args) },
    'message-format (reuse object)': function () { return mf(args) },
    'format-message': function () { return formatMessage(pattern, args, 'en') },
    'format-message (inlined)': function () { return formatMessage('Simple string with nothing special', args, 'en') }
  }
)

pattern = 'Simple string with { placeholder }.'
args = { placeholder: 'replaced value' }
formatMessage(pattern, args, 'en') // prime cache
intlMF = new IntlMF(pattern, 'en').format
mf2 = new MessageFormat2('en').compile(pattern)
mf = new MessageFormat(pattern, 'en').format
BENCHMARK_PARSE && benchmark(
  'Parse common one arg message', {
    'intl-messageformat-parser': function () { return intlParse(pattern) },
    'messageformat-parser': function () { return parse2(pattern) },
    'format-message-parse': function () { return parse(pattern) }
  }
)
benchmark(
  'Format common one arg message', {
    'intl-messageformat (reuse object)': function () { return intlMF(args) },
    'messageformat (reuse object)': function () { return mf2(args) },
    'message-format (reuse object)': function () { return mf(args) },
    'format-message': function () { return formatMessage(pattern, args, 'en') },
    'format-message (inlined)': function () { return formatMessage('Simple string with { placeholder }.', { placeholder: 'replaced value' }, 'en') }
  }
)

pattern = `{name} had {
  gender, select,
    male {his}
    female {her}
    other {their}
  } {
  nth, selectordinal,
    one {#st}
    two {#nd}
    few {#rd}
    other {#th}
  } banana today, which makes {
  numBananas, plural,
       =0 {no bananas}
       =1 {a banana}
    other {lots of bananas}
  } total.`
args = {
  date: new Date(),
  name: 'Curious George',
  gender: 'male',
  numBananas: 300,
  nth: 3
}
formatMessage(pattern, args, 'en') // prime cache
intlMF = new IntlMF(pattern, 'en').format
mf2 = new MessageFormat2('en').compile(pattern)
mf = new MessageFormat(pattern, 'en').format
BENCHMARK_PARSE && benchmark(
  'Parse complex message (no numbers or dates)', {
    'intl-messageformat-parser': function () { return intlParse(pattern) },
    'messageformat-parser': function () { return parse2(pattern) },
    'format-message-parse': function () { return parse(pattern) }
  }
)
benchmark(
  'Format complex message (no numbers or dates)', {
    'intl-messageformat (reuse object)': function () { return intlMF(args) },
    'messageformat (reuse object)': function () { return mf2(args) },
    'message-format (reuse object)': function () { return mf(args) },
    'format-message': function () { return formatMessage(pattern, args) },
    'format-message (inlined)': function () {
      return formatMessage(`{name} had {
        gender, select,
          male {his}
          female {her}
          other {their}
        } {
        nth, selectordinal,
          one {#st}
          two {#nd}
          few {#rd}
          other {#th}
        } banana today, which makes {
        numBananas, plural,
             =0 {no bananas}
             =1 {a banana}
          other {lots of bananas}
        } total.`, args, 'en')
    }
  }
)

pattern = `On { date, date, short } {name} had {
  numBananas, plural,
       =0 {no bananas}
       =1 {a banana}
    other {# bananas}
  } {
  gender, select,
    male {in his room.}
    female {in her room.}
    other {in their room.}
  }`
args = {
  date: new Date(),
  name: 'Curious George',
  gender: 'male',
  numBananas: 300
}
formatMessage(pattern, args, 'en') // prime cache
intlMF = new IntlMF(pattern, 'en').format
mf2 = new MessageFormat2('en').compile(pattern)
mf = new MessageFormat(pattern, 'en').format
BENCHMARK_PARSE && benchmark(
  'Parse complex message', {
    'intl-messageformat-parser': function () { return intlParse(pattern) },
    'messageformat-parser': function () { return parse2(pattern) },
    'format-message-parse': function () { return parse(pattern) }
  }
)
benchmark(
  'Format complex message', {
    'intl-messageformat (reuse object)': function () { return intlMF(args) },
    'messageformat (reuse object)': function () { return mf2(args) },
    'message-format (reuse object)': function () { return mf(args) },
    'format-message': function () { return formatMessage(pattern, args) },
    'format-message (inlined)': function () {
      return formatMessage(`On { date, date, short } {name} had {
          numBananas, plural,
               =0 {no bananas}
               =1 {a banana}
            other {# bananas}
          } {
          gender, select,
            male {in his room.}
            female {in her room.}
            other {in their room.}
          }`, args, 'en')
    }
  }
)


text:
<CartAddResponse xmlns="http://webservices.amazon.com/AWSECommerceService/2011-08-01">
  <OperationRequest>
    <HTTPHeaders>

    </HTTPHeaders>
    <RequestId>00R69TNBPR2TRWQEEP6D</RequestId>
    <Arguments>
      <Argument Name="Service" Value="AWSECommerceService"/>
      <Argument Name="Item.1.Quantity" Value="2"/>
      <Argument Name="Operation" Value="CartAdd"/>
      <Argument Name="Timestamp" Value="2011-11-13T13:03:24Z"/>
      <Argument Name="Version" Value="2011-08-01"/>
      <Argument Name="AssociateTag" Value="XXXXXXXXXXXXXXX"/>
      <Argument Name="Item.1.ASIN" Value="0201896834"/>
      <Argument Name="Signature" Value="XXXXXXXXXXXXXXX"/>
      <Argument Name="HMAC" Value="d2e5zrVgl2FuLdZUeE7YIhC+UIA="/>
      <Argument Name="CartId" Value="179-9450958-5945469"/>
      <Argument Name="AWSAccessKeyId" Value="XXXXXXXXXXXXXXX"/>
    </Arguments>
    <RequestProcessingTime>0.195571899414062</RequestProcessingTime>
  </OperationRequest>
  <Cart>
    <Request>
      <IsValid>True</IsValid>
      <CartAddRequest>
        <CartId>179-9450958-5945469</CartId>
        <HMAC>d2e5zrVgl2FuLdZUeE7YIhC+UIA=</HMAC>
        <Items>
          <Item>
            <ASIN>0201896834</ASIN>
            <Quantity>2</Quantity>
          </Item>
        </Items>
      </CartAddRequest>
      <Errors>
        <Error>
          AWS.ECommerceService.InvalidQuantity
          <Message>You have exceeded the maximum quantity allowed for the following items: 0201896834.</Message>
        </Error>
        <Error>
          AWS.ECommerceService.ItemAlreadyInCart
          <Message>The item you specified, 0201896834, is already in your cart.</Message>
        </Error>
      </Errors>
    </Request>
    <CartId>179-9450958-5945469</CartId>
    <HMAC>d2e5zrVgl2FuLdZUeE7YIhC+UIA=</HMAC>
    <URLEncodedHMAC>d2e5zrVgl2FuLdZUeE7YIhC%2BUIA%3D</URLEncodedHMAC>
    <PurchaseURL>https://www.amazon.ca/gp/cart/aws-merge.html?cart-id=179-9450958-5945469%26associate-id=redtoad-21%26hmac=d2e5zrVgl2FuLdZUeE7YIhC%2BUIA=%26SubscriptionId=AKIAJTJID3GQ4PAFYOEQ%26MergeCart=False</PurchaseURL>
    <SubTotal>
      <Amount>16271</Amount>
      <CurrencyCode>CAD</CurrencyCode>
      <FormattedPrice>CDN$ 162.71</FormattedPrice>
    </SubTotal>
    <CartItems>
      <SubTotal>
        <Amount>16271</Amount>
        <CurrencyCode>CAD</CurrencyCode>
        <FormattedPrice>CDN$ 162.71</FormattedPrice>
      </SubTotal>
      <CartItem>
        <CartItemId>U24U0TK50FRSUK</CartItemId>
        <ASIN>0201896834</ASIN>
        <SellerNickname>Amazon.ca</SellerNickname>
        <Quantity>1</Quantity>
        <Title>Art of Computer Programming, Volume 1: Fundamental Algorithms</Title>
        <ProductGroup>Book</ProductGroup>
        <Price>
          <Amount>6319</Amount>
          <CurrencyCode>CAD</CurrencyCode>
          <FormattedPrice>CDN$ 63.19</FormattedPrice>
        </Price>
        <ItemTotal>
          <Amount>6319</Amount>
          <CurrencyCode>CAD</CurrencyCode>
          <FormattedPrice>CDN$ 63.19</FormattedPrice>
        </ItemTotal>
      </CartItem>
      <CartItem>
        <CartItemId>U1BO8U3ZYW2PV6</CartItemId>
        <ASIN>0201896842</ASIN>
        <SellerNickname>Amazon.ca</SellerNickname>
        <Quantity>2</Quantity>
        <Title>Art of Computer Programming, Volume 2: Seminumerical Algorithms</Title>
        <ProductGroup>Book</ProductGroup>
        <Price>
          <Amount>4976</Amount>
          <CurrencyCode>CAD</CurrencyCode>
          <FormattedPrice>CDN$ 49.76</FormattedPrice>
        </Price>
        <ItemTotal>
          <Amount>9952</Amount>
          <CurrencyCode>CAD</CurrencyCode>
          <FormattedPrice>CDN$ 99.52</FormattedPrice>
        </ItemTotal>
      </CartItem>
    </CartItems>
  </Cart>
</CartAddResponse>


text:
package ua.riaval.quiztest.entity;

import static javax.persistence.GenerationType.IDENTITY;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name = "AnswerResult", catalog = "QuizTest")
public class AnswerResult implements Serializable {

	private static final long serialVersionUID = 1L;

	@Id
	@GeneratedValue(strategy = IDENTITY)
	@Column(name = "id", unique = true, nullable = false)
	private Integer id;

	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name = "questionResult_id", nullable = false)
	private QuestionResult questionResult;

	@Column(name = "text", nullable = false, length = 200)
	private String text;

	@Column(name = "correct")
	private Boolean correct;

	@Column(name = "checked", nullable = false)
	private boolean checked;

	public AnswerResult() {
	}

	public AnswerResult(String text, boolean checked) {
		this.text = text;
		this.checked = checked;
	}

	public AnswerResult(QuestionResult questionResult, String text,
			Boolean correct, boolean checked) {
		this.questionResult = questionResult;
		this.text = text;
		this.correct = correct;
		this.checked = checked;
	}

	public AnswerResult(Answer answer) {
		this.text = answer.getText();
		this.correct = answer.getCorrect();
	}

	public Integer getId() {
		return this.id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public QuestionResult getQuestionResult() {
		return this.questionResult;
	}

	public void setQuestionResult(QuestionResult questionResult) {
		this.questionResult = questionResult;
	}

	public String getText() {
		return this.text;
	}

	public void setText(String text) {
		this.text = text;
	}

	public Boolean getCorrect() {
		return this.correct;
	}

	public void setCorrect(Boolean correct) {
		this.correct = correct;
	}

	public boolean getChecked() {
		return this.checked;
	}

	public void setChecked(boolean checked) {
		this.checked = checked;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + (checked ? 1231 : 1237);
		result = prime * result + ((correct == null) ? 0 : correct.hashCode());
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		result = prime * result + ((text == null) ? 0 : text.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		AnswerResult other = (AnswerResult) obj;
		if (checked != other.checked)
			return false;
		if (correct == null) {
			if (other.correct != null)
				return false;
		} else if (!correct.equals(other.correct))
			return false;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		if (text == null) {
			if (other.text != null)
				return false;
		} else if (!text.equals(other.text))
			return false;
		return true;
	}

}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package br.edu.ifnmg.AutomatosCelulares.Simulacao;

/**
 *
 * @author petronio
 */
public class TipoSolo {
    private double taxaInfiltracao;
    private double taxaEvaporacao;
}


text:
<!DOCTYPE html>

Detalles

    Contenido


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

namespace Genexcel.Models {
	public abstract class Chart {
		public ChartData Data { get; set; } = new ChartData();
	}

	public class ChartData {
		public List<string> Labels { get; set; } = new List<string>();
		public List<ChartDataset> Datasets { get; set; } = new List<ChartDataset>();
	}

	public class ChartDataset {
		public string Title { get; set; }
		public List<decimal> Data { get; set; } = new List<decimal>();
	}

	public class AreaChart : Chart {
	}

	public class BarChart : Chart {

	}
}


text:
require 'HDLRuby'
require 'HDLRuby/hruby_low2high'
include HDLRuby::Low

# Read a yaml file.
hardwares = HDLRuby::from_yaml(File.read($*[0]))

# Generate the corresponding HDLruby::High code.
puts hardwares[-1].to_high


text:
/*
 * PipelineRun.h
 *
 *
 */

#ifndef TINY_CPP_CLIENT_PipelineRun_H_
#define TINY_CPP_CLIENT_PipelineRun_H_

#include <string>
#include "bourne/json.hpp"
#include "Helpers.h"
#include "PipelineRunartifacts.h"
#include <list>

namespace Tiny {

/*! \brief
 *
 *  \ingroup Models
 *
 */

class PipelineRun{
public:

    /*! \brief Constructor.
	 */
    PipelineRun();
    PipelineRun(std::string jsonString);

    /*! \brief Destructor.
	 */
    virtual ~PipelineRun();

    /*! \brief Retrieve a bourne JSON representation of this class.
	 */
    bourne::json toJson();

    /*! \brief Fills in members of this class from bourne JSON object representing it.
	 */
    void fromJson(std::string jsonObj);

	/*! \brief Get
	 */
	std::string getClass();

	/*! \brief Set
	 */
	void setClass(std::string  _class);
	/*! \brief Get
	 */
	std::list<PipelineRunartifacts> getArtifacts();

	/*! \brief Set
	 */
	void setArtifacts(std::list <PipelineRunartifacts> artifacts);
	/*! \brief Get
	 */
	int getDurationInMillis();

	/*! \brief Set
	 */
	void setDurationInMillis(int  durationInMillis);
	/*! \brief Get
	 */
	int getEstimatedDurationInMillis();

	/*! \brief Set
	 */
	void setEstimatedDurationInMillis(int  estimatedDurationInMillis);
	/*! \brief Get
	 */
	std::string getEnQueueTime();

	/*! \brief Set
	 */
	void setEnQueueTime(std::string  enQueueTime);
	/*! \brief Get
	 */
	std::string getEndTime();

	/*! \brief Set
	 */
	void setEndTime(std::string  endTime);
	/*! \brief Get
	 */
	std::string getId();

	/*! \brief Set
	 */
	void setId(std::string  id);
	/*! \brief Get
	 */
	std::string getOrganization();

	/*! \brief Set
	 */
	void setOrganization(std::string  organization);
	/*! \brief Get
	 */
	std::string getPipeline();

	/*! \brief Set
	 */
	void setPipeline(std::string  pipeline);
	/*! \brief Get
	 */
	std::string getResult();

	/*! \brief Set
	 */
	void setResult(std::string  result);
	/*! \brief Get
	 */
	std::string getRunSummary();

	/*! \brief Set
	 */
	void setRunSummary(std::string  runSummary);
	/*! \brief Get
	 */
	std::string getStartTime();

	/*! \brief Set
	 */
	void setStartTime(std::string  startTime);
	/*! \brief Get
	 */
	std::string getState();

	/*! \brief Set
	 */
	void setState(std::string  state);
	/*! \brief Get
	 */
	std::string getType();

	/*! \brief Set
	 */
	void setType(std::string  type);
	/*! \brief Get
	 */
	std::string getCommitId();

	/*! \brief Set
	 */
	void setCommitId(std::string  commitId);

    private:
    std::string _class{};
    std::list<PipelineRunartifacts> artifacts;
    int durationInMillis{};
    int estimatedDurationInMillis{};
    std::string enQueueTime{};
    std::string endTime{};
    std::string id{};
    std::string organization{};
    std::string pipeline{};
    std::string result{};
    std::string runSummary{};
    std::string startTime{};
    std::string state{};
    std::string type{};
    std::string commitId{};
};
}

#endif /* TINY_CPP_CLIENT_PipelineRun_H_ */


text:
package org.g4studio.core.net.smtp;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Enumeration;
import java.util.Vector;

import org.g4studio.core.net.MalformedServerReplyException;
import org.g4studio.core.net.ProtocolCommandListener;
import org.g4studio.core.net.ProtocolCommandSupport;
import org.g4studio.core.net.SocketClient;

/***
 * SMTP provides the basic the functionality necessary to implement your own
 * SMTP client. To derive the full benefits of the SMTP class requires some
 * knowledge of the FTP protocol defined in RFC 821. However, there is no reason
 * why you should have to use the SMTP class. The
 * {@link org.apache.commons.net.smtp.SMTPClient} class, derived from SMTP,
 * implements all the functionality required of an SMTP client. The SMTP class
 * is made public to provide access to various SMTP constants and to make it
 * easier for adventurous programmers (or those with special needs) to interact
 * with the SMTP protocol and implement their own clients. A set of methods with
 * names corresponding to the SMTP command names are provided to facilitate this
 * interaction.
 *

 * You should keep in mind that the SMTP server may choose to prematurely close
 * a connection for various reasons. The SMTP class will detect a premature SMTP
 * server connection closing when it receives a
 * {@link org.apache.commons.net.smtp.SMTPReply#SERVICE_NOT_AVAILABLE
 * SMTPReply.SERVICE_NOT_AVAILABLE } response to a command. When that occurs,
 * the SMTP class method encountering that reply will throw an
 * {@link org.apache.commons.net.smtp.SMTPConnectionClosedException} .
 * SMTPConectionClosedException is a subclass of
 *  IOException  and therefore need not be caught separately, but
 * if you are going to catch it separately, its catch block must appear before
 * the more general  IOException  catch block. When you encounter
 * an {@link org.apache.commons.net.smtp.SMTPConnectionClosedException} , you
 * must disconnect the connection with
 * {@link org.apache.commons.net.SocketClient#disconnect disconnect() } to
 * properly clean up the system resources used by SMTP. Before disconnecting,
 * you may check the last reply code and text with {@link #getReplyCode
 * getReplyCode }, {@link #getReplyString getReplyString }, and
 * {@link #getReplyStrings getReplyStrings}.
 *

 * Rather than list it separately for each method, we mention here that every
 * method communicating with the server and throwing an IOException can also
 * throw a {@link org.apache.commons.net.MalformedServerReplyException} , which
 * is a subclass of IOException. A MalformedServerReplyException will be thrown
 * when the reply received from the server deviates enough from the protocol
 * specification that it cannot be interpreted in a useful manner despite
 * attempts to be as lenient as possible.
 *

 *

 *
 * @author Daniel F. Savarese
 * @see SMTPClient
 * @see SMTPConnectionClosedException
 * @see org.apache.commons.net.MalformedServerReplyException
 ***/

public class SMTP extends SocketClient {
	/*** The default SMTP port (25). ***/
	public static final int DEFAULT_PORT = 25;

	// We have to ensure that the protocol communication is in ASCII
	// but we use ISO-8859-1 just in case 8-bit characters cross
	// the wire.
	private static final String __DEFAULT_ENCODING = "ISO-8859-1";

	private StringBuffer __commandBuffer;

	BufferedReader _reader;
	BufferedWriter _writer;
	int _replyCode;
	Vector _replyLines;
	boolean _newReplyString;
	String _replyString;

	/***
	 * A ProtocolCommandSupport object used to manage the registering of
	 * ProtocolCommandListeners and te firing of ProtocolCommandEvents.
	 ***/
	protected ProtocolCommandSupport _commandSupport_;

	/***
	 * The default SMTP constructor. Sets the default port to
	 * DEFAULT_PORT and initializes internal data structures for
	 * saving SMTP reply information.
	 ***/
	public SMTP() {
		setDefaultPort(DEFAULT_PORT);
		__commandBuffer = new StringBuffer();
		_replyLines = new Vector();
		_newReplyString = false;
		_replyString = null;
		_commandSupport_ = new ProtocolCommandSupport(this);
	}

	private int __sendCommand(String command, String args, boolean includeSpace) throws IOException {
		String message;

		__commandBuffer.setLength(0);
		__commandBuffer.append(command);

		if (args != null) {
			if (includeSpace)
				__commandBuffer.append(' ');
			__commandBuffer.append(args);
		}

		__commandBuffer.append(SocketClient.NETASCII_EOL);

		_writer.write(message = __commandBuffer.toString());
		_writer.flush();

		if (_commandSupport_.getListenerCount() > 0)
			_commandSupport_.fireCommandSent(command, message);

		__getReply();
		return _replyCode;
	}

	private int __sendCommand(int command, String args, boolean includeSpace) throws IOException {
		return __sendCommand(SMTPCommand._commands[command], args, includeSpace);
	}

	private void __getReply() throws IOException {
		int length;

		_newReplyString = true;
		_replyLines.setSize(0);

		String line = _reader.readLine();

		if (line == null)
			throw new SMTPConnectionClosedException("Connection closed without indication.");

		// In case we run into an anomaly we don't want fatal index exceptions
		// to be thrown.
		length = line.length();
		if (length < 3)
			throw new MalformedServerReplyException("Truncated server reply: " + line);

		try {
			String code = line.substring(0, 3);
			_replyCode = Integer.parseInt(code);
		} catch (NumberFormatException e) {
			throw new MalformedServerReplyException("Could not parse response code.\nServer Reply: " + line);
		}

		_replyLines.addElement(line);

		// Get extra lines if message continues.
		if (length > 3 && line.charAt(3) == '-') {
			do {
				line = _reader.readLine();

				if (line == null)
					throw new SMTPConnectionClosedException("Connection closed without indication.");

				_replyLines.addElement(line);

				// The length() check handles problems that could arise from
				// readLine()
				// returning too soon after encountering a naked CR or some
				// other
				// anomaly.
			} while (!(line.length() >= 4 && line.charAt(3) != '-' && Character.isDigit(line.charAt(0))));
			// This is too strong a condition because a non-conforming server
			// could screw things up like ftp.funet.fi does for FTP
			// line.startsWith(code)));
		}

		if (_commandSupport_.getListenerCount() > 0)
			_commandSupport_.fireReplyReceived(_replyCode, getReplyString());

		if (_replyCode == SMTPReply.SERVICE_NOT_AVAILABLE)
			throw new SMTPConnectionClosedException("SMTP response 421 received.  Server closed connection.");
	}

	/*** Initiates control connections and gets initial reply. ***/
	protected void _connectAction_() throws IOException {
		super._connectAction_();
		_reader = new BufferedReader(new InputStreamReader(_input_, __DEFAULT_ENCODING));
		_writer = new BufferedWriter(new OutputStreamWriter(_output_, __DEFAULT_ENCODING));
		__getReply();
	}

	/***
	 * Adds a ProtocolCommandListener. Delegates this task to
	 * {@link #_commandSupport_ _commandSupport_ }.
	 *

	 *
	 * @param listener
	 *            The ProtocolCommandListener to add.
	 ***/
	public void addProtocolCommandListener(ProtocolCommandListener listener) {
		_commandSupport_.addProtocolCommandListener(listener);
	}

	/***
	 * Removes a ProtocolCommandListener. Delegates this task to
	 * {@link #_commandSupport_ _commandSupport_ }.
	 *

	 *
	 * @param listener
	 *            The ProtocolCommandListener to remove.
	 ***/
	public void removeProtocolCommandistener(ProtocolCommandListener listener) {
		_commandSupport_.removeProtocolCommandListener(listener);
	}

	/***
	 * Closes the connection to the SMTP server and sets to null some internal
	 * data so that the memory may be reclaimed by the garbage collector. The
	 * reply text and code information from the last command is voided so that
	 * the memory it used may be reclaimed.
	 *

	 *
	 * @exception IOException
	 *                If an error occurs while disconnecting.
	 ***/
	public void disconnect() throws IOException {
		super.disconnect();
		_reader = null;
		_writer = null;
		_replyString = null;
		_replyLines.setSize(0);
		_newReplyString = false;
	}

	/***
	 * Sends an SMTP command to the server, waits for a reply and returns the
	 * numerical response code. After invocation, for more detailed information,
	 * the actual reply text can be accessed by calling {@link #getReplyString
	 * getReplyString } or {@link #getReplyStrings getReplyStrings }.
	 *

	 *
	 * @param command
	 *            The text representation of the SMTP command to send.
	 * @param args
	 *            The arguments to the SMTP command. If this parameter is set to
	 *            null, then the command is sent with no argument.
	 * @return The integer value of the SMTP reply code returned by the server
	 *         in response to the command.
	 * @exception SMTPConnectionClosedException
	 *                If the SMTP server prematurely closes the connection as a
	 *                result of the client being idle or some other reason
	 *                causing the server to send SMTP reply code 421. This
	 *                exception may be caught either as an IOException or
	 *                independently as itself.
	 * @exception IOException
	 *                If an I/O error occurs while either sending the command or
	 *                receiving the server reply.
	 ***/
	public int sendCommand(String command, String args) throws IOException {
		return __sendCommand(command, args, true);
	}

	/***
	 * Sends an SMTP command to the server, waits for a reply and returns the
	 * numerical response code. After invocation, for more detailed information,
	 * the actual reply text can be accessed by calling {@link #getReplyString
	 * getReplyString } or {@link #getReplyStrings getReplyStrings }.
	 *

	 *
	 * @param command
	 *            The SMTPCommand constant corresponding to the SMTP command to
	 *            send.
	 * @param args
	 *            The arguments to the SMTP command. If this parameter is set to
	 *            null, then the command is sent with no argument.
	 * @return The integer value of the SMTP reply code returned by the server
	 *         in response to the command.
	 * @exception SMTPConnectionClosedException
	 *                If the SMTP server prematurely closes the connection as a
	 *                result of the client being idle or some other reason
	 *                causing the server to send SMTP reply code 421. This
	 *                exception may be caught either as an IOException or
	 *                independently as itself.
	 * @exception IOException
	 *                If an I/O error occurs while either sending the command or
	 *                receiving the server reply.
	 ***/
	public int sendCommand(int command, String args) throws IOException {
		return sendCommand(SMTPCommand._commands[command], args);
	}

	/***
	 * Sends an SMTP command with no arguments to the server, waits for a reply
	 * and returns the numerical response code. After invocation, for more
	 * detailed information, the actual reply text can be accessed by calling
	 * {@link #getReplyString getReplyString } or {@link #getReplyStrings
	 * getReplyStrings }.
	 *

	 *
	 * @param command
	 *            The text representation of the SMTP command to send.
	 * @return The integer value of the SMTP reply code returned by the server
	 *         in response to the command.
	 * @exception SMTPConnectionClosedException
	 *                If the SMTP server prematurely closes the connection as a
	 *                result of the client being idle or some other reason
	 *                causing the server to send SMTP reply code 421. This
	 *                exception may be caught either as an IOException or
	 *                independently as itself.
	 * @exception IOException
	 *                If an I/O error occurs while either sending the command or
	 *                receiving the server reply.
	 ***/
	public int sendCommand(String command) throws IOException {
		return sendCommand(command, null);
	}

	/***
	 * Sends an SMTP command with no arguments to the server, waits for a reply
	 * and returns the numerical response code. After invocation, for more
	 * detailed information, the actual reply text can be accessed by calling
	 * {@link #getReplyString getReplyString } or {@link #getReplyStrings
	 * getReplyStrings }.
	 *

	 *
	 * @param command
	 *            The SMTPCommand constant corresponding to the SMTP command to
	 *            send.
	 * @return The integer value of the SMTP reply code returned by the server
	 *         in response to the command.
	 * @exception SMTPConnectionClosedException
	 *                If the SMTP server prematurely closes the connection as a
	 *                result of the client being idle or some other reason
	 *                causing the server to send SMTP reply code 421. This
	 *                exception may be caught either as an IOException or
	 *                independently as itself.
	 * @exception IOException
	 *                If an I/O error occurs while either sending the command or
	 *                receiving the server reply.
	 ***/
	public int sendCommand(int command) throws IOException {
		return sendCommand(command, null);
	}

	/***
	 * Returns the integer value of the reply code of the last SMTP reply. You
	 * will usually only use this method after you connect to the SMTP server to
	 * check that the connection was successful since  connect  is
	 * of type void.
	 *

	 *
	 * @return The integer value of the reply code of the last SMTP reply.
	 ***/
	public int getReplyCode() {
		return _replyCode;
	}

	/***
	 * Fetches a reply from the SMTP server and returns the integer reply code.
	 * After calling this method, the actual reply text can be accessed from
	 * either calling {@link #getReplyString getReplyString } or
	 * {@link #getReplyStrings getReplyStrings }. Only use this method if you
	 * are implementing your own SMTP client or if you need to fetch a secondary
	 * response from the SMTP server.
	 *

	 *
	 * @return The integer value of the reply code of the fetched SMTP reply.
	 * @exception SMTPConnectionClosedException
	 *                If the SMTP server prematurely closes the connection as a
	 *                result of the client being idle or some other reason
	 *                causing the server to send SMTP reply code 421. This
	 *                exception may be caught either as an IOException or
	 *                independently as itself.
	 * @exception IOException
	 *                If an I/O error occurs while receiving the server reply.
	 ***/
	public int getReply() throws IOException {
		__getReply();
		return _replyCode;
	}

	/***
	 * Returns the lines of text from the last SMTP server response as an array
	 * of strings, one entry per line. The end of line markers of each are
	 * stripped from each line.
	 *

	 *
	 * @return The lines of text from the last SMTP response as an array.
	 ***/
	public String[] getReplyStrings() {
		String[] lines;
		lines = new String[_replyLines.size()];
		_replyLines.copyInto(lines);
		return lines;
	}

	/***
	 * Returns the entire text of the last SMTP server response exactly as it
	 * was received, including all end of line markers in NETASCII format.
	 *

	 *
	 * @return The entire text from the last SMTP response as a String.
	 ***/
	public String getReplyString() {
		Enumeration en;
		StringBuffer buffer;

		if (!_newReplyString)
			return _replyString;

		buffer = new StringBuffer(256);
		en = _replyLines.elements();
		while (en.hasMoreElements()) {
			buffer.append((String) en.nextElement());
			buffer.append(SocketClient.NETASCII_EOL);
		}

		_newReplyString = false;

		return (_replyString = buffer.toString());
	}

	/***
	 * A convenience method to send the SMTP HELO command to the server, receive
	 * the reply, and return the reply code.
	 *

	 *
	 * @param hostname
	 *            The hostname of the sender.
	 * @return The reply code received from the server.
	 * @exception SMTPConnectionClosedException
	 *                If the SMTP server prematurely closes the connection as a
	 *                result of the client being idle or some other reason
	 *                causing the server to send SMTP reply code 421. This
	 *                exception may be caught either as an IOException or
	 *                independently as itself.
	 * @exception IOException
	 *                If an I/O error occurs while either sending the command or
	 *                receiving the server reply.
	 ***/
	public int helo(String hostname) throws IOException {
		return sendCommand(SMTPCommand.HELO, hostname);
	}

	/***
	 * A convenience method to send the SMTP MAIL command to the server, receive
	 * the reply, and return the reply code.
	 *

	 *
	 * @param reversePath
	 *            The reverese path.
	 * @return The reply code received from the server.
	 * @exception SMTPConnectionClosedException
	 *                If the SMTP server prematurely closes the connection as a
	 *                result of the client being idle or some other reason
	 *                causing the server to send SMTP reply code 421. This
	 *                exception may be caught either as an IOException or
	 *                independently as itself.
	 * @exception IOException
	 *                If an I/O error occurs while either sending the command or
	 *                receiving the server reply.
	 ***/
	public int mail(String reversePath) throws IOException {
		return __sendCommand(SMTPCommand.MAIL, reversePath, false);
	}

	/***
	 * A convenience method to send the SMTP RCPT command to the server, receive
	 * the reply, and return the reply code.
	 *

	 *
	 * @param forwardPath
	 *            The forward path.
	 * @return The reply code received from the server.
	 * @exception SMTPConnectionClosedException
	 *                If the SMTP server prematurely closes the connection as a
	 *                result of the client being idle or some other reason
	 *                causing the server to send SMTP reply code 421. This
	 *                exception may be caught either as an IOException or
	 *                independently as itself.
	 * @exception IOException
	 *                If an I/O error occurs while either sending the command or
	 *                receiving the server reply.
	 ***/
	public int rcpt(String forwardPath) throws IOException {
		return __sendCommand(SMTPCommand.RCPT, forwardPath, false);
	}

	/***
	 * A convenience method to send the SMTP DATA command to the server, receive
	 * the reply, and return the reply code.
	 *

	 *
	 * @return The reply code received from the server.
	 * @exception SMTPConnectionClosedException
	 *                If the SMTP server prematurely closes the connection as a
	 *                result of the client being idle or some other reason
	 *                causing the server to send SMTP reply code 421. This
	 *                exception may be caught either as an IOException or
	 *                independently as itself.
	 * @exception IOException
	 *                If an I/O error occurs while either sending the command or
	 *                receiving the server reply.
	 ***/
	public int data() throws IOException {
		return sendCommand(SMTPCommand.DATA);
	}

	/***
	 * A convenience method to send the SMTP SEND command to the server, receive
	 * the reply, and return the reply code.
	 *

	 *
	 * @param reversePath
	 *            The reverese path.
	 * @return The reply code received from the server.
	 * @exception SMTPConnectionClosedException
	 *                If the SMTP server prematurely closes the connection as a
	 *                result of the client being idle or some other reason
	 *                causing the server to send SMTP reply code 421. This
	 *                exception may be caught either as an IOException or
	 *                independently as itself.
	 * @exception IOException
	 *                If an I/O error occurs while either sending the command or
	 *                receiving the server reply.
	 ***/
	public int send(String reversePath) throws IOException {
		return sendCommand(SMTPCommand.SEND, reversePath);
	}

	/***
	 * A convenience method to send the SMTP SOML command to the server, receive
	 * the reply, and return the reply code.
	 *

	 *
	 * @param reversePath
	 *            The reverese path.
	 * @return The reply code received from the server.
	 * @exception SMTPConnectionClosedException
	 *                If the SMTP server prematurely closes the connection as a
	 *                result of the client being idle or some other reason
	 *                causing the server to send SMTP reply code 421. This
	 *                exception may be caught either as an IOException or
	 *                independently as itself.
	 * @exception IOException
	 *                If an I/O error occurs while either sending the command or
	 *                receiving the server reply.
	 ***/
	public int soml(String reversePath) throws IOException {
		return sendCommand(SMTPCommand.SOML, reversePath);
	}

	/***
	 * A convenience method to send the SMTP SAML command to the server, receive
	 * the reply, and return the reply code.
	 *

	 *
	 * @param reversePath
	 *            The reverese path.
	 * @return The reply code received from the server.
	 * @exception SMTPConnectionClosedException
	 *                If the SMTP server prematurely closes the connection as a
	 *                result of the client being idle or some other reason
	 *                causing the server to send SMTP reply code 421. This
	 *                exception may be caught either as an IOException or
	 *                independently as itself.
	 * @exception IOException
	 *                If an I/O error occurs while either sending the command or
	 *                receiving the server reply.
	 ***/
	public int saml(String reversePath) throws IOException {
		return sendCommand(SMTPCommand.SAML, reversePath);
	}

	/***
	 * A convenience method to send the SMTP RSET command to the server, receive
	 * the reply, and return the reply code.
	 *

	 *
	 * @return The reply code received from the server.
	 * @exception SMTPConnectionClosedException
	 *                If the SMTP server prematurely closes the connection as a
	 *                result of the client being idle or some other reason
	 *                causing the server to send SMTP reply code 421. This
	 *                exception may be caught either as an IOException or
	 *                independently as itself.
	 * @exception IOException
	 *                If an I/O error occurs while either sending the command or
	 *                receiving the server reply.
	 ***/
	public int rset() throws IOException {
		return sendCommand(SMTPCommand.RSET);
	}

	/***
	 * A convenience method to send the SMTP VRFY command to the server, receive
	 * the reply, and return the reply code.
	 *

	 *
	 * @param user
	 *            The user address to verify.
	 * @return The reply code received from the server.
	 * @exception SMTPConnectionClosedException
	 *                If the SMTP server prematurely closes the connection as a
	 *                result of the client being idle or some other reason
	 *                causing the server to send SMTP reply code 421. This
	 *                exception may be caught either as an IOException or
	 *                independently as itself.
	 * @exception IOException
	 *                If an I/O error occurs while either sending the command or
	 *                receiving the server reply.
	 ***/
	public int vrfy(String user) throws IOException {
		return sendCommand(SMTPCommand.VRFY, user);
	}

	/***
	 * A convenience method to send the SMTP VRFY command to the server, receive
	 * the reply, and return the reply code.
	 *

	 *
	 * @param name
	 *            The name to expand.
	 * @return The reply code received from the server.
	 * @exception SMTPConnectionClosedException
	 *                If the SMTP server prematurely closes the connection as a
	 *                result of the client being idle or some other reason
	 *                causing the server to send SMTP reply code 421. This
	 *                exception may be caught either as an IOException or
	 *                independently as itself.
	 * @exception IOException
	 *                If an I/O error occurs while either sending the command or
	 *                receiving the server reply.
	 ***/
	public int expn(String name) throws IOException {
		return sendCommand(SMTPCommand.EXPN, name);
	}

	/***
	 * A convenience method to send the SMTP HELP command to the server, receive
	 * the reply, and return the reply code.
	 *

	 *
	 * @return The reply code received from the server.
	 * @exception SMTPConnectionClosedException
	 *                If the SMTP server prematurely closes the connection as a
	 *                result of the client being idle or some other reason
	 *                causing the server to send SMTP reply code 421. This
	 *                exception may be caught either as an IOException or
	 *                independently as itself.
	 * @exception IOException
	 *                If an I/O error occurs while either sending the command or
	 *                receiving the server reply.
	 ***/
	public int help() throws IOException {
		return sendCommand(SMTPCommand.HELP);
	}

	/***
	 * A convenience method to send the SMTP HELP command to the server, receive
	 * the reply, and return the reply code.
	 *

	 *
	 * @param command
	 *            The command name on which to request help.
	 * @return The reply code received from the server.
	 * @exception SMTPConnectionClosedException
	 *                If the SMTP server prematurely closes the connection as a
	 *                result of the client being idle or some other reason
	 *                causing the server to send SMTP reply code 421. This
	 *                exception may be caught either as an IOException or
	 *                independently as itself.
	 * @exception IOException
	 *                If an I/O error occurs while either sending the command or
	 *                receiving the server reply.
	 ***/
	public int help(String command) throws IOException {
		return sendCommand(SMTPCommand.HELP, command);
	}

	/***
	 * A convenience method to send the SMTP NOOP command to the server, receive
	 * the reply, and return the reply code.
	 *

	 *
	 * @return The reply code received from the server.
	 * @exception SMTPConnectionClosedException
	 *                If the SMTP server prematurely closes the connection as a
	 *                result of the client being idle or some other reason
	 *                causing the server to send SMTP reply code 421. This
	 *                exception may be caught either as an IOException or
	 *                independently as itself.
	 * @exception IOException
	 *                If an I/O error occurs while either sending the command or
	 *                receiving the server reply.
	 ***/
	public int noop() throws IOException {
		return sendCommand(SMTPCommand.NOOP);
	}

	/***
	 * A convenience method to send the SMTP TURN command to the server, receive
	 * the reply, and return the reply code.
	 *

	 *
	 * @return The reply code received from the server.
	 * @exception SMTPConnectionClosedException
	 *                If the SMTP server prematurely closes the connection as a
	 *                result of the client being idle or some other reason
	 *                causing the server to send SMTP reply code 421. This
	 *                exception may be caught either as an IOException or
	 *                independently as itself.
	 * @exception IOException
	 *                If an I/O error occurs while either sending the command or
	 *                receiving the server reply.
	 ***/
	public int turn() throws IOException {
		return sendCommand(SMTPCommand.TURN);
	}

	/***
	 * A convenience method to send the SMTP QUIT command to the server, receive
	 * the reply, and return the reply code.
	 *

	 *
	 * @return The reply code received from the server.
	 * @exception SMTPConnectionClosedException
	 *                If the SMTP server prematurely closes the connection as a
	 *                result of the client being idle or some other reason
	 *                causing the server to send SMTP reply code 421. This
	 *                exception may be caught either as an IOException or
	 *                independently as itself.
	 * @exception IOException
	 *                If an I/O error occurs while either sending the command or
	 *                receiving the server reply.
	 ***/
	public int quit() throws IOException {
		return sendCommand(SMTPCommand.QUIT);
	}

}

/*
 * Emacs configuration Local variables: ** mode: java ** c-basic-offset: 4 **
 * indent-tabs-mode: nil ** End: **
 */


text:
var fs = require('fs');
var path = require('path');
var pngquant = require('node-pngquant-native');
var childProcess = require('child_process');

function scanFolder(path) {
    var fileList = [],
        folderList = [],
        walk = function(path, fileList, folderList) {
            files = fs.readdirSync(path);
            files.forEach(function(item) {
                var tmpPath = path + '\\' + item,
                    stats = fs.statSync(tmpPath);

                if (stats.isDirectory()) {
                    walk(tmpPath, fileList, folderList);
                    folderList.push(tmpPath);
                } else {
                    fileList.push(tmpPath);
                }
            });
        };

    walk(path, fileList, folderList);

    return {
        'files': fileList,
        'folders': folderList
    }
}

function mkdirsSync(dirname, mode) {
    if (fs.existsSync(dirname)) {
        return true;
    } else {
        if (mkdirsSync(path.dirname(dirname), mode)) {
            fs.mkdirSync(dirname, mode);
            return true;
        }
    }
}

var srcPath = path.normalize(__dirname + "/../publish/html5/res");

var result = scanFolder(srcPath);

var numCPUs = require('os').cpus().length;

var subPs=[];

var closePs=0;

(function(){
    for(var i = 0 ;i<numCPUs;i++ ){
        var n=childProcess.fork('./______zip1.js');
        n.on('message', function(data) {
            if(data){
                this.send(result.files.pop()+"");
            }else{

                closePs++;
                this.disconnect();
                if(closePs==numCPUs){
                    process.exit();

                }
            }

        });
        n.send(result.files.pop());

    }

})();

for (var j in result.files) {
    var filePath = result.files[j];
    (function(_filePath) {
        for(var k =0; k < subPs.length;k++){
            subPs[k].send(_filePath);

        }

    })(filePath)

}


text:
<?php

namespace Itkg\Core\Event;

/**
 * Class KernelEvents
 *
 * @package Itkg\Core\Event
 */
final class KernelEvents
{
    const CONFIG_LOADED = 'kernel.config.loaded';
    const APP_LOADED = 'kernel.app.loaded';
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<sem:triples xmlns:sem="http://marklogic.com/semantics">
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/presiding-bishop</sem:subject>
    <sem:predicate>http://www.w3.org/1999/02/22-rdf-syntax-ns#type</sem:predicate>
    <sem:object datatype="sem:iri">http://www.w3.org/2004/02/skos/core#Concept</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/presiding-bishop</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#prefLabel</sem:predicate>
    <sem:object xml:lang="eng" datatype="xsd:string">Presiding Bishop</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/presiding-bishop</sem:subject>
    <sem:predicate>http://www.lds.org/core#entityType</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/Role</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/presiding-bishop</sem:subject>
    <sem:predicate>http://www.lds.org/core#partOfSpeech</sem:predicate>
    <sem:object xml:lang="eng" datatype="xsd:string">noun</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/presiding-bishop</sem:subject>
    <sem:predicate>http://www.lds.org/core#instanceOf</sem:predicate>
    <sem:object datatype="xsd:anyURI">http://www.lds.org/scriptures/gs/presiding-bishop</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/presiding-bishop</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#definition</sem:predicate>
    <sem:object xml:lang="eng" datatype="xsd:string">A General Authority in the Church. He has general responsibility over the temporal welfare of the Church (). The Presiding Bishop and his counselors, who are also General Authorities, preside over the Aaronic Priesthood of the Church (; ).</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/presiding-bishop</sem:subject>
    <sem:predicate>http://www.w3.org/2004/02/skos/core#inScheme</sem:predicate>
    <sem:object datatype="sem:iri">http://www.lds.org/concept-scheme/guide-to-the-scriptures</sem:object>
  </sem:triple>
  <sem:triple>
    <sem:subject>http://www.lds.org/concept/gs/presiding-bishop</sem:subject>
    <sem:predicate>http://www.lds.org/core#relCount</sem:predicate>
    <sem:object datatype="xsd:integer">0</sem:object>
  </sem:triple>
</sem:triples>