text:
#include "cor_type/sources/basic_types.h"
#include "cor_type/sources/math/vector2_tmpl.h"

namespace cor
{
    namespace type
    {
        template<class T>class Vector3Tmpl
        {
        public:
            typedef Vector2Tmpl<T> Vector2T;

            typedef T value_type;
            typedef const T* const_iterator;
            typedef T* iterator;

            T x;
            T y;
            T z;

            Vector3Tmpl();
            Vector3Tmpl(const Vector3Tmpl& v);
            Vector3Tmpl(const T& x, const T& y, const T& z);
            template<class Y>Vector3Tmpl(const Y& v)
            {
                if(v.size() >= 1) x = (T)v[0]; else x = (T)0.0;
                if(v.size() >= 2) y = (T)v[1]; else y = (T)0.0;
                if(v.size() >= 3) z = (T)v[2]; else z = (T)0.0;
            }

            ~Vector3Tmpl();

            void set(const T& x, const T& y, const T& z);

            iterator begin();
            iterator end();
            const_iterator begin() const;
            const_iterator end() const;

            RSize size() const;
            T* get_p();
            const T* get_p() const;
            T& operator[](int i);
            const T& operator[](int i) const;

            T get_square_magnitude() const;
            T get_magnitude() const;
            Vector2T& xy();
            const Vector2T& xy() const;
            RBool normalize();
            T dot(const Vector3Tmpl& a) const;
            Vector3Tmpl cross(const Vector3Tmpl& a) const;
            T distance(const Vector3Tmpl& a) const;
            Vector3Tmpl& operator *=(const T& a);
            Vector3Tmpl& operator +=(const Vector3Tmpl& a);
            Vector3Tmpl operator-();

            static Vector3Tmpl zero();
            static Vector3Tmpl one();
            Vector3Tmpl max_vec(const Vector3Tmpl& v) const;
            Vector3Tmpl min_vec(const Vector3Tmpl& v) const;
            RBool all_less(const Vector3Tmpl& v) const;
            RBool some_less(const Vector3Tmpl& v) const;
            RBool all_greater(const Vector3Tmpl& v) const;
            RBool some_greater(const Vector3Tmpl& v) const;
            RBool all_less_equal(const Vector3Tmpl& v) const;
            RBool some_less_equal(const Vector3Tmpl& v) const;
            RBool all_greater_equal(const Vector3Tmpl& v) const;
            RBool some_greater_equal(const Vector3Tmpl& v) const;
            T sum();
        };

        template<class T> Vector3Tmpl<T> operator +(const Vector3Tmpl<T>& a, const Vector3Tmpl<T>& b);
        template<class T> Vector3Tmpl<T> operator -(const Vector3Tmpl<T>& a, const Vector3Tmpl<T>& b);
        template<class T> Vector3Tmpl<T> operator *(const T& a, const Vector3Tmpl<T>& b);
        template<class T> Vector3Tmpl<T> operator *(const Vector3Tmpl<T>& a, const T& b);

        typedef Vector3Tmpl<RFloat> Vector3F;
        typedef Vector3Tmpl<RInt32> Vector3I;
    }
}

#endif


text:
Learning Haskell
================

Some scripts as part of my way of learning Haskell

## Programming in Haskell
Exercises of Gramham Hutton's book **Programming in Haskell**

## Real World Haskell
Exercises of the book **Real World Haskell** by Bryan O'sullivan, John Goerzen and Don Stewart

## Euler
Solutions to some Project Euler problems

## Advent of code
Solutions to some problems from [AdventOfCode](http://adventofcode.com)

redpajama_set_name: RedPajamaGithub


text:
package org.saiku.olap.dto;

public class SaikuMember extends AbstractSaikuObject {

	private String caption;
	private String dimensionUniqueName;
	private String description;
	private String levelUniqueName;
	private String hierarchyUniqueName;

	public SaikuMember() {}

	public SaikuMember(
			String name,
			String uniqueName,
			String caption,
			String description,
			String dimensionUniqueName,
			String hierarchyUniqueName,
			String levelUniqueName)
	{
		super(uniqueName,name);
		this.caption = caption;
		this.description = description;
		this.dimensionUniqueName = dimensionUniqueName;
		this.levelUniqueName = levelUniqueName;
		this.hierarchyUniqueName = hierarchyUniqueName;
	}

	public String getCaption() {
		return caption;
	}

	public String getDescription() {
		return description;
	}

	public String getLevelUniqueName() {
		return levelUniqueName;
	}

	public String getDimensionUniqueName() {
		return dimensionUniqueName;
	}

	public String getHierarchyUniqueName() {
		return hierarchyUniqueName;
	}
}


text:
'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true
});

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var _FuncCompose = require('../Func/compose');

var _FuncCompose2 = _interopRequireDefault(_FuncCompose);

exports['default'] = function (x) {
  return JSON.parse(JSON.stringify(x));
};

module.exports = exports['default'];


text:
<?php
namespace Ratchet\Component\Server;
use Ratchet\Component\MessageComponentInterface;
use Ratchet\Resource\Socket\SocketInterface;
use Ratchet\Resource\ConnectionInterface;
use Ratchet\Resource\Connection;
use Ratchet\Resource\Command\CommandInterface;

/**
 * Creates an open-ended socket to listen on a port for incomming connections.  Events are delegated through this to attached applications
 */
class IOServerComponent implements MessageComponentInterface {
    /**
     * @var array of Socket Resources
     */
    protected $_resources = array();

    /**
     * @var array of resources/Connections
     */
    protected $_connections = array();

    /**
     * The decorated application to send events to
     * @var Ratchet\Component\ComponentInterface
     */
    protected $_decorating;

    /**
     * Number of bytes to read in the TCP buffer at a time
     * Default is (currently) 4kb
     * @var int
     */
    protected $_buffer_size = 4096;

    /**
     * After run() is called, the server will loop as long as this is true
     * This is here for unit testing purposes
     * @var bool
     * @internal
     */
    protected $_run = true;

    public function __construct(MessageComponentInterface $component) {
        $this->_decorating = $component;
    }

    /**
     * Set the incoming buffer size in bytes
     * @param int
     * @return App
     * @throws InvalidArgumentException If the parameter is less than 1
     */
    public function setBufferSize($recv_bytes) {
        if ((int)$recv_bytes < 1) {
            throw new \InvalidArgumentException('Invalid number of bytes set, must be more than 0');
        }

        $this->_buffer_size = (int)$recv_bytes;

        return $this;
    }

    /*
     * Run the server infinitely
     * @param Ratchet\Resource\Socket\SocketInterface
     * @param mixed The address to listen for incoming connections on.  "0.0.0.0" to listen from anywhere
     * @param int The port to listen to connections on (make sure to run as root if < 1000)
     * @throws Ratchet\Exception
     */
    public function run(SocketInterface $host, $address = '127.0.0.1', $port = 1025) {
        $this->_connections[$host->getResource()] = new Connection($host);
        $this->_resources[] = $host->getResource();

        gc_enable();
        set_time_limit(0);
        ob_implicit_flush();

        declare(ticks = 1);

        $host->set_option(SOL_SOCKET, SO_SNDBUF, $this->_buffer_size);
        $host->set_nonblock()->bind($address, (int)$port)->listen();

        do {
            $this->loop($host);
        } while ($this->_run);
    }

    protected function loop(SocketInterface $host) {
        $changed = $this->_resources;

        try {
            $write = $except = null;

            $num_changed = $host->select($changed, $write, $except, null);
        } catch (Exception $e) {
            // master had a problem?...what to do?
            return;
        }

        foreach($changed as $resource) {
            try {
                $conn = $this->_connections[$resource];

                if ($host->getResource() === $resource) {
                    $res = $this->onOpen($conn);
                } else {
                    $data  = $buf = '';
                    $bytes = $conn->getSocket()->recv($buf, $this->_buffer_size, MSG_DONTWAIT);
                    if ($bytes > 0) {
                        $data = $buf;

                        // This idea works* but...
                        // 1) A single DDOS attack will block the entire application (I think)
                        // 2) What if the last message in the frame is equal to $recv_bytes?  Would loop until another msg is sent
                        // 3) This failed...an intermediary can set their buffer lower and this still propagates a fragment
                        // Need to 1) proc_open the recv() calls.  2) ???

                        /*
                        while ($bytes === $recv_bytes) {
                            $bytes = $conn->recv($buf, $recv_bytes, 0);
                            $data .= $buf;
                        }
                        */

                        $res = $this->onMessage($conn, $data);
                    } else {
                        $res = $this->onClose($conn);
                    }
                }
            } catch (\Exception $e) {
                $res = $this->onError($conn, $e);
            }

            while ($res instanceof CommandInterface) {
                try {
                    $new_res = $res->execute($this);
                } catch (\Exception $e) {
                    break;
                    // trigger new error
                    // $new_res = $this->onError($e->getSocket()); ???
                    // this is dangerous territory...could get in an infinte loop...Exception might not be Ratchet\Exception...$new_res could be ActionInterface|Composite|NULL...
                }

                $res = $new_res;
            }
        }
    }

    /**
     * @{inheritdoc}
     */
    public function onOpen(ConnectionInterface $conn) {
        $new_socket     = clone $conn->getSocket();
        $new_socket->set_nonblock();
        $new_connection = new Connection($new_socket);

        $this->_resources[] = $new_connection->getSocket()->getResource();
        $this->_connections[$new_connection->getSocket()->getResource()] = $new_connection;

        return $this->_decorating->onOpen($new_connection);
    }

    /**
     * @{inheritdoc}
     */
    public function onMessage(ConnectionInterface $from, $msg) {
        return $this->_decorating->onMessage($from, $msg);
    }

    /**
     * @{inheritdoc}
     */
    public function onClose(ConnectionInterface $conn) {
        $resource = $conn->getSocket()->getResource();

        $cmd = $this->_decorating->onClose($conn);

        unset($this->_connections[$resource], $this->_resources[array_search($resource, $this->_resources)]);

        return $cmd;
    }

    /**
     * @{inheritdoc}
     */
    public function onError(ConnectionInterface $conn, \Exception $e) {
        return $this->_decorating->onError($conn, $e);
    }
}


text:
ACCEPTED

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

#### Published in
Prelim. rep. forest Pegu. , app. A:lxv, app. B:65. 1875

#### Original name
null

### Remarks
null


text:
package dominio;

public class Hechicero extends Casta {

	public Hechicero(double prob_crit, double evasion, double daño_crit) {
		super(prob_crit, evasion, daño_crit);
		this.nombreCasta="Hechicero";
	}

	public Hechicero()
	{
		super();
		this.nombreCasta="Hechicero";
	}

	//ataca
	public boolean habilidad1(Personaje caster, Peleable atacado) {
		if (caster.getEnergia() > 10) {
			caster.setEnergia(caster.getEnergia() - 10);
			if (atacado.serAtacado((int) (caster.calcularPuntosDeMagia() * 1.5)) != 0)
				return true;
		}
		return false;
	}

	//se cura
	public boolean habilidad2(Personaje caster, Peleable aliado) {
		if (caster.getEnergia() > 10) {
			caster.setEnergia(caster.getEnergia() - 10);
			if (aliado instanceof Personaje) {
				((Personaje) aliado).serCurado(caster.calcularPuntosDeMagia());
				return true;
			}
		}
		return false;
	}

	//roba energia y se cura
	public boolean habilidad3(Personaje caster, Peleable atacado)
	{
		if (caster.getEnergia() > 10) {
			caster.setEnergia(caster.getEnergia() - 10);
			if (atacado instanceof Personaje) {
				int energia_robada = ((Personaje) atacado).serDesernegizado(caster.calcularPuntosDeMagia());
				int salud_robada = ((Personaje) atacado).serRobadoSalud(caster.calcularPuntosDeMagia() / 2);
				caster.serEnergizado(energia_robada);
				caster.serCurado(salud_robada);
				return true;
			}

		}
		return false;
	}

}


text:
#include "stdafx.h"
#include "DataSourceDialog.h"
#include "Library.h"
#include "resource.h"

namespace {
  Cask::CdapOdbc::DataSourceDialog* getSelf(HWND window) {
    return reinterpret_cast<Cask::CdapOdbc::DataSourceDialog*>(::GetWindowLongPtrW(window, GWLP_USERDATA));
  }
}

INT_PTR Cask::CdapOdbc::DataSourceDialog::dialogProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) {
  switch (uMsg) {
    case WM_INITDIALOG:
      ::SetWindowLongPtrW(hwndDlg, GWLP_USERDATA, lParam);
      getSelf(hwndDlg)->init(hwndDlg);
      return TRUE;
    case WM_COMMAND:
      switch (LOWORD(wParam)) {
        case IDOK:
          getSelf(hwndDlg)->readFromDialog(hwndDlg);
        case IDCANCEL:
          ::EndDialog(hwndDlg, wParam);
          return TRUE;
      }
  }

  return FALSE;
}

void Cask::CdapOdbc::DataSourceDialog::init(HWND window) {
  ::SetDlgItemTextW(window, IDC_NAME, this->getName().c_str());
}

void Cask::CdapOdbc::DataSourceDialog::readFromDialog(HWND window) {
  const int MaxLen = 255;
  wchar_t buffer[MaxLen];
  UINT size = 0;
  BOOL result = FALSE;

  size = ::GetDlgItemTextW(window, IDC_NAME, buffer, MaxLen);
  if (size > 0) {
    this->setName(buffer);
  }
}

Cask::CdapOdbc::DataSourceDialog::DataSourceDialog(HWND parent)
  : parent(parent)
  , result(false) {
}

Cask::CdapOdbc::DataSourceDialog::~DataSourceDialog() {
}

bool Cask::CdapOdbc::DataSourceDialog::show() {
  return ::DialogBoxParamW(
    Library::getInstanceHandle(),
    MAKEINTRESOURCE(IDD_DSNDIALOG),
    this->parent,
    dialogProc,
    reinterpret_cast<LPARAM>(this)) == IDOK;
}


text:
package io.crate.integrationtests;

import io.crate.metadata.PartitionName;
import io.crate.testing.SQLResponse;
import io.crate.testing.TestingHelpers;
import org.apache.lucene.util.Version;
import org.elasticsearch.cluster.metadata.IndexMetadata;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.test.ESIntegTestCase;
import org.junit.Before;
import org.junit.Test;

import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static io.crate.protocols.postgres.PGErrorStatus.INTERNAL_ERROR;
import static io.crate.protocols.postgres.PGErrorStatus.UNDEFINED_COLUMN;
import static io.crate.protocols.postgres.PGErrorStatus.UNDEFINED_TABLE;
import static io.crate.testing.Asserts.assertThrows;
import static io.crate.testing.SQLErrorMatcher.isSQLError;
import static io.crate.testing.TestingHelpers.resolveCanonicalString;
import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND;
import static org.hamcrest.Matchers.arrayContaining;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;

@ESIntegTestCase.ClusterScope(numClientNodes = 0, numDataNodes = 2, supportsDedicatedMasters = false)
public class SysShardsTest extends SQLTransportIntegrationTest {

    @Before
    public void initTestData() throws Exception {
        Setup setup = new Setup(sqlExecutor);
        setup.groupBySetup();
        execute("create table quotes (id integer primary key, quote string) with (number_of_replicas=1)");
        execute("create blob table blobs clustered into 5 shards with (number_of_replicas=1)");
        ensureGreen();
    }

    @Test
    public void testPathAndBlobPath() throws Exception {
        Path blobs = createTempDir("blobs");
        execute("create table t1 (x int) clustered into 1 shards with (number_of_replicas = 0)");
        execute("create blob table b1 clustered into 1 shards with (number_of_replicas = 0)");
        execute("create blob table b2 " +
                "clustered into 1 shards with (number_of_replicas = 0, blobs_path = '" + blobs.toString() + "')");
        ensureYellow();

        execute("select path, blob_path from sys.shards where table_name in ('t1', 'b1', 'b2') " +
                "order by table_name asc");
        // b1
        // path + /blobs == blob_path without custom blob path
        assertThat(response.rows()[0][0] + resolveCanonicalString("/blobs"), is(response.rows()[0][1]));

        ClusterService clusterService = internalCluster().getInstance(ClusterService.class);
        Metadata metadata = clusterService.state().getMetadata();
        IndexMetadata index = metadata.index(".blob_b2");
        String indexUUID = index.getIndexUUID();

        // b2
        String b2Path = (String) response.rows()[1][0];
        assertThat(b2Path, containsString(resolveCanonicalString("/nodes/")));
        assertThat(b2Path, endsWith(resolveCanonicalString("/indices/" + indexUUID + "/0")));

        String b2BlobPath = (String) response.rows()[1][1];
        assertThat(b2BlobPath, containsString(resolveCanonicalString("/nodes/")));
        assertThat(b2BlobPath, endsWith(resolveCanonicalString("/indices/" + indexUUID + "/0/blobs")));
        // t1
        assertThat(response.rows()[2][1], nullValue());
    }

    @Test
    public void testSelectGroupByWhereTable() throws Exception {
        SQLResponse response = execute("" +
                                       "select count(*), num_docs from sys.shards where table_name = 'characters' " +
                                       "group by num_docs order by count(*)");
        assertThat(response.rowCount(), greaterThan(0L));
    }

    @Test
    public void testSelectGroupByAllTables() throws Exception {
        SQLResponse response = execute("select count(*), table_name from sys.shards " +
                                       "group by table_name order by table_name");
        assertEquals(3L, response.rowCount());
        assertEquals(10L, response.rows()[0][0]);
        assertEquals("blobs", response.rows()[0][1]);
        assertEquals("characters", response.rows()[1][1]);
        assertEquals("quotes", response.rows()[2][1]);
    }

    @Test
    public void testGroupByWithLimitUnassignedShards() throws Exception {
        try {
            execute("create table t (id int, name string) with (number_of_replicas=2, \"write.wait_for_active_shards\"=1)");
            ensureYellow();

            SQLResponse response = execute("select sum(num_docs), table_name, sum(num_docs) from sys.shards group by table_name order by table_name desc limit 1000");
            assertThat(response.rowCount(), is(4L));
            assertThat(TestingHelpers.printedTable(response.rows()),
                is("0| t| 0\n" +
                   "0| quotes| 0\n" +
                   "14| characters| 14\n" +
                   "0| blobs| 0\n"));
        } finally {
            execute("drop table t");
        }
    }

    @Test
    public void testSelectGroupByWhereNotLike() throws Exception {
        SQLResponse response = execute("select count(*), table_name from sys.shards " +
                                       "where table_name not like 'my_table%' group by table_name order by table_name");
        assertEquals(3L, response.rowCount());
        assertEquals(10L, response.rows()[0][0]);
        assertEquals("blobs", response.rows()[0][1]);
        assertEquals(8L, response.rows()[1][0]);
        assertEquals("characters", response.rows()[1][1]);
        assertEquals(8L, response.rows()[2][0]);
        assertEquals("quotes", response.rows()[2][1]);
    }

    @Test
    public void testSelectWhereTable() throws Exception {
        SQLResponse response = execute(
            "select id, size from sys.shards " +
            "where table_name = 'characters'");
        assertEquals(8L, response.rowCount());
    }

    @Test
    public void testSelectStarWhereTable() throws Exception {
        SQLResponse response = execute(
            "select * from sys.shards where table_name = 'characters'");
        assertEquals(8L, response.rowCount());
    }

    @Test
    public void testSelectStarAllTables() throws Exception {
        SQLResponse response = execute("select * from sys.shards");
        assertEquals(26L, response.rowCount());
        assertEquals(19, response.cols().length);
        assertThat(response.cols(), arrayContaining(
            "blob_path",
            "id",
            "min_lucene_version",
            "node",
            "num_docs",
            "orphan_partition",
            "partition_ident",
            "path",
            "primary",
            "recovery",
            "relocating_node",
            "retention_leases",
            "routing_state",
            "schema_name",
            "seq_no_stats",
            "size",
            "state",
            "table_name",
            "translog_stats"));
    }

    @Test
    public void testSelectStarLike() throws Exception {
        SQLResponse response = execute(
            "select * from sys.shards where table_name like 'charact%'");
        assertEquals(8L, response.rowCount());
    }

    @Test
    public void testSelectStarNotLike() throws Exception {
        SQLResponse response = execute(
            "select * from sys.shards where table_name not like 'quotes%'");
        assertEquals(18L, response.rowCount());
    }

    @Test
    public void testSelectStarIn() throws Exception {
        SQLResponse response = execute(
            "select * from sys.shards where table_name in ('characters')");
        assertEquals(8L, response.rowCount());
    }

    @Test
    public void test_translog_stats_can_be_retrieved() {
        execute("SELECT translog_stats, translog_stats['size'] FROM sys.shards " +
                "WHERE id = 0 AND \"primary\" = true AND table_name = 'characters'");
        Object[] resultRow = response.rows()[0];
        Map<String, Object> translogStats = (Map<String, Object>) resultRow[0];
        assertThat(((Number) translogStats.get("size")).longValue(), is(resultRow[1]));
        assertThat(((Number) translogStats.get("uncommitted_size")).longValue(), greaterThanOrEqualTo(0L));
        assertThat(((Number) translogStats.get("number_of_operations")).longValue(), greaterThanOrEqualTo(0L));
        assertThat(((Number) translogStats.get("uncommitted_operations")).longValue(), greaterThanOrEqualTo(0L));
    }

    @Test
    public void testSelectStarMatch() throws Exception {
        assertThrows(() -> execute("select * from sys.shards where match(table_name, 'characters')"),
                     isSQLError(is("Cannot use MATCH on system tables"), INTERNAL_ERROR, BAD_REQUEST, 4004));
    }

    @Test
    public void testSelectOrderBy() throws Exception {
        SQLResponse response = execute("select table_name, min_lucene_version, * " +
                                       "from sys.shards order by table_name");
        assertEquals(26L, response.rowCount());
        List<String> tableNames = Arrays.asList("blobs", "characters", "quotes");
        for (Object[] row : response.rows()) {
            assertThat(tableNames.contains(row[0]), is(true));
            assertThat(row[1], is(Version.LATEST.toString()));
        }
    }

    @Test
    public void testSelectGreaterThan() throws Exception {
        SQLResponse response = execute("select * from sys.shards where num_docs > 0");
        assertThat(response.rowCount(), greaterThan(0L));
    }

    @Test
    public void testSelectWhereBoolean() throws Exception {
        SQLResponse response = execute("select * from sys.shards where \"primary\" = false");
        assertEquals(13L, response.rowCount());
    }

    @Test
    public void testSelectGlobalAggregates() throws Exception {
        SQLResponse response = execute(
            "select sum(size), min(size), max(size), avg(size) from sys.shards");
        assertEquals(1L, response.rowCount());
        assertEquals(4, response.rows()[0].length);
        assertNotNull(response.rows()[0][0]);
        assertNotNull(response.rows()[0][1]);
        assertNotNull(response.rows()[0][2]);
        assertNotNull(response.rows()[0][3]);
    }

    @Test
    public void testSelectGlobalCount() throws Exception {
        SQLResponse response = execute("select count(*) from sys.shards");
        assertEquals(1L, response.rowCount());
        assertEquals(26L, response.rows()[0][0]);
    }

    @Test
    public void testSelectGlobalCountAndOthers() throws Exception {
        SQLResponse response = execute("select count(*), max(table_name) from sys.shards");
        assertEquals(1L, response.rowCount());
        assertEquals(26L, response.rows()[0][0]);
        assertEquals("quotes", response.rows()[0][1]);
    }

    @Test
    public void testGroupByUnknownResultColumn() throws Exception {
        assertThrows(() -> execute("select lol from sys.shards group by table_name"),
                     isSQLError(is("Column lol unknown"), UNDEFINED_COLUMN, NOT_FOUND, 4043));
    }

    @Test
    public void testGroupByUnknownGroupByColumn() throws Exception {
        assertThrows(() -> execute("select max(num_docs) from sys.shards group by lol"),
                     isSQLError(is("Column lol unknown"), UNDEFINED_COLUMN, NOT_FOUND, 4043));
    }

    @Test
    public void testGroupByUnknownOrderBy() throws Exception {
        assertThrows(() -> execute(
            "select sum(num_docs), table_name from sys.shards group by table_name order by lol"),
                     isSQLError(is("Column lol unknown"), UNDEFINED_COLUMN, NOT_FOUND, 4043));
    }

    @Test
    public void testGroupByUnknownWhere() throws Exception {
        assertThrows(() -> execute(
            "select sum(num_docs), table_name from sys.shards where lol='funky' group by table_name"),
                     isSQLError(is("Column lol unknown"), UNDEFINED_COLUMN, NOT_FOUND, 4043));
        ;
    }

    @Test
    public void testGlobalAggregateUnknownWhere() throws Exception {
        assertThrows(() -> execute(
            "select sum(num_docs) from sys.shards where lol='funky'"),
                     isSQLError(is("Column lol unknown"), UNDEFINED_COLUMN, NOT_FOUND, 4043));
    }

    @Test
    public void testSelectShardIdFromSysNodes() throws Exception {
        assertThrows(() -> execute(
            "select sys.shards.id from sys.nodes"),
                     isSQLError(is("Relation 'sys.shards' unknown"), UNDEFINED_TABLE, NOT_FOUND, 4041));
    }

    @Test
    public void testSelectWithOrderByColumnNotInOutputs() throws Exception {
        // regression test... query failed with ArrayOutOfBoundsException due to inputColumn mangling in planner
        SQLResponse response = execute("select id from sys.shards order by table_name limit 1");
        assertThat(response.rowCount(), is(1L));
        assertThat(response.rows()[0][0], instanceOf(Integer.class));
    }

    @Test
    public void testSelectGroupByHaving() throws Exception {
        SQLResponse response = execute("select count(*) " +
                                       "from sys.shards " +
                                       "group by table_name " +
                                       "having table_name = 'quotes'");
        assertThat(TestingHelpers.printedTable(response.rows()), is("8\n"));
    }

    @Test
    public void testSelectNodeSysExpression() throws Exception {
        SQLResponse response = execute(
            "select node, node['name'], id from sys.shards order by node['name'], id  limit 1");
        assertEquals(1L, response.rowCount());
        Map<String, Object> fullNode = (Map<String, Object>) response.rows()[0][0];
        String nodeName = response.rows()[0][1].toString();
        assertEquals("node_s0", nodeName);
        assertEquals("node_s0", fullNode.get("name"));
    }

    @Test
    public void testOrphanedPartitionExpression() throws Exception {
        try {
            execute("create table c.orphan_test (id int primary key, p string primary key) " +
                    "partitioned by (p) " +
                    "clustered into 1 shards " +
                    "with (number_of_replicas = 0)"
            );
            execute("insert into c.orphan_test (id, p) values (1, 'foo')");
            ensureYellow();

            SQLResponse response = execute(
                "select orphan_partition from sys.shards where table_name = 'orphan_test'");
            assertThat(TestingHelpers.printedTable(response.rows()), is("false\n"));

            client().admin().indices()
                .prepareDeleteTemplate(PartitionName.templateName("c", "orphan_test"))
                .execute().get(1, TimeUnit.SECONDS);

            response = execute(
                "select orphan_partition from sys.shards where table_name = 'orphan_test'");
            assertThat(TestingHelpers.printedTable(response.rows()), is("true\n"));
        } finally {
            execute("drop table c.orphan_test");
        }
    }

    @Test
    public void testSelectNodeSysExpressionWithUnassignedShards() throws Exception {
        try {
            execute("create table users (id integer primary key, name string) " +
                    "clustered into 5 shards with (number_of_replicas=2, \"write.wait_for_active_shards\"=1)");
            ensureYellow();
            SQLResponse response = execute(
                "select node['name'], id from sys.shards where table_name = 'users' order by node['name'] nulls last"
            );
            String nodeName = response.rows()[0][0].toString();
            assertEquals("node_s0", nodeName);
            assertThat(response.rows()[12][0], is(nullValue()));
        } finally {
            execute("drop table users");
        }
    }

    @Test
    public void testSelectRecoveryExpression() throws Exception {
        SQLResponse response = execute("select recovery, " +
                                       "recovery['files'], recovery['files']['used'], recovery['files']['reused'], recovery['files']['recovered'], " +
                                       "recovery['size'], recovery['size']['used'], recovery['size']['reused'], recovery['size']['recovered'] " +
                                       "from sys.shards");
        for (Object[] row : response.rows()) {
            Map recovery = (Map) row[0];
            Map<String, Integer> files = (Map<String, Integer>) row[1];
            assertThat(((Map<String, Integer>) recovery.get("files")).entrySet(), equalTo(files.entrySet()));
            Map<String, Long> size = (Map<String, Long>) row[5];
            assertThat(((Map<String, Long>) recovery.get("size")).entrySet(), equalTo(size.entrySet()));
        }
    }

    @Test
    public void testScalarEvaluatesInErrorOnSysShards() throws Exception {
        // we need at least 1 shard, otherwise the table is empty and no evaluation occurs
        execute("create table t1 (id integer) clustered into 1 shards with (number_of_replicas=0)");
        ensureYellow();
        assertThrows(() -> execute(
            "select 1/0 from sys.shards"),
                     isSQLError(is("/ by zero"), INTERNAL_ERROR, BAD_REQUEST, 4000));
    }
}


text:
Findable::Base.query.redis.flushdb

# Initialize SQLite
ActiveRecord::Base.establish_connection({
  adapter: "sqlite3",
  database: ":memory:",
})

ActiveRecord::Migration.create_table :users do |t|
  t.string :name
  t.integer :cart_id
  t.string :content_type
  t.integer :content_id
end

ActiveRecord::Migration.create_table :statuses do |t|
  t.integer :total_payments
  t.integer :user_id
end

ActiveRecord::Migration.create_table :comments do |t|
  t.text :body
  t.integer :user_id
  t.integer :product_id
end

ActiveRecord::Migration.create_table :pictures do |t|
  t.string :name
end

# =========================
# Model definitions
# =========================

# Model < Findable
%w(Category Product Image PurchaseHistory Cart).each do |class_name|
  Object.const_set(class_name, Class.new(Findable::Base))
end

# Model < ActiveRecord
%w(User Comment Status Picture).each do |class_name|
  Object.const_set(class_name, Class.new(ActiveRecord::Base))
end

ActiveRecord::Base.subclasses.each do |ar|
  ar.include Findable::Associations::ActiveRecordExt
end

# Associations (Findable <=> Findable)
Category.has_many :products
Product.belongs_to :category
Product.has_one :image
Image.belongs_to :product

# Associations (ActiveRecord <=> ActiveRecord)
User.has_many :comments
User.has_one :status
Comment.belongs_to :user
Status.belongs_to :user

# Associations (Findable <=> ActiveRecord)
Product.has_many :comments
Comment.belongs_to :product

Cart.has_one :user
User.belongs_to :cart

User.has_many :purchase_histories
PurchaseHistory.belongs_to :user

User.has_one :image
Image.belongs_to :user

# Polymorphic association
User.belongs_to :content, polymorphic: true
Image.belongs_to :content, polymorphic: true

# =========================
# Data import
# =========================
CategoryData = [
  {id: 1, name: "Book"},
  {id: 2, name: "Computer"},
]
Category.query.import(CategoryData)

ProductData = [
  {id: 1, name: "book1", category_id: 1},
  {id: 2, name: "book2", category_id: 1},
]
Product.query.import(ProductData)

ImageData = [
  {id: 1, product_id: 1, user_id: 1, content_type: "User", content_id: 1},
  {id: 2, product_id: 2, user_id: 2, content_type: "Category", content_id: 1},
]
Image.query.import(ImageData)

CartData = [{id: 1}, {id: 2}]
Cart.query.import(CartData)

Picture.create(name: "example.jpg")
User.create(name: "user1", content_type: "Picture", content_id: Picture.first.id, cart_id: CartData.first[:id])
User.create(name: "user2", content_type: "Image", content_id: Image.first.id, cart_id: CartData.second[:id])
User.all.each do |user|
  user.create_status!(total_payments: rand(100_000))
  user.comments.create!(body: "some comment", product_id: Product.take.id)
end

User.all.each do |user|
  PurchaseHistory.create(user_id: user.id)
end


text:
$Title = "VSAN Configuration Maximum Total Magnetic Disks In All Disk Groups Per Host Report"
$Header =  "VSAN Config Max -  Total Magnetic Disks In All Disk Groups Per Host"
$Display = "Table"
$Author = "William Lam"
$PluginVersion = 1.2
$PluginCategory = "vSphere"

# Start of Settings
# Percentage threshold to warn?
$vsanWarningThreshold = 50
# End of Settings

# Update settings where there is an override
$vsanWarningThreshold = Get-vCheckSetting $Title "vsanWarningThreshold" $vsanWarningThreshold

# This config maximum is different for each version of VSAN, 35 for 5.5
$vsanTotalMDMaximum = 35

foreach ($cluster in $clusviews) {
   if($cluster.ConfigurationEx.VsanConfigInfo.Enabled) {
      foreach ($vmhost in $cluster.Host |  Sort-Object -Property Name) {
         $totalMDs = 0
         $vmhostView = Get-View $vmhost -Property Name,ConfigManager.VsanSystem
         $vsanSys = Get-View -Id $vmhostView.ConfigManager.VsanSystem
         foreach ($diskMapping in $vsanSys.Config.StorageInfo.DiskMapping) {
            $mds = ($diskMapping.NonSsd | Measure-Object).count
            $totalMDs += $mds
         }
         $checkValue = [int]($totalMDs/$vsanTotalMDMaximum * 100)

         if($checkValue -gt $vsanWarningThreshold) {
            New-Object -TypeName PSObject -Property @{
               "VMhost" = $vmhostView.Name
               "TotalMDCount" = $mds }
         }
      }
   }
}

$Comments = ("VSAN hosts approaching {0}% limit of {1} total magnetic disks in all Disk Groups per host" -f $vsanWarningThreshold, $vsanTotalMDMaximum)

# Changelog
## 1.0 : Initial Release
## 1.1 : Fix indentation + using global $clusviews
## 1.2 : Add Get-vCheckSetting


text:
namespace Watcher.Messages
{
    public class ManagementResponse
    {
        public int NotifyHour { get; set; }
        public bool NotifyDayLater { get; set; }
        public bool GetEmailNotifications { get; set; }
        public bool Success { get; set; }
    }
}


text:
package org.dashbuilder.common.client.validation.editors;

import com.github.gwtbootstrap.client.ui.Tooltip;
import com.github.gwtbootstrap.client.ui.constants.Placement;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.dom.client.Style;
import com.google.gwt.editor.client.EditorError;
import com.google.gwt.editor.client.HasEditorErrors;
import com.google.gwt.editor.client.IsEditor;
import com.google.gwt.editor.ui.client.adapters.ValueBoxEditor;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.logical.shared.HasValueChangeHandlers;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiChild;
import com.google.gwt.uibinder.client.UiConstructor;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.*;

import java.util.List;

/**
 *
Editor component decorator that wraps an editor widget and provides displaying of output validation messages.

 *
The output validation messages can be displayed as:

 *

 *
Labels - The validation errors are placed in a label on the RIGHT or LEFT side of the editor widget.

 *
Tooltip - The validation errors are displayed using a tooltip.

 *

 * @param <T> The type of the value that contains the editor widget.
 */
public class ValueBoxEditorDecorator<T> extends Composite implements
        HasValue<T>, HasEditorErrors<T>, IsEditor<ValueBoxEditor<T>> {

    // The GWT bootstrap styles for error panels.
    private static final String STYLE_ERROR = " control-group error ";
    private T value;

    @Override
    public HandlerRegistration addValueChangeHandler(ValueChangeHandler<T> handler) {
        return addHandler(handler, ValueChangeEvent.getType());
    }

    @Override
    public T getValue() {
        return value;
    }

    @Override
    public void setValue(T value) {
        setValue(value, false);
    }

    @Override
    public void setValue(T value, boolean fireEvents) {
        // Disable current error markers, if present.
        disableError();

        if (value == this.value || (this.value != null && this.value.equals(value))) {
            return;
        }

        T before = this.value;
        this.value = value;

        if (fireEvents) {
            ValueChangeEvent.fireIfNotEqual(this, before, value);
        }
    }

    interface Binder extends UiBinder<Widget, ValueBoxEditorDecorator<?>> {
        Binder BINDER = GWT.create(Binder.class);
    }

    interface ValueBoxEditorDecoratorStyle extends CssResource {
        String contents();
        String errorLabel();
        String errorLabelLeft();
        String errorLabelRight();

    }

    @UiField ValueBoxEditorDecoratorStyle style;

    @UiField
    SimplePanel contents;

    @UiField
    DivElement errorLabel;

    @UiField
    Tooltip errorTooltip;

    public enum ErrorLabelPosition {
        LEFT, RIGHT, TOOLTIP_TOP, TOOLTIP_BOTTOM;
    }

    private ValueBoxEditor<T> editor;
    private ErrorLabelPosition errorLabelPosition;

    /**
     * Constructs a ValueBoxEditorDecorator.
     */
    @UiConstructor
    public ValueBoxEditorDecorator() {
        // By default, show errors using tooltips.
        errorLabelPosition = ErrorLabelPosition.TOOLTIP_TOP;
        initWidget(Binder.BINDER.createAndBindUi(this));
    }

    /**
     * Constructs a ValueBoxEditorDecorator using a {@link com.google.gwt.user.client.ui.ValueBoxBase}
     * widget and a {@link com.google.gwt.editor.ui.client.adapters.ValueBoxEditor} editor.
     *
     * @param widget the widget
     * @param editor the editor
     */
    public ValueBoxEditorDecorator(ValueBoxBase<T> widget,
                                   ValueBoxEditor<T> editor) {
        this();
        contents.add(widget);
        this.editor = editor;
        listenToValueBoxBaseChangeEvent(widget);
    }

    /**
     * Returns the associated {@link com.google.gwt.editor.ui.client.adapters.ValueBoxEditor}.
     *
     * @return a {@link com.google.gwt.editor.ui.client.adapters.ValueBoxEditor} instance
     * @see #setEditor(com.google.gwt.editor.ui.client.adapters.ValueBoxEditor)
     */
    public ValueBoxEditor<T> asEditor() {
        return editor;
    }

    /**
     * Sets the associated {@link com.google.gwt.editor.ui.client.adapters.ValueBoxEditor}.
     *
     * @param editor a {@link com.google.gwt.editor.ui.client.adapters.ValueBoxEditor} instance
     * @see #asEditor()
     */
    public void setEditor(ValueBoxEditor<T> editor) {
        this.editor = editor;
    }

    /**
     * Set the widget that the EditorPanel will display. This method will
     * automatically call {@link #setEditor}.
     *
     * @param widget a {@link com.google.gwt.user.client.ui.ValueBoxBase} widget
     */
    @UiChild(limit = 1, tagname = "valuebox")
    public void setValueBox(final ValueBoxBase<T> widget) {
        contents.add(widget);
        listenToValueBoxBaseChangeEvent(widget);
        setEditor(widget.asEditor());
    }

    public void setEnabled(final boolean enabled) {
        ((ValueBoxBase)contents.getWidget()).setEnabled(enabled);
    }

    private void listenToValueBoxBaseChangeEvent(final ValueBoxBase<T> widget) {
        if (widget != null) {
            final T before = widget.getValue();
            widget.addChangeHandler(new ChangeHandler() {
                @Override
                public void onChange(ChangeEvent event) {
                    disableError();
                }
            });
            widget.addValueChangeHandler(new ValueChangeHandler<T>() {
                @Override
                public void onValueChange(ValueChangeEvent<T> event) {
                    disableError();
                    ValueChangeEvent.fireIfNotEqual(ValueBoxEditorDecorator.this, before, event.getValue());
                }
            });
        }
    }

    /**
     * The default implementation will display, but not consume, received errors
     * whose {@link com.google.gwt.editor.client.EditorError#getEditor() getEditor()} method returns the Editor
     * passed into {@link #setEditor}.
     *
     * @param errors a List of {@link com.google.gwt.editor.client.EditorError} instances
     */
    public void showErrors(List<EditorError> errors) {
        StringBuilder sb = new StringBuilder();
        for (EditorError error : errors) {
            if (error.getEditor().equals(editor)) {
                sb.append("\n").append(error.getMessage());
            }
        }

        boolean hasErrors = sb.length() > 0;
        if (!hasErrors) {
            disableError();
            return;
        }

        // Show the errors.
        enableError(sb.substring(1));
    }

    private void enableError(String text) {
        contents.addStyleName(STYLE_ERROR);
        if (isUsingErrorLabel()) {
            setErrorLabelText(text);
            setTooltipText(null);
        } else {
            setErrorLabelText(null);
            setTooltipText(text);
        }
    }

    private void disableError() {
        contents.removeStyleName(STYLE_ERROR);
        setErrorLabelText(null);
        setTooltipText(null);
    }

    private void setTooltipText(String text) {
        if (text == null || text.trim().length() == 0) {
            errorTooltip.setText("");
        } else {
            errorTooltip.setText(text);
        }
        reconfigureTooltip();
    }

    private void setErrorLabelText(String text) {
        if (text == null || text.trim().length() == 0) {
            errorLabel.setInnerText("");
            errorLabel.getStyle().setDisplay(Style.Display.NONE);
        } else {
            errorLabel.setInnerText(text);
            errorLabel.getStyle().setDisplay(Style.Display.INLINE);
        }
    }

    private boolean isUsingErrorLabel() {
        return !isUsingErrorTooltip();
    }

    private boolean isUsingErrorTooltip() {
        return ErrorLabelPosition.TOOLTIP_TOP.equals(getErrorLabelPosition()) || ErrorLabelPosition.TOOLTIP_BOTTOM.equals(getErrorLabelPosition());
    }

    public ErrorLabelPosition getErrorLabelPosition() {
        return errorLabelPosition;
    }

    public void setErrorLabelPosition(ErrorLabelPosition errorLabelPosition) {
        this.errorLabelPosition = errorLabelPosition;
        positionErrorLabel();
    }

    private void positionErrorLabel() {
        switch (errorLabelPosition) {
            case TOOLTIP_TOP:
                errorTooltip.setPlacement(Placement.TOP);
                reconfigureTooltip();
                break;
            case TOOLTIP_BOTTOM:
                errorTooltip.setPlacement(Placement.BOTTOM);
                reconfigureTooltip();
                break;
            case LEFT:
                errorLabel.addClassName(style.errorLabelLeft());
                break;
            default:
                errorLabel.addClassName(style.errorLabelRight());
                break;
        }
    }

    // See issue https://github.com/gwtbootstrap/gwt-bootstrap/issues/287
    private void reconfigureTooltip() {
        errorTooltip.reconfigure();
    }

    public void clear() {
        setValue(null);
        disableError();
    }

}


text:
layout: post
date:	2007-09-06 14:23:00
title:  Pleasant Surprise...and Migration to other blogs...
tags: [archived-posts]
categories: archives
permalink: /:categories/:year/:month/:day/:title/
---
Got a call from <LJ user="chirdeep_shetty"> (who has moved his journal to Blogspot, alas!)and am trying to maximize the very little time he has here, and see what birding we can do....completely forgot to ask him about Manasi Prasad, whom I got to know through <LJ user="say_yes04"> and Radio Verve...and my friend in Tanzania invited her to Dar es Salaam for two concerts. She tells me that <LJ user="anirudhc"> (who has ALSO moved to Blogspot, gaaahhhh...), Chirdeep and all, were buddies in engg college...

Connections are so convoluted, and in Bengaluru they sometimes have a way of leading over the same ground again, too.

But why is everyone moving to Blogspot? Is there something that I am missing? All it means is, I have to physically visit these people's blogs instead of having them pop up on my friends' list...of course there is probably a technical way to solve this problem, but I am not a "software" person and I don't know how!


text:
layout: post
title: The World Once Laughed at North Korean Cyberpower. No More.
source: https://www.nytimes.com/2017/10/15/world/asia/north-korea-hacking-cyber-sony.html
category: HackerNews
description: SiteLog - While the world is fixated on its nuclear missiles, North Korea has also developed a cyberattack program that is stealing millions and unleashing havoc.
numwords: 1
hnscore:
---

...

![](https://static01.nyt.com/images/2017/10/16/world/16nkoreahack-1alt/16nkoreahack-1alt-facebookJumbo-v3.jpg)
<!--description-->


text:
/**
 * Gerado por template generation
 * Diretiva de overwrite atual:
 * TemplateName:
 **/
package br.com.dlp.jazzqa.tiporequisito;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.springframework.stereotype.Component;

import br.com.dlp.framework.dao.AbstractHibernateDAO;
import br.com.dlp.framework.dao.QueryOrder;

/**
 * Incluir arquivo com comentários
 *
 * Implementação de DAO para o componente TipoRequisitoVO
 *
 **/
@Component
public class TipoRequisitoHibernateDAOImpl extends AbstractHibernateDAO<TipoRequisitoVO> implements TipoRequisitoDAO {

	private static final long serialVersionUID = 4188683927282245182L;

	/**
	 * Pesquisa entidades do tipo TipoRequisitoVO
	 * @author dpacifico
	 * @param nome
 	 * @param descricao
	 * @returns Coleção de TipoRequisitoVO
	 */
	public List<TipoRequisitoVO> findTipoRequisitoVO(String nome, String descricao){

		DetachedCriteria criteria = createDetachedCriteria();

	 	eqRestriction(nome, criteria, "nome");
 		ilikeRestriction(descricao, criteria, "descricao");

		return getHibernateTemplate().findByCriteria(criteria);

	}

	/**
	 * Pesquisa entidades do tipo TipoRequisitoVO
	 * @author dpacifico
	 * @param nome
 	 * @param descricao
	 * @param QueryOrder Ordenação de pesquisa
	 * @returns Coleção de TipoRequisitoVO
	 */
	public List<TipoRequisitoVO> findTipoRequisitoVO(String nome, String descricao, QueryOrder... queryOrders){

		DetachedCriteria criteria = createDetachedCriteria();

	 	eqRestriction(nome, criteria, "nome");
 		ilikeRestriction(descricao, criteria, "descricao");

		order(criteria, queryOrders);
		return getHibernateTemplate().findByCriteria(criteria);

	}
}


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>

<link href="../../libs/css/import_basic.css" rel="stylesheet" type="text/css"/>
<link rel="stylesheet" type="text/css" id="skin" prePath="../../"/>
<link rel="stylesheet" type="text/css" id="customSkin"/>

 <fieldset>
   <legend>1、不含标题</legend>

  </fieldset>

   <fieldset>
   <legend>2、含标题</legend>

  </fieldset>

  <fieldset>
   <legend>3、含边框效果</legend>

  </fieldset>

   <fieldset>
   <legend>4、文字链接</legend>
   文字链接
  </fieldset>


text:
<?php

namespace PHPCR\Shell\Subscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use PHPCR\Shell\Event\PhpcrShellEvents;
use PHPCR\Shell\Event\ProfileInitEvent;
use Symfony\Component\Console\Helper\QuestionHelper;
use PHPCR\Shell\Config\ProfileLoader;

class ProfileWriterSubscriber implements EventSubscriberInterface
{
    protected $profileLoader;
    protected $questionHelper;

    public static function getSubscribedEvents()
    {
        return array(
            PhpcrShellEvents::PROFILE_INIT => 'handleProfileInit',
        );
    }

    public function __construct(ProfileLoader $profileLoader, $questionHelper)
    {
        $this->profileLoader = $profileLoader;
        $this->questionHelper = $questionHelper;
    }

    public function handleProfileInit(ProfileInitEvent $e)
    {
        $profile = $e->getProfile();
        $input = $e->getInput();
        $output = $e->getOutput();
        $transport = $input->getOption('transport');
        $profileName = $input->getOption('profile');

        // if both transport and profile specified, then user wants
        // to create or update an existing profile
        if ($profileName && $transport) {
            $profile->setName($profileName);
            $overwrite = false;

            if (file_exists($this->profileLoader->getProfilePath($profileName))) {
                $res = $this->questionHelper->askConfirmation($output, sprintf('Update existing profile "%s"?', $profileName));
                $overwrite = true;
            } else {
                $res = $this->questionHelper->askConfirmation($output, sprintf('Create new profile "%s"?', $profileName));
            }

            if ($res) {
                $this->profileLoader->saveProfile($profile, $overwrite);
            }
        }
    }
}


text:
{-# LANGUAGE GeneralizedNewtypeDeriving, TemplateHaskell,
             DeriveDataTypeable, PatternGuards,
             DeriveFunctor, DeriveFoldable, DeriveTraversable #-}

-- Those extensions are required by the Uniplate instances.
--{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-}
module Language.LaTeX.Types where

import Prelude hiding (and, foldr, foldl, foldr1, foldl1, elem, concatMap, concat)
import Data.Monoid (Monoid(..))
import Data.List (intercalate)
import Data.Ratio ((%))
import Data.Foldable
import Data.String (IsString(..))
-- import Data.Generics.PlateTypeable
import Data.Data
import Control.Applicative
import Control.Arrow (second)
import Control.Monad.Writer (Writer)
import Control.Monad.Trans ()
import Control.Monad.Error

data Document = Document { documentClass     :: DocumentClss
                         , documentPreamble  :: PreambleItm
                         , documentBody      :: ParItm }
  deriving (Show, Eq, Typeable, Data)

type LineNumber = Int
type CharNumber = Int

data Loc = Loc { locFile :: FilePath
               , locLine :: LineNumber
               , locChar :: CharNumber
               }
   deriving (Show, Eq, Typeable, Data)

data Note = TextNote String
          | IntNote Int
          | LocNote Loc
   deriving (Show, Eq, Typeable, Data)

data DocumentClassKind  = Article
                        | Book
                        | Report
                        | Letter
                        | OtherDocumentClassKind String
  deriving (Show, Eq, Typeable, Data)

data DocumentClss
  = DocClass  {  docClassKind     :: DocumentClassKind
              ,  docClassOptions  :: [AnyItm]
              }
  deriving (Show, Eq, Typeable, Data)

data AnyItm = PreambleItm PreambleItm
            | LatexItm    LatexItm
            | MathItm     MathItm
            | ParItm      ParItm
            | LocSpecs    [LocSpec]
            | Key         Key
            | PackageName PackageName
            | Coord       Coord
            | Length      LatexLength
            | SaveBin     SaveBin
  deriving (Show, Eq, Typeable, Data)

data PreambleItm = PreambleCmdArgs String [Arg AnyItm]
                 | PreambleEnv String [Arg AnyItm] AnyItm
                 | PreambleCast AnyItm
                 | PreambleConcat [PreambleItm]
                 | RawPreamble String
                 | PreambleNote Key Note PreambleItm
  deriving (Show, Eq, Typeable, Data)

instance Semigroup PreambleItm where
  PreambleConcat xs <> PreambleConcat ys = PreambleConcat (xs ++ ys)
  PreambleConcat xs <> y                 = PreambleConcat (xs ++ [y])
  x                 <> PreambleConcat ys = PreambleConcat (x : ys)
  x                 <> y                 = PreambleConcat [x, y]

instance Monoid PreambleItm where
  mempty = PreambleConcat []

data TexDcl = TexDcl { texDeclName :: String
                     , texDeclArgs :: [Arg AnyItm]
                     }
  deriving (Show, Eq, Typeable, Data)

-- This is the subset of tex strings that fits in the LR mode.
-- The distinction between the paragraph and the LR mode is always
-- made explicit using the Para constructor.
--
-- Modes: http://www.personal.ceu.hu/tex/modes.htm
data LatexItm
           = LatexCmdArgs String [Arg LatexItm]
           | LatexCmdAnyArgs String [Arg AnyItm]
           | TexDecls [TexDcl]
           | TexCmdNoArg String
           | TexCmdArg String LatexItm
           | Environment String [Arg AnyItm] AnyItm
           | RawTex String
           | LatexCast AnyItm -- a cast from math induce $...$
           | TexGroup LatexItm
           | LatexEmpty
           | LatexAppend LatexItm LatexItm
           | LatexNote Key Note LatexItm
  deriving (Show, Eq, Typeable, Data)

appendAny :: AnyItm -> AnyItm -> Maybe AnyItm
appendAny (PreambleItm x) (PreambleItm y) = Just $ PreambleItm (x `mappend` y)
appendAny (LatexItm x)    (LatexItm y)    = Just $ LatexItm (x `mappend` y)
appendAny (MathItm x)     (MathItm y)     = Just $ MathItm (x `mappend` y)
appendAny (ParItm x)      (ParItm y)      = Just $ ParItm (x `mappend` y)
appendAny (LocSpecs x)    (LocSpecs y)    = Just $ LocSpecs (x `mappend` y)
-- this lengthy matching is to get a warning when we extend the AnyItm type
appendAny PreambleItm{} _ = Nothing
appendAny LatexItm{}    _ = Nothing
appendAny MathItm{}     _ = Nothing
appendAny ParItm{}      _ = Nothing
appendAny LocSpecs{}    _ = Nothing
appendAny Key{}         _ = Nothing
appendAny PackageName{} _ = Nothing
appendAny Coord{}       _ = Nothing
appendAny Length{}      _ = Nothing
appendAny SaveBin{}     _ = Nothing

instance Semigroup LatexItm where
  RawTex xs       <> RawTex ys = RawTex (xs ++ ys)
  LatexCast x     <> LatexCast y | Just z <- appendAny x y = LatexCast z
  LatexEmpty      <> x = x
  x               <> LatexEmpty = x
  LatexAppend x y <> z = x <> (y <> z) -- TODO complexity issue?
  x <> LatexAppend y z =
    case x <> y of
      LatexAppend x' y' -> x' `LatexAppend` (y' <> z) -- TODO complexity issue?
      xy                -> xy <> z
  x               <> y = x `LatexAppend` y

instance Monoid LatexItm where
  mempty  = LatexEmpty -- LatexConcat []

{-
  LatexConcat xs `mappend` LatexConcat ys = LatexConcat (xs ++ ys)
  LatexConcat xs `mappend` y              = LatexConcat (xs ++ [y])
  x              `mappend` LatexConcat ys = LatexConcat (x : ys)
  x              `mappend` y              = LatexConcat [x, y]
-}

instance IsString LatexItm where
  fromString s
    | null s    = mempty
    | otherwise = f s
    where f = RawTex . concatMap rawhchar . intercalate "\n" . filter (not . null) . lines

data Named a = Named String a
  deriving (Show, Eq, Typeable, Data, Functor, Foldable, Traversable)

data PackageAction = PackageDependency PackageName
                   | ProvidePackage    PackageName
  deriving (Show, Eq, Typeable, Data)

data Arg a = NoArg
           | StarArg             -- `*'
           | Mandatory [a]       -- surrounded by `{' `}', separated by `,'
           | Optional [a]        -- surrounded by `[' `]', separated by `,' or empty if null
           | NamedArgs [Named a] -- surrounded by `{' `}', separated by `=` and `,'
           | NamedOpts [Named a] -- surrounded by `[' `]', separated by `=' and `,' or empty if null
           | Coordinates a a     -- surrounded by `(' `)', separated by ` '
           | RawArg String
           | LiftArg a
           | PackageAction PackageAction
  deriving (Show, Eq, Typeable, Data, Functor, Foldable, Traversable)

data Star = Star | NoStar
  deriving (Show, Eq, Typeable, Data)

instance Semigroup Star where
  NoStar <> x      = x
  x      <> _      = x

instance Monoid Star where
  mempty = NoStar

data Coord = MkCoord LatexLength LatexLength
  deriving (Show, Eq, Typeable, Data)

newtype Percentage = Percentage { percentage :: Int } deriving (Eq,Show,Ord,Num)

data ParItm  = ParCmdArgs String [Arg AnyItm]
             | ParEnv String [Arg AnyItm] AnyItm
             | Tabular [RowSpec LatexItm] [Row LatexItm]
             | RawParMode String
             | ParCast AnyItm -- a cast from Math induce \[...\]
             | ParGroup ParItm -- check validity of this
             | ParConcat [ParItm]
             | ParNote Key Note ParItm
  deriving (Show, Eq, Typeable, Data)

instance Semigroup ParItm where
  ParConcat xs <> ParConcat ys = ParConcat (xs ++ ys)
  ParConcat xs <> y            = ParConcat (xs ++ [y])
  x            <> ParConcat ys = ParConcat (x : ys)
  x            <> y            = ParConcat [x, y]

instance Monoid ParItm where
  mempty = ParConcat []

unParNote :: ParItm -> Maybe (Key, Note, ParItm)
unParNote (ParNote k n p) = Just (k, n, p)
unParNote _               = Nothing

uncatParItm :: ParItm -> [ParItm]
uncatParItm (ParConcat pars) = pars
uncatParItm par              = [par]

newtype MathDcl = MathDcl String
  deriving (Show, Eq, Typeable, Data)

data MathItm   = MathDecls [MathDcl]
               | MathCmdArgs String [Arg AnyItm]
               | MathArray [RowSpec MathItm] [Row MathItm]
               | RawMath String
               | MathCast AnyItm
               | MathRat Rational
               | MathGroup MathItm
               | MathConcat [MathItm]
               | MathBinOp String MathItm MathItm
               | MathUnOp String MathItm
               | MathNote Key Note MathItm
  deriving (Show, Eq, Typeable, Data)

instance Semigroup MathItm where
  MathConcat xs <> MathConcat ys = MathConcat (xs ++ ys)
  MathConcat xs <> y             = MathConcat (xs ++ [y])
  x             <> MathConcat ys = MathConcat (x : ys)
  x             <> y             = MathConcat [x, y]

instance Monoid MathItm where
  mempty = MathConcat []

instance Num MathItm where
  (+) = MathBinOp "+"
  (*) = MathBinOp "*"
  (-) = MathBinOp "-"
  negate = MathUnOp "-"
  abs x = MathCmdArgs "abs" [Mandatory [MathItm x]] -- TODO check
  signum = error "MathItm.signum is undefined"
  fromInteger = MathRat . (%1)

instance Fractional MathItm where
  (/) = MathBinOp "/"
  fromRational = MathRat

{-
instance Real MathItm where
  toRational = error "MathItm.toRational is undefined"

instance Integral MathItm where
  mod = MathBinOp "bmod"
  -- TODO quot, rem
-}

data TexUnit
  = Sp -- ^ Scalled point (1pt = 65536sp)
  | Pt -- ^ Point unit size (1pt = 0.351mm)
  | Bp -- ^ Big point (1in = 72bp), also PostScript point
  | Dd -- ^ Didôt point (1dd = 0.376mm)
  | Em -- ^ One em is about the width of the letter M in the current font
  | Ex -- ^ One ex is about the hoigh of the letter x in the current font
  | Cm -- ^ Centimeter unit size
  | Mm -- ^ Milimeter unit size (1mm = 2.845pt)
  | In -- ^ Inch unit size (1in = 72.27pt)
  | Pc -- ^ Picas (1pc = 12pt)
  | Cc -- ^ Cicero (1dd = 12dd = 4.531mm)
  | Mu -- ^ Math unit (18mu = 1em)
  deriving (Eq, Ord, Enum, Show, Typeable, Data)

data LatexLength = LengthScaledBy Rational LatexLength
                 | LengthCmdRatArg String Rational
                 | LengthCmd String
                 | LengthCst (Maybe TexUnit) Rational
  deriving (Show, Eq, Typeable, Data)

lengthCst :: LatexLength -> Maybe (Maybe TexUnit, Rational)
lengthCst (LengthScaledBy rat len) = second (rat *) <$> lengthCst len
lengthCst (LengthCmdRatArg _ _)    = Nothing
lengthCst (LengthCmd _)            = Nothing
lengthCst (LengthCst mtu rat)      = Just (mtu, rat)

safeLengthOp :: String -> (Rational -> Rational -> Rational) -> LatexLength -> LatexLength -> LatexLength
safeLengthOp _ op (LengthCst Nothing     rx) (LengthCst munit ry)
  = LengthCst munit (op rx ry)
safeLengthOp _ op (LengthCst (Just unit) rx) (LengthCst Nothing ry)
  = LengthCst (Just unit) (op rx ry)
safeLengthOp op _ x y
  = error $ "LatexLength." ++ op
         ++ ": undefined on non constants terms (" ++ show x ++ op ++ show y ++ ")"

scaleBy :: Rational -> LatexLength -> LatexLength
scaleBy rx (LengthScaledBy ry l)   = LengthScaledBy (rx * ry) l
scaleBy rx (LengthCst munit ry)    = LengthCst munit (rx * ry)
scaleBy rx (LengthCmd cmd)         = LengthScaledBy rx (LengthCmd cmd)
scaleBy rx (LengthCmdRatArg cmd r) = LengthScaledBy rx (LengthCmdRatArg cmd r)

instance Num LatexLength where
  LengthCst Nothing x * y = scaleBy x y
  x * LengthCst Nothing y = scaleBy y x
  x * y                   = safeLengthOp "*" (*) x y

  (+) = safeLengthOp "+" (+)
  (-) = safeLengthOp "-" (-)
  negate x = LengthCst Nothing (-1) * x
  abs = error "LatexLength.abs is undefined"
  signum = error "LatexLength.signum is undefined"
  fromInteger = LengthCst Nothing . (%1)

instance Semigroup LatexLength where
  (<>) = (+)

instance Monoid LatexLength where
  mempty = 0

instance Fractional LatexLength where
  x / LengthCst Nothing ry = scaleBy (1/ry) x
  x / y                    = safeLengthOp "/" (/) x y
  fromRational = LengthCst Nothing

-- p{wd}, and *{num}{cols} are explicitly
-- not supported, it seems much more natural and
-- simple to obtain the same goals using standard
-- programming uppon the rows and cells.
data RowSpec a = Rc --- ^ Centered
               | Rl --- ^ Left
               | Rr --- ^ Right
               | Rvline --- ^ A vertical line
               | Rtext a --- ^ A fixed text column (@-expression in LaTeX parlance)
  deriving (Show, Eq, Typeable, Data, Functor, Foldable, Traversable)

{-
instance Functor RowSpec where
  _ `fmap` Rc         = Rc
  _ `fmap` Rl         = Rl
  _ `fmap` Rr         = Rr
  _ `fmap` Rvline     = Rvline
  f `fmap` (Rtext x)  = Rtext $ f x

instance Foldable RowSpec where
  foldr _ z Rc        = z
  foldr _ z Rl        = z
  foldr _ z Rr        = z
  foldr _ z Rvline    = z
  foldr f z (Rtext x) = f x z

instance Traversable RowSpec where
  sequenceA Rc        = pure Rc
  sequenceA Rl        = pure Rl
  sequenceA Rr        = pure Rr
  sequenceA Rvline    = pure Rvline
  sequenceA (Rtext x) = Rtext <$> x
-}

data LocSpec = Lh --- ^ Here
             | Lt --- ^ Top
             | Lb --- ^ Bottom
             | Lp --- ^ Page of floats: on a sperate page containing no text,
                  ---   only figures and tables.
  deriving (Show, Eq, Typeable, Data)

locSpecChar :: LocSpec -> Char
locSpecChar Lh = 'h'
locSpecChar Lt = 't'
locSpecChar Lb = 'b'
locSpecChar Lp = 'p'

data Pos = Centered   -- ^ Centered (default).
         | FlushLeft  -- ^ Flush left
         | FlushRight -- ^ Flush right
         | Stretch -- ^ Stretch (justify) across entire width; text must contain
                   -- stretchable space for this to work.

charPos :: Pos -> Char
charPos Centered   = 'c'
charPos FlushLeft  = 'l'
charPos FlushRight = 'r'
charPos Stretch    = 's'

-- TODO: add more paper sizes
data LatexPaperSize = A4paper | OtherPaperSize String
  deriving (Show, Eq, Typeable, Data)

{- NOTE: their is no handling of the \multicolumn command at the moment -}
data Row cell = Cells [cell]
              | Hline
              | Cline Int Int
  deriving (Show, Eq, Typeable, Data, Functor, Foldable, Traversable)

{-
instance Functor Row where
  f `fmap` Cells cs  = Cells (fmap f cs)
  _ `fmap` Hline     = Hline
  _ `fmap` Cline i j = Cline i j

instance Foldable Row where
  foldr f z (Cells cs)  = foldr f z cs
  foldr _ z Hline       = z
  foldr _ z (Cline _ _) = z

instance Traversable Row where
  sequenceA (Cells cs)  = Cells <$> sequenceA cs
  sequenceA Hline       = pure Hline
  sequenceA (Cline i j) = pure $ Cline i j
-}

data ListItm = ListItm { itemOptions :: [Arg LatexItm], itemContents :: ParItm }

newtype PackageName = PkgName { getPkgName :: String }
  deriving (Ord, Eq, Show, Typeable, Data)

newtype Key = MkKey { getKey :: String }
  deriving (Eq, Show, Typeable, Data)

newtype SaveBin = UnsafeMakeSaveBin { unsafeGetSaveBin :: Int }
  deriving (Eq, Show, Typeable, Data)

data LatexState = LS { freshSaveBin :: SaveBin }

instance (Error a, Eq a, Show a, Num b) => Num (Either a b) where
  fromInteger = pure . fromInteger
  (+)         = liftM2 (+)
  (-)         = liftM2 (-)
  (*)         = liftM2 (*)
  negate      = liftM negate
  abs         = liftM abs
  signum      = liftM signum

instance (Error a, Eq a, Show a, Fractional b) => Fractional (Either a b) where
  (/) = liftM2 (/)
  fromRational = pure . fromRational

type ErrorMessage = String

newtype LatexM a = LatexM { runLatexM :: Either ErrorMessage a }
  deriving (Functor, Applicative, Alternative, Monad, MonadPlus,
            MonadError ErrorMessage, Show, Eq, Num, Fractional,
            Typeable, Data)

instance Semigroup a => Semigroup (LatexM a) where
  (<>) = liftM2 (<>)
-- sconcat = liftM sconcat . sequenceA

instance Monoid a => Monoid (LatexM a) where
  mempty = pure mempty

instance IsString a => IsString (LatexM a) where fromString = pure . fromString

type TexDecl   = LatexM TexDcl
type LatexItem = LatexM LatexItm
type ParItem   = LatexM ParItm
type MathDecl  = LatexM MathDcl
newtype AnyItem   = AnyItem { anyItmM :: LatexM AnyItm }
  deriving (Eq, Show, Typeable, Data)
newtype MathItem  = MathItem { mathItmM :: LatexM MathItm }
  deriving (Semigroup, Monoid, Eq, Show, Num, Fractional, Typeable, Data)

type ListItem  = LatexM ListItm
type PreambleItem = LatexM PreambleItm
type DocumentClass = LatexM DocumentClss

type TexDeclW      = Writer TexDecl ()
type LatexItemW    = Writer LatexItem ()
type ParItemW      = Writer ParItem ()
type MathDeclW     = Writer MathDecl ()
type MathItemW     = Writer MathItem ()
type PreambleItemW = Writer PreambleItem ()

-- TODO: Maybe one should handle quotes in a less LaTeX
-- way: provide a replacement for ``...'' and escape `'"
--
-- NOTE: Don't confuse this function with ttchar
-- NOTE: this raw Tex is ugly
rawhchar :: Char -> String
rawhchar '\\'  = "\\textbackslash{}"
rawhchar '<'   = "\\textless{}"
rawhchar '>'   = "\\textgreater{}"
rawhchar '|'   = "\\textbar{}"
rawhchar x
  | x `elem` "~^_#&{}$%" = ['\\',x,'{','}']
  | x `elem` ":]["       = ['{', x, '}'] -- '[' and ']' are escaped to avoid mess up optional args
  | otherwise            = [x]

-- | Type for encodings used in commands like.
-- @\usepackage[utf8]{inputenc}@, that we can
-- express as 'useInputenc' 'utf8'.
newtype Encoding = Encoding { fromEncoding :: String }
  deriving (Eq,Ord,Show)

-- instance (Integral a, Typeable a, Typeable b, PlateAll a b) => PlateAll (Ratio a) b where
--   plateAll r = plate (%) |+ numerator r |+ denominator r

{-
$(derive makeUniplateTypeable ''SaveBin)
$(derive makeUniplateTypeable ''PackageName)
$(derive makeUniplateTypeable ''Loc)
$(derive makeUniplateTypeable ''Note)
$(derive makeUniplateTypeable ''Arg)
$(derive makeUniplateTypeable ''Key)
$(derive makeUniplateTypeable ''Row)
$(derive makeUniplateTypeable ''RowSpec)
$(derive makeUniplateTypeable ''LocSpec)
$(derive makeUniplateTypeable ''LatexLength)
$(derive makeUniplateTypeable ''Coord)
$(derive makeUniplateTypeable ''DocumentClassKind)

$(derive makeUniplateTypeable ''TexDcl)
$(derive makeUniplateTypeable ''MathItm)
$(derive makeUniplateTypeable ''MathDcl)
$(derive makeUniplateTypeable ''ParItm)
$(derive makeUniplateTypeable ''TexUnit)
$(derive makeUniplateTypeable ''LatexItm)
$(derive makeUniplateTypeable ''DocumentClass)
$(derive makeUniplateTypeable ''PreambleItm)
$(derive makeUniplateTypeable ''Document)
-}


text:
LuCI hd-idle
(c) 2008 Yanira <forum-2008@email.de>

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

$Id$

]]--

module("luci.controller.hd_idle", package.seeall)

function index()
	if not nixio.fs.access("/etc/config/hd-idle") then
		return
	end

	local page

	page = entry({"admin", "services", "hd_idle"}, cbi("hd_idle"), _("hd-idle"), 60)
	page.dependent = true
end


text:
package com.coolweather.app.model;

public class Country {

	private int id;
	private int cityId;
	private String countryname;
	private String countrycode;

	public void setid(int id){
		this.id = id;
	}
	public int getid(){
		return id;
	}

	public void setname(String name){
		this.countryname = name;
	}
	public String getname(){
		return countryname;
	}

	public void setcode(String code){
		this.countrycode = code;
	}
	public String getcode(){
		return countrycode;
	}

	public void setcityId(int id){
		this.cityId = id;
	}
	public int getcityId(){
		return cityId;
	}
}


text:
package com.cubolabs.bibliaofflinearc.ui;

public class LINE {
    public static final int FIRST = 0;
    public static final int FOOTER = 2;
    public static final int HEADER = 3;
    public static final int HEADER_FIRST = 4;
    public static final int SUBHEADER = 5;
    public static final int SUBHEADER_FIRST = 6;
}


text:
=head1 NAME

HiveLoadAlphaFoldDBProteinFeatures.pm

=head1 DESCRIPTION

This module inserts protein features into an Ensembl core database based on the AlphaFoldDB-UniProt mappings found in the EMBL-EBI AlphaFoldDB SIFTS data and the UniProt-ENSP mappings found in the GIFTS database in order to make the link between AlphaFoldDB and ENSP having a AlphaFoldDB entry as a protein feature for a given ENSP protein.

It also populates the "pdb_ens" table in the GIFTS database with similar data.

=head1 OPTIONS

-alpha_path     Path to file containing the AlphaFoldDB mapping data (including file name).

-core_dbhost    Core database host name.

-core_dbport    Core database port.

-core_dbname    Core database name.

-core_dbuser    Core database username to connect as.

-core_dbpass    Core database password to use.

-cs_version     Coordinate system version.

-species        Production name of species to process

-rest_server    GIFTS rest server to fetch the perfect matches data from.

=head1 EXAMPLE USAGE

standaloneJob.pl Bio::EnsEMBL::Production::Pipeline::AlphaFold::HiveLoadAlphaFoldDBProteinFeatures -alpha_path /hps/nobackup/flicek/ensembl/mr6/AlphaFoldDB/homo_sapiens/alpha_mappings.txt -core_dbhost genebuild3 -core_dbport 4500 -core_dbname carlos_homo_sapiens_core_89_test -core_dbuser *** -core_dbpass *** -cs_version GRCh38 -species homo_sapiens -rest_server https://www.ebi.ac.uk/gifts/api/

=cut

package Bio::EnsEMBL::Production::Pipeline::AlphaFold::HiveLoadAlphaFoldDBProteinFeatures;

use strict;
use warnings;

use 5.014002;
use Bio::EnsEMBL::Analysis::Tools::Utilities;
use parent ('Bio::EnsEMBL::Analysis::Hive::RunnableDB::HiveBaseRunnableDB');
use Bio::EnsEMBL::Production::Pipeline::AlphaFold::MakeAlphaFoldDBProteinFeatures;
use Bio::EnsEMBL::Utils::Exception qw(throw info);

use Net::FTP;
use Bio::EnsEMBL::DBSQL::DBAdaptor;
use Getopt::Long;
use File::Basename;
use File::Find;
use List::Util qw(sum);

use Bio::EnsEMBL::Analysis::Tools::Utilities qw(run_command);

sub param_defaults {
    my ($self) = @_;

    return {
      %{$self->SUPER::param_defaults},
      alpha_path => undef,
      core_dbhost => undef,
      core_dbport => undef,
      core_dbname => undef,
      core_dbuser => undef,
      core_dbpass => undef,
      cs_version => undef,
      species => undef,
      rest_server => undef,
    }
}

sub fetch_input {
  my $self = shift;

  $self->param_required('alpha_path');
  $self->param_required('core_dbhost');
  $self->param_required('core_dbport');
  $self->param_required('core_dbname');
  $self->param_required('core_dbuser');
  $self->param_required('core_dbpass');
  $self->param_required('cs_version');
  $self->param_required('species');
  $self->param_required('rest_server');

  # connect to the core database
  my $core_dba = Bio::EnsEMBL::DBSQL::DBAdaptor->new(
                   '-no_cache' => 1,
                   '-host'     => $self->param('core_dbhost'),
                   '-port'     => $self->param('core_dbport'),
                   '-user'     => $self->param('core_dbuser'),
                   '-pass' => $self->param('core_dbpass'),
                   '-dbname' => $self->param('core_dbname'),
  ) or die('Failed to connect to the core database.');

  $self->hrdb_set_con($core_dba,"core");

  info(sprintf("Cleaning up old protein features and analysis for species %s\n", $self->{'species'}));
  $self->cleanup_protein_features('alphafold_import');

  info(sprintf("Initiating MakeAlphaFoldDBProteinFeatures and creating the analysis object for species %s\n", $self->{'species'}));
  my $runnable = Bio::EnsEMBL::Production::Pipeline::AlphaFold::MakeAlphaFoldDBProteinFeatures->new(
    -analysis => new Bio::EnsEMBL::Analysis(-logic_name => 'alphafold_import',
                                            -db => 'alphafold',
                                            #-db_version => , it will be populated in the MakePDBProteinFeatures module when parsing the file
                                            -db_file => $self->param('alpha_path'),
                                            -display_label => 'AlphaFoldDB import',
                                            -displayable => '1',
                                            -description => 'Protein features based on the AlphaFoldDB-UniProt mappings'),
    -core_dba => $self->hrdb_get_con("core"),
    -alpha_path => $self->param('alpha_path'),
    -species => $self->param('species'),
    -cs_version => $self->param('cs_version'),
    -rest_server => $self->param('rest_server')
    );
  $self->runnable($runnable);

  return 1;
}

sub run {
  my $self = shift;

  foreach my $runnable (@{$self->runnable}) {
    $runnable->run();
    $self->output($runnable->output);
  }
}

sub write_output {
  my $self = shift;

  # insert the Ensembl-PDB links into the protein_feature table in the core database
  # and add its associated xrefs
  $self->insert_protein_features();

  return 1;
}

sub insert_protein_features() {
# insert the protein features and their associated xrefs into the database 'core_dba'

  my $self = shift;

  my $core_dba = $self->hrdb_get_con("core");
  my $pfa = $core_dba->get_ProteinFeatureAdaptor();

  foreach my $pf_hashref (@{$self->output}) {
    my ($translation_id) = keys %$pf_hashref;
    $pfa->store($pf_hashref->{$translation_id},$translation_id);

    # This is not done because we only want to insert "real" IDs in the dbprimary_acc column.
    # Fake "abcd.A" PDB.chain IDs are not linkable to any external DB at the moment.
    #$self->insert_protein_features_xrefs($core_dba,$pf_hashref->{$translation_id},$translation_id);
  }
}

sub insert_protein_features_xrefs {
# Inserts a PDB protein feature translation xref
  my ($self,$db_adaptor,$pf,$translation_id) = @_;

  my $dbe_adaptor = $db_adaptor->get_DBEntryAdaptor();
  my ($pdb_acc,$pdb_chain) = split(/\./,$pf->hseqname());
  my $pf_description = $pf->hdescription();
  my @pf_description_array = split(' ',$pf_description);

  my $pdb_xref = new Bio::EnsEMBL::DBEntry(
                                             -adaptor => $dbe_adaptor,
                                             -primary_id => $pdb_acc.".".$pdb_chain,
                                             -version => 0,
                                             -dbname  => 'PDB',
                                             -release => 1,
                                             -display_id => $pdb_acc.".".$pdb_chain,
                                             -description => $pf_description,
                                             -priority => 5,
                                             -db_display_name => 'PDB',
                                             -info_type => 'DEPENDENT',
                                             -type => 'MISC'
                                           );
  $pdb_xref->status('XREF');
  $pdb_xref->analysis($pf->analysis());
  $dbe_adaptor->store($pdb_xref,$translation_id,'Translation');
}

sub cleanup_protein_features() {
# cleans up the protein features from the database 'core_dba'

  my ($self, $analysis_logic_name) = @_;

  my $core_dba = $self->hrdb_get_con("core");
  my $ana = $core_dba->get_AnalysisAdaptor();

  my $analysis = $ana->fetch_by_logic_name($analysis_logic_name);

  if (defined($analysis)) {
      my $analysis_id = $analysis->dbID();
      info(sprintf("Found alphafold_import analysis (ID: $analysis_id) for species %s. Deleting it ...\n", $self->{'species'}));

      my $pfa = $core_dba->get_ProteinFeatureAdaptor();
      $pfa->remove_by_analysis_id($analysis_id);

      $ana->remove($analysis);
  }

}

1;


text:
<?php

namespace BingAds\CampaignManagement;

/**
 * Retrieves the ads that belong to the specified ad group and have the specified editorial review status.
 * @link http://msdn.microsoft.com/en-us/library/dn277538(v=msads.90).aspx GetAdsByEditorialStatusRequest Request Object
 */
final class GetAdsByEditorialStatusRequest
{
    /**
     * The identifier of the ad group to retrieve the ads from.
     * @var long
     */
    public $AdGroupId;

    /**
     * The AdEditorialStatus value that specifies the review status that the ads must have to be returned.
     * @var AdEditorialStatus
     */
    public $EditorialStatus;
}


text:
ActiveRecord::Schema.define(version: 20140604025304) do

  create_table "ingredients", force: true do |t|
    t.string   "name"
    t.string   "description"
    t.string   "type"
    t.integer  "quanity"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

end


text:
<?php
/**
 * AppViewer.php
 *
 * @since 29/05/15
 * @author gseidel
 */

namespace Enhavo\Bundle\AppBundle\Viewer\Viewer;

use Enhavo\Bundle\AppBundle\Controller\RequestConfiguration;
use Enhavo\Bundle\AppBundle\Viewer\AbstractResourceViewer;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\OptionsResolver\OptionsResolver;

class BaseViewer extends AbstractResourceViewer
{
    public function getType()
    {
        return 'base';
    }

    protected function buildTemplateParameters(ParameterBag $parameters, RequestConfiguration $requestConfiguration, array $options)
    {
        parent::buildTemplateParameters($parameters, $requestConfiguration, $options);

        $parameters->set('stylesheets', $this->mergeConfigArray([
            $this->container->getParameter('enhavo_app.stylesheets'),
            $options['stylesheets'],
            $this->getViewerOption('stylesheets', $requestConfiguration)
        ]));

        $parameters->set('javascripts', $this->mergeConfigArray([
            $this->container->getParameter('enhavo_app.javascripts'),
            $options['javascripts'],
            $this->getViewerOption('javascripts', $requestConfiguration)
        ]));

        $parameters->set('translation_domain', $this->mergeConfig([
            $options['translation_domain'],
            $this->getViewerOption('translation_domain', $requestConfiguration)
        ]));

        $parameters->set('routes', $this->mergeConfig([
            $options['translation_domain'],
            $this->getViewerOption('translation_domain', $requestConfiguration)
        ]));

        $dumper = $this->container->get('enhavo_app.translation.translation_dumper');
        $translations = $dumper->getTranslations('javascript', $this->container->get('enhavo_app.locale_resolver')->resolve());
        $parameters->set('translations', $translations);
        $parameters->set('routes', $this->getRoutes());

        $data = [
            'view' => [
                'id' => $this->getViewId(),
                'label' => $this->container->get('translator')->trans($options['label'], [], $parameters->get('translation_domain'))
            ],
        ];
        $parameters->set('data', $data);

        foreach($options['parameters'] as $key => $value) {
            $parameters->set($key, $value);
        }
    }

    public function configureOptions(OptionsResolver $optionsResolver)
    {
        parent::configureOptions($optionsResolver);
        $optionsResolver->setDefaults([
            'javascripts' => [],
            'stylesheets' => [],
            'translation_domain' => null,
            'template' => 'admin/view/base.html.twig',
            'parameters' => [],
            'label' => ''
        ]);
    }

    private function getRoutes()
    {
        $file = $this->container->getParameter('kernel.project_dir').'/public/js/fos_js_routes.json';
        if(file_exists($file)) {
            return file_get_contents($file);
        }
        return null;
    }

    /**
     * @param $bundlePrefix
     * @param $resourceName
     * @param $action
     * @return string
     */
    public function getRoleNameByResourceName($bundlePrefix, $resourceName, $action)
    {
        $roleName = strtoupper(sprintf('ROLE_%s_%s_%s', $bundlePrefix, $resourceName, $action));
        return $roleName;
    }
}


text:
exports.definition = {
	config: {
		'adapter': {
			'type': 'sql',
			'db_file': '/dbs/colors.sqlite',
			'collection_name': 'colors'
		}
	},
	extendCollection: function(Collection) {
		_.extend(Collection.prototype, {

			// For Backbone v1.1.2, uncomment this to override the fetch method
			/*
			fetch: function(options) {
				options = options ? _.clone(options) : {};
				options.reset = true;
				return Backbone.Collection.prototype.fetch.call(this, options);
			},
			*/
		});
		return Collection;
	}
};


text: Este programa é financiado pela União Europeia


text:
using System;
using Pliant.Tokens;
using Pliant.Utilities;

namespace Pliant.Grammars
{
    public class TerminalLexerRule : BaseLexerRule, ITerminalLexerRule
    {
        public ITerminal Terminal { get; }

        public static readonly LexerRuleType TerminalLexerRuleType = new LexerRuleType("Terminal");

        private readonly int _hashCode;

        public TerminalLexerRule(char character)
            : this(new CharacterTerminal(character), new TokenType(character.ToString()))
        {
        }

        public TerminalLexerRule(ITerminal terminal, TokenType tokenType)
            : base(TerminalLexerRuleType, tokenType)
        {
            Terminal = terminal;
            _hashCode = ComputeHashCode(terminal, TerminalLexerRuleType, tokenType);
        }

        public TerminalLexerRule(ITerminal terminal, string tokenTypeId)
            : this(terminal, new TokenType(tokenTypeId))
        {
        }

        public override string ToString()
        {
            return Terminal.ToString();
        }

        public override bool Equals(object obj)
        {
            if (((object)obj) == null)
                return false;
            var terminalLexerRule = obj as TerminalLexerRule;
            if (((object)terminalLexerRule) == null)
                return false;
            return LexerRuleType.Equals(terminalLexerRule.LexerRuleType)
                && Terminal.Equals(terminalLexerRule.Terminal);
        }

        public override int GetHashCode()
        {
            return _hashCode;
        }

        private static int ComputeHashCode(
            ITerminal terminal,
            LexerRuleType terminalLexerRuleType,
            TokenType tokenType)
        {
            return HashCode.Compute(
                terminalLexerRuleType.GetHashCode(),
                tokenType.GetHashCode(),
                terminal.GetHashCode());
        }
    }
}


text:
namespace UwpNetworkingEssentials.Channels
{
    public enum DisconnectReason
    {
        /// <summary>
        /// The connection has been closed without a known reason.
        /// </summary>
        Unknown,

        /// <summary>
        /// The connection has been closed due to a network error.
        /// </summary>
        UnexpectedDisconnect,

        /// <summary>
        /// The local peer has explicitly closed the connection.
        /// </summary>
        LocalPeerDisconnected,

        /// <summary>
        /// The remote peer has explicitly closed the connection.
        /// </summary>
        RemotePeerDisconnected
    }
}


text:
<?php

namespace Acl\Form;

use Zend\Form\Form,
    Zend\Form\Element\Select;

class AclPrivilegio extends Form {

    public function __construct($name = null, array $papel, array $recurso) {

        parent::__construct($name);
        $this->papel = $papel;
        $this->recurso = $recurso;

        $this->setAttribute('method', 'post');

        $id = new \Zend\Form\Element\Hidden('id');
        $this->add($id);

        $nome = new \Zend\Form\Element\Text("nome");
        $nome->setLabel("Nome: ")
            ->setAttribute('placeholder', "Entre com o nome");
        $this->add($nome);

        $role = new Select();
        $role->setLabel("Papel: ")
            ->setName("papel")
            ->setOptions(array('value_options' => $papel));
        $this->add($role);

        $resource = new Select();
        $resource->setLabel("Recurso: ")
            ->setName("recurso")
            ->setOptions(array('value_options' => $recurso));
        $this->add($resource);

        $this->add(array(
            'name' => 'submit',
            'type' => 'Zend\Form\Element\Submit',
            'attributes' => array(
                'value' => 'Salvar',
                'class' => 'btn-success'
            )
        ));
    }

}


text:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "nodes.h"

ast_node *
node_alloc()
{
  // Allocate and return a new node
  struct ast_node *node = calloc(1, sizeof(*node));
  node->type = NODE_UNKNOWN;
  node->sub_type = NODE_UNKNOWN;
  node->visited = false;
  return node;
}

ast_node *
node_new(enum ast_node_type type, ast_node *e1, ast_node *e2, ast_node *e3,
         double x, char *s, int line, int column)
{
  ast_node *node = node_alloc();

  // Assign expression subtypes
  if (type == NODE_UNARY_POST || type == NODE_UNARY_PRE) {
    node->sub_type = type;
    node->type = NODE_EXP;
    type = NODE_EXP;
  }
  else {
    node->type = type;
  }

  node->e1 = e1;
  node->e2 = e2;
  node->e3 = e3;

  node->line = line;
  node->column = column;

  node->val = 0;
  if (type == NODE_NUM || type == NODE_BOOL || type == NODE_MEMBER)
    node->val = x;

  node->sval = NULL;
  if (s != NULL) {
    node->sval = malloc((strlen(s) + 1) * sizeof(char));
    strcpy(node->sval, s);
    node->sval[strlen(s)] = '\0';
  }
  return node;
}

ast_node *
node_pop(ast_node *node)
{
  if (node->e2 != NULL && !node->e2->visited)
    return node_pop(node->e2);
  node->visited = true;
  return node->e1;
}

bool
node_empty(ast_node *node)
{
  return node->visited;
}

void
node_rewind(ast_node *node)
{
  // Unset visited on a node linked list.
  if (!node->e1) return;
  node->visited = false;
  if (node->e2 != NULL) node_rewind(node->e2);
}

int
node_count(ast_node *node)
{
  int count = 0;
  ast_node *head = node;
  while (head) {
    if (head->e1) count++;
    head = head->e2;
  }
  return count;
}

void
node_print(ast_node *node, bool rec, int depth)
{
  if (depth) printf("%*s", depth, " ");
  switch (node->type) {
    case NODE_ARG_LST:     printf("argument list"); break;
    case NODE_ARR:         printf("array literal"); break;
    case NODE_ASGN:        printf("assignment"); break;
    case NODE_BLOCK:       printf("block"); break;
    case NODE_BREAK:       printf("break"); break;
    case NODE_CALL:        printf("call expression"); break;
    case NODE_CASE_BLOCK:  printf("case block"); break;
    case NODE_CATCH:       printf("catch"); break;
    case NODE_CLAUSE:      printf("case clause"); break;
    case NODE_CLAUSE_LST:  printf("case clause list"); break;
    case NODE_CONT:        printf("continue"); break;
    case NODE_DOWHILE:     printf("dowhile"); break;
    case NODE_ELISION:     printf("elision"); break;
    case NODE_EL_LST:      printf("element list"); break;
    case NODE_EMPT_STMT:   printf("empty statement"); break;
    case NODE_EXPGRP:      printf("expression group"); break;
    case NODE_EXP_STMT:    printf("expression statement"); break;
    case NODE_FINALLY:     printf("finally"); break;
    case NODE_FOR:         printf("for"); break;
    case NODE_FORIN:       printf("for-in"); break;
    case NODE_FUNC:        printf("function"); break;
    case NODE_IF:          printf("if"); break;
    case NODE_MEMBER:      printf("member expression"); break;
    case NODE_NEW:         printf("new expression"); break;
    case NODE_OBJ:         printf("object"); break;
    case NODE_PARAM_LST:   printf("parameter list"); break;
    case NODE_PROP:        printf("property"); break;
    case NODE_PROP_LST:    printf("property list"); break;
    case NODE_RETURN:      printf("return"); break;
    case NODE_SRC_LST:     printf("source list"); break;
    case NODE_STMT_LST:    printf("statement list"); break;
    case NODE_SWITCH_STMT: printf("switch statement"); break;
    case NODE_TERN:        printf("conditional expression"); break;
    case NODE_THIS:        printf("this"); break;
    case NODE_THROW:       printf("throw"); break;
    case NODE_TRY_STMT:    printf("try statement"); break;
    case NODE_VAR_DEC:     printf("variable declaration"); break;
    case NODE_VAR_DEC_LST: printf("variable declaration list"); break;
    case NODE_VAR_STMT:    printf("variable statement"); break;
    case NODE_WHILE:       printf("while"); break;
    case NODE_WITH_STMT:   printf("with statement"); break;

    // Literals
    case NODE_BOOL:        printf("bool (%d)\n", (int)node->val); return;
    case NODE_IDENT:       printf("identifier (%s)\n", node->sval); return;
    case NODE_NULL:        printf("null (NULL)\n"); return;
    case NODE_NUM:         printf("number (%f)\n", node->val); return;
    case NODE_REGEXP:      printf("regexp (%s)\n", node->sval); return;
    case NODE_STR:         printf("string (%s)\n", node->sval); return;

    // Expressions
    case NODE_EXP:
      printf("expression ");
      if (node->sub_type == NODE_UNARY_PRE) printf("(unary prefix)");
      else if (node->sub_type == NODE_UNARY_POST) printf("(unary postfix)");
      else printf ("(binary)");
      break;

    default:
      printf("unknown type: %d", node->type);
  }
  printf("\n");
  if (!rec) return;
  if (node->sval) {
    printf("%*s%s\n", depth+2, " ", node->sval);
  }
  if (node->e1 != NULL) node_print(node->e1, rec, depth + 2);
  if (node->e2 != NULL) node_print(node->e2, rec, depth + 2);
  if (node->e3 != NULL) node_print(node->e3, rec, depth + 2);
}