text:
#include <assert.h>
#include <io_driver.h>
#include <io_storage.h>
#include <semihosting.h>

/* Identify the device type as semihosting */
static io_type_t device_type_sh(void)
{
	return IO_TYPE_SEMIHOSTING;
}

/* Semi-hosting functions, device info and handle */

static int sh_dev_open(const uintptr_t dev_spec, io_dev_info_t **dev_info);
static int sh_file_open(io_dev_info_t *dev_info, const uintptr_t spec,
		io_entity_t *entity);
static int sh_file_seek(io_entity_t *entity, int mode, ssize_t offset);
static int sh_file_len(io_entity_t *entity, size_t *length);
static int sh_file_read(io_entity_t *entity, uintptr_t buffer, size_t length,
		size_t *length_read);
static int sh_file_write(io_entity_t *entity, const uintptr_t buffer,
		size_t length, size_t *length_written);
static int sh_file_close(io_entity_t *entity);

static const io_dev_connector_t sh_dev_connector = {
	.dev_open = sh_dev_open
};

static const io_dev_funcs_t sh_dev_funcs = {
	.type = device_type_sh,
	.open = sh_file_open,
	.seek = sh_file_seek,
	.size = sh_file_len,
	.read = sh_file_read,
	.write = sh_file_write,
	.close = sh_file_close,
	.dev_init = NULL,	/* NOP */
	.dev_close = NULL,	/* NOP */
};

/* No state associated with this device so structure can be const */
static const io_dev_info_t sh_dev_info = {
	.funcs = &sh_dev_funcs,
	.info = (uintptr_t)NULL
};

/* Open a connection to the semi-hosting device */
static int sh_dev_open(const uintptr_t dev_spec __unused,
		io_dev_info_t **dev_info)
{
	assert(dev_info != NULL);
	*dev_info = (io_dev_info_t *)&sh_dev_info; /* cast away const */
	return 0;
}

/* Open a file on the semi-hosting device */
static int sh_file_open(io_dev_info_t *dev_info __unused,
		const uintptr_t spec, io_entity_t *entity)
{
	int result = -ENOENT;
	long sh_result;
	const io_file_spec_t *file_spec = (const io_file_spec_t *)spec;

	assert(file_spec != NULL);
	assert(entity != NULL);

	sh_result = semihosting_file_open(file_spec->path, file_spec->mode);

	if (sh_result > 0) {
		entity->info = (uintptr_t)sh_result;
		result = 0;
	}
	return result;
}

/* Seek to a particular file offset on the semi-hosting device */
static int sh_file_seek(io_entity_t *entity, int mode, ssize_t offset)
{
	long file_handle, sh_result;

	assert(entity != NULL);

	file_handle = (long)entity->info;

	sh_result = semihosting_file_seek(file_handle, offset);

	return (sh_result == 0) ? 0 : -ENOENT;
}

/* Return the size of a file on the semi-hosting device */
static int sh_file_len(io_entity_t *entity, size_t *length)
{
	int result = -ENOENT;

	assert(entity != NULL);
	assert(length != NULL);

	long sh_handle = (long)entity->info;
	long sh_result = semihosting_file_length(sh_handle);

	if (sh_result >= 0) {
		result = 0;
		*length = (size_t)sh_result;
	}

	return result;
}

/* Read data from a file on the semi-hosting device */
static int sh_file_read(io_entity_t *entity, uintptr_t buffer, size_t length,
		size_t *length_read)
{
	int result = -ENOENT;
	long sh_result;
	size_t bytes = length;
	long file_handle;

	assert(entity != NULL);
	assert(buffer != (uintptr_t)NULL);
	assert(length_read != NULL);

	file_handle = (long)entity->info;

	sh_result = semihosting_file_read(file_handle, &bytes, buffer);

	if (sh_result >= 0) {
		*length_read = (bytes != length) ? bytes : length;
		result = 0;
	}

	return result;
}

/* Write data to a file on the semi-hosting device */
static int sh_file_write(io_entity_t *entity, const uintptr_t buffer,
		size_t length, size_t *length_written)
{
	long sh_result;
	long file_handle;
	size_t bytes = length;

	assert(entity != NULL);
	assert(buffer != (uintptr_t)NULL);
	assert(length_written != NULL);

	file_handle = (long)entity->info;

	sh_result = semihosting_file_write(file_handle, &bytes, buffer);

	*length_written = length - bytes;

	return (sh_result == 0) ? 0 : -ENOENT;
}

/* Close a file on the semi-hosting device */
static int sh_file_close(io_entity_t *entity)
{
	long sh_result;
	long file_handle;

	assert(entity != NULL);

	file_handle = (long)entity->info;

	sh_result = semihosting_file_close(file_handle);

	return (sh_result >= 0) ? 0 : -ENOENT;
}

/* Exported functions */

/* Register the semi-hosting driver with the IO abstraction */
int register_io_dev_sh(const io_dev_connector_t **dev_con)
{
	int result;
	assert(dev_con != NULL);

	result = io_register_device(&sh_dev_info);
	if (result == 0)
		*dev_con = &sh_dev_connector;

	return result;
}


text:
package com.creditease.uav.apm.invokechain.spi;

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

public class InvokeChainContext extends HashMap<String, Object> {

    private static final long serialVersionUID = 8758694368762576773L;

    public <T> void put(Class<T> key, T value) {

        if (key == null || value == null)
            return;

        put(key.getName(), value);
    }

    @SuppressWarnings("unchecked")
    public <T> T get(Class<T> key) {

        if (key == null)
            return null;

        return (T) get(key.getName());
    }

    public void put(Map<String, Object> map) {

        if (map == null) {
            return;
        }

        super.putAll(map);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Created by PhpStorm.
 * User: Adrian Dumitru
 * Date: 8/20/2017
 * Time: 12:36 AM
 */

namespace Qpdb\QueryBuilder\Traits;

use Qpdb\QueryBuilder\Dependencies\QueryException;
use Qpdb\QueryBuilder\Dependencies\QueryHelper;
use Qpdb\QueryBuilder\Dependencies\QueryStructure;
use Qpdb\QueryBuilder\Statements\QuerySelect;
use Qpdb\QueryBuilder\Statements\QueryStatement;

trait TableValidation
{

	/**
	 * @param $table
	 * @return mixed|string
	 * @throws QueryException
	 */
	private function validateTable( $table )
	{
		switch ( gettype( $table ) ) {

			case QueryStructure::ELEMENT_TYPE_STRING:
				$table = $this->validateTableName( $table );
				break;
			case QueryStructure::ELEMENT_TYPE_OBJECT:
				$table = $this->validateTableSubQuery( $table );
				break;
			default:
				throw new QueryException( 'Invalid table type parameter: ' . gettype( $table ), QueryException::QUERY_ERROR_INVALID_TABLE_STATEMENT );

		}

		return $table;
	}

	/**
	 * @param $table
	 * @return mixed|string
	 * @throws QueryException
	 */
	private function validateTableName( $table )
	{
		$table = trim( $table );

		if ( '' === $table )
			throw new QueryException( 'Table name is empty string!', QueryException::QUERY_ERROR_INVALID_TABLE_STATEMENT );

		return QueryHelper::addBacktick($table);
	}

	/**
	 * @param $table
	 * @return mixed
	 * @throws QueryException
	 */
	private function validateTableSubQuery( $table )
	{
		if ( $this->statement !== QueryStatement::QUERY_STATEMENT_SELECT )
			throw new QueryException( 'Invalid subQuery statement!', QueryException::QUERY_ERROR_INVALID_TABLE_STATEMENT );

		if ( !is_a( $table, QuerySelect::class ) )
			throw new QueryException( 'Invalid subQuery statement!', QueryException::QUERY_ERROR_INVALID_TABLE_STATEMENT );

		return $table;
	}

}


text:
package com.hannesdorfmann.mosby.mvp.delegate;

import android.os.Bundle;
import com.hannesdorfmann.mosby.mvp.MvpPresenter;
import com.hannesdorfmann.mosby.mvp.MvpView;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

/**
 * @author Hannes Dorfmann
 */
public class FragmentMvpDelegateImplTest {

  private MvpView view;
  private MvpPresenter<MvpView> presenter;
  private BaseMvpDelegateCallback<MvpView, MvpPresenter<MvpView>> callback;
  private FragmentMvpDelegateImpl<MvpView, MvpPresenter<MvpView>> delegate;

  @Before public void initComponents() {
    view = new MvpView() {
    };

    presenter = Mockito.mock(MvpPresenter.class);
    callback = Mockito.mock(PartialMvpDelegateCallbackImpl.class);
    Mockito.doCallRealMethod().when(callback).setPresenter(presenter);
    Mockito.doCallRealMethod().when(callback).getPresenter();

    Mockito.when(callback.getMvpView()).thenReturn(view);

    delegate = new FragmentMvpDelegateImpl<>(callback);
  }

  @Test public void startFragmentNullBundle() {
    testStartFragment(null);
  }

  @Test public void startFragmentWithBundle() {
    testStartFragment(new Bundle());
  }

  private void testStartFragment(Bundle bundle) {
    Mockito.when(callback.createPresenter()).thenReturn(presenter);

    startFragment(bundle);

    Mockito.verify(callback, Mockito.times(1)).createPresenter();
    Mockito.verify(callback, Mockito.times(1)).setPresenter(presenter);
    Mockito.verify(presenter, Mockito.times(1)).attachView(view);
  }

  private void startFragment(Bundle bundle){
    delegate.onAttach(null);
    delegate.onCreate(bundle);
    delegate.onViewCreated(null, bundle);
    delegate.onActivityCreated(bundle);
    delegate.onStart();
    delegate.onResume();
  }

  @Test
  public void reuseRetainingPresenter(){
    Mockito.when(callback.getPresenter()).thenReturn(presenter);

    startFragment(null);

    Mockito.verify(callback, Mockito.never()).createPresenter();
    Mockito.verify(callback, Mockito.times(1)).setPresenter(presenter);
    Mockito.verify(presenter, Mockito.times(1)).attachView(view);
  }

  @Test public void finishFragmentNotRetaining() {
    testFinishFragment(false);
  }

  @Test public void finishFragmentIsRetaining() {
    testFinishFragment(true);
  }

  private void testFinishFragment(boolean retainingInstanceState) {
    Mockito.when(callback.getPresenter()).thenReturn(presenter);
    Mockito.when(callback.shouldInstanceBeRetained()).thenReturn(retainingInstanceState);

    delegate.onPause();
    delegate.onSaveInstanceState(new Bundle());
    delegate.onStop();
    delegate.onDestroyView();
    delegate.onDestroy();
    delegate.onDetach();

    Mockito.verify(presenter, Mockito.times(1)).detachView(retainingInstanceState);
  }

}


text:
namespace Bit.BlazorUI;

public enum Visual
{
    Fluent,
    Material,
    Cupertino
}


text:
package websocket

import (
	"bytes"
	"fmt"
	"net/http"
	"sync"

	"github.com/gorilla/websocket"
)

type (
	// ConnectionFunc is the callback which fires when a client/connection is connected to the Server.
	// Receives one parameter which is the Connection
	ConnectionFunc func(Connection)

	// websocketRoomPayload is used as payload from the connection to the Server
	websocketRoomPayload struct {
		roomName     string
		connectionID string
	}

	// payloads, connection -> Server
	websocketMessagePayload struct {
		from string
		to   string
		data []byte
	}

	// Server is the websocket Server's implementation.
	//
	// It listens for websocket clients (either from the javascript client-side or from any websocket implementation).
	// See `OnConnection` , to register a single event which will handle all incoming connections and
	// the `Handler` which builds the upgrader handler that you can register to a route based on an Endpoint.
	//
	// To serve the built'n javascript client-side library look the `websocket.ClientHandler`.
	Server struct {
		config Config
		// ClientSource contains the javascript side code
		// for the websocket communication
		// based on the configuration's `EvtMessagePrefix`.
		//
		// Use a route to serve this file on a specific path, i.e
		// mux.HandleFUNC("/go-websocket.js", func(w http.ResponseWriter, _ *http.Request) { w.Write(mywebsocketServer.ClientSource) })
		ClientSource          []byte
		messageSerializer     *messageSerializer
		connections           sync.Map            // key = the Connection ID.
		rooms                 map[string][]string // by default a connection is joined to a room which has the connection id as its name
		mu                    sync.RWMutex        // for rooms.
		onConnectionListeners []ConnectionFunc
		//connectionPool        sync.Pool // sadly we can't make this because the websocket connection is live until is closed.
		upgrader websocket.Upgrader
	}
)

// New returns a new websocket Server based on a configuration.
// See `OnConnection` , to register a single event which will handle all incoming connections and
// the `Handler` which builds the upgrader handler that you can register to a route based on an Endpoint.
//
// To serve the built'n javascript client-side library look the `websocket.ClientHandler`.
func New(cfg Config) *Server {
	cfg = cfg.Validate()
	return &Server{
		config:                cfg,
		ClientSource:          bytes.Replace(ClientSource, []byte(DefaultEvtMessageKey), cfg.EvtMessagePrefix, -1),
		messageSerializer:     newMessageSerializer(cfg.EvtMessagePrefix),
		connections:           sync.Map{}, // ready-to-use, this is not necessary.
		rooms:                 make(map[string][]string),
		onConnectionListeners: make([]ConnectionFunc, 0),
		upgrader: websocket.Upgrader{
			HandshakeTimeout:  cfg.HandshakeTimeout,
			ReadBufferSize:    cfg.ReadBufferSize,
			WriteBufferSize:   cfg.WriteBufferSize,
			Error:             cfg.Error,
			CheckOrigin:       cfg.CheckOrigin,
			Subprotocols:      cfg.Subprotocols,
			EnableCompression: cfg.EnableCompression,
		},
	}
}

// Handler is the websocket handler which registers the endpoint's handler
// and fires the events to the registered `OnConnection` event.
// It should be called once per Server, its result should be passed
// as a route handler to register the websocket's endpoint.
//
// Endpoint is the path which the websocket Server will listen for clients/connections.
//
// To serve the built'n javascript client-side library look the `websocket.ClientHandler`.
// This handles any websocket error, use the `Upgrade` for custom error reporting and connection handling.
func (s *Server) Handler(w http.ResponseWriter, r *http.Request) {
	c := s.Upgrade(w, r)
	if c.Err() != nil {
		http.Error(w, fmt.Sprintf("websocket error: %v\n", c.Err()), http.StatusServiceUnavailable)
		return
	}
	// NOTE TO ME: fire these first BEFORE startReader and startPinger
	// in order to set the events and any messages to send
	// the startPinger will send the OK to the client and only
	// then the client is able to send and receive from Server
	// when all things are ready and only then. DO NOT change this order.

	// fire the on connection event callbacks, if any
	for i := range s.onConnectionListeners {
		s.onConnectionListeners[i](c)
	}

	// start the ping and the messages reader
	c.Wait()
}

// Upgrade upgrades the HTTP Server connection to the WebSocket protocol.
//
// The responseHeader is included in the response to the client's upgrade
// request. Use the responseHeader to specify cookies (Set-Cookie) and the
// application negotiated subprotocol (Sec--Protocol).
//
// If the upgrade fails, then Upgrade replies to the client with an HTTP error
// response and the return `Connection.Err()` is filled with that error.
//
// For a more high-level function use the `Handler()` and `OnConnecton` events.
// This one does not starts the connection's writer and reader, so after your `On/OnMessage` events registration
// the caller has to call the `Connection#Wait` function, otherwise the connection will be not handled.
//
// Caller should handle the error based on the connection's Err().
func (s *Server) Upgrade(w http.ResponseWriter, r *http.Request) Connection {
	conn, err := s.upgrader.Upgrade(w, r, w.Header())
	if err != nil {
		// caller should handle the error: http.Error(w, fmt.Sprintf("websocket error: %v\n", err), http.StatusServiceUnavailable)
		return &connection{err: err}
	}

	return s.handleConnection(w, r, conn)
}

func (s *Server) addConnection(c *connection) {
	s.connections.Store(c.id, c)
}

func (s *Server) getConnection(connID string) (*connection, bool) {
	if cValue, ok := s.connections.Load(connID); ok {
		// this cast is not necessary,
		// we know that we always save a connection, but for good or worse let it be here.
		if conn, ok := cValue.(*connection); ok {
			return conn, ok
		}
	}

	return nil, false
}

// wrapConnection wraps an underline connection to a *connection.
// It does NOT starts its writer, reader and event mux, the caller is responsible for that.
func (s *Server) handleConnection(w http.ResponseWriter, r *http.Request, websocketConn UnderlineConnection) *connection {
	// use the config's id generator (or the default) to create a websocket client/connection id
	cid := s.config.IDGenerator(w, r)
	// create the new connection
	c := newConnection(r, s, websocketConn, cid)
	// add the connection to the Server's list
	s.addConnection(c)

	// join to itself
	s.Join(c.id, c.id)

	return c
}

/* Notes:
   We use the id as the signature of the connection because with the custom IDGenerator
	 the developer can share this ID with a database field, so we want to give the oportunnity to handle
	 his/her websocket connections without even use the connection itself.

	 Another question may be:
	 Q: Why you use Server as the main actioner for all of the connection actions?
	 	  For example the Server.Disconnect(connID) manages the connection internal fields, is this code-style correct?
	 A: It's the correct code-style for these type of applications and libraries, Server manages all, the connnection's functions
	 should just do some internal checks (if needed) and push the action to its parent, which is the Server, the Server is able to
	 remove a connection, the rooms of its connected and all these things, so in order to not split the logic, we have the main logic
	 here, in the Server, and let the connection with some exported functions whose exists for the per-connection action user's code-style.

	 Ok my english are s** I can feel it, but these comments are mostly for me.
*/

/*
   connection actions, same as the connection's method,
    but these methods accept the connection ID,
    which is useful when the developer maps
    this id with a database field (using config.IDGenerator).
*/

// OnConnection is the main event you, as developer, will work with each of the websocket connections.
func (s *Server) OnConnection(cb ConnectionFunc) {
	s.onConnectionListeners = append(s.onConnectionListeners, cb)
}

// IsConnected returns true if the connection with that ID is connected to the Server
// useful when you have defined a custom connection id generator (based on a database)
// and you want to check if that connection is already connected (on multiple tabs)
func (s *Server) IsConnected(connID string) bool {
	_, found := s.getConnection(connID)
	return found
}

// Join joins a websocket client to a room,
// first parameter is the room name and the second the connection.ID()
//
// You can use connection.Join("room name") instead.
func (s *Server) Join(roomName string, connID string) {
	s.mu.Lock()
	s.join(roomName, connID)
	s.mu.Unlock()
}

// join used internally, no locks used.
func (s *Server) join(roomName string, connID string) {
	if s.rooms[roomName] == nil {
		s.rooms[roomName] = make([]string, 0)
	}
	s.rooms[roomName] = append(s.rooms[roomName], connID)
}

// IsJoined reports if a specific room has a specific connection into its values.
// First parameter is the room name, second is the connection's id.
//
// It returns true when the "connID" is joined to the "roomName".
func (s *Server) IsJoined(roomName string, connID string) bool {
	s.mu.RLock()
	room := s.rooms[roomName]
	s.mu.RUnlock()

	if room == nil {
		return false
	}

	for _, connid := range room {
		if connID == connid {
			return true
		}
	}

	return false
}

// LeaveAll kicks out a connection from ALL of its joined rooms
func (s *Server) LeaveAll(connID string) {
	s.mu.Lock()
	for name := range s.rooms {
		s.leave(name, connID)
	}
	s.mu.Unlock()
}

// Leave leaves a websocket client from a room,
// first parameter is the room name and the second the connection.ID()
//
// You can use connection.Leave("room name") instead.
// Returns true if the connection has actually left from the particular room.
func (s *Server) Leave(roomName string, connID string) bool {
	s.mu.Lock()
	left := s.leave(roomName, connID)
	s.mu.Unlock()
	return left
}

// leave used internally, no locks used.
func (s *Server) leave(roomName string, connID string) (left bool) {
	///THINK: we could add locks to its room but we still use the lock for the whole rooms or we can just do what we do with connections
	// I will think about it on the next revision, so far we use the locks only for rooms so we are ok...
	if s.rooms[roomName] != nil {
		for i := range s.rooms[roomName] {
			if s.rooms[roomName][i] == connID {
				s.rooms[roomName] = append(s.rooms[roomName][:i], s.rooms[roomName][i+1:]...)
				left = true
				break
			}
		}
		if len(s.rooms[roomName]) == 0 { // if room is empty then delete it
			delete(s.rooms, roomName)
		}
	}

	if left {
		// fire the on room leave connection's listeners,
		// the existence check is not necessary here.
		if c, ok := s.getConnection(connID); ok {
			c.fireOnLeave(roomName)
		}
	}
	return
}

// GetTotalConnections returns the number of total connections
func (s *Server) GetTotalConnections() (n int) {
	s.connections.Range(func(k, v interface{}) bool {
		n++
		return true
	})

	return n
}

// GetConnections returns all connections
func (s *Server) GetConnections() []Connection {
	// first call of Range to get the total length, we don't want to use append or manually grow the list here for many reasons.
	length := s.GetTotalConnections()
	conns := make([]Connection, length, length)
	i := 0
	// second call of Range.
	s.connections.Range(func(k, v interface{}) bool {
		conn, ok := v.(*connection)
		if !ok {
			// if for some reason (should never happen), the value is not stored as *connection
			// then stop the iteration and don't continue insertion of the result connections
			// in order to avoid any issues while end-dev will try to iterate a nil entry.
			return false
		}
		conns[i] = conn
		i++
		return true
	})

	return conns
}

// GetConnection returns single connection
func (s *Server) GetConnection(connID string) Connection {
	conn, ok := s.getConnection(connID)
	if !ok {
		return nil
	}

	return conn
}

// GetConnectionsByRoom returns a list of Connection
// which are joined to this room.
func (s *Server) GetConnectionsByRoom(roomName string) []Connection {
	var conns []Connection
	s.mu.RLock()
	if connIDs, found := s.rooms[roomName]; found {
		for _, connID := range connIDs {
			// existence check is not necessary here.
			if cValue, ok := s.connections.Load(connID); ok {
				if conn, ok := cValue.(*connection); ok {
					conns = append(conns, conn)
				}
			}
		}
	}

	s.mu.RUnlock()

	return conns
}

// emitMessage is the main 'router' of the messages coming from the connection
// this is the main function which writes the RAW websocket messages to the client.
// It sends them(messages) to the correct room (self, broadcast or to specific client)
//
// You don't have to use this generic method, exists only for extreme
// apps which you have an external goroutine with a list of custom connection list.
//
// You SHOULD use connection.EmitMessage/Emit/To().Emit/EmitMessage instead.
// let's keep it unexported for the best.
func (s *Server) emitMessage(from, to string, data []byte) {
	if to != All && to != Broadcast {
		s.mu.RLock()
		room := s.rooms[to]
		s.mu.RUnlock()
		if room != nil {
			// it suppose to send the message to a specific room/or a user inside its own room
			for _, connectionIDInsideRoom := range room {
				if c, ok := s.getConnection(connectionIDInsideRoom); ok {
					c.writeDefault(data) //send the message to the client(s)
				} else {
					// the connection is not connected but it's inside the room, we remove it on disconnect but for ANY CASE:
					cid := connectionIDInsideRoom
					if c != nil {
						cid = c.id
					}
					s.Leave(cid, to)
				}
			}
		}
	} else {
		// it suppose to send the message to all opened connections or to all except the sender.
		s.connections.Range(func(k, v interface{}) bool {
			connID, ok := k.(string)
			if !ok {
				// should never happen.
				return true
			}

			if to != All && to != connID { // if it's not suppose to send to all connections (including itself)
				if to == Broadcast && from == connID { // if broadcast to other connections except this
					// here we do the opossite of previous block,
					// just skip this connection when it's suppose to send the message to all connections except the sender.
					return true
				}

			}

			// not necessary cast.
			conn, ok := v.(*connection)
			if ok {
				// send to the client(s) when the top validators passed
				conn.writeDefault(data)
			}

			return ok
		})
	}
}

// Disconnect force-disconnects a websocket connection based on its connection.ID()
// What it does?
// 1. remove the connection from the list
// 2. leave from all joined rooms
// 3. fire the disconnect callbacks, if any
// 4. close the underline connection and return its error, if any.
//
// You can use the connection.Disconnect() instead.
func (s *Server) Disconnect(connID string) (err error) {
	// leave from all joined rooms before remove the actual connection from the list.
	// note: we cannot use that to send data if the client is actually closed.
	s.LeaveAll(connID)

	// remove the connection from the list.
	if conn, ok := s.getConnection(connID); ok {
		conn.disconnected = true
		// fire the disconnect callbacks, if any.
		conn.fireDisconnect()
		// close the underline connection and return its error, if any.
		err = conn.underline.Close()

		s.connections.Delete(connID)
	}

	return
}


text:
import { QueryInfo } from '@airbrake/browser';
import { Notifier } from '../notifier';

const SPAN_NAME = 'sql';

export function patch(mysql, airbrake: Notifier): void {
  mysql.createPool = wrapCreatePool(mysql.createPool, airbrake);

  const origCreatePoolCluster = mysql.createPoolCluster;
  mysql.createPoolCluster = function abCreatePoolCluster() {
    const cluster = origCreatePoolCluster.apply(this, arguments);
    cluster.of = wrapCreatePool(cluster.of, airbrake);
    return cluster;
  };

  const origCreateConnection = mysql.createConnection;
  mysql.createConnection = function abCreateConnection() {
    const conn = origCreateConnection.apply(this, arguments);
    wrapConnection(conn, airbrake);
    return conn;
  };
}

function wrapCreatePool(origFn, airbrake: Notifier) {
  return function abCreatePool() {
    const pool = origFn.apply(this, arguments);
    pool.getConnection = wrapGetConnection(pool.getConnection, airbrake);
    return pool;
  };
}

function wrapGetConnection(origFn, airbrake: Notifier) {
  return function abGetConnection() {
    const cb = arguments[0];
    if (typeof cb === 'function') {
      arguments[0] = function abCallback(_err, conn) {
        if (conn) {
          wrapConnection(conn, airbrake);
        }
        return cb.apply(this, arguments);
      };
    }
    return origFn.apply(this, arguments);
  };
}

function wrapConnection(conn, airbrake: Notifier): void {
  const origQuery = conn.query;
  conn.query = function abQuery(sql, values, cb) {
    let foundCallback = false;
    function wrapCallback(callback) {
      foundCallback = true;
      return function abCallback() {
        endSpan();
        return callback.apply(this, arguments);
      };
    }

    const metric = airbrake.scope().routeMetric();
    if (!metric.isRecording()) {
      return origQuery.apply(this, arguments);
    }
    metric.startSpan(SPAN_NAME);

    let qinfo: QueryInfo;
    const endSpan = () => {
      metric.endSpan(SPAN_NAME);
      if (qinfo) {
        airbrake.queries.notify(qinfo);
      }
    };

    let query: string;
    switch (typeof sql) {
      case 'string':
        query = sql;
        break;
      case 'function':
        arguments[0] = wrapCallback(sql);
        break;
      case 'object':
        if (typeof sql._callback === 'function') {
          sql._callback = wrapCallback(sql._callback);
        }
        query = sql.sql;
        break;
    }

    if (query) {
      qinfo = airbrake.queries.start(query);
    }

    if (typeof values === 'function') {
      arguments[1] = wrapCallback(values);
    } else if (typeof cb === 'function') {
      arguments[2] = wrapCallback(cb);
    }

    const res = origQuery.apply(this, arguments);

    if (!foundCallback && res && res.emit) {
      const origEmit = res.emit;
      res.emit = function abEmit(evt) {
        switch (evt) {
          case 'end':
          case 'error':
            endSpan();
            break;
        }
        return origEmit.apply(this, arguments);
      };
    }

    return res;
  };
}


text:
/* @LICENSE(MUSLC_MIT) */

#include "libm.h"

//FIXME
long double complex cexpl(long double complex z)
{
	return cexp(z);
}


text:
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chromeos/ash/components/proximity_auth/messenger_impl.h"

#include <memory>
#include <utility>

#include "base/base64url.h"
#include "base/bind.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/location.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chromeos/ash/components/multidevice/logging/logging.h"
#include "chromeos/ash/components/proximity_auth/messenger_observer.h"
#include "chromeos/ash/components/proximity_auth/remote_status_update.h"

namespace proximity_auth {

namespace {

// The key names of JSON fields for messages sent between the devices.
const char kTypeKey[] = "type";
const char kNameKey[] = "name";
const char kDataKey[] = "data";
const char kEncryptedDataKey[] = "encrypted_data";

// The types of messages that can be sent and received.
const char kMessageTypeLocalEvent[] = "event";
const char kMessageTypeRemoteStatusUpdate[] = "status_update";
const char kMessageTypeDecryptRequest[] = "decrypt_request";
const char kMessageTypeDecryptResponse[] = "decrypt_response";
const char kMessageTypeUnlockRequest[] = "unlock_request";
const char kMessageTypeUnlockResponse[] = "unlock_response";

// The name for an unlock event originating from the local device.
const char kUnlockEventName[] = "easy_unlock";

// Serializes the |value| to a JSON string and returns the result.
std::string SerializeValueToJson(const base::Value::Dict& value) {
  std::string json;
  base::JSONWriter::Write(value, &json);
  return json;
}

// Returns the message type represented by the |message|. This is a convenience
// wrapper that should only be called when the |message| is known to specify its
// message type, i.e. this should not be called for untrusted input.
std::string GetMessageType(const base::Value::Dict& message) {
  const std::string* type = message.FindString(kTypeKey);
  return type ? *type : std::string();
}

}  // namespace

MessengerImpl::MessengerImpl(
    std::unique_ptr<ash::secure_channel::ClientChannel> channel)
    : channel_(std::move(channel)) {
  DCHECK(!channel_->is_disconnected());
  channel_->AddObserver(this);
}

MessengerImpl::~MessengerImpl() {
  channel_->RemoveObserver(this);
}

void MessengerImpl::AddObserver(MessengerObserver* observer) {
  observers_.AddObserver(observer);
}

void MessengerImpl::RemoveObserver(MessengerObserver* observer) {
  observers_.RemoveObserver(observer);
}

void MessengerImpl::DispatchUnlockEvent() {
  base::Value::Dict message;
  message.Set(kTypeKey, kMessageTypeLocalEvent);
  message.Set(kNameKey, kUnlockEventName);
  queued_messages_.push_back(PendingMessage(message));
  ProcessMessageQueue();
}

void MessengerImpl::RequestDecryption(const std::string& challenge) {
  const std::string encrypted_message_data = challenge;
  std::string encrypted_message_data_base64;
  base::Base64UrlEncode(encrypted_message_data,
                        base::Base64UrlEncodePolicy::INCLUDE_PADDING,
                        &encrypted_message_data_base64);

  base::Value::Dict message;
  message.Set(kTypeKey, kMessageTypeDecryptRequest);
  message.Set(kEncryptedDataKey, encrypted_message_data_base64);
  queued_messages_.push_back(PendingMessage(message));
  ProcessMessageQueue();
}

void MessengerImpl::RequestUnlock() {
  base::Value::Dict message;
  message.Set(kTypeKey, kMessageTypeUnlockRequest);
  queued_messages_.push_back(PendingMessage(message));
  ProcessMessageQueue();
}

ash::secure_channel::ClientChannel* MessengerImpl::GetChannel() const {
  if (channel_->is_disconnected())
    return nullptr;

  return channel_.get();
}

MessengerImpl::PendingMessage::PendingMessage() = default;

MessengerImpl::PendingMessage::~PendingMessage() = default;

MessengerImpl::PendingMessage::PendingMessage(const base::Value::Dict& message)
    : json_message(SerializeValueToJson(message)),
      type(GetMessageType(message)) {}

MessengerImpl::PendingMessage::PendingMessage(const std::string& message)
    : json_message(message), type(std::string()) {}

void MessengerImpl::ProcessMessageQueue() {
  if (pending_message_ || queued_messages_.empty())
    return;

  if (channel_->is_disconnected())
    return;

  pending_message_ = std::make_unique<PendingMessage>(queued_messages_.front());
  queued_messages_.pop_front();

  channel_->SendMessage(
      pending_message_->json_message,
      base::BindOnce(&MessengerImpl::OnSendMessageResult,
                     weak_ptr_factory_.GetWeakPtr(), true /* success */));
}

void MessengerImpl::HandleRemoteStatusUpdateMessage(
    const base::Value::Dict& message) {
  std::unique_ptr<RemoteStatusUpdate> status_update =
      RemoteStatusUpdate::Deserialize(message);
  if (!status_update) {
    PA_LOG(ERROR) << "Unexpected remote status update: " << message;
    return;
  }

  for (auto& observer : observers_)
    observer.OnRemoteStatusUpdate(*status_update);
}

void MessengerImpl::HandleDecryptResponseMessage(
    const base::Value::Dict& message) {
  const std::string* base64_data = message.FindString(kDataKey);
  std::string decrypted_data;
  if (!base64_data || base64_data->empty()) {
    PA_LOG(ERROR) << "Decrypt response missing '" << kDataKey << "' value.";
  } else if (!base::Base64UrlDecode(
                 *base64_data, base::Base64UrlDecodePolicy::REQUIRE_PADDING,
                 &decrypted_data)) {
    PA_LOG(ERROR) << "Unable to base64-decode decrypt response.";
  }

  for (auto& observer : observers_)
    observer.OnDecryptResponse(decrypted_data);
}

void MessengerImpl::HandleUnlockResponseMessage(
    const base::Value::Dict& message) {
  for (auto& observer : observers_)
    observer.OnUnlockResponse(true);
}

void MessengerImpl::OnDisconnected() {
  for (auto& observer : observers_)
    observer.OnDisconnected();
}

void MessengerImpl::OnMessageReceived(const std::string& payload) {
  HandleMessage(payload);
}

void MessengerImpl::HandleMessage(const std::string& message) {
  // The decoded message should be a JSON string.
  absl::optional<base::Value> message_value = base::JSONReader::Read(message);
  if (!message_value || !message_value->is_dict()) {
    PA_LOG(ERROR) << "Unable to parse message as JSON:\n" << message;
    return;
  }

  const base::Value::Dict& message_dictionary = message_value->GetDict();
  const std::string* type = message_dictionary.FindString(kTypeKey);
  if (!type) {
    PA_LOG(ERROR) << "Missing '" << kTypeKey << "' key in message:\n "
                  << message;
    return;
  }

  // Remote status updates can be received out of the blue.
  if (*type == kMessageTypeRemoteStatusUpdate) {
    HandleRemoteStatusUpdateMessage(message_dictionary);
    return;
  }

  // All other messages should only be received in response to a message that
  // the messenger sent.
  if (!pending_message_) {
    PA_LOG(WARNING) << "Unexpected message received: " << message;
    return;
  }

  std::string expected_type;
  if (pending_message_->type == kMessageTypeDecryptRequest)
    expected_type = kMessageTypeDecryptResponse;
  else if (pending_message_->type == kMessageTypeUnlockRequest)
    expected_type = kMessageTypeUnlockResponse;
  else
    NOTREACHED();  // There are no other message types that expect a response.

  if (*type != expected_type) {
    PA_LOG(ERROR) << "Unexpected '" << kTypeKey << "' value in message. "
                  << "Expected '" << expected_type << "' but received '"
                  << *type << "'.";
    return;
  }

  if (*type == kMessageTypeDecryptResponse)
    HandleDecryptResponseMessage(message_dictionary);
  else if (*type == kMessageTypeUnlockResponse)
    HandleUnlockResponseMessage(message_dictionary);
  else
    NOTREACHED();  // There are no other message types that expect a response.

  pending_message_.reset();
  ProcessMessageQueue();
}

void MessengerImpl::OnSendMessageResult(bool success) {
  if (!pending_message_) {
    PA_LOG(ERROR) << "Unexpected message sent.";
    return;
  }

  // In the common case, wait for a response from the remote device.
  // Don't wait if the message could not be sent, as there won't ever be a
  // response in that case. Likewise, don't wait for a response to local
  // event messages, as there is no response for such messages.
  if (success && pending_message_->type != kMessageTypeLocalEvent)
    return;

  // Notify observer of failure if sending the message fails.
  // For local events, we don't expect a response, so on success, we
  // notify observers right away.
  if (pending_message_->type == kMessageTypeDecryptRequest) {
    for (auto& observer : observers_)
      observer.OnDecryptResponse(std::string());
  } else if (pending_message_->type == kMessageTypeUnlockRequest) {
    for (auto& observer : observers_)
      observer.OnUnlockResponse(false);
  } else if (pending_message_->type == kMessageTypeLocalEvent) {
    for (auto& observer : observers_)
      observer.OnUnlockEventSent(success);
  } else {
    PA_LOG(ERROR) << "Message of unknown type '" << pending_message_->type
                  << "' sent.";
  }

  pending_message_.reset();
  ProcessMessageQueue();
}

}  // namespace proximity_auth


text:
{-| Implementation of the RAPI client interface.

-}

{-

Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

-}

{-# LANGUAGE BangPatterns, CPP #-}

module Ganeti.HTools.Backend.Rapi
  ( loadData
  , parseData
  ) where

import Control.Exception
import Data.List (isPrefixOf)
import Data.Maybe (fromMaybe)
import Network.Curl
import Network.Curl.Types ()
import Control.Monad
import Text.JSON (JSObject, fromJSObject, decodeStrict)
import Text.JSON.Types (JSValue(..))
import Text.Printf (printf)
import System.FilePath

import Ganeti.BasicTypes
import Ganeti.HTools.Loader
import Ganeti.HTools.Types
import Ganeti.JSON (loadJSArray, JSRecord, tryFromObj, fromJVal, maybeFromObj, fromJResult, tryArrayMaybeFromObj, readEitherString, fromObjWithDefault, asJSObject, emptyContainer)
import qualified Ganeti.HTools.Group as Group
import qualified Ganeti.HTools.Node as Node
import qualified Ganeti.HTools.Instance as Instance
import qualified Ganeti.Constants as C

{-# ANN module "HLint: ignore Eta reduce" #-}

-- | File method prefix.
filePrefix :: String
filePrefix = "file://"

-- | Read an URL via curl and return the body if successful.
getUrl :: (Monad m) => String -> IO (m String)

-- | Connection timeout (when using non-file methods).
connTimeout :: Long
connTimeout = 15

-- | The default timeout for queries (when using non-file methods).
queryTimeout :: Long
queryTimeout = 60

-- | The curl options we use.
curlOpts :: [CurlOption]
curlOpts = [ CurlSSLVerifyPeer False
           , CurlSSLVerifyHost 0
           , CurlTimeout queryTimeout
           , CurlConnectTimeout connTimeout
           ]

getUrl url = do
  (code, !body) <- curlGetString url curlOpts
  return (case code of
            CurlOK -> return body
            _ -> fail $ printf "Curl error for '%s', error %s"
                 url (show code))

-- | Helper to convert I/O errors in 'Bad' values.
ioErrToResult :: IO a -> IO (Result a)
ioErrToResult ioaction =
  Control.Exception.catch (liftM Ok ioaction)
    (\e -> return . Bad . show $ (e::IOException))

-- | Append the default port if not passed in.
formatHost :: String -> String
formatHost master =
  if ':' `elem` master
    then  master
    else "https://" ++ master ++ ":" ++ show C.defaultRapiPort

-- | Parse a instance list in JSON format.
getInstances :: NameAssoc
             -> String
             -> Result [(String, Instance.Instance)]
getInstances ktn body =
  loadJSArray "Parsing instance data" body >>=
  mapM (parseInstance ktn . fromJSObject)

-- | Parse a node list in JSON format.
getNodes :: NameAssoc -> String -> Result [(String, Node.Node)]
getNodes ktg body = loadJSArray "Parsing node data" body >>=
                    mapM (parseNode ktg . fromJSObject)

-- | Parse a group list in JSON format.
getGroups :: String -> Result [(String, Group.Group)]
getGroups body = loadJSArray "Parsing group data" body >>=
                 mapM (parseGroup . fromJSObject)

-- | Construct an instance from a JSON object.
parseInstance :: NameAssoc
              -> JSRecord
              -> Result (String, Instance.Instance)
parseInstance ktn a = do
  name <- tryFromObj "Parsing new instance" a "name"
  let owner_name = "Instance '" ++ name ++ "', error while parsing data"
  let extract s x = tryFromObj owner_name x s
  disk <- extract "disk_usage" a
  dsizes <- extract "disk.sizes" a
  dspindles <- tryArrayMaybeFromObj owner_name a "disk.spindles"
  beparams <- liftM fromJSObject (extract "beparams" a)
  omem <- extract "oper_ram" a
  mem <- case omem of
           JSRational _ _ -> annotateResult owner_name (fromJVal omem)
           _ -> extract "memory" beparams `mplus` extract "maxmem" beparams
  vcpus <- extract "vcpus" beparams
  pnode <- extract "pnode" a >>= lookupNode ktn name
  snodes <- extract "snodes" a
  snode <- case snodes of
             [] -> return Node.noSecondary
             x:_ -> readEitherString x >>= lookupNode ktn name
  running <- extract "status" a
  tags <- extract "tags" a
  auto_balance <- extract "auto_balance" beparams
  dt <- extract "disk_template" a
  su <- extract "spindle_use" beparams
  -- Not forthcoming by default.
  forthcoming <- extract "forthcoming" a `orElse` Ok False
  let disks = zipWith Instance.Disk dsizes dspindles
  let inst = Instance.create name mem disk disks vcpus running tags
             auto_balance pnode snode dt su [] forthcoming
  return (name, inst)

-- | Construct a node from a JSON object.
parseNode :: NameAssoc -> JSRecord -> Result (String, Node.Node)
parseNode ktg a = do
  name <- tryFromObj "Parsing new node" a "name"
  let desc = "Node '" ++ name ++ "', error while parsing data"
      extract key = tryFromObj desc a key
      extractDef def key = fromObjWithDefault a key def
  offline <- extract "offline"
  drained <- extract "drained"
  vm_cap  <- annotateResult desc $ maybeFromObj a "vm_capable"
  let vm_cap' = fromMaybe True vm_cap
  ndparams <- extract "ndparams" >>= asJSObject
  excl_stor <- tryFromObj desc (fromJSObject ndparams) "exclusive_storage"
  guuid   <- annotateResult desc $ maybeFromObj a "group.uuid"
  guuid' <-  lookupGroup ktg name (fromMaybe defaultGroupID guuid)
  let live = not offline && vm_cap'
      lvextract def = eitherLive live def . extract
      lvextractDef def = eitherLive live def . extractDef def
  sptotal <- if excl_stor
             then lvextract 0 "sptotal"
             else tryFromObj desc (fromJSObject ndparams) "spindle_count"
  spfree <- lvextractDef 0 "spfree"
  mtotal <- lvextract 0.0 "mtotal"
  mnode <- lvextract 0 "mnode"
  mfree <- lvextract 0 "mfree"
  dtotal <- lvextractDef 0.0 "dtotal"
  dfree <- lvextractDef 0 "dfree"
  ctotal <- lvextract 0.0 "ctotal"
  cnos <- lvextract 0 "cnos"
  tags <- extract "tags"
  hv_state <- extractDef emptyContainer "hv_state"
  let node_mem = obtainNodeMemory hv_state mnode
      node = flip Node.setNodeTags tags $
             Node.create name mtotal node_mem mfree dtotal dfree ctotal cnos
             (not live || drained) sptotal spfree guuid' excl_stor
  return (name, node)

-- | Construct a group from a JSON object.
parseGroup :: JSRecord -> Result (String, Group.Group)
parseGroup a = do
  name <- tryFromObj "Parsing new group" a "name"
  let extract s = tryFromObj ("Group '" ++ name ++ "'") a s
  let extractDef s d = fromObjWithDefault a s d
  uuid <- extract "uuid"
  apol <- extract "alloc_policy"
  ipol <- extract "ipolicy"
  tags <- extract "tags"
  nets <- extractDef "networks" []
  return (uuid, Group.create name uuid apol nets ipol tags)

-- | Parse cluster data from the info resource.
parseCluster :: JSObject JSValue -> Result ([String], IPolicy, String)
parseCluster obj = do
  let obj' = fromJSObject obj
      extract s = tryFromObj "Parsing cluster data" obj' s
  master <- extract "master"
  tags <- extract "tags"
  ipolicy <- extract "ipolicy"
  return (tags, ipolicy, master)

-- | Loads the raw cluster data from an URL.
readDataHttp :: String -- ^ Cluster or URL to use as source
             -> IO (Result String, Result String, Result String, Result String)
readDataHttp master = do
  let url = formatHost master
  group_body <- getUrl $ printf "%s/2/groups?bulk=1" url
  node_body <- getUrl $ printf "%s/2/nodes?bulk=1" url
  inst_body <- getUrl $ printf "%s/2/instances?bulk=1" url
  info_body <- getUrl $ printf "%s/2/info" url
  return (group_body, node_body, inst_body, info_body)

-- | Loads the raw cluster data from the filesystem.
readDataFile:: String -- ^ Path to the directory containing the files
             -> IO (Result String, Result String, Result String, Result String)
readDataFile path = do
  group_body <- ioErrToResult . readFile $ path </> "groups.json"
  node_body <- ioErrToResult . readFile $ path </> "nodes.json"
  inst_body <- ioErrToResult . readFile $ path </> "instances.json"
  info_body <- ioErrToResult . readFile $ path </> "info.json"
  return (group_body, node_body, inst_body, info_body)

-- | Loads data via either 'readDataFile' or 'readDataHttp'.
readData :: String -- ^ URL to use as source
         -> IO (Result String, Result String, Result String, Result String)
readData url =
  if filePrefix `isPrefixOf` url
    then readDataFile (drop (length filePrefix) url)
    else readDataHttp url

-- | Builds the cluster data from the raw Rapi content.
parseData :: (Result String, Result String, Result String, Result String)
          -> Result ClusterData
parseData (group_body, node_body, inst_body, info_body) = do
  group_data <- group_body >>= getGroups
  let (group_names, group_idx) = assignIndices group_data
  node_data <- node_body >>= getNodes group_names
  let (node_names, node_idx) = assignIndices node_data
  inst_data <- inst_body >>= getInstances node_names
  let (_, inst_idx) = assignIndices inst_data
  (tags, ipolicy, master) <-
    info_body >>=
    (fromJResult "Parsing cluster info" . decodeStrict) >>=
    parseCluster
  node_idx' <- setMaster node_names node_idx master
  return (ClusterData group_idx node_idx' inst_idx tags ipolicy)

-- | Top level function for data loading.
loadData :: String -- ^ Cluster or URL to use as source
         -> IO (Result ClusterData)
loadData = fmap parseData . readData


text:
package network;

import data.Data;

public interface PredictionNetwork extends NeuralNetworkWithTeacher {
    double predictNext(Data data);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name = "button">#191919</color>
</resources>


text:
package view;

import java.sql.SQLException;

import application.Main;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import model.DAO;
import utility.Crittografia;

public class RegistraAdminViewController
{

	private Main  mainApp;

	@FXML
	private TextField usernameTF;

	@FXML
	private PasswordField pswdTF, repPswsTF;

	@FXML
	private Button registratiButton, annullaButton;

	@FXML
	private void premutoRegistrati()
	{
		if (verificaForm())
		{
			if (isNuovoUtente())
			{
				String username = usernameTF.getText();
				String pswd = pswdTF.getText();
				String enPswd = Crittografia.encrypt(pswd);
				//Registro l'utente nel DB
				String comando = String.format("INSERT INTO `admin` (Username,PASSWORD) VALUES ('%s','%s')", username,enPswd);
				boolean registrato = DAO.esegui(comando);

				if (registrato)
				{
					Main.lanciaInfo("Registrazione avvenuta", "L'Admin " + username + " è stato registrato!");

					//Reimposto l'interfaccia di Login su MainApp
					mainApp.lanciaLogin();
				}

			}
		}

	}

	@FXML
	private void premutoAnnulla()
	{
		//Reimposto l'interfaccia di Login su MainApp
		mainApp.lanciaLogin();
	}

	private boolean verificaForm()
	{
		boolean risposta = false;

		String username = usernameTF.getText();
		String pswd = pswdTF.getText();
		String rePswd = repPswsTF.getText();

		//Se i tre campi sono stati valorizzati
		if (username.length() > 0 && pswd.length() > 0 && rePswd.length() > 0)
		{
			if (username.length() > 6)
			{
				if (pswd.equals(rePswd))
				{
					risposta = true;
				}else
				{
					Main.lanciaWarning("Form non corretto","Le password devono essere uguali");
				}
			}else
			{
				Main.lanciaWarning("Form non corretto","Username deve essere maggiore di 6 caratteri");
			}
		}else
		{
			Main.lanciaWarning("Form non corretto","Non sono stati riempiti tutti i campi!");
		}

		return risposta;

	}

	private boolean isNuovoUtente()
	{
		boolean risposta = false;

			//Cerco se nel DB è presente già un utente con questo nome
			String comando = String.format("SELECT Username FROM admin WHERE Username = '%s'", usernameTF.getText());
			try {
				//DAO.connetti();
				boolean utenteTrovato = DAO.cerca(comando);
				//Se non ho trovato nessuno (quindi utenteTrovat == false) allora isNuovoUtente.risposta deve essere true
				risposta = !utenteTrovato;
			} catch (SQLException e) {
				System.out.println("Errore in RegistraAdminViewController.isNuovoUtente()");
				e.printStackTrace();
			}

			if (!risposta)
			{
				Main.lanciaWarning("Utente già esistente","Inserisci un nuovo Username");
			}

		return risposta;
	}

	public Main getMainApp() {
		return mainApp;
	}

	public void setMainApp(Main mainApp) {
		this.mainApp = mainApp;
	}
}


text:
package com.helicalinsight.hwf.controller;

import com.helicalinsight.hwf.core.api.HWFEngine;
import com.helicalinsight.hwf.validator.WorkFlowValidator;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@SuppressWarnings("ALL")
public class HWFController {

    private static final Logger logger = LoggerFactory.getLogger(HWFController.class);

    @RequestMapping(value = "/workflow", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView getData(HttpServletRequest request, HttpServletResponse response) {

        String hwfFileName = request.getParameter("fileName");
        String dir = request.getParameter("dir");
        String hwfpath = WorkFlowValidator.validateUserInput(hwfFileName, dir, request);

        HWFEngine hwfEngine = new HWFEngine(hwfpath, request, response);
        JSONObject output = hwfEngine.processHWF();
        String viewPage = output.optString("viewPage");
        if (viewPage == null || viewPage.isEmpty()) {
            viewPage = "workflow";
        }
        output.discard("viewPage");
        return new ModelAndView(viewPage, "json", output);
    }

}


text:
<?php
namespace PureMachine\Bundle\WebServiceBundle\Service\Annotation;

use Doctrine\Common\Annotations\Annotation;

/**
 * @Annotation
 * @Target("METHOD")
 */
class ReturnClass extends InputClass {}


text:
create table tab_mod_immediate
(
  col_add_ix_1 number(15) not null,
  primary key (col_add_ix_1)
);

create materialized view log on tab_mod_immediate with rowid;

create table tab_mod_asynchronous
(
  col_add_ix_1 number(15) not null,
  primary key (col_add_ix_1)
);

create materialized view log on tab_mod_asynchronous with rowid;

create table tab_mod_sw
(
  col_add_ix_1 number(15) not null,
  primary key (col_add_ix_1)
);

create materialized view log on tab_mod_sw with primary key purge start with to_date('31.10.14','dd.mm.yy');

create table tab_mod_nsw
(
  col_add_ix_1 number(15) not null,
  primary key (col_add_ix_1)
);

create materialized view log on tab_mod_nsw with primary key purge start with to_date('31.10.14','dd.mm.yy') next to_date('31.10.15','dd.mm.yy');

create table tab_mod_int
(
  col_add_ix_1 number(15) not null,
  primary key (col_add_ix_1)
);

create materialized view log on tab_mod_int with primary key purge start with to_date('31.10.14','dd.mm.yy') repeat interval 3;


text:
<?php
/**
 * Prelude
 *
 * The place where it all begins
 *
 * @package Prelude
 **/
namespace Linoge\PHPFunctional\Prelude;

use ReflectionFunction;
use DeepCopy\DeepCopy;
use Exception;

const module = 'Linoge\\PHPFunctional\\Prelude\\';
/**
 * Y
 *
 * Y combinator for PHP
 *
 * @param callable $fn
 * @return callable
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function Y($fn) {
    $call_fn = function ($make_fn) use ($fn) {
        return function (... $args) use ($fn, $make_fn) {
            return $fn($make_fn($make_fn))(... $args);
        };
    };

    $make_fn = function($make_fn) use ($fn) {
        return function(... $args) use ($make_fn, $fn) {
            return $fn($make_fn($make_fn))(... $args);
        };
    };

    return $call_fn($make_fn);
}
const Y = module . 'Y';

/**
 * partial
 *
 * creates a function that might be partial applied
 *
 * partial :: (a -> b -> ... -> c) -> a -> b -> ... -> c
 *
 * @param callable $fn
 * @param mixed $args
 * @return callable
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function partial($fn, ... $args) {
    $n_params = arity($fn);

    return n_partial($fn, $n_params, ... $args);
}

const partial = module . 'partial';

/**
 * n_partial
 *
 * creates a function that might be partial applied n args
 *
 * n_partial :: (a -> b -> ... -> c) -> Int -> a -> b -> ... -> c
 *
 * @param callable $fn
 * @param mixed $args
 * @return callable
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function n_partial($fn, $n, ... $args) {
    $n_partial = function ($recurse) {
        return function ($fn, $params_left, $args) use ($recurse) {
            if ($params_left === 0) {
                return $fn(... $args);
            }

            return function (... $args_provided)
                use ($params_left, $recurse, $args, $fn) {
                    $n_provided = count($args_provided);

                    if (count($args_provided) === 0) {
                        return $recurse($fn, $params_left, $args);
                    }

                    foreach ($args_provided as $arg) {
                        $args[] = $arg;
                    }

                    if ($params_left - $n_provided > 0) {
                        return $recurse($fn, $params_left - $n_provided, $args);
                    }

                    return $fn(... $args);
                };
        };
    };

    return Y($n_partial)($fn, $n - count($args), $args);
}

const n_partial = module . 'n_partial';

/**
 * curry
 *
 * curries a function of N arguments
 *
 * curry :: ((a, b, ..., z) -> c) -> (((a -> b) ...) -> z) -> c
 *
 * @param callable $fn
 * @return callable
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function curry($fn) {
    $n_params = arity($fn);

    $_curry = function ($recurse) {
        return function ($fn, $params_left, $args) use ($recurse) {
            return function ($x) use ($params_left, $recurse, $args, $fn) {
                $args[] = $x;

                if ($params_left - 1 > 0) {
                    return $recurse($fn, $params_left - 1, $args);
                }
                return $fn(... $args);
            };
        };
    };

    return Y($_curry)($fn, $n_params, []);
}

const curry = module . 'curry';

/**
 * arity
 *
 * return the arity of a function
 *
 * arity :: (a -> ... -> z) -> Int
 *
 * @param callable $fn
 * @return int
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function arity($fn) {
    $refl = new ReflectionFunction($fn);
    return $refl->getNumberOfParameters();
}

const arity = module . 'arity';

/**
 * uncurry
 *
 * uncurries a function of N arguments
 *
 * uncurry :: (((a -> b) -> ...) -> c) -> (a, b, ..., z) -> c
 *
 * @param callable
 * @return callable
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function uncurry(... $args) {
    $uncurry = function($fn) {
        return function(... $args) use ($fn) {
            if (count($args) < arity($fn)) {
                error('Not enough argument for call');
            }
            return $fn(... $args);
        };
    };

    return partial($uncurry, ... $args);
}

const uncurry = module . 'uncurry';

/**
 * id
 *
 * the id function
 *
 * id :: a -> a
 * @param mixed $x
 * @return mixed
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function id(... $args) {
    $id = function($x) {
        return $x;
    };

    return partial($id, ... $args);
}

const id = module . 'id';

/**
 * pair
 *
 * construct a pair out of two arguments
 *
 * pair :: a -> b -> (a, b)
 *
 * @param mixed $a
 * @param mixed $b
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function pair(... $args) {
    $pair = function($a, $b) {
        return [$a, $b];
    };

    return partial($pair, ... $args);
}

const pair = module . 'pair';

/**
 * zip
 *
 * zip a pair of arrays together
 *
 * zip :: [a] -> [b] -> [(a,b)]
 *
 * @param array $xs
 * @param array $ys
 * @return array
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function zip(... $args) {
    $zip = function($xs, $ys) {
        return array_map(pair(), $xs, $ys);
    };

    return partial($zip, ... $args);
}

const zip = module . 'zip';

/**
 * flatten
 *
 * flatten an n-dimensional array
 *
 * flatten :: [a] -> [a]
 *
 * @param array $xs
 * @return array
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function flatten(... $args) {
    $flatten = function($recurse) {
        return function($xs, $ys = [], $acc = []) use ($recurse) {
            if (is_empty($xs) && is_empty($ys)) {
                return $acc;
            }
            if (is_empty($xs)) {
                return $recurse(car($ys), cdr($ys), $acc);
            }
            if (is_list($xs)) {
                return $recurse(car($xs), append($ys, cdr($xs)), $acc);
            }
            return $recurse(car($ys), cdr($ys), append($acc, $xs));
        };
    };

    return n_partial(Y($flatten), 1, ... $args);
}

const flatten = module . 'flatten';

/**
 * foldl
 *
 * fold elements to the left
 *
 * foldl :: (a -> b -> a) -> a -> [b] -> a
 *
 * @param callable $fn
 * @param mixed $initial
 * @param array $xs
 * @return mixed
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function foldl(... $args) {
    $foldl = function($recurse) {
        return partial(function ($fn, $acc, $xs) use ($recurse) {
            if (is_empty($xs)) {
                return $acc;
            }
            return $recurse($fn, $fn($acc, car($xs)), cdr($xs));
        });
    };

    return Y($foldl)(... $args);
}

const foldl = module . 'foldl';

/**
 * add
 *
 * add two numbers
 *
 * add :: (Num a) => a -> a -> a
 *
 * @param mixed $x
 * @param mixed $y
 * @return mixed
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function add(... $args) {
    $add = function($x, $y) {
        return $x + $y;
    };

    return partial($add, ... $args);
}

const add = module . 'add';

/**
 * mult
 *
 * multiply two numbers
 *
 * mult :: (Num a) => a -> a -> a
 *
 * @param mixed $x
 * @param mixed $y
 * @return mixed
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function mult(... $args) {
    $mult = function($x, $y) {
        return $x * $y;
    };

    return partial($mult, ... $args);
}

const mult = module . 'mult';

/**
 * div
 *
 * divide two numbers
 *
 * div :: (Num a) => a -> a -> a
 *
 * @param mixed $x
 * @param mixed $y
 * @return mixed
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function div(... $args) {
    $div = function($x, $y) {
        return $x / $y;
    };

    return partial($div, ... $args);
}

const div = module . 'div';

/**
 * mod
 *
 * modulus operator
 *
 * mod :: (Num a) => a -> a -> a
 *
 * @param mixed $x
 * @param mixed $y
 * @return mixed
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function mod(... $args) {
    $mod = function($x, $y) {
        return $x % $y;
    };

    return partial($mod, ... $args);
}

const mod = module . 'mod';

/**
 * l_or
 *
 * or operation turn to a function
 *
 * l_or :: Bool -> Bool -> Bool
 *
 * @param boolean $x
 * @param boolean $y
 * @return boolean
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function l_or(... $args) {
    $l_or = function($x, $y) {
        if ($x === true || $y === true) {
            return true;
        }

        return false;
    };

    return partial($l_or, ...$args);
}

const l_or = module . 'l_or';

/**
 * max
 *
 * return biggest element between
 *
 * max :: a -> a -> a
 *
 * @param mixed $x
 * @param mixed $y
 * @return mixed
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function max(... $args) {
    $max = function($x, $y) {
        if ($x > $y) {
            return $x;
        }
        else {
            return $y;
        }
    };

    return partial($max, ... $args);
}

const max = module . 'max';

/**
 * foldr
 *
 * fold elements to the right
 *
 * foldr :: (a -> b -> b) -> b -> [a] -> b
 *
 * @param callable $fn
 * @param mixed $initial
 * @param array $xs
 * @return mixed
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function foldr(... $args) {
    $foldr = function($recurse) {
        return function($fn, $initial, $xs) use ($recurse) {
            if (is_empty($xs)) {
                return $initial;
            }
            return $fn(car($xs), $recurse($fn, $initial, cdr($xs)));
        };
    };

    return partial(Y($foldr), ... $args);
}

const foldr = module . 'foldr';

/**
 * append
 *
 * append an element to a list
 *
 * append :: [a] -> a -> [a]
 *
 * @param array $xs
 * @param mixed $x
 * @return array
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function append(... $args) {
    $append = function($xs, $x) {
        $xss = copy($xs);
        if (is_list($x)) {
            return foldl(function($acc, $x) {$acc[] = $x; return $acc;},
                         $xss,
                         $x);
        }
        $xss[] = $x;
        return $xss;
    };

    return partial($append, ... $args);
}

const append = module . 'append';

/**
 * concatenate
 *
 * concatenate two lists
 *
 * concatenate :: [a] -> [a] -> [a]
 *
 * @param array $xs
 * @param array $ys
 * @return array
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function concatenate(... $args) {
    $concatenate = function($xs, $ys) {
        return foldl(append, $xs, $ys);
    };

    return partial($concatenate, ... $args);
}

const concatenate = module . 'concatenate';

/**
 * nullp
 *
 * true if value is null
 *
 * nullp

 /**
 * is_empty
 *
 * true if a list is empty
 *
 * is_empty :: [a] -> Bool
 *
 * @param array $xs
 * @return boolean
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
     function is_empty(... $args) {
         $is_empty = function($xs) {
             if (empty($xs) === true) {
                 return true;
             }
             return false;
         };

         return partial($is_empty, ... $args);
     }

const is_empty = module . 'is_empty';

/**
 * map
 *
 * map a function f over an array
 *
 * zip :: (a -> b) -> [a] -> [b]
 *
 * @param callable $fn
 * @param array $xs
 * @return array
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function map(... $args) {
    $map = function($fn, $xs) {
        return array_map($fn, $xs);
    };

    return partial($map, ... $args);
}

const map = module . 'map';

/**
 * make_dispatcher
 *
 * construct an instance of the dispatcher
 *
 * make-dispatcher :: b
 *
 * @return array
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function make_dispatcher() {
    return [];
}

const make_dispatcher = module . 'make_dispatcher';

/**
 * error
 *
 * throw an error
 *
 * error :: String -> ()
 *
 * @param string $message
 * @return void
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function error(... $args) {
    $error = function($message) {
        throw new Exception($message);
    };

    return partial($error, ... $args);
}

const error = module . 'error';

/** copy
 *
 * copy anything
 *
 * copy :: a -> a
 *
 * @param mixed $x
 * @return mixed
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function copy(... $args) {
    $deep = new DeepCopy();
    $copy = function($x) use ($deep) {
        return $deep->copy($x);
    };

    return partial($copy, ... $args);
}

const copy = module . 'copy';

/**
 * defgeneric
 *
 * defines a lisp-like generic method
 *
 * defgeneric :: Dispatcher -> String -> (a -> b) -> Dispatcher
 *
 * @param array $dispatcher
 * @param string $name
 * @param callable $dfunc
 * @return array
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function defgeneric(... $args) {
    $defgeneric = function($dispatcher, $name, $dfunc) {
        if (isset($dispatcher[$name])) {
            error('Function defined twice');
        }
        $new_dispatcher = copy($dispatcher);
        $new_dispatcher[$name] = [
            'dispatching_function' => $dfunc
            ,'functions' => []
        ];

        return $new_dispatcher;
    };

    return partial($defgeneric, ... $args);
}

const defgeneric = module . 'defgeneric';

/**
 * defmethod
 *
 * instantiates a lisp-like generic method
 *
 * defmethod :: Dispatcher -> String -> [a]  -> (a -> ... -> c) -> Dispatcher
 *
 * @param array $dispatcher
 * @param string $name
 * @param mixed $results
 * @param callable $fn
 * @return mixed
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function defmethod(... $args) {
    $defmethod = function($dispatcher, $name, $matching, $fn) {
        if (!isset($dispatcher[$name])) {
            error('Generic method not defined');
        }

        $new_dispatcher = copy($dispatcher);
        $new_dispatcher[$name]['functions'][] = [
            'matching' => $matching
            ,'function' => $fn
        ];

        return $new_dispatcher;
    };

    return partial($defmethod, ... $args);
}

const defmethod = module . 'defmethod';

/**
 * filter
 *
 * filter an array
 *
 * filter :: (a -> Bool) -> [a] -> [a]
 *
 * @param callable $fn
 * @param array $xs
 * @return array
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function filter(... $args) {
    $filter = function($fn, $xs) {
        return array_reduce($xs, function($xs, $x) use ($fn) {
            if ($fn($x)) {
                $xs[] = $x;
            }
            return $xs;
        }, []);
    };

    return partial($filter, ... $args);
}

const filter = module . 'filter';

/**
 * equals
 *
 * equals operator turn to a function
 *
 * equals :: a -> b -> Bool
 *
 * @param mixed $x
 * @param mixed $y
 * @return bool
 * @author Carlos Gottberg <42linonge@gmail.com>
 **/
function equals(... $args) {
    $equals = function($x, $y) {
        return $x === $y;
    };

    return partial($equals, ... $args);
}

const equals = module . 'equals';

/**
 * compose
 *
 * function composition
 *
 * compose :: (b -> c) -> (a -> b) -> ... (w -> a) -> w -> c
 *
 * @param callable $f1
 * @param callable $fn
 * @return callable
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function compose(... $args) {
    $compose = function($args) {
        return array_reduce($args, function($acc, $fn) {
            return function($x) use ($fn, $acc) {
                return $acc($fn($x));
            };
        }, id());
    };

    return partial($compose, $args);
}

const compose = module . 'compose';

/**
 * dispatch
 *
 * dispatches a function throguh a dispatcher
 *
 * dispatch :: Dispatcher -> String -> (a, b, ...) -> c
 *
 * @param array $dispatcher
 * @param string $name
 * @param array $args
 * @return mixed
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function dispatch(... $args) {
    $dispatch = function ($dispatcher, $name, $args) {
        $exists_in_dispatcher = isset($dispatcher[$name]);
        $exists_outside = function_exists($name);
        $exists = $exists_in_dispatcher || $exists_outside;

        if ($exists_in_dispatcher === false) {
            error('No function with name: ' . $name);
        }

        $dispatching_fn = $dispatcher[$name]['dispatching_function'];

        $n_args = count($args);
        $n_params = arity($dispatching_fn);

        if ($n_params === 1) {
            $result = map($dispatching_fn, $args);
        } else if ($n_params === $n_args) {
            $result = [$dispatching_fn(... $args)];
        } else {
            error('Dispatching function does not match arguments');
        }

        $functions = $dispatcher[$name]['functions'];

        $matching_functions = filter(function($fn) use ($result) {
            if ($result === $fn['matching']) {
                return true;
            }
            return false;
        }, $functions);

        if (count($matching_functions) === 0) {
            error('No dispatching function matched arguments');
        }

        $fn = $matching_functions[0]['function'];
        return $fn(... $args);
    };

    return partial($dispatch, ... $args);
}

const dispatch = module . 'dispatch';

/**
 * cons
 *
 * create a cons cell (not precise)
 *
 * @param mixed $x
 * @param mixed $y
 * @return array
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function cons(... $args) {
    $cons = function($x, $y) {
        return append([$x], $y);
    };

    return partial($cons, ... $args);
};

const cons = module . 'cons';

/**
 * stream_cons
 *
 * create a new stream
 *
 * stream_cons :: a -> ([b] -> c) -> [b] -> (a, ([b] -> c))
 *
 * @param mixed $a
 * @param callable $fn
 * @param array $b
 * @return array
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function stream_cons(... $args) {
    $stream_cons = function($x, $fn, ...$args) {
        return [$x, function () { return $fn(...$args); }];
    };

    return $stream_cons(... $args);
}

const stream_cons = module . 'stream_cons';

/**
 * stream_car
 *
 * get first element out of a stream
 *
 * stream_car :: Stream a b -> a
 *
 * @param array $stream
 * @return mixed $a
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function stream_car(... $args) {
    $stream_car = function($stream) {
        return $stream[0];
    };

    return partial($stream_car, ... $args);
}

const stream_car = module . 'stream_car';

/**
 * stream_cdr
 *
 * get second element out of a stream
 *
 * stream_cdr :: Stream a b -> b
 *
 * @param array $stream
 * @return mixed $b
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function stream_cdr(... $args) {
    $stream_cdr = function($stream) {
        return $stream[1]();
    };

    return partial($stream_cdr, ... $args);
}

const stream_cdr = module . 'stream_cdr';

/**
 * car
 *
 * get first element out of a list
 *
 * car :: [a] -> a
 *
 * @param array $xs
 * @return mixed $x
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function car(... $args) {
    $car = function($xs) {
        if (isset($xs[0])) {
            return $xs[0];
        }
        return [];
    };

    return partial($car, ... $args);
}

const car = module . 'car';

/**
 * cdr
 *
 * get tail of list
 *
 * cdr :: [a] -> [a]
 *
 * @param mixed $xs
 * @return mixed
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function cdr(... $args) {
    $cdr = function ($xs) {
        if (is_empty($xs)) {
            return [];
        }

        $result =  array_slice($xs, 1);

        if ($result === NULL) {
            return [];
        }

        return $result;
    };

    return partial($cdr, ... $args);
}

const cdr = module . 'cdr';

/**
 * is_list
 *
 * is the argument a list?
 *
 * is_list :: a -> Bool
 *
 * @param mixed $a
 * @return boolean
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function is_list(... $args) {
    $is_list = function($x) {
        if (is_array($x) === true) {
            return true;
        }
        return false;
    };

    return partial($is_list, ... $args);
}

const is_list = module . 'is_list';

/**
 * any
 *
 * does any of the function application return true
 *
 * any :: (a -> Bool) -> [a] -> Bool
 *
 * @param callable $fn
 * @param array $xs
 * @return boolean
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function any(... $args) {
    $any = function($fn, $xs) {
        $xss = map($fn, $xs);
        return foldl(l_or, false, $xs);
    };

    return partial($any, ... $args);
}

const any = module . 'any';

/**
 * has_list
 *
 * does the list contain any sub-list
 *
 * has_list :: [a] -> Bool
 *
 * @param array $xs
 * @return boolean
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function has_list(... $args) {
    $has_list = function($xs) {
        return any(is_list, $xs);
    };

    return partial($has_list, ... $args);
}

const has_list = module . 'has_list';

/**
 * evaluate
 *
 * evaluate an expression a la Lisp
 *
 * evaluate :: ??
 *
 * @param $expr
 * @return mixed
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function evaluate(... $args) {
    $evaluate = function($recurse) {
        return partial(function($xs) use ($recurse) {
            if (! is_list($xs)) {
                return $xs;
            }

            $result = map($recurse, $xs);

            $fn = car($xs);
            $args = cdr($result);

            if (function_exists($fn) || is_callable($fn)) {
                return $fn(... $args);
            }

            return $xs;
        });
    };

    return Y($evaluate)(... $args);
}

const evaluate = module . 'evaluate';

/**
 * l_and
 *
 * and operation turn to a function
 *
 * l_and :: Bool -> Bool -> Bool
 *
 * @param $x
 * @param $y
 * @return boolean
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function l_and(... $args) {
    $l_and = function($x, $y) {
        if ($x === true && $y === true) {
            return true;
        }
        return false;
    };

    return partial($l_and, ... $args);
}

const l_and = module . 'l_and';

/**
 * all
 *
 * do a function, applied to every argument on a list,
 * always returns true?
 *
 * all :: (a -> Bool) -> [a] -> Bool
 *
 * @param callable $fn
 * @param array $xs
 * @return boolean
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function all(... $args) {
    $all = function($fn, $xs) {
        $xss = map($fn, $xs);
        return foldl(l_and, true, $xss);
    };

    return partial($all, ... $args);
}

const all = module . 'all';

/**
 * export
 *
 * register all functions within the module
 *
 * export :: Dispatcher -> Dispatcher
 *
 * @param array $dispatcher
 * @return array
 * @author Carlos Gottberg <42linoge@gmail.com>
 **/
function export(... $args) {
    $export = function($dispatcher) {

    };

    return partial($export, ... $args);
}

const export = module . 'export';