text:
<?php

namespace App\Http\Controllers\Document;

use App\Http\Controllers\Controller;
use App\Search\Elasticsearch;

/**
 * Index `types` that are added with a `_routing` must
 * need a `_routing` parameter to `_get`, `_update` &
 * `_delete` except for `_delete_by_query`
 */
class GetController extends Controller
{
    private $es;

    public function __construct(Elasticsearch $es)
    {
        $this->es = $es;
    }

    public function get()
    {
        $request = request()->only(['_routing', '_type', '_id']);

        $routing = $request['_routing'] ? '?routing='.$request['_routing'] : '';
        $response = $this->es->initialize()
            ->request('GET', $request['_type'].'/'.$request['_id'].$routing)
            ->send()
            ->getResponse();

        dump($this->es->getRequestUri());
        dump($this->es->getBody());
        dd($response);
    }

    public function sourceFilter()
    {
        $request = request()->only(['_routing', '_type', '_id', '_include', '_exclude']);
        $routing = $request['_routing'] ? 'routing='.$request['_routing'].'&' : '';
        $uri     = $request['_type'].'/'.$request['_id'].'?'.$routing.'_source_include='.$request['_include'].'&_source_exclude='.$request['_exclude'];

        $response = $this->es->initialize()
            ->request('GET', $uri)
            ->send()
            ->getResponse();

        dump($this->es->getRequestUri());
        dump($this->es->getBody());
        dd($response);
    }

    public function source()
    {
        $request = request()->only(['_routing', '_type', '_id', '_include', '_exclude']);
        $routing = $request['_routing'] ? 'routing='.$request['_routing'].'&' : '';
        $uri     = $request['_type'].'/'.$request['_id'].'/_source?'.$routing.'_source_include='.$request['_include'].'&_source_exclude='.$request['_exclude'];

        $response = $this->es->initialize()
            ->request('GET', $uri)
            ->send()
            ->getResponse();

        dump($this->es->getRequestUri());
        dump($this->es->getBody());
        dd($response);
    }

    /** Fields must be stored in mapping to take advantage of this feature */
    public function stored()
    {
        $request = request()->only(['_routing', '_type', '_id', '_stored']);
        $routing = $request['_routing'] ? 'routing='.$request['_routing'].'&' : '';
        $uri     = $request['_type'].'/'.$request['_id'].'?'.$routing.'stored_fields='.$request['_stored'];

        $response = $this->es->initialize()
            ->request('GET', $uri)
            ->send()
            ->getResponse();

        dump($this->es->getRequestUri());
        dump($this->es->getBody());
        dd($response);
    }

    public function multiGet()
    {
        $request = request()->only([ '_id1', '_id2', '_id3', '_id4', '_routing' ]);

        $docs = json_encode([
            'docs' => [
                [
                    '_index'        => 'elasticsearchtrial',
                    '_type'         => 'user',
                    '_id'           => $request['_id1'],
                    '_source'       => false
                ],
                [
                    '_index'        => 'elasticsearchtrial',
                    '_type'         => 'user',
                    '_id'           => $request['_id2'],
                    '_source'       => [
                        'include'   => ['addresses.city', 'addresses.state', 'email'],
                        'exclude'   => ['addresses.country']
                    ]
                ],
                [
                    '_index'        => 'elasticsearchtrial',
                    '_type'         => 'user',
                    '_id'           => $request['_id3'],
                    'stored_fields' => ['firstName', 'lastName']
                ],
                [
                    '_index'        => 'elasticsearchtrial',
                    '_type'         => 'product',
                    '_id'           => $request['_id4'],
                    '_source'       => true,
                    '_routing'      => $request['_routing']
                ]
            ]
        ]);

        $response = $this->es->initialize()
            ->request('GET', '_mget', $docs)
            ->setJsonAsHeader()
            ->send()
            ->getResponse();

        dump($this->es->getRequestUri());
        dump($this->es->getBody());
        dd($response);
    }

    /**
     * NOTE: `user` pnly endpoint. (too lazy too implement others)
     * since `_types` with routing needs a `_routing` parameter on the uri
     */
    public function multiGetId()
    {
        $request = request()->only(['_type', '_id1', '_id2', '_id3' ]);

        $docs = json_encode([
            'ids' => [ $request['_id1'], $request['_id2'], $request['_id3'] ]
        ]);

        $response = $this->es->initialize()
            ->request('GET', $request['_type'].'/_mget', $docs)
            ->setJsonAsHeader()
            ->send()
            ->getResponse();

        dump($this->es->getRequestUri());
        dump($this->es->getBody());
        dd($response);
    }

    public function count()
    {
        $request = request()->only(['_routing', '_type', '_field', '_value']);
        $routing = $request['_routing'] ? '?routing='.$request['_routing'] : '';

        $data = [
            'query' => [
                'term' => [
                    $request['_field'] => $request['_value']
                ]
            ]
        ];

        $response = $this->es->initialize()
            ->request('GET', $request['_type'].'/_count'.$routing, json_encode($data))
            ->setJsonAsHeader()
            ->send()
            ->getResponse();

        dump($this->es->getRequestUri());
        dump($this->es->getBody());
        dd($response);
    }
}


text:
<?php
namespace Admin\Libs;

class AdminAuth implements \Asgard\Auth\IAuth {
	protected $container;

	public function __construct($container) {
		$this->container = $container;
	}

	public function isConnected() {
		return $this->container['session']->has('admin_id');
	}

	public function isGuest() {
		return !$this->isConnected();
	}

	public function check() {
		if(!$this->isConnected())
			throw new \Asgard\Auth\NotAuthenticatedException();
	}

	public function attempt($user, $password) {
		$administrator = \Admin\Entity\Administrator::where(['username' => $user, 'password' => \Admin\Entity\Administrator::hash($password)])->first();
		if(!$administrator)
			$administrator = $this->attemptRemember($user, $password);

		if($administrator) {
			$this->connect($administrator->id);
			return $administrator;
		}
		return false;
	}

	public function attemptRemember() {
		$remember = $this->container['cookies']['asgard_remember'];
		return \Admin\Entity\Administrator::where(['MD5(CONCAT(username, \'-\', password))' => $remember])->first();
	}

	public function remember($user, $password) {
		$this->container['cookies']['asgard_remember'] = md5($user.'-'.\Admin\Entity\Administrator::hash($password));
	}

	public function connect($id) {
		$this->container['session']['admin_id'] = $id;
	}

	public function disconnect() {
		unset($this->container['session']['admin_id']);
	}

	public function user() {
		return \Admin\Entity\Administrator::load($this->container['session']['admin_id']);
	}

	protected function getRequest() {
		return $this->container['httpKernel']->getRequest();
	}
}

redpajama_set_name: RedPajamaGithub


text:
package com.dmdirc.addons.lagdisplay;

import com.dmdirc.ServerState;
import com.dmdirc.addons.ui_swing.EdtHandlerInvocation;
import com.dmdirc.addons.ui_swing.components.frames.TextFrame;
import com.dmdirc.addons.ui_swing.events.SwingEventBus;
import com.dmdirc.addons.ui_swing.events.SwingWindowSelectedEvent;
import com.dmdirc.addons.ui_swing.interfaces.ActiveFrameManager;
import com.dmdirc.config.GlobalConfig;
import com.dmdirc.config.prefs.PluginPreferencesCategory;
import com.dmdirc.config.prefs.PreferencesCategory;
import com.dmdirc.config.prefs.PreferencesDialogModel;
import com.dmdirc.config.prefs.PreferencesSetting;
import com.dmdirc.config.prefs.PreferencesType;
import com.dmdirc.events.ClientPrefsOpenedEvent;
import com.dmdirc.events.DisplayProperty;
import com.dmdirc.events.ServerDisconnectedEvent;
import com.dmdirc.events.ServerGotPingEvent;
import com.dmdirc.events.ServerNoPingEvent;
import com.dmdirc.events.ServerNumericEvent;
import com.dmdirc.events.ServerPingSentEvent;
import com.dmdirc.events.StatusBarComponentAddedEvent;
import com.dmdirc.events.StatusBarComponentRemovedEvent;
import com.dmdirc.interfaces.Connection;
import com.dmdirc.events.eventbus.EventBus;
import com.dmdirc.interfaces.WindowModel;
import com.dmdirc.config.provider.AggregateConfigProvider;
import com.dmdirc.config.provider.ConfigChangeListener;
import com.dmdirc.plugins.PluginDomain;
import com.dmdirc.plugins.PluginInfo;
import com.dmdirc.util.collections.RollingList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.WeakHashMap;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
import net.engio.mbassy.listener.Handler;

/**
 * Manages the lifecycle of the lag display plugin.
 */
@Singleton
public class LagDisplayManager implements ConfigChangeListener {

    /** Event bus to receive events on. */
    private final EventBus eventBus;
    /** Swing event bus to receive events from. */
    private final SwingEventBus swingEventBus;
    /** Active frame manager. */
    private final ActiveFrameManager activeFrameManager;
    private final Provider<LagDisplayPanel> panelProvider;
    /** The settings domain to use. */
    private final String domain;
    private final PluginInfo pluginInfo;
    /** Config to read global settings from. */
    private final AggregateConfigProvider globalConfig;
    /** A cache of ping times. */
    private final Map<Connection, String> pings = new WeakHashMap<>();
    /** Ping history. */
    private final Map<Connection, RollingList<Long>> history = new HashMap<>();
    /** Whether or not to show a graph in the info popup. */
    private boolean showGraph = true;
    /** Whether or not to show labels on that graph. */
    private boolean showLabels = true;
    /** The length of history to keep per-server. */
    private int historySize = 100;
    /** The panel currently in use. Null before {@link #load()} or after {@link #unload()}. */
    private LagDisplayPanel panel;

    @Inject
    public LagDisplayManager(final EventBus eventBus,
            final SwingEventBus swingEventBus,
            final ActiveFrameManager activeFrameManager,
            final Provider<LagDisplayPanel> panelProvider,
            @PluginDomain(LagDisplayPlugin.class) final String domain,
            @PluginDomain(LagDisplayPlugin.class) final PluginInfo pluginInfo,
            @GlobalConfig final AggregateConfigProvider globalConfig) {
        this.eventBus = eventBus;
        this.swingEventBus = swingEventBus;
        this.activeFrameManager = activeFrameManager;
        this.panelProvider = panelProvider;
        this.domain = domain;
        this.pluginInfo = pluginInfo;
        this.globalConfig = globalConfig;
    }

    public void load() {
        panel = panelProvider.get();
        eventBus.publishAsync(new StatusBarComponentAddedEvent(panel));
        globalConfig.addChangeListener(domain, this);
        readConfig();
        swingEventBus.subscribe(this);
        eventBus.subscribe(this);
    }

    public void unload() {
        eventBus.publishAsync(new StatusBarComponentRemovedEvent(panel));
        globalConfig.removeListener(this);
        swingEventBus.unsubscribe(this);
        eventBus.unsubscribe(this);
        panel = null;
    }

    /** Reads the plugin's global configuration settings. */
    private void readConfig() {
        showGraph = globalConfig.getOptionBool(domain, "graph");
        showLabels = globalConfig.getOptionBool(domain, "labels");
        historySize = globalConfig.getOptionInt(domain, "history");
    }

    /**
     * Retrieves the history of the specified server. If there is no history, a new list is added to
     * the history map and returned.
     *
     * @param connection The connection whose history is being requested
     *
     * @return The history for the specified server
     */
    protected RollingList<Long> getHistory(final Connection connection) {
        if (!history.containsKey(connection)) {
            history.put(connection, new RollingList<>(historySize));
        }
        return history.get(connection);
    }

    /**
     * Determines if the {@link ServerInfoDialog} should show a graph of the ping time for the
     * current server.
     *
     * @return True if a graph should be shown, false otherwise
     */
    public boolean shouldShowGraph() {
        return showGraph;
    }

    /**
     * Determines if the {@link PingHistoryPanel} should show labels on selected points.
     *
     * @return True if labels should be shown, false otherwise
     */
    public boolean shouldShowLabels() {
        return showLabels;
    }

    @Handler(invocation = EdtHandlerInvocation.class)
    public void selectionChanged(final SwingWindowSelectedEvent event) {
        if (event.getWindow().isPresent()) {
            final Optional<Connection> connection = event.getWindow().get().getContainer()
                    .getConnection();
            if (connection.isPresent() && connection.get().getState() != ServerState.CONNECTED) {
                panel.getComponent().setText("Not connected");
            } else {
                panel.getComponent().setText(getTime(connection.get()));
            }
        } else {
            panel.getComponent().setText("Unknown");
        }
        panel.refreshDialog();
    }

    @Handler
    public void handleServerNumeric(final ServerNumericEvent event) {
        if (event.getNumeric() != 421) {
            return;
        }
        final boolean useAlternate = event.getConnection().getWindowModel().getConfigManager()
                .getOptionBool(domain, "usealternate");
        final boolean isActive = isActiveWindow(event.getConnection());
        final String[] args = event.getArgs();
        if (useAlternate && args[3].startsWith("LAGCHECK_")) {
            try {
                final long sent = Long.parseLong(args[3].substring(9));
                final Long duration = new Date().getTime() - sent;
                final String value = formatTime(duration);
                pings.put(event.getConnection(), value);
                getHistory(event.getConnection()).add(duration);
                if (isActive) {
                    panel.getComponent().setText(value);
                }
            } catch (NumberFormatException ex) {
                pings.remove(event.getConnection());
            }
            event.setDisplayProperty(DisplayProperty.DO_NOT_DISPLAY, true);

            panel.refreshDialog();
        }
    }

    @Handler
    public void handleServerDisconnected(final ServerDisconnectedEvent event) {
        final boolean isActive = isActiveWindow(event.getConnection());
        if (isActive) {
                panel.getComponent().setText("Not connected");
                pings.remove(event.getConnection());
            }

            panel.refreshDialog();
    }

    @Handler
    public void handleServerGotPing(final ServerGotPingEvent event) {
        if (event.getConnection().getWindowModel().getConfigManager().
                getOptionBool(domain, "usealternate")) {
            return;
        }
        final boolean isActive = isActiveWindow(event.getConnection());
        final String value = formatTime(event.getPing());

        getHistory(event.getConnection()).add(event.getPing());
        pings.put(event.getConnection(), value);

        if (isActive) {
            panel.getComponent().setText(value);
        }

        panel.refreshDialog();
    }

    @Handler
    public void handleServerNoPing(final ServerNoPingEvent event) {
        if (event.getConnection().getWindowModel().getConfigManager().
                getOptionBool(domain, "usealternate")) {
            return;
        }
        final boolean isActive = isActiveWindow(event.getConnection());
        final String value = formatTime(event.getPing()) + '+';

        pings.put(event.getConnection(), value);

        if (isActive) {
            panel.getComponent().setText(value);
        }

        panel.refreshDialog();
    }

    @Handler
    public void handleServerPingSent(final ServerPingSentEvent event) {
        if (!event.getConnection().getWindowModel().getConfigManager().
                getOptionBool(domain, "usealternate")) {
            return;
        }
        event.getConnection().getParser().get().sendRawMessage("LAGCHECK_" + new Date().getTime());
    }

    /**
     * Retrieves the ping time for the specified connection.
     *
     * @param connection The connection whose ping time is being requested
     *
     * @return A String representation of the current lag, or "Unknown"
     */
    public String getTime(final Connection connection) {
        return pings.get(connection) == null ? "Unknown" : pings.get(connection);
    }

    /**
     * Formats the specified time so it's a nice size to display in the label.
     *
     * @param object An uncast Long representing the time to be formatted
     *
     * @return Formatted time string
     */
    protected String formatTime(final Object object) {
        final Long time = (Long) object;

        if (time >= 10000) {
            return Math.round(time / 1000.0) + "s";
        } else {
            return time + "ms";
        }
    }

    @Override
    public void configChanged(final String domain, final String key) {
        readConfig();
    }

    private boolean isActiveWindow(final Connection connection) {
        return activeFrameManager.getActiveFrame().map(TextFrame::getContainer)
                .flatMap(WindowModel::getConnection)
                .filter(connection::equals).isPresent();
    }

    @Handler
    public void showConfig(final ClientPrefsOpenedEvent event) {
        final PreferencesDialogModel manager = event.getModel();
        final PreferencesCategory cat = new PluginPreferencesCategory(
                pluginInfo, "Lag display plugin", "");
        cat.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
                pluginInfo.getDomain(), "usealternate",
                "Alternate method", "Use an alternate method of determining "
                + "lag which bypasses bouncers or proxies that may reply?",
                manager.getConfigManager(), manager.getIdentity()));
        cat.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
                pluginInfo.getDomain(), "graph", "Show graph", "Show a graph of ping times "
                + "for the current server in the information popup?",
                manager.getConfigManager(), manager.getIdentity()));
        cat.addSetting(new PreferencesSetting(PreferencesType.BOOLEAN,
                pluginInfo.getDomain(), "labels", "Show labels", "Show labels on selected "
                + "points on the ping graph?",
                manager.getConfigManager(), manager.getIdentity()));
        cat.addSetting(new PreferencesSetting(PreferencesType.INTEGER,
                pluginInfo.getDomain(), "history", "Graph points", "Number of data points "
                + "to plot on the graph, if enabled.",
                manager.getConfigManager(), manager.getIdentity()));
        manager.getCategory("Plugins").addSubCategory(cat);
    }

}


text:
/** @file i2c.h
 * I2C bus driver.
 * XXX for now only master mode.
 */

#ifndef I2C_H_
#define I2C_H_

/** I2C lines port and pins for internal pull-up resistors if used. Define
 * I2C_USE_PULLUP for enabling internal pull-up resistors.
 */
#ifndef I2C_SCL_PORT
#define I2C_SCL_PORT    C
#endif

#ifndef I2C_SCL_PIN
#define I2C_SCL_PIN     5
#endif

#ifndef I2C_SDA_PORT
#define I2C_SDA_PORT    C
#endif

#ifndef I2C_SDA_PIN
#define I2C_SDA_PIN     4
#endif

/** Maximal number of queued I2C transfer request. */
#ifndef I2C_REQ_QUEUE_SIZE
#define I2C_REQ_QUEUE_SIZE 8
#endif

#define I2C_REQ_QUEUE_PTR_BITS 4
#if (1 << I2C_REQ_QUEUE_PTR_BITS) < I2C_REQ_QUEUE_SIZE
#error I2C_REQ_QUEUE_SIZE is too big. Number of bits in queue pointer should \
    be increased.
#endif

class I2cBus {
public:
    enum TransferStatus {
        /** Do not call the transfer handler. Never seen by the handler. */
        NONE,
        /** SLA+W successfully transferred. Ready to transmit bytes. The handler
         * should call TransmitByte() function to schedule next byte.
         * transmission.
         */
        TRANSMIT_READY,
        /** SLA+R successfully transferred. Ready to receive bytes. Nack()
         * method can be called to send NACK on the first received byte.
         */
        RECEIVE_READY,
        /** Byte was successfully transmitted, ready to transmit next byte. */
        BYTE_TRANSMITTED,
        /** Byte was successfully received, ready to receive next byte. */
        BYTE_RECEIVED,

        /* A transfer is closed on the codes below. */
        /** The bit which indicates that a transfer is closed after such status. */
        CLOSE_MASK = 0x80,
        /** Either arbitration lost, NACK on SLA+W or other failure. */
        TRANSMIT_FAILED = 0x80,
        /** Either arbitration lost, NACK on SLA+R or other failure. */
        RECEIVE_FAILED,
        /** NACK received when transmitting byte. */
        NACK,
        /** Byte was successfully received and NACK has been returned. */
        LAST_BYTE_RECEIVED,

        /** Special status for final read after transfer was closed by handler
         * but NACK was not sent. Never seen by handler.
         */
        READ_CLOSED
    };

    /** Handles I2C transfer steps.
     *
     * @param status Current status of the transfer. The transfer is closed after
     *      the handler invocation if I2cIsClosingStatus(status) is true.
     * @param data Received data byte. Valid with @ref BYTE_RECEIVED and @ref
     *      LAST_BYTE_RECEIVED status codes.
     * @return True to continue the transfer if permitted, false to end the transfer.
     */
    typedef bool (*TransferHandler)(TransferStatus status, u8 data);

    /** Initialize I2C driver. */
    I2cBus();

    /** Call from main loop. */
    void
    Poll();

    /** Check if a transfer is closed after the specified status code received. */
    static inline bool
    IsClosingStatus(TransferStatus status)
    {
        return status & CLOSE_MASK;
    }

    /** Enqueue new transfer.
     *
     * @param address Target device address. Seven least significant bits are used.
     * @param isTransmit Transmission if true, receiving if false.
     * @param handler Handles the transfer steps.
     * @return True if the transfer enqueued, false if failed.
     */
    bool
    RequestTransfer(u8 address, bool isTransmit, TransferHandler handler);

    /** Enqueue new transfer right after the current one. The transfer is guaranteed
     * to be executed with repeated start condition. Should be called in transfer
     * handler only. The current transfer is closed. For read transfer the
     * scheduled instant transfer will be deferred until NACK is sent.
     */
    void
    RequestInstantTransfer(u8 address, bool isTransmit, TransferHandler handler);

    /** Send NACK on next received byte. Should be called in transfer handler
     * only. Have effect in read transfer only.
     */
    void
    Nack()
    {
        if (state == State::READ) {
            nackPending = true;
        }
    }

    /** Specify next byte for transmission.  Should be called in transfer handler
     * only. Have effect in write transfer only. The transfer is closed if not
     * called in write transfer handler.
     *
     * @param data Byte to transmit.
     */
    void
    TransmitByte(u8 data)
    {
        if (state == State::WRITE) {
            pendingTransmitByte = data;
            transmitPending = true;
        }
    }

    /** Should be called by interrupt only. */
    void
    HandleInterrupt();
private:
    enum State {
        IDLE,
        SLA_W,
        SLA_R,
        SLA_W_SENT,
        SLA_R_SENT,
        READ,
        WRITE,
        /** Transfer closed by handler, NACK should be sent on next byte. */
        CLOSING_READ
    };

    /** Hardware unit status codes. */
    enum HwStatus {
        START_SENT =            0x08,
        REPEATED_START_SENT =   0x10,
        SLA_W_ACK =             0x18,
        SLA_W_NACK =            0x20,
        DATA_SENT_ACK =         0x28,
        DATA_SENT_NACK =        0x30,
        ARBITRATION_LOST =      0x38,
        SLA_R_ACK =             0x40,
        SLA_R_NACK =            0x48,
        DATA_RCVD_ACK =         0x50,
        DATA_RCVD_NACK =        0x58,

        NO_STATE =              0xf8
    };

    /** Transfer request. */
    struct TransferReq {
        /** Null for free slot. */
        TransferHandler handler;
        /** Address packet byte. */
        u8 sla;
    } __PACKED;

    /** Pending requests queue. */
    TransferReq reqQueue[I2C_REQ_QUEUE_SIZE];
    /** Byte to transmit. */
    u8 pendingTransmitByte;
    /** Index of next element in the requests queue. */
    u8 queuePtr:I2C_REQ_QUEUE_PTR_BITS,
    /** Transfer at current queue position should be started by repeated start. */
       instantTransferPending:1,
       state:3,

   /** Send NACK on next received byte. */
       nackPending:1,
   /** Next transmission byte specified. */
       transmitPending:1;

    /** Check if hardware is currently idle. */
    inline bool
    IsHwIdle()
    {
        return (TWCR & _BV(TWINT)) || (TWSR == HwStatus::NO_STATE);
    }

    /** Send START condition. */
    inline void
    SendStart()
    {
        TWCR = (TWCR & ~(_BV(TWINT) | _BV(TWSTA) | _BV(TWSTO))) |
               (_BV(TWINT) | _BV(TWSTA));
    }

    /** Send STOP condition. */
    inline void
    SendStop()
    {
        TWCR = (TWCR & ~(_BV(TWINT) | _BV(TWSTA) | _BV(TWSTO))) |
               (_BV(TWINT) | _BV(TWSTO));
    }

    /** Send data byte. */
    inline void
    SendByte(u8 byte)
    {
        TWDR = byte;
        TWCR = (TWCR & ~(_BV(TWINT) | _BV(TWSTA) | _BV(TWSTO))) |
               _BV(TWINT);
    }

    inline void
    ReceiveByte()
    {
        TWCR = (TWCR & ~(_BV(TWINT) | _BV(TWSTA) | _BV(TWSTO) | _BV(TWEA))) |
                (_BV(TWINT) | (nackPending ? 0 : _BV(TWEA)));
        nackPending = false;
    }

    /** Close current trasfer. Should be called with interrupts disabled. */
    void
    CloseTransfer();

} __PACKED;

extern I2cBus i2cBus;

#endif /* I2C_H_ */


text:
extern "C" {
#endif

// Forward declaration since it's passed into some of the functions in this
// header.
struct GumboInternalParser;

// Initializes a new GumboVector with the specified initial capacity.
void gumbo_vector_init(
    struct GumboInternalParser* parser, size_t initial_capacity,
    GumboVector* vector);

// Frees the memory used by an GumboVector.  Does not free the contained
// pointers.
void gumbo_vector_destroy(
    struct GumboInternalParser* parser, GumboVector* vector);

// Adds a new element to an GumboVector.
void gumbo_vector_add(
    struct GumboInternalParser* parser, void* element, GumboVector* vector);

// Removes and returns the element most recently added to the GumboVector.
// Ownership is transferred to caller.  Capacity is unchanged.  If the vector is
// empty, NULL is returned.
void* gumbo_vector_pop(struct GumboInternalParser* parser, GumboVector* vector);

// Inserts an element at a specific index.  This is potentially O(N) time, but
// is necessary for some of the spec's behavior.
void gumbo_vector_insert_at(
    struct GumboInternalParser* parser, void* element, int index,
    GumboVector* vector);

// Removes an element from the vector, or does nothing if the element is not in
// the vector.
void gumbo_vector_remove(
    struct GumboInternalParser* parser, void* element, GumboVector* vector);

// Removes and returns an element at a specific index.  Note that this is
// potentially O(N) time and should be used sparingly.
void* gumbo_vector_remove_at(
    struct GumboInternalParser* parser, int index, GumboVector* vector);

#ifdef __cplusplus
}
#endif

#endif  // GUMBO_VECTOR_H_


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:paddingLeft="5dp"
    android:paddingRight="5dp"
    android:background="@color/yellow4">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:text="@string/alarm_no_mimics_label"
            android:textAppearance="@style/TextAppearance.AppCompat.Title"
            android:textColor="@color/white" />

        <TextView
            android:id="@+id/alarm_no_mimics_label"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:layout_marginTop="5dp"
            android:textAppearance="@style/TextAppearance.AppCompat.Display2"
            android:textColor="@color/white"
            android:visibility="gone"/>

        <TextView
            android:id="@+id/alarm_no_mimics_tap_to_add"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:layout_marginTop="40dp"
            android:text="@string/alarm_no_mimics_tap_to_add"
            android:textAppearance="@style/TextAppearance.AppCompat.Title"
            android:textColor="@color/yellow1" />

    </LinearLayout>

</RelativeLayout>


text:
define(['text!version.json', 'jquery', 'underscore', 'readium_shared_js/views/reader_view', 'readium_js/epub-fetch/publication_fetcher',
        'readium_js/epub-model/package_document_parser', 'readium_js/epub-fetch/iframe_zip_loader', 'readium_shared_js/views/iframe_loader'
        ],
    function (versionText, $, _, ReaderView, PublicationFetcher,
              PackageParser, IframeZipLoader, IframeLoader) {

    var Readium = function(readiumOptions, readerOptions){

        var _options = { mathJaxUrl: readerOptions.mathJaxUrl };

        var _contentDocumentTextPreprocessor = function(src, contentDocumentHtml) {

            function injectedScript() {

                navigator.epubReadingSystem = window.parent.navigator.epubReadingSystem;
            }

            var sourceParts = src.split("/");
            //sourceParts.pop(); //remove source file name
            var baseHref = sourceParts.join("/"); // + "/";

            console.log("EPUB doc base href:");
            console.log(baseHref);
            var base = "<base href=\"" + baseHref + "\"/>";

            var scripts = "<script type=\"text/javascript\">(" + injectedScript.toString() + ")()<\/script>";

            if (_options && _options.mathJaxUrl && contentDocumentHtml.indexOf("<math") >= 0) {
                scripts += "<script type=\"text/javascript\" src=\"" + _options.mathJaxUrl + "\"> <\/script>";
            }

            contentDocumentHtml = contentDocumentHtml.replace(/(<head[\s\S]*?>)/, "$1" + base + scripts);

            contentDocumentHtml = contentDocumentHtml.replace(/(<iframe[\s\S]+?)src[\s\S]*?=[\s\S]*?(["'])([^"']+?)(["'])([\s\S]*?>)/g, '$1data-src=$2$3$4$5');
//console.debug(contentDocumentHtml);

            return contentDocumentHtml;
        };

        var self = this;

        var _currentPublicationFetcher;

        var jsLibRoot = readiumOptions.jsLibRoot;

        if (!readiumOptions.useSimpleLoader){
            readerOptions.iframeLoader = new IframeZipLoader(function() { return _currentPublicationFetcher; }, _contentDocumentTextPreprocessor);
        }
        else{
            readerOptions.iframeLoader = new IframeLoader();
        }

        // Chrome extension and cross-browser cloud reader build configuration uses this scaling method across the board (no browser sniffing for Chrome)
        // See https://github.com/readium/readium-js-viewer/issues/313#issuecomment-101578284
        // true means: apply CSS scale transform to the root HTML element of spine item documents (fixed layout / pre-paginated)
        // and to any spine items in scroll view (both continuous and document modes). Scroll view layout includes reflowable spine items, but the zoom level is 1x so there is no impact.
        readerOptions.needsFixedLayoutScalerWorkAround = true;

        this.reader = new ReaderView(readerOptions);
        ReadiumSDK.reader = this.reader;

        this.openPackageDocument = function(bookRoot, callback, openPageRequest)  {
            if (_currentPublicationFetcher) {
                _currentPublicationFetcher.flushCache();
            }

            var cacheSizeEvictThreshold = null;
            if (readiumOptions.cacheSizeEvictThreshold) {
                cacheSizeEvictThreshold = readiumOptions.cacheSizeEvictThreshold;
            }

            _currentPublicationFetcher = new PublicationFetcher(bookRoot, jsLibRoot, window, cacheSizeEvictThreshold, _contentDocumentTextPreprocessor);

            _currentPublicationFetcher.initialize(function(resourceFetcher) {

                var _packageParser = new PackageParser(bookRoot, _currentPublicationFetcher);

                _packageParser.parse(function(packageDocument){
                    var openBookOptions = readiumOptions.openBookOptions || {};
                    var openBookData = $.extend(packageDocument.getSharedJsPackageData(), openBookOptions);

                    if (openPageRequest) {
                        openBookData.openPageRequest = openPageRequest;
                    }
                    self.reader.openBook(openBookData);

                    var options = {
                        metadata: packageDocument.getMetadata()
                    };

                    if (callback){
                        // gives caller access to document metadata like the table of contents
                        callback(packageDocument, options);
                    }
                });
            });
        };

        this.closePackageDocument = function() {
            if (_currentPublicationFetcher) {
                _currentPublicationFetcher.flushCache();
            }
        };

        ReadiumSDK.emit(ReadiumSDK.Events.READER_INITIALIZED, ReadiumSDK.reader);
    };

    Readium.version = JSON.parse(versionText);

    Readium.getVersion = function(callback) {

        var version = Readium.version;

        if (version.needsPopulating) {

            console.log("version.json needsPopulating ...");

            var nextRepo = function(i) {
                if (i >= version.repos.length) {
                    delete version.needsPopulating;
                    delete version.repos;

                    console.log("version");
                    console.debug(version);

                    Readium.version = version;
                    callback(version);
                    return;
                }

                var repo = version.repos[i];

                console.log("##########################");

                console.log("repo.name");
                console.debug(repo.name);

                console.log("repo.path");
                console.debug(repo.path);

                version[repo.name] = {};
                version[repo.name].timestamp = new Date().getTime();

                  //
                  // "readiumJs":
                  // {
                  //   "sha":"xxx",
                  //   "clean":false,
                  //   "version":"yyy",
                  //   "chromeVersion":"yyy",
                  //   "tag":"zzz",
                  //   "branch":"fff",
                  //   "release":false,
                  //   "timestamp":000
                  // }

                $.getJSON(repo.path + '/package.json', function(data) {

                    console.log("version");
                    console.debug(data.version);

                    version[repo.name].version = data.version;
                    version[repo.name].chromeVersion = '2.' + data.version.substring(2);

                    var getRef = function(gitFolder, repo, ref) {
                        var url = gitFolder + '/' + ref;

                        console.log("getRef");
                        console.debug(url);

                        $.get(url, function(data) {

                            console.log("getRef OKAY");
                            console.debug(url);

                            console.log(data);

                            version[repo.name].branch = ref;
                            console.log("branch");
                            console.debug(ref);

                            var sha = data.substring(0, data.length - 1);
                            version[repo.name].sha = sha;
                            console.log("sha");
                            console.debug(sha);

                            nextRepo(++i);

                        }).fail(function(err) {

                            console.log("getRef ERROR");
                            console.debug(url);

                            nextRepo(++i);
                        });
                    };

                    var getGit = function(repo) {
                        var url = repo.path + '/.git';

                        console.log("getGit");
                        console.debug(url);

                        $.get(url, function(data) {

                            console.log("getGit OKAY");
                            console.debug(url);

                            console.log(data);

                            if (data.indexOf('gitdir: ') == 0) {

                                var gitDir = repo.path + "/" + data.substring('gitdir: '.length).trim();

                                console.log("gitdir: OKAY");
                                console.log(gitDir);

                                getHead(gitDir, repo);

                            } else {
                                console.log("gitdir: ERROR");

                                nextRepo(++i);
                            }

                        }).fail(function(err) {

                            console.log("getGit ERROR");
                            console.debug(url);

                            nextRepo(++i);
                        });
                    };

                    var getHead = function(gitFolder, repo, first) {
                        var url = gitFolder + "/HEAD";

                        console.log("getHead");
                        console.debug(url);

                        $.get(url, function(data) {

                            console.log("getHead OKAY");
                            console.debug(url);

                            console.log(data);

                            var ref = data.substring(5, data.length - 1);
                            getRef(gitFolder, repo, ref);

                        }).fail(function(err) {

                            console.log("getHead ERROR");
                            console.debug(url);

                            if (first) {
                                getGit(repo);
                            } else {
                                console.log("getHead ABORT");
                                nextRepo(++i);
                            }
                        });
                    };

                    getHead(repo.path + '/.git', repo, true);

                }).fail(function(err) { nextRepo(++i); });
            };

            nextRepo(0);

        } else { callback(version); }
    };

    return Readium;
});


text:
<?php

    $lang['auto.lang_english']				= "English";
    $lang['auto.lang_arabic']				= "العربية";

    $lang['auto.home']					  = "Home";
    $lang['auto.about_us']				= "About Us";

    $lang['auto.our_services']					  = "Our Services";
    $lang['auto.event_portfolio']					  = "Event Portfolio";
    $lang['auto.our_clients']					  = "Our Clients";
    $lang['auto.contact_us']					  = "Contact Us";
    $lang['auto.login']					  = "Log in";
    $lang['auto.register']					  = "Register";
    $lang['auto.follow_us_on']					  = "Follow us on";
    $lang['auto.select_language']					  = "Select Language";
    $lang['auto.register_with_us']					  = "register with us";

    $lang['auto.visit_us']					  = "Visit Us";
    $lang['auto.connect_us']					  = "Connect Us";
    $lang['auto.request_callback']					  = "Request a Callback";
    $lang['auto.name']					  = "Name";
    $lang['auto.phone']					  = "Phone";
    $lang['auto.regards']					  = "Regards";
    $lang['auto.send_request']					  = "Send request";
    $lang['auto.designed_developed']					  = "Designed & Developed by";
    $lang['auto.copyright_text']					  = "© Copyright 2015. Avenir Events Dubai";

    $lang['auto.we_combine_experience']					  = "We compine experience, quality & reliability";
    $lang['auto.models']					  = "Models";
    $lang['auto.photographers']					  = "PHOTOGRAPHERS";
    $lang['auto.stylist']					  = "STYLIST";
    $lang['auto.cast']					  = "CAST";
    $lang['auto.entertainers']					  = "ENTERTAINERS";
    $lang['auto.event_support']					  = "EVENT SUPPORT";
    $lang['auto.conference_seminars']					  = "CONFERANCE & Seminars";
    $lang['auto.auction_organizing']					  = "Auction Organising";
    $lang['auto.parties']					  = "Parties";
    $lang['auto.promotions']					  = "PROMOTIONS";
    $lang['auto.hostess']					  = "Hostess";
    $lang['auto.promoters']					  = "Promoters";
    $lang['auto.exhibitions']					  = "Exhibitions";
    $lang['auto.we_proud_display_recent_works']					  = "We Proud to Display Our Works - Check our recent works";
    $lang['auto.photos']					  = "PHOTOS";
    $lang['auto.videos']					  = "Videos";
    $lang['auto.find_out_more_from_our']					  = "FIND OUT MORE FROM OUR";
    $lang['auto.some_of_top_brands']					  = "Some of the top brands we work with";
    $lang['auto.clients_review']					  = "Our Clients Review";
    $lang['auto.our_strength_our_clients']					  = "Our Strength is Our Clients";

    $lang['auto.register_subhead']					  = "Be a part of Avenir family & start an awesome career.";
    $lang['auto.model']					  = "MODEL";
    $lang['auto.promoter']					  = "PROMOTER";
    $lang['auto.stylist']					  = "STYLIST";

    $lang['auto.model_info']					  = "Model Info";
    $lang['auto.i_am']					  = "I am";
    $lang['auto.international']					  = "International";
    $lang['auto.celebrity']					  = "Celebrity";
    $lang['auto.new_face']					  = "New Face";
    $lang['auto.ramp_walk']					  = "Ramp & Catwalk";
    $lang['auto.type']					  = "Type";
    $lang['auto.premium']					  = "Premium";
    $lang['auto.secondary']					  = "Secondary";
    $lang['auto.region']					  = "Region";
    $lang['auto.arabic']					  = "Arabic";
    $lang['auto.meditaranian']					  = "Meditaranian";
    $lang['auto.oriental']					  = "Oriental";
    $lang['auto.indian']					  = "Indian";
    $lang['auto.european']					  = "European";
    $lang['auto.measurements']					  = "Measurements (cm)";
    $lang['auto.height']					  = "Height";
    $lang['auto.weight']					  = "Weight";
    $lang['auto.bust']					  = "Bust";
    $lang['auto.waist']					  = "Waist";
    $lang['auto.hip']					  = "Hip";
    $lang['auto.dress_size']					  = "Dress Size";
    $lang['auto.pant_size']					  = "Pant Size";
    $lang['auto.shoe_size']					  = "Shoe Size";
    $lang['auto.hair_long']					  = "Hair Long";
    $lang['auto.eye_color']					  = "Eye Color";
    $lang['auto.languages']					  = "Languages";
    $lang['auto.upload_photos']					  = "Upload Photos";
    $lang['auto.select_photos']					  = "Select Photos";
    $lang['auto.upload_cv']					  = "Upload CV";
    $lang['auto.select_file']					  = "Select File";

    $lang['auto.personal_info']					  = "Personal Info";
    $lang['auto.name']					  = "Name";
    $lang['auto.email']					  = "Email";
    $lang['auto.phone']					  = "Phone";
    $lang['auto.password']					  = "Password";
    $lang['auto.confirm_password']					  = "Confirm Password";
    $lang['auto.message']					  = "Message";
    $lang['auto.send_request']					  = "Send Request";
    $lang['auto.registration_completed_successfully']					  = "Registration completed successfully,";
    $lang['auto.send_email_success']					  = "We just send you an email containing the registration details of your profile with us.";
    $lang['auto.go_home']					  = "GO HOME";

    $lang['auto.hostess']					  = "Hostess";
    $lang['auto.beauty']					  = "Beauty";
    $lang['auto.premium_promoter']					  = "Premium Promoter";
    $lang['auto.secondary_promoter']					  = "Secondary Promoter";
    $lang['auto.i_like_promote']					  = "I like Promote";
    $lang['auto.cars']					  = "Cars";
    $lang['auto.alcoholic_beverages']					  = "Alchaholic Beverages";
    $lang['auto.non_alcoholic_beverages']					  = "Non Alchaholic Beverages";
    $lang['auto.cigarettes']					  = "Cigarettes";
    $lang['auto.electronics']					  = "Electronics";
    $lang['auto.other']					  = "Other";

    $lang['auto.hair_stylist']					  = "Hair Stylist";
    $lang['auto.makeup_artist']					  = "Makeup Artist";
    $lang['auto.hari_n_makeup']					  = "Hair & Make Up";
    $lang['auto.prop_stylist']					  = "Prop Stylist";
    $lang['auto.wardrobe']					  = "Wardrob";

    $lang['auto.upcoming_events']  = "Upcomming Events";

    $lang['auto.auction_title'] = "Auction Organising";
    $lang['auto.casting'] = "Casting";
    $lang['auto.conference_header'] = "Conference & Seminars";
    $lang['auto.service_subtitle'] = "Send your details and one of our executive will get back to you";

?>


text:
namespace ImageGallery.Services.Data.Contracts
{
    using System.Linq;
    using Models;

    public interface ITagsService
    {
        IQueryable<Tag> GetAll(int albumId);

        int Add(Tag tag);

        IQueryable<Tag> GetById(int id);

        int DeleteTagById(int id);
    }
}


text:
[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Sen-Zhang/bootstrap_ui_helper?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
[![Code Climate](https://codeclimate.com/github/Sen-Zhang/bootstrap_ui_helper/badges/gpa.svg)](https://codeclimate.com/github/Sen-Zhang/bootstrap_ui_helper)

Bootstrap style UI helpers engine

## Requirement
* Rails 3.0+
* Bootstrap v3.0+  (http://getbootstrap.com/)
* Font Awesome v4.4.0  (https://fortawesome.github.io/Font-Awesome/)
* jQuery 1.7+ (http://jquery.com/download/)

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'bootstrap_ui_helper'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install bootstrap_ui_helper

In `application.js`, add the following line:

    //= require bootstrap_ui_helper

In `application.css`, add the following line:

     *= require bootstrap_ui_helper

## Usage

Please proceed to http://sen-zhang.github.io/#/articles/bootstrap_ui_helper for more details and examples on how to use the helpers.


text:
package simpleTests;

import utils.GenericObject;
import utils.TasksImplementation;

public class IndependentWithSync {

    private static final int N = 3;

    public static void main(String[] args) {
        GenericObject[] values = new GenericObject[N];

        for (int i = 0; i < N; ++i) {
            values[i] = TasksImplementation.initialize();
        }

        // Final sync
        for (int i = 0; i < N; ++i) {
            System.out.println("Value " + i + " is " + values[i].getValue());
        }
    }

}


text:
/*
 * Dynamic linked library for the olsr.org olsr daemon
 */

#ifndef _OLSRD_DOT_DRAW
#define _OLSRD_DOT_DRAW

#include "olsrd_plugin.h"
#include "plugin_util.h"

extern union olsr_ip_addr ipc_accept_ip;
extern int ipc_port;

int olsrd_plugin_interface_version(void);
int olsrd_plugin_init(void);
void olsr_plugin_exit(void);
void olsrd_get_plugin_parameters(const struct olsrd_plugin_parameters **params, int *size);

#endif

/*
 * Local Variables:
 * c-basic-offset: 2
 * indent-tabs-mode: nil
 * End:
 */


text:
class CrawlingsController < ::ApplicationController
  PER_PAGE = 20

  def index
    @crawlings = Crawling.all.order(:id).page(params[:page]).per(PER_PAGE)
  end

  def show
    @crawling = Crawling.preload(:event).find(params[:id])
  end

  def new
    @crawling = Crawling.new
    @sites = Crawling.site_type_options
  end

  def create
    crawling = Crawling.new(crawling_params)
    if crawling.crawl_and_insert
      redirect_to crawlings_path, notice: '作成が完了しました'
    else
      render :new
    end
  end

  def scrape
    crawling = Crawling.unscraped.find(params[:id])
    @event = crawling.scrape
    if @event.nil?
      crawling.update(scraped: true)
      redirect_to crawlings_path, notice: 'フォーマットNG'
      return
    end
    @crawling_id = crawling.id
    prepare_sellect_collections
    render '/events/new'
  end

  private

  def crawling_params
    params.require(:crawling).permit(:site_type, :base_url)
  end

  def prepare_sellect_collections
    @sports = Sport.order(:id)
    @prefectures = Master::Prefecture.order(:id)
  end
end


text:
.. _Events:

Events
======

The "events" namespace can be used to setup and receive asynchronous
updates about system status and other types of system notifications.

.. warning:: The events namespace does not really translate over to REST
             which was not designed for asynchronous events. For this
             reason, only Websocket examples are used in this section.

Every events request contains several parameters, seen here in
:numref:`Table %s <eventpar>`.

.. _eventpar:
.. table:: Event Request Parameters

   +---------------+-----------+--------------------------------------+
   | **Parameter** | **Value** | **Description**                      |
   |               |           |                                      |
   +===============+===========+======================================+
   | id            |           | Any unique value for the request,    |
   |               |           | including a hash, checksum, or uuid. |
   +---------------+-----------+--------------------------------------+
   | name          |           | Supported values are "subscribe" or  |
   |               |           | "unsubscribe".                       |
   +---------------+-----------+--------------------------------------+
   | namespace     | events    |                                      |
   |               |           |                                      |
   +---------------+-----------+--------------------------------------+
   | args          |           | Values vary by type of class.        |
   |               |           |                                      |
   +---------------+-----------+--------------------------------------+

Subsystems can also be tracked using the events namespace. Currently,
there are three trackable subsystems: Dispatcher, Life Preserver, and
System State. Use this template to subscribe to various subsystem event
notifications:

**Websocket Request**

.. code-block:: json

 {
  "namespace" : "events",
  "name" : "subscribe",
  "id" : "sampleID",
  "args" : ["dispatcher", "life-preserver", "system-state"]
 }

Once subscribed, events will be received as they are produced. To
unsubscribe from events, repeat the request, using
:command:`"unsubscribe"` for the :command:`"name"`.

Here is an example reply from the Life Preserver subsystem:

**Websocket Reply**

.. code-block:: json

 {
    "namespace" : "events",
    "name" : "life_preserver",
    "id" : "<none>"
    "args" : {
       "message" : "<message>",
       "priority" : "<number>/<category>",
       "class" : "[snapshot/replication]"
     }
 }

Dispatcher
----------

The Dispatcher subsystem is used by |sysadm| to process external
commands and return specific information from the utility. This is
managed on the server as a separate process, and will not interrupt
primary server tasks. Subscribe to the Dispatcher subsystem for event
updates with this request:

**Websocket Request**

.. code-block:: json

 {
  "namespace" : "events",
  "name" : "subscribe",
  "id" : "sampleID",
  "args" : ["dispatcher"]
 }

The Dispatcher event log will display three different states: *pending*,
*running*, and *finished*. Depending upon the current state, the log can
change in some minor but noteworthy ways. The following sample logs will
reflect the differences between these states:

.. note:: The variable **event_system** will only appear when one of
   the three available systems initiates the request and response.
   Additional elements tied to these systems will also appear.

**Dispatcher Response: Pending**

.. code-block:: json

 {
 "namespace" : "events",
 "name" : "dispatcher",
 "id" : "none",
 "args" : {
   "state" : "pending",
   "process_id" : "<random>"
   }
 }

**Dispatcher Response: Running**

.. code-block:: json

 {
 "namespace" : "events",
 "name" : "dispatcher",
 "id" : "none",
 "args" : {
   "event_system" : "<sysadm with /pkg, /update, or /iohyve]>",
   "state" : "running",
   "process_id" : "<random>",
   "process_details" : {
     "state" : "running",
     "process_id" : "<random id>",
     "time_started" : "<ISO 8601 time date string>",
     "cmd_list" : ["<command 1>", "<command 2>"],
     "<command1>" : "<log after running command1>",
     "return_codes/<command1>" : "<integer return code>",
     "current_cmd" : "<command 2>",
     }
   }
 }

**Dispatcher Response: Finished**

.. code-block:: json

 {
 "namespace" : "events",
 "name" : "dispatcher",
 "id" : "none",
 "args" : {
   "event_system" : "<sysadm with /pkg, /update, or /iohyve]>",
   "state" : "finished",
   "process_id" : "<random>",
   "process_details" : {
     "state" : "finished",
     "process_id" : "<random id>",
     "time_started" : "<ISO 8601 time date string>",
     "time_finished" : "<ISO 8601 time date string>",
     "cmd_list" : ["<command 1>", "<command 2>"],
     "<command1>" : "<log after running command1>",
     "<command2>" : "<log after running command2>",
     "return_codes/<command1>" : "<integer return code>",
     "return_codes/<command2>" : "<integer return code>"
     }
   }
 }

Individual classes such as iohyve will move these dispatcher elements
into a "process_details" section. Tailored sample responses will be
provided in these classes' individual documentation pages. Here is a
generalized sample:

**Dispatcher Class Event Message**

.. code-block:: json

 {
  "namespace" : "events",
  "name" : "dispatcher",
  "id" : "none",
  "args" : {
    "event_system" : "<namespace>/<name>",
    "state" : "<pending/running/finished>",
    "<field>" : "<Other fields depending on class>",
    "process_details" : "<pending, running, or finished message as above>"
    }
 }

For specific details on these special types of events please refer to
the :ref:`classes` section of this guide.

Life Preserver
--------------

Subscribe to the Life Preserver subsystem for event updates with this:

**Websocket Request**

.. code-block:: json

 {
  "namespace" : "events",
  "name" : "subscribe",
  "id" : "sampleID",
  "args" : ["life-preserver"]
 }

**Websocket Event Message**

.. code-block:: json

 {
  "namespace" : "events",
  "name" : "life_preserver",
  "id" : "none",
  "args" : {
    "message" : "<text string>",
    "priority" : "<number/warning level>",
    "class" : "snapshot/replication"
  }
 }

System State
------------

Subscribe to the System State subsystem for event updates with this:

**Websocket Request**

.. code-block:: json

 {
  "namespace" : "events",
  "name" : "subscribe",
  "id" : "sampleID",
  "args" : ["system-state"]
 }

**Websocket Event Message**

This message will appear if the host name has changed and a priority
error has occurred:

.. code-block:: json

 {
  "namespace" : "events",
  "name" : "system_state",
  "id" : "none",
  "args" : {
    "hostname" : "<name>",
    "hostnamechanged" : "true",
    "zpools" : {
      "<poolname>" : {
        "size" : "<107G>",
        "alloc" : "<13.1G>",
        "free" : "<93.9G>",
        "frag" : "<6%>",
        "expandsz" : "<->",
        "dedup" : "<1.00x>",
        "altroot" : "<->",
        "capacity" : "<12%>",
        "health" : "<online>",
        "priority" : "<priority>"
      }
    }
  }
 }

Bridge
------

Bridge events are automatically received by any system connected to a
bridge, with no subscription required. This event will get sent out any
time a new connection/disconnection is made from the bridge which
impacts the current connection. A client will only get the event when a
server connects/disconnects or vice versa.

**Websocket Reply: Connected Bridge**

.. code-block:: json

  {
    "id" : "",
    "namespace" : "events",
    "name" : "bridge",
    "args" : {
      "available_connections" : ["ID1", "ID2", "<etc..>"]
      }
  }

.. tip:: Available_connections are **all** the connections available at
         the time, **not** a difference from a previous state. There may
         be both new ID's in the list and ID's which are no longer
         listed.


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

import com.mysql.jdbc.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 *
 * @author Iulian
 */
public class dbconnect {
    public static Connection con = null;
    public static int nrutilz = 0 ;
    static String url = "jdbc:mysql://localhost:3306/javabase";
    static String username = "root";
    static String password = "proiectpao";

    public static Connection connect() {

    System.out.println("Conectare baza de date...");

    try (Connection connection = (Connection) DriverManager.getConnection(url, username, password)) {
        System.out.println("Conectat cu succes!");
        con = connection;
        }

    catch (SQLException e) {
        String message = "ERR";
        message =message+e;
        JOptionPane.showMessageDialog(new JFrame(), message, "Dialog",
        JOptionPane.ERROR_MESSAGE);
        throw new IllegalStateException("Cannot connect the database!", e);

        }
        return con;
    }

    static ArrayList<String> reslist;
    static ArrayList<String> chestlist;
    static String res=null;
    public static ArrayList<String> viewUser() throws SQLException {
    Statement stmt = null;
    ResultSet rs  = null;
    res=null;
    String query ="SELECT PersonID, LastName, Parola, username, email FROM Users";
    try {
        con = (Connection) DriverManager.getConnection(url, username, password);
        stmt = con.createStatement();
        rs = stmt.executeQuery(query);
        reslist = new ArrayList<String>();
        while (rs.next()) {
            int ID =rs.getInt(1);
            reslist.add(rs.getString(1));
            reslist.add(rs.getString(2));
            reslist.add(rs.getString(4));
            reslist.add(rs.getString(5));
            nrutilz++;
        }
        rs.close();
        return reslist;
    } catch (SQLException e ) {

    } finally {
        if (stmt != null) { stmt.close(); }
    }
    return reslist;

}
    public static void createUser(String util, String parola, String usrname, String email) throws SQLException {
        //creaza un utilizator nou
        PreparedStatement ps = null;
        PreparedStatement ps1=null;
        ResultSet rs = null;
        try{
        con = (Connection) DriverManager.getConnection(url, username, password);
        String insert ="INSERT INTO Users (PersonID, LastName, Parola, username, email) VALUES (?, ? ,?, ?, ?)";
        String check="SELECT * FROM Users WHERE LastName = ?";
        //testeaza daca utilizatorul deja exista
        ps1=con.prepareStatement(check);
        ps1.setString(1,util);
        rs=ps1.executeQuery();
        if(rs.absolute(1)) {
            System.out.println("utilizatorul deja exista!");
            con.close();
            return;
        }
        else {
            md5crypt parolaCriptata = new md5crypt();
            String parolaFinal=parolaCriptata.crypt(parola);
            int nr=nrutilz+1;
            ps=con.prepareStatement(insert);
            ps.setInt(1,nr);
            ps.setString(2, util);
            ps.setString(3, parolaFinal);
            ps.setString(4, usrname);
            ps.setString(5, email);
            ps.executeUpdate();
        }
        }
        catch (SQLException e) {
            System.out.println(e);
            System.out.println("Actualizare esuata!");
        }

    }
    public static void deleteUser(String util) throws SQLException {
        //creaza un utilizator nou
        PreparedStatement ps = null;
        PreparedStatement ps1 = null;
        ResultSet rs = null;
        try
        {
            con = (Connection) DriverManager.getConnection(url, username, password);
            String delete ="DELETE FROM Users WHERE LastName = ?";
            String check="SELECT * FROM Users WHERE LastName = ?";
            ps1=con.prepareStatement(check);
            ps1.setString(1,util);
            rs=ps1.executeQuery();
            if (!(rs.absolute(1)))
            {
                System.out.println("user inexistent!");
                con.close();
                return;
            }
            else
            {
                ps=con.prepareStatement(delete);
                ps.setString(1, util);
                ps.executeUpdate();
                con.close();
            }
        }
        catch (SQLException e) {
            //con.rollback();
            System.out.println(e);
            System.out.println("Stergere esuata!");
        }
    }
    public static boolean checkUser(String util, String parola) throws SQLException {
        //verifica daca exista utilizatorul in bd. se foloseste la logare
        PreparedStatement ps = null;
        ResultSet rs = null;
        try{
            con = (Connection) DriverManager.getConnection(url, username, password);
            String check="SELECT * FROM Users WHERE (LastName = ?) AND (Parola = ?)";
            ps=con.prepareStatement(check);

            md5crypt parolaCriptata = new md5crypt();
            String parolaFinal=parolaCriptata.crypt(parola);
            ps.setString(1,util); ps.setString(2,parolaFinal);
            rs=ps.executeQuery();
            while (rs.next()) {
                String nume = rs.getString(2);
                String pass = rs.getString(3);
                if (parolaFinal.equals(pass) && nume.equals(util))
                {con.close(); return true; }
            }
            return false;
        }
        catch (SQLException e) {
            System.out.println(e);
            System.out.println("Nu s-a putut face interogarea.");
            con.close();
            return false;
        }
    }
        public static boolean checkExistence(String util) throws SQLException {
        //verifica daca exista utilizatorul in bd. se foloseste la stergere
        PreparedStatement ps = null;
        ResultSet rs = null;
        try{
            con = (Connection) DriverManager.getConnection(url, username, password);
            String check="SELECT * FROM Users WHERE (LastName = ?)";
            ps=con.prepareStatement(check);
            ps.setString(1,util);
            rs=ps.executeQuery();
            while (rs.next()) {
                String nume = rs.getString(2);
                if (nume.equals(util))
                {con.close(); return true; }
            }
            return false;
        }
        catch (SQLException e) {
            System.out.println(e);
            System.out.println("Nu s-a putut face interogarea.");
            con.close();
            return false;
        }

    }
     public static boolean adminLogin(String util, String parola){
         if (util.equals(username) && parola.equals(password))
             return true;
         return false;
     }

}


text:
var MasterTab = {
    session: {
        id: new Date().toISOString(),
        startTime: new Date(),
    },
    pages: {
        listPage: {
            name: 'list.html',
            url: chrome.extension.getURL('list.html'),
            open: function () {
                MasterTab.pages.open(this);
            },
        }
    },
    config: {
        TABID_PREFIX : 'T_',
    },
};

MasterTab.isSupportedPage = function(url) {
	return url.substring(0, 4) == 'http'
		&& url != MasterTab.pages.listPage.url;
}

MasterTab.getTabKey = function (tabId) {
    return this.session.id + '_' + tabId;
};

MasterTab.pages.open = function (page) {
    var url = page.url;
    chrome.tabs.query({}, function (extensionTabs) {
        var found = false;
		var focus = (url !== MasterTab.pages.listPage.url); // Do not grab focus if this is the List page.
        for (var i = 0; i < extensionTabs.length; i++) {
            if (url == extensionTabs[i].url) {
                found = true;
                console.log("tab id: " + extensionTabs[i].id);
				if (focus) {
					chrome.tabs.update(extensionTabs[i].id, {active: focus});
				} else {
					chrome.tabs.reload(extensionTabs[i].id, null, null);
				}
				break;
            }
        }
        if (found == false) {
            chrome.tabs.create({ url: page.url });
        }
    });
};

MasterTab.session.tabs = {
    get: function(tabId){
        return this[MasterTab.config.TABID_PREFIX + tabId];
    },

    add: function(nTabId, sUrl){
            var tabInfo = {
                session: MasterTab.session.id,
                storageKey: MasterTab.getTabKey(nTabId),
                url: sUrl,
                title: sUrl,
                favIconUrl: null,
				lastUpdatd: new Date(),
            }
            this[MasterTab.config.TABID_PREFIX + nTabId] = tabInfo;
            return tabInfo;
        },

	find: function(url, callback) {
		for (var internalTabId in this) {
			var value = this[internalTabId];
			if (Object.hasOwnProperty(internalTabId) && value && value.url && value.url === url) {
				callback(value);
				return;
			}
		}
		callback(null);
	},

    remove: function(tabId) {
        var key = MasterTab.getTabKey(tabId);
        MasterTab.history.remove(key);
        delete this[MasterTab.config.TABID_PREFIX + tabId];
    }
};

MasterTab.history = {
	storage: chrome.storage.local,

    save: function(tabInfo) {
        var data = {};
        data[tabInfo.storageKey] = tabInfo;

        this.storage.set(data, function () {
            console.log('Saved %s to storage', tabInfo.url);
            MasterTab.pages.listPage.open();
        });
    },

    remove: function (key) {
        this.storage.remove(key, function () {
            console.log('Removed %s from storage', key);
            MasterTab.pages.listPage.open();
        });
    },

    getAll: function(callback) {
        this.storage.get(
			null,
            callback);
    },

    clear: function () {
        // Remove the items that are in memory
        var tabs = MasterTab.session.tabs;
        for (var id in tabs) {
            if (tabs.hasOwnProperty(id) && id.substring(0, MasterTab.config.TABID_PREFIX.length) == MasterTab.config.TABID_PREFIX) {
                tabs.remove(id.substring(MasterTab.config.TABID_PREFIX.length));
            }
        };
        // Clear the history
        this.storage.clear(function () {
            console.log('Tab history was cleared.');
        });
    },
};


text:
/*
 * U-boot - Configuration file for BF527 AD7160-EVAL board
 */

#ifndef __CONFIG_BF527_AD7160_EVAL_H__
#define __CONFIG_BF527_AD7160_EVAL_H__

#include <asm/config-pre.h>

/*
 * Processor Settings
 */
#define CONFIG_BFIN_CPU             bf527-0.2
#define CONFIG_BFIN_BOOT_MODE       BFIN_BOOT_SPI_MASTER

/*
 * Clock Settings
 *	CCLK = (CLKIN * VCO_MULT) / CCLK_DIV
 *	SCLK = (CLKIN * VCO_MULT) / SCLK_DIV
 */
/* CONFIG_CLKIN_HZ is any value in Hz					*/
#define CONFIG_CLKIN_HZ			24000000
/* CLKIN_HALF controls the DF bit in PLL_CTL      0 = CLKIN		*/
/*                                                1 = CLKIN / 2		*/
#define CONFIG_CLKIN_HALF		0
/* PLL_BYPASS controls the BYPASS bit in PLL_CTL  0 = do not bypass	*/
/*                                                1 = bypass PLL	*/
#define CONFIG_PLL_BYPASS		0
/* VCO_MULT controls the MSEL (multiplier) bits in PLL_CTL		*/
/* Values can range from 0-63 (where 0 means 64)			*/
#define CONFIG_VCO_MULT			25
/* CCLK_DIV controls the core clock divider				*/
/* Values can be 1, 2, 4, or 8 ONLY					*/
#define CONFIG_CCLK_DIV			1
/* SCLK_DIV controls the system clock divider				*/
/* Values can range from 1-15						*/
#define CONFIG_SCLK_DIV			5

/*
 * Memory Settings
 */
#define CONFIG_MEM_ADD_WDTH	10
#define CONFIG_MEM_SIZE		64

#define CONFIG_EBIU_SDRRC_VAL	0x03F6
#define CONFIG_EBIU_SDGCTL_VAL	(SCTLE | CL_3 | PASR_ALL | TRAS_6 | TRP_3 | TRCD_3 | TWR_2 | PSS)

#define CONFIG_EBIU_AMGCTL_VAL	(AMCKEN | AMBEN_ALL)
#define CONFIG_EBIU_AMBCTL0_VAL	(B1WAT_15 | B1RAT_15 | B1HT_3 | B1RDYPOL | B0WAT_15 | B0RAT_15 | B0HT_3 | B0RDYPOL)
#define CONFIG_EBIU_AMBCTL1_VAL	(B3WAT_15 | B3RAT_15 | B3HT_3 | B3RDYPOL | B2WAT_15 | B2RAT_15 | B2HT_3 | B2RDYPOL)

#define CONFIG_SYS_MONITOR_LEN	(768 * 1024)
#define CONFIG_SYS_MALLOC_LEN	(640 * 1024)

/*
 * NAND Settings
 * (can't be used same time as ethernet)
 */
#if (CONFIG_BFIN_BOOT_MODE == BFIN_BOOT_NAND)
# define CONFIG_BFIN_NFC
# define CONFIG_BFIN_NFC_BOOTROM_ECC
#endif
#ifdef CONFIG_BFIN_NFC
#define CONFIG_BFIN_NFC_CTL_VAL	0x0033
#define CONFIG_DRIVER_NAND_BFIN
#define CONFIG_SYS_NAND_BASE		0 /* not actually used */
#define CONFIG_SYS_MAX_NAND_DEVICE	1
#endif

/*
 * Flash Settings
 */
#define CONFIG_FLASH_CFI_DRIVER
#define CONFIG_SYS_FLASH_BASE		0x20000000
#define CONFIG_SYS_FLASH_CFI
#define CONFIG_SYS_FLASH_PROTECTION
#define CONFIG_SYS_MAX_FLASH_BANKS	1
#define CONFIG_SYS_MAX_FLASH_SECT	259

/*
 * SPI Settings
 */
#define CONFIG_BFIN_SPI
#define CONFIG_ENV_SPI_MAX_HZ	30000000
#define CONFIG_SF_DEFAULT_SPEED	30000000
#define CONFIG_SPI_FLASH
#define CONFIG_SPI_FLASH_STMICRO

/*
 * Env Storage Settings
 */
#if (CONFIG_BFIN_BOOT_MODE == BFIN_BOOT_SPI_MASTER)
#define CONFIG_ENV_IS_IN_SPI_FLASH
#define CONFIG_ENV_OFFSET	0x10000
#define CONFIG_ENV_SIZE		0x2000
#define CONFIG_ENV_SECT_SIZE	0x10000
#define CONFIG_ENV_IS_EMBEDDED_IN_LDR
#elif (CONFIG_BFIN_BOOT_MODE == BFIN_BOOT_NAND)
#define CONFIG_ENV_IS_IN_NAND
#define CONFIG_ENV_OFFSET	0x40000
#define CONFIG_ENV_SIZE		0x20000
#else
#define CONFIG_ENV_IS_IN_FLASH
#define CONFIG_ENV_OFFSET	0x4000
#define CONFIG_ENV_ADDR		(CONFIG_SYS_FLASH_BASE + CONFIG_ENV_OFFSET)
#define CONFIG_ENV_SIZE		0x2000
#define CONFIG_ENV_SECT_SIZE	0x2000
#define CONFIG_ENV_IS_EMBEDDED_IN_LDR
#endif

/*
 * I2C Settings
 */
#define CONFIG_BFIN_TWI_I2C	1
#define CONFIG_HARD_I2C		1

/*
 * SPI_MMC Settings
 */
#define CONFIG_MMC
#define CONFIG_GENERIC_MMC
#define CONFIG_MMC_SPI

/*
 * Misc Settings
 */
#define CONFIG_MISC_INIT_R
#define CONFIG_UART_CONSOLE	0
#define CONFIG_CC_OPTIMIZE_LIBS_FOR_SPEED

/*
 * Pull in common ADI header for remaining command/environment setup
 */
#include <configs/bfin_adi_common.h>

#endif


text:
package com.architecting.ch11;

import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;

import scala.Tuple2;

public class CountLines {

  @SuppressWarnings("serial")
  public static void main(String[] args) {
    SparkConf sparkConf = new SparkConf().setAppName("JavaHBaseBulkGetExample ").setMaster("local[2]");
    JavaSparkContext jsc = new JavaSparkContext(sparkConf);
    JavaRDD<String> textFile = jsc.textFile("hdfs://localhost/user/cloudera/data.txt");
    JavaPairRDD<String, Integer> pairs = textFile.mapToPair(new PairFunction<String, String, Integer>() {
      public Tuple2<String, Integer> call(String s) { return new Tuple2<String, Integer>(s.substring(0, s.indexOf("|")), 1); }
    });
    JavaPairRDD<String, Integer> counts = pairs.reduceByKey(new Function2<Integer, Integer, Integer>() {
      public Integer call(Integer a, Integer b) { return a + b; }
    });
    System.out.println ("We have generaged " + counts.count() + " users");
    jsc.close();
  }

}


text:
<?php

namespace SIWOZ\EguardianBundle\Entity;

use JMS\Serializer\Annotation\Type;
use JMS\Serializer\Annotation\Discriminator;
use JMS\Serializer\Annotation\Groups;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 * Description of Event
 *
 * @author Marcin
 */
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="SIWOZ\EguardianBundle\Repository\EventRepository")
 * @ORM\Table(name="event")
 * @ORM\InheritanceType("SINGLE_TABLE")
 * @ORM\DiscriminatorColumn(name="discr", type="string")
 * @ORM\DiscriminatorMap({"meal" = "MealEvent", "visit" = "VisitEvent","medicine" = "MedicineEvent","test" = "TestEvent"})
 * @Discriminator(field = "discr", map = {"meal":"SIWOZ\EguardianBundle\Entity\MealEvent", "visit":"SIWOZ\EguardianBundle\Entity\VisitEvent","medicine":"SIWOZ\EguardianBundle\Entity\MedicineEvent","test":"SIWOZ\EguardianBundle\Entity\TestEvent"})
 */
class Event {

    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @Type("integer")
     * @Groups({"All"})
     */
    protected $id;

    /**
     *
     * @ORM\ManyToOne(targetEntity="SeniorUser")
     * @ORM\JoinColumn(name="senior_user_id", referencedColumnName="id")
     * @Type("SIWOZ\EguardianBundle\Entity\SeniorUser")
     * @Groups({"Default", "All"})
     */
    protected $senior;

    /**
     *
     * @ORM\ManyToOne(targetEntity="GuardianUser")
     * @ORM\JoinColumn(name="guardian_user_id", referencedColumnName="id")
     * @Type("SIWOZ\EguardianBundle\Entity\GuardianUser")
     * @Groups({"Default", "All"})
     */
    protected $guardian;

    /**
     * @ORM\Column(name="start_date", type="datetime")
     * @Type("DateTime")
     * @Groups({"Default", "All","Notification"})
     */
    protected $startDate;
      /**
     * @ORM\Column(name="end_date", type="datetime")
     * @Type("DateTime")
     * @Groups({"Default", "All","Notification"})
     */
    protected $endDate;

    /**
     * @ORM\Column(name="event_interval", type="integer")
     * @Type("integer")
     * @Groups({"Default", "All","Notification"})
     */
    protected $interval;

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

    /**
     * Set startDate
     *
     * @param \DateTime $startDate
     * @return Event
     */
    public function setStartDate($startDate) {
        $this->startDate = $startDate;

        return $this;
    }

    /**
     * Get startDate
     *
     * @return \DateTime
     */
    public function getStartDate() {
        return $this->startDate;
    }

    /**
     * Set interval
     *
     * @param integer $interval
     * @return Event
     */
    public function setInterval($interval) {
        $this->interval = $interval;

        return $this;
    }

    /**
     * Get interval
     *
     * @return integer
     */
    public function getInterval() {
        return $this->interval;
    }

    /**
     * Set senior
     *
     * @param \SIWOZ\EguardianBundle\Entity\SeniorUser $senior
     * @return Event
     */
    public function setSenior(\SIWOZ\EguardianBundle\Entity\SeniorUser $senior) {
        $this->senior = $senior;

        return $this;
    }

    /**
     * Get senior
     *
     * @return \SIWOZ\EguardianBundle\Entity\SeniorUser
     */
    public function getSenior() {
        return $this->senior;
    }

    /**
     * Set guardian
     *
     * @param \SIWOZ\EguardianBundle\Entity\GuardianUser $guardian
     * @return Event
     */
    public function setGuardian(\SIWOZ\EguardianBundle\Entity\GuardianUser $guardian) {
        $this->guardian = $guardian;

        return $this;
    }

    /**
     * Get guardian
     *
     * @return \SIWOZ\EguardianBundle\Entity\GuardianUser
     */
    public function getGuardian() {
        return $this->guardian;
    }

    /**
     * Set endDate
     *
     * @param \DateTime $endDate
     * @return Event
     */
    public function setEndDate($endDate)
    {
        $this->endDate = $endDate;

        return $this;
    }

    /**
     * Get endDate
     *
     * @return \DateTime
     */
    public function getEndDate()
    {
        return $this->endDate;
    }
}


text:
'use strict';

var app = angular.module('swamp', [
    'ngCookies',
    'ngResource',
    'ngSanitize',
    'ui.router',
    'ui.bootstrap',
    'Scope.safeApply',
    'Scope.onReady',
    'swamp.config',
    'swamp.filters',
    'swamp.controllers',
    'swamp.directives',
    'swamp.services'
]);

angular.module('swamp.config', []);
angular.module('swamp.filters', []);
angular.module('swamp.controllers', []);
angular.module('swamp.directives', []);
angular.module('swamp.services', []);


text:
package com.appdynamics.extensions.cloudwatch.metricsmanager.metricsmanagerimpl;

import com.amazonaws.services.cloudwatch.AmazonCloudWatch;
import com.amazonaws.services.cloudwatch.model.Datapoint;
import com.appdynamics.extensions.cloudwatch.metricsmanager.MetricsManager;
import com.singularity.ee.agent.systemagent.api.MetricWriter;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Logger;

public final class SNSMetricsManager extends MetricsManager {

	private Logger logger = Logger.getLogger("com.singularity.extensions.SNSMetricsManager");

    private static final String NAMESPACE = "AWS/SNS";

    /**
     * Gather metrics for AWS/SNS
     * @return	Map     Map containing metrics
     */
    @Override
    public Map gatherMetrics(AmazonCloudWatch awsCloudWatch, String region) {
        Map<String, Map<String, Map<String, List<Datapoint>>>> snsMetrics = new ConcurrentHashMap<String, Map<String, Map<String, List<Datapoint>>>>();

        Map<String, Map<String, List<Datapoint>>> applicationMetrics = gatherMetricsHelper(awsCloudWatch, NAMESPACE, region, "Application");
        Map<String, Map<String, List<Datapoint>>> platformMetrics = gatherMetricsHelper(awsCloudWatch, NAMESPACE, region, "Platform");
        Map<String, Map<String, List<Datapoint>>> topicNameMetrics = gatherMetricsHelper(awsCloudWatch, NAMESPACE, region, "TopicName");

        snsMetrics.put("Application", applicationMetrics);
        snsMetrics.put("Platform", platformMetrics);
        snsMetrics.put("TopicName", topicNameMetrics);

        return snsMetrics;
    }

    /**
     * Print metrics for AWS/SNS
     * @param metrics   Map containing metrics
     */
    @Override
    public void printMetrics(String region, Map metrics) {
        Map<String, Map<String, Map<String, List<Datapoint>>>> snsMetrics = (Map<String, Map<String,Map<String,List<Datapoint>>>>) metrics;
        Iterator dimensionFilterIterator = snsMetrics.keySet().iterator();

        while (dimensionFilterIterator.hasNext()) {
            String metricType = dimensionFilterIterator.next().toString();
            Map<String, Map<String,List<Datapoint>>> dimensionMetrics = snsMetrics.get(metricType);
            Iterator dimensionIterator = dimensionMetrics.keySet().iterator();
            while (dimensionIterator.hasNext()) {
                String dimensionId = dimensionIterator.next().toString();
                Map<String, List<Datapoint>> metricsMap = dimensionMetrics.get(dimensionId);
                Iterator metricsIterator = metricsMap.keySet().iterator();
                while (metricsIterator.hasNext()) {
                    String metricName = metricsIterator.next().toString();
                    List<Datapoint> datapoints = metricsMap.get(metricName);
                    if (datapoints != null && datapoints.size() > 0) {
                        Datapoint data = getLatestDatapoint(datapoints);
                        amazonCloudWatchMonitor.printMetric(region + "|", getNamespacePrefix() + metricType + "|" +  dimensionId + "|",metricName + "(" + data.getUnit() + ")",
                        		getValue(NAMESPACE, metricName, data),
                                MetricWriter.METRIC_AGGREGATION_TYPE_OBSERVATION,
                                MetricWriter.METRIC_TIME_ROLLUP_TYPE_AVERAGE,
                                MetricWriter.METRIC_CLUSTER_ROLLUP_TYPE_INDIVIDUAL);

                    }
                }
            }
        }
    }

    /**
     * Construct namespace prefix for AWS/SNS
     * @return String   Namespace prefix
     */
    @Override
    public String getNamespacePrefix() {
        return NAMESPACE.substring(4,NAMESPACE.length()) + "|";
    }
}


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

using System;
using System.Threading.Tasks;

namespace Minio.Examples.Cases;

internal class RemoveBucket
{
    // Remove a bucket
    public static async Task Run(MinioClient minio,
        string bucketName = "my-bucket-name")
    {
        try
        {
            await minio.RemoveBucketAsync(
                new RemoveBucketArgs()
                    .WithBucket(bucketName)
            );
            Console.WriteLine($"Removed the bucket {bucketName} successfully");
        }
        catch (Exception e)
        {
            Console.WriteLine($"[Bucket]  Exception: {e}");
        }
    }
}


text:
package org.ihtsdo.otf.mapping.helpers;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

import org.ihtsdo.otf.mapping.rf2.Relationship;
import org.ihtsdo.otf.mapping.rf2.jpa.RelationshipJpa;

/**
 * JAXB enabled implementation of {@link RelationshipList}.
 */
@XmlRootElement(name = "relationshipList")
public class RelationshipListJpa extends AbstractResultList<Relationship>
    implements RelationshipList {

  /** The map relationships. */
  private List<Relationship> relationships = new ArrayList<>();

  /**
   * Instantiates a new map relationship list.
   */
  public RelationshipListJpa() {
    // do nothing
  }

  /*
   * (non-Javadoc)
   *
   * @see
   * org.ihtsdo.otf.mapping.helpers.RelationshipList#addRelationship(org.ihtsdo
   * .otf.mapping.rf2.Relationship)
   */
  @Override
  public void addRelationship(Relationship relationship) {
    relationships.add(relationship);
  }

  /*
   * (non-Javadoc)
   *
   * @see
   * org.ihtsdo.otf.mapping.helpers.RelationshipList#removeRelationship(org.
   * ihtsdo.otf.mapping.rf2.Relationship)
   */
  @Override
  public void removeRelationship(Relationship relationship) {
    relationships.remove(relationship);
  }

  /*
   * (non-Javadoc)
   *
   * @see
   * org.ihtsdo.otf.mapping.helpers.RelationshipList#setRelationships(java.util
   * .List)
   */
  @Override
  public void setRelationships(List<Relationship> relationships) {
    this.relationships = new ArrayList<>();
    if (relationships != null) {
      this.relationships.addAll(relationships);
    }
  }

  /*
   * (non-Javadoc)
   *
   * @see
   * org.ihtsdo.otf.mapping.helpers.RelationshipList#setRelationships(java.util
   * .Set)
   */
  @Override
  public void setRelationships(Set<Relationship> relationships) {
    Iterator<Relationship> iter = relationships.iterator();
    while (iter.hasNext()) {
      this.relationships.add(iter.next());
    }
  }

  /*
   * (non-Javadoc)
   *
   * @see org.ihtsdo.otf.mapping.helpers.RelationshipList#getRelationships()
   */
  @Override
  @XmlElement(type = RelationshipJpa.class, name = "relationship")
  public List<Relationship> getRelationships() {
    return relationships;
  }

  /*
   * (non-Javadoc)
   *
   * @see org.ihtsdo.otf.mapping.helpers.ResultList#getCount()
   */
  @Override
  @XmlElement(name = "count")
  public int getCount() {
    return relationships.size();
  }

  /*
   * (non-Javadoc)
   *
   * @see org.ihtsdo.otf.mapping.helpers.ResultList#sortBy(java.util.Comparator)
   */
  @Override
  public void sortBy(Comparator<Relationship> comparator) {
    Collections.sort(relationships, comparator);
  }

  /*
   * (non-Javadoc)
   *
   * @see org.ihtsdo.otf.mapping.helpers.ResultList#contains(java.lang.Object)
   */
  @Override
  public boolean contains(Relationship element) {
    return relationships.contains(element);
  }

  /*
   * (non-Javadoc)
   *
   * @see org.ihtsdo.otf.mapping.helpers.ResultList#getIterable()
   */
  @Override
  @XmlTransient
  public Iterable<Relationship> getIterable() {
    return relationships;
  }

}


text:
[![build status][1]][2]

[![browser support][3]][4]

A requirable version of Date.now()

Use-case is to be able to mock out Date.now() using require interception.

## Example

```js
var now = require("date-now")

var ts = now()
var ts2 = Date.now()
assert.equal(ts, ts2)
```

## example of seed

```
var now = require("date-now/seed")(timeStampFromServer)

// ts is in "sync" with the seed value from the server
// useful if your users have their local time being a few minutes
// out of your server time.
var ts = now()
```

## Installation

`npm install date-now`

## Contributors

 - Raynos

## MIT Licenced

  [1]: https://secure.travis-ci.org/Colingo/date-now.png
  [2]: http://travis-ci.org/Colingo/date-now
  [3]: http://ci.testling.com/Colingo/date-now.png
  [4]: http://ci.testling.com/Colingo/date-now


text:
#ifndef _ARKKLU_H
#define _ARKKLU_H

#ifdef __cplusplus  /* wrapper to enable C++ usage */
extern "C" {
#endif

#include "arkode/arkode_sparse.h"
#include "sundials/sundials_sparse.h"

/*---------------------------------------------------------------
 Function: ARKKLU
-----------------------------------------------------------------
 A call to the ARKKLU function links the main integrator with
 the ARKKLU linear solver module.

 arkode_mem is the pointer to integrator memory returned by
            ARKodeCreate.

 n is the size of the linear system (nrows = ncols = n)

 nnz is the maximum number of nonzeros in the sparse matrix
     A = M + gamma*J

 The return value of ARKKLU is one of:
     ARKSLS_SUCCESS   if successful
     ARKSLS_MEM_NULL  if the ARKode memory was NULL
     ARKSLS_MEM_FAIL  if there was a memory allocation failure
     ARKSLS_ILL_INPUT if a required vector operation is missing

 NOTE: The KLU linear solver assumes a serial implementation
       of the NVECTOR package. Therefore, ARKKLU will first
       test for a compatible N_Vector internal representation
       by checking that the function N_VGetArrayPointer exists.
---------------------------------------------------------------*/
SUNDIALS_EXPORT int ARKKLU(void *arkode_mem, int n, int nnz);

/*---------------------------------------------------------------
 Function: ARKMassKLU
-----------------------------------------------------------------
 A call to the ARKMassKLU function links the mass matrix solve
 with the ARKKLU linear solver module.

 arkode_mem is the pointer to integrator memory returned by
            ARKodeCreate.

 n is the size of the linear system (nrows = ncols = n)

 nnz is the maximum number of nonzeros in the sparse mass matrix

 smass is the user-supplied sparse mass matrix setup function.

 The return value of ARKMassKLU is one of:
     ARKSLS_SUCCESS   if successful
     ARKSLS_MEM_NULL  if the ARKode memory was NULL
     ARKSLS_MEM_FAIL  if there was a memory allocation failure
     ARKSLS_ILL_INPUT if a required vector operation is missing

 NOTE: The KLU linear solver assumes a serial implementation
       of the NVECTOR package. Therefore, ARKKLU will first
       test for a compatible N_Vector internal representation
       by checking that the function N_VGetArrayPointer exists.
---------------------------------------------------------------*/
SUNDIALS_EXPORT int ARKMassKLU(void *arkode_mem, int n, int nnz,
			       ARKSlsSparseMassFn smass);

/*================================================================
 Optional Input Specification Functions
=================================================================*/

/*---------------------------------------------------------------
 Function: ARKKLUSetOrdering
-----------------------------------------------------------------
 This routine sets the ordering used by KLU for reducing fill in
 the system matrix solve.  Options for ordering_choice are:
        0 for AMD,
	1 for COLAMD, and
	2 for the natural ordering.
 The default used in ARKODE is 1 for COLAMD.
---------------------------------------------------------------*/
SUNDIALS_EXPORT int ARKKLUSetOrdering(void *arkode_mem,
				      int ordering_choice);

/*---------------------------------------------------------------
 Function: ARKMassKLUSetOrdering
-----------------------------------------------------------------
 This routine sets the ordering used by KLU for reducing fill in
 the mass matrix solve.  Options for ordering_choice are:
        0 for AMD,
	1 for COLAMD, and
	2 for the natural ordering.
 The default used in ARKODE is 1 for COLAMD.
---------------------------------------------------------------*/
SUNDIALS_EXPORT int ARKMassKLUSetOrdering(void *arkode_mem,
					  int ordering_choice);

#ifdef __cplusplus
}
#endif

#endif


text:
layout: post
title: Duplicated Frames
categories: film analog
tags: [Analog, Film]
formats: [Film]
lang: English
---

Duplicated frames may occur when the triggering of the camera is not correctly timed.

## Can it be fixed?

Yes, delete one of the duplicated frames.

## Example(s)

Two errors in the same clip: missing frame followed by duplicated frame:

<img src="{{ site.baseurl }}/images/missing_duplicated.gif">


text:
class CSkybox11
{
public:
    CSkybox11();

    HRESULT CALLBACK OnD3D11CreateDevice( ID3D11Device* pd3dDevice, float fSize,
        ID3D11Texture2D* pCubeTexture, ID3D11ShaderResourceView* pCubeRV );

    void    OnD3D11ResizedSwapChain( const DXGI_SURFACE_DESC* pBackBufferSurfaceDesc );
    void    D3D11Render( D3DXMATRIX* pmWorldViewProj, ID3D11DeviceContext* pd3dImmediateContext );
    void    OnD3D11ReleasingSwapChain();
    void    OnD3D11DestroyDevice();

    ID3D11Texture2D* GetD3D10EnvironmentMap()
    {
        return m_pEnvironmentMap11;
    }
    ID3D11ShaderResourceView* GetD3D10EnvironmentMapRV()
    {
        return m_pEnvironmentRV11;
    }
    void    SetD3D11EnvironmentMap( ID3D11Texture2D* pCubeTexture )
    {
        m_pEnvironmentMap11 = pCubeTexture;
    }

protected:
    struct CB_VS_PER_OBJECT
    {
        D3DXMATRIX m_WorldViewProj;
    };

    ID3D11Texture2D* m_pEnvironmentMap11;
    ID3D11ShaderResourceView* m_pEnvironmentRV11;
    ID3D11Device* m_pd3dDevice11;
    ID3D11VertexShader* m_pVertexShader;
    ID3D11PixelShader* m_pPixelShader;
    ID3D11SamplerState* m_pSam;
    ID3D11InputLayout* m_pVertexLayout11;
    ID3D11Buffer* m_pcbVSPerObject;
    ID3D11Buffer* m_pVB11;
    ID3D11DepthStencilState* m_pDepthStencilState11;

    float m_fSize;
};

#endif


text:
#ifndef GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_SSL_UTILS_H
#define GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_SSL_UTILS_H

#include <grpc/support/port_platform.h>

#include <stdbool.h>

#include <grpc/grpc_security.h>
#include <grpc/slice_buffer.h>

#include "src/core/lib/gprpp/ref_counted_ptr.h"
#include "src/core/tsi/ssl_transport_security.h"
#include "src/core/tsi/transport_security_interface.h"

/* --- Util. --- */

/* --- URL schemes. --- */
#define GRPC_SSL_URL_SCHEME "https"

/* Return HTTP2-compliant cipher suites that gRPC accepts by default. */
const char* grpc_get_ssl_cipher_suites(void);

/* Map from grpc_ssl_client_certificate_request_type to
 * tsi_client_certificate_request_type. */
tsi_client_certificate_request_type
grpc_get_tsi_client_certificate_request_type(
    grpc_ssl_client_certificate_request_type grpc_request_type);

/* Return an array of strings containing alpn protocols. */
const char** grpc_fill_alpn_protocol_strings(size_t* num_alpn_protocols);

/* Exposed for testing only. */
grpc_core::RefCountedPtr<grpc_auth_context> grpc_ssl_peer_to_auth_context(
    const tsi_peer* peer);
tsi_peer grpc_shallow_peer_from_ssl_auth_context(
    const grpc_auth_context* auth_context);
void grpc_shallow_peer_destruct(tsi_peer* peer);
int grpc_ssl_host_matches_name(const tsi_peer* peer, const char* peer_name);

/* --- Default SSL Root Store. --- */
namespace grpc_core {

// The class implements default SSL root store.
class DefaultSslRootStore {
 public:
  // Gets the default SSL root store. Returns nullptr if not found.
  static const tsi_ssl_root_certs_store* GetRootStore();

  // Gets the default PEM root certificate.
  static const char* GetPemRootCerts();

 protected:
  // Returns default PEM root certificates in nullptr terminated grpc_slice.
  // This function is protected instead of private, so that it can be tested.
  static grpc_slice ComputePemRootCerts();

 private:
  // Construct me not!
  DefaultSslRootStore();

  // Initialization of default SSL root store.
  static void InitRootStore();

  // One-time initialization of default SSL root store.
  static void InitRootStoreOnce();

  // SSL root store in tsi_ssl_root_certs_store object.
  static tsi_ssl_root_certs_store* default_root_store_;

  // Default PEM root certificates.
  static grpc_slice default_pem_root_certs_;
};

}  // namespace grpc_core

#endif /* GRPC_CORE_LIB_SECURITY_SECURITY_CONNECTOR_SSL_UTILS_H \
        */


text:
import * as mutationTypes from './mutation-type'

const mutations = {
  [mutationTypes.SAVE_PAPER_VALUE] (state, value) {
    state.value = value
  }
}

export default mutations


text:
import sys

_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pb2
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database

# @@protoc_insertion_point(imports)

_sym_db = _symbol_database.Default()

DESCRIPTOR = _descriptor.FileDescriptor(
  name='FeatureVectorizer.proto',
  package='CoreML.Specification',
  syntax='proto3',
  serialized_pb=_b('\n\x17\x46\x65\x61tureVectorizer.proto\x12\x14\x43oreML.Specification\"\x98\x01\n\x11\x46\x65\x61tureVectorizer\x12\x46\n\tinputList\x18\x01 \x03(\x0b\x32\x33.CoreML.Specification.FeatureVectorizer.InputColumn\x1a;\n\x0bInputColumn\x12\x13\n\x0binputColumn\x18\x01 \x01(\t\x12\x17\n\x0finputDimensions\x18\x02 \x01(\x04\x42\x02H\x03\x62\x06proto3')
)

_FEATUREVECTORIZER_INPUTCOLUMN = _descriptor.Descriptor(
  name='InputColumn',
  full_name='CoreML.Specification.FeatureVectorizer.InputColumn',
  filename=None,
  file=DESCRIPTOR,
  containing_type=None,
  fields=[
    _descriptor.FieldDescriptor(
      name='inputColumn', full_name='CoreML.Specification.FeatureVectorizer.InputColumn.inputColumn', index=0,
      number=1, type=9, cpp_type=9, label=1,
      has_default_value=False, default_value=_b("").decode('utf-8'),
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
    _descriptor.FieldDescriptor(
      name='inputDimensions', full_name='CoreML.Specification.FeatureVectorizer.InputColumn.inputDimensions', index=1,
      number=2, type=4, cpp_type=4, label=1,
      has_default_value=False, default_value=0,
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
  ],
  extensions=[
  ],
  nested_types=[],
  enum_types=[
  ],
  options=None,
  is_extendable=False,
  syntax='proto3',
  extension_ranges=[],
  oneofs=[
  ],
  serialized_start=143,
  serialized_end=202,
)

_FEATUREVECTORIZER = _descriptor.Descriptor(
  name='FeatureVectorizer',
  full_name='CoreML.Specification.FeatureVectorizer',
  filename=None,
  file=DESCRIPTOR,
  containing_type=None,
  fields=[
    _descriptor.FieldDescriptor(
      name='inputList', full_name='CoreML.Specification.FeatureVectorizer.inputList', index=0,
      number=1, type=11, cpp_type=10, label=3,
      has_default_value=False, default_value=[],
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
  ],
  extensions=[
  ],
  nested_types=[_FEATUREVECTORIZER_INPUTCOLUMN, ],
  enum_types=[
  ],
  options=None,
  is_extendable=False,
  syntax='proto3',
  extension_ranges=[],
  oneofs=[
  ],
  serialized_start=50,
  serialized_end=202,
)

_FEATUREVECTORIZER_INPUTCOLUMN.containing_type = _FEATUREVECTORIZER
_FEATUREVECTORIZER.fields_by_name['inputList'].message_type = _FEATUREVECTORIZER_INPUTCOLUMN
DESCRIPTOR.message_types_by_name['FeatureVectorizer'] = _FEATUREVECTORIZER
_sym_db.RegisterFileDescriptor(DESCRIPTOR)

FeatureVectorizer = _reflection.GeneratedProtocolMessageType('FeatureVectorizer', (_message.Message,), dict(

  InputColumn = _reflection.GeneratedProtocolMessageType('InputColumn', (_message.Message,), dict(
    DESCRIPTOR = _FEATUREVECTORIZER_INPUTCOLUMN,
    __module__ = 'FeatureVectorizer_pb2'
    # @@protoc_insertion_point(class_scope:CoreML.Specification.FeatureVectorizer.InputColumn)
    ))
  ,
  DESCRIPTOR = _FEATUREVECTORIZER,
  __module__ = 'FeatureVectorizer_pb2'
  # @@protoc_insertion_point(class_scope:CoreML.Specification.FeatureVectorizer)
  ))
_sym_db.RegisterMessage(FeatureVectorizer)
_sym_db.RegisterMessage(FeatureVectorizer.InputColumn)

DESCRIPTOR.has_options = True
DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('H\003'))
# @@protoc_insertion_point(module_scope)