package eventstore.j;

import java.io.Closeable;
import java.util.Collection;
import scala.concurrent.Future;
import akka.NotUsed;
import akka.stream.javadsl.Source;
import eventstore.akka.SubscriptionObserver;
import eventstore.core.settings.PersistentSubscriptionSettings;
import eventstore.core.*;

/**
 * Maintains a full duplex connection to the EventStore
 *

 * All operations are handled in a full async manner.
 * Many threads can use an EsConnection at the same time or a single thread can make many asynchronous requests.
 * To get the most performance out of the connection it is generally recommended to use it in this way.
 */
public interface EsConnection {

  /**
   * Write events to a stream
   *

   * When writing events to a stream the {@link eventstore.core.ExpectedVersion} choice can
   * make a very large difference in the observed behavior. For example, if no stream exists
   * and ExpectedVersion.Any is used, a new stream will be implicitly created when appending.
   *

   * There are also differences in idempotency between different types of calls.
   * If you specify an ExpectedVersion aside from ExpectedVersion.Any the Event Store
   * will give you an idempotency guarantee. If using ExpectedVersion.Any the Event Store
   * will do its best to provide idempotency but does not guarantee idempotency
   *
   * @param stream          name of the stream to write events to
   * @param expectedVersion expected version of the stream to write to, or ExpectedVersion.Any if null
   * @param events          events to append to the stream
   * @param credentials     optional user credentials to perform operation with.
   * @return A {@link scala.concurrent.Future} that the caller can await on
   */
  Future<WriteResult> writeEvents(
      String stream,
      ExpectedVersion expectedVersion,
      Collection<EventData> events,
      UserCredentials credentials);

  /**
   * Write events to a stream
   *

   * When writing events to a stream the {@link eventstore.core.ExpectedVersion} choice can
   * make a very large difference in the observed behavior. For example, if no stream exists
   * and ExpectedVersion.Any is used, a new stream will be implicitly created when appending.
   *

   * There are also differences in idempotency between different types of calls.
   * If you specify an ExpectedVersion aside from ExpectedVersion.Any the Event Store
   * will give you an idempotency guarantee. If using ExpectedVersion.Any the Event Store
   * will do its best to provide idempotency but does not guarantee idempotency
   *
   * @param stream          name of the stream to write events to
   * @param expectedVersion expected version of the stream to write to, or ExpectedVersion.Any if null
   * @param events          events to append to the stream
   * @param credentials     optional user credentials to perform operation with.
   * @param requireMaster   Require Event Store to refuse operation if it is not master
   * @return A {@link scala.concurrent.Future} that the caller can await on
   */
  Future<WriteResult> writeEvents(
      String stream,
      ExpectedVersion expectedVersion,
      Collection<EventData> events,
      UserCredentials credentials,
      boolean requireMaster);

  /**
   * Deletes a stream from the Event Store
   *
   * @param stream          name of the stream to delete
   * @param expectedVersion optional expected version that the stream should have when being deleted, or ExpectedVersion.Any if null
   * @param credentials     optional user credentials to perform operation with.
   * @return A {@link scala.concurrent.Future} that the caller can await on
   */
  Future<DeleteResult> deleteStream(
      String stream,
      ExpectedVersion.Existing expectedVersion,
      UserCredentials credentials);

  /**
   * Deletes a stream from the Event Store
   *
   * @param stream          name of the stream to delete
   * @param expectedVersion optional expected version that the stream should have when being deleted, or ExpectedVersion.Any if null
   * @param hardDelete      Indicator for tombstoning vs soft-deleting the stream. Tombstoned streams can never be recreated. Soft-deleted streams can be written to again, but the EventNumber sequence will not start from 0.
   * @param credentials     optional user credentials to perform operation with.
   * @return A {@link scala.concurrent.Future} that the caller can await on
   */
  Future<DeleteResult> deleteStream(
      String stream,
      ExpectedVersion.Existing expectedVersion,
      boolean hardDelete,
      UserCredentials credentials);

  /**
   * Deletes a stream from the Event Store
   *
   * @param stream          name of the stream to delete
   * @param expectedVersion optional expected version that the stream should have when being deleted, or ExpectedVersion.Any if null
   * @param hardDelete      Indicator for tombstoning vs soft-deleting the stream. Tombstoned streams can never be recreated. Soft-deleted streams can be written to again, but the EventNumber sequence will not start from 0.
   * @param credentials     optional user credentials to perform operation with.
   * @param requireMaster   Require Event Store to refuse operation if it is not master
   * @return A {@link scala.concurrent.Future} that the caller can await on
   */
  Future<DeleteResult> deleteStream(
      String stream,
      ExpectedVersion.Existing expectedVersion,
      boolean hardDelete,
      UserCredentials credentials,
      boolean requireMaster);

  /**
   * Starts a transaction in the event store on a given stream asynchronously
   *

   * A {@link eventstore.j.EsTransaction} allows the calling of multiple writes with multiple
   * round trips over long periods of time between the caller and the event store. This method
   * is only available through the TCP interface and no equivalent exists for the RESTful interface.
   *
   * @param stream          The stream to start a transaction on
   * @param expectedVersion The expected version of the stream at the time of starting the transaction
   * @param credentials     The optional user credentials to perform operation with
   * @return A {@link scala.concurrent.Future} containing an actual transaction
   */
  Future<EsTransaction> startTransaction(
      String stream,
      ExpectedVersion expectedVersion,
      UserCredentials credentials);

  /**
   * Starts a transaction in the event store on a given stream asynchronously
   *

   * A {@link eventstore.j.EsTransaction} allows the calling of multiple writes with multiple
   * round trips over long periods of time between the caller and the event store. This method
   * is only available through the TCP interface and no equivalent exists for the RESTful interface.
   *
   * @param stream          The stream to start a transaction on
   * @param expectedVersion The expected version of the stream at the time of starting the transaction
   * @param credentials     The optional user credentials to perform operation with
   * @param requireMaster   Require Event Store to refuse operation if it is not master
   * @return A {@link scala.concurrent.Future} containing an actual transaction
   */
  Future<EsTransaction> startTransaction(
      String stream,
      ExpectedVersion expectedVersion,
      UserCredentials credentials,
      boolean requireMaster);

  /**
   * Continues transaction by provided transaction ID.
   *

   * A {@link eventstore.j.EsTransaction} allows the calling of multiple writes with multiple
   * round trips over long periods of time between the caller and the event store. This method
   * is only available through the TCP interface and no equivalent exists for the RESTful interface.
   *
   * @param transactionId The transaction ID that needs to be continued.
   * @param credentials   The optional user credentials to perform operation with
   * @return A transaction for given id
   */
  EsTransaction continueTransaction(long transactionId, UserCredentials credentials);

  /**
   * Reads a single event from a stream at event number
   *
   * @param stream         name of the stream to read from
   * @param eventNumber    optional event number to read, or EventNumber.Last for reading latest event, EventNumber.Last if null
   * @param resolveLinkTos whether to resolve LinkTo events automatically
   * @param credentials    The optional user credentials to perform operation with
   * @return A {@link scala.concurrent.Future} containing an event
   */
  Future<Event> readEvent(
      String stream,
      EventNumber eventNumber,
      boolean resolveLinkTos,
      UserCredentials credentials);

  /**
   * Reads a single event from a stream at event number
   *
   * @param stream         name of the stream to read from
   * @param eventNumber    optional event number to read, or EventNumber.Last for reading latest event, EventNumber.Last if null
   * @param resolveLinkTos whether to resolve LinkTo events automatically
   * @param credentials    The optional user credentials to perform operation with
   * @param requireMaster  Require Event Store to refuse operation if it is not master
   * @return A {@link scala.concurrent.Future} containing an event
   */
  Future<Event> readEvent(
      String stream,
      EventNumber eventNumber,
      boolean resolveLinkTos,
      UserCredentials credentials,
      boolean requireMaster);

  /**
   * Reads count events from a stream forwards (e.g. oldest to newest) starting from event number
   *
   * @param stream         name of stream to read from
   * @param fromNumber     optional event number to read, EventNumber.First if null
   * @param maxCount       maximum count of items to read
   * @param resolveLinkTos whether to resolve LinkTo events automatically
   * @param credentials    The optional user credentials to perform operation with
   * @return A {@link scala.concurrent.Future} containing the results of the read operation
   */
  Future<ReadStreamEventsCompleted> readStreamEventsForward(
      String stream,
      EventNumber.Exact fromNumber,
      int maxCount,
      boolean resolveLinkTos,
      UserCredentials credentials);

  /**
   * Reads count events from a stream forwards (e.g. oldest to newest) starting from event number
   *
   * @param stream         name of stream to read from
   * @param fromNumber     optional event number to read, EventNumber.First if null
   * @param maxCount       maximum count of items to read
   * @param resolveLinkTos whether to resolve LinkTo events automatically
   * @param credentials    The optional user credentials to perform operation with
   * @param requireMaster  Require Event Store to refuse operation if it is not master
   * @return A {@link scala.concurrent.Future} containing the results of the read operation
   */
  Future<ReadStreamEventsCompleted> readStreamEventsForward(
      String stream,
      EventNumber.Exact fromNumber,
      int maxCount,
      boolean resolveLinkTos,
      UserCredentials credentials,
      boolean requireMaster);

  /**
   * Reads count events from from a stream backwards (e.g. newest to oldest) starting from event number
   *
   * @param stream         name of stream to read from
   * @param fromNumber     optional event number to read, EventNumber.Last if null
   * @param maxCount       maximum count of items to read
   * @param resolveLinkTos whether to resolve LinkTo events automatically
   * @param credentials    The optional user credentials to perform operation with
   * @return A {@link scala.concurrent.Future} containing the results of the read operation
   */
  Future<ReadStreamEventsCompleted> readStreamEventsBackward(
      String stream,
      EventNumber fromNumber,
      int maxCount,
      boolean resolveLinkTos,
      UserCredentials credentials);

  /**
   * Reads count events from from a stream backwards (e.g. newest to oldest) starting from event number
   *
   * @param stream         name of stream to read from
   * @param fromNumber     optional event number to read, EventNumber.Last if null
   * @param maxCount       maximum count of items to read
   * @param resolveLinkTos whether to resolve LinkTo events automatically
   * @param credentials    The optional user credentials to perform operation with
   * @param requireMaster  Require Event Store to refuse operation if it is not master
   * @return A {@link scala.concurrent.Future} containing the results of the read operation
   */
  Future<ReadStreamEventsCompleted> readStreamEventsBackward(
      String stream,
      EventNumber fromNumber,
      int maxCount,
      boolean resolveLinkTos,
      UserCredentials credentials,
      boolean requireMaster);

  /**
   * Reads all events in the node forward (e.g. beginning to end) starting from position
   *
   * @param fromPosition   optional position to start reading from, Position.First of null
   * @param maxCount       maximum count of items to read
   * @param resolveLinkTos whether to resolve LinkTo events automatically
   * @param credentials    The optional user credentials to perform operation with
   * @return A {@link scala.concurrent.Future} containing the results of the read operation
   */
  Future<ReadAllEventsCompleted> readAllEventsForward(
      Position fromPosition,
      int maxCount,
      boolean resolveLinkTos,
      UserCredentials credentials);

  /**
   * Reads all events in the node forward (e.g. beginning to end) starting from position
   *
   * @param fromPosition   optional position to start reading from, Position.First of null
   * @param maxCount       maximum count of items to read
   * @param resolveLinkTos whether to resolve LinkTo events automatically
   * @param credentials    The optional user credentials to perform operation with
   * @param requireMaster  Require Event Store to refuse operation if it is not master
   * @return A {@link scala.concurrent.Future} containing the results of the read operation
   */
  Future<ReadAllEventsCompleted> readAllEventsForward(
      Position fromPosition,
      int maxCount,
      boolean resolveLinkTos,
      UserCredentials credentials,
      boolean requireMaster);

  /**
   * Reads all events in the node backwards (e.g. end to beginning) starting from position
   *
   * @param fromPosition   optional position to start reading from, Position.Last of null
   * @param maxCount       maximum count of items to read
   * @param resolveLinkTos whether to resolve LinkTo events automatically
   * @param credentials    The optional user credentials to perform operation with
   * @return A {@link scala.concurrent.Future} containing the results of the read operation
   */
  Future<ReadAllEventsCompleted> readAllEventsBackward(
      Position fromPosition,
      int maxCount,
      boolean resolveLinkTos,
      UserCredentials credentials);

  /**
   * Reads all events in the node backwards (e.g. end to beginning) starting from position
   *
   * @param fromPosition   optional position to start reading from, Position.Last of null
   * @param maxCount       maximum count of items to read
   * @param resolveLinkTos whether to resolve LinkTo events automatically
   * @param credentials    The optional user credentials to perform operation with
   * @param requireMaster  Require Event Store to refuse operation if it is not master
   * @return A {@link scala.concurrent.Future} containing the results of the read operation
   */
  Future<ReadAllEventsCompleted> readAllEventsBackward(
      Position fromPosition,
      int maxCount,
      boolean resolveLinkTos,
      UserCredentials credentials,
      boolean requireMaster);

  /**
   * Subscribes to a single event stream. New events
   * written to the stream while the subscription is active will be
   * pushed to the client.
   *
   * @param stream         The stream to subscribe to
   * @param observer       A {@link eventstore.akka.SubscriptionObserver} to handle a new event received over the subscription
   * @param resolveLinkTos Whether to resolve LinkTo events automatically
   * @param credentials    The optional user credentials to perform operation with
   * @return A {@link java.io.Closeable} representing the subscription which can be closed.
   */
  Closeable subscribeToStream(
      String stream,
      SubscriptionObserver<Event> observer,
      boolean resolveLinkTos,
      UserCredentials credentials);

  /**
   * Subscribes to a single event stream. Existing events from
   * lastCheckpoint onwards are read from the stream
   * and presented to the user of SubscriptionObserver
   * as if they had been pushed.
   *

   * Once the end of the stream is read the subscription is
   * transparently (to the user) switched to push new events as
   * they are written.
   *

   * If events have already been received and resubscription from the same point
   * is desired, use the event number of the last event processed which
   * appeared on the subscription.
   *
   * @param stream                   The stream to subscribe to
   * @param observer                 A {@link eventstore.akka.SubscriptionObserver} to handle a new event received over the subscription
   * @param fromEventNumberExclusive The event number from which to start, or null to read all events.
   * @param resolveLinkTos           Whether to resolve LinkTo events automatically
   * @param credentials              The optional user credentials to perform operation with
   * @return A {@link java.io.Closeable} representing the subscription which can be closed.
   */
  Closeable subscribeToStreamFrom(
      String stream,
      SubscriptionObserver<Event> observer,
      Long fromEventNumberExclusive,
      boolean resolveLinkTos,
      UserCredentials credentials);

  /**
   * Subscribes to all events in the Event Store. New events written to the stream
   * while the subscription is active will be pushed to the client.
   *
   * @param observer       A {@link eventstore.akka.SubscriptionObserver} to handle a new event received over the subscription
   * @param resolveLinkTos Whether to resolve LinkTo events automatically
   * @param credentials    The optional user credentials to perform operation with
   * @return A {@link java.io.Closeable} representing the subscription which can be closed.
   */
  Closeable subscribeToAll(
      SubscriptionObserver<IndexedEvent> observer,
      boolean resolveLinkTos,
      UserCredentials credentials);

  /**
   * Subscribes to a all events. Existing events from position
   * onwards are read from the Event Store and presented to the user of
   * SubscriptionObserver as if they had been pushed.
   *

   * Once the end of the stream is read the subscription is
   * transparently (to the user) switched to push new events as
   * they are written.
   *

   * If events have already been received and resubscription from the same point
   * is desired, use the position representing the last event processed which
   * appeared on the subscription.
   *
   * @param observer              A {@link eventstore.akka.SubscriptionObserver} to handle a new event received over the subscription
   * @param fromPositionExclusive The position from which to start, or null to read all events
   * @param resolveLinkTos        Whether to resolve LinkTo events automatically
   * @param credentials           The optional user credentials to perform operation with
   * @return A {@link java.io.Closeable} representing the subscription which can be closed.
   */
  Closeable subscribeToAllFrom(
      SubscriptionObserver<IndexedEvent> observer,
      Position.Exact fromPositionExclusive,
      boolean resolveLinkTos,
      UserCredentials credentials);

// TODO support stream not found
//    Future<Unit> setStreamMetadata(String stream, int expectedMetastreamVersion, StreamMetadata metadata, UserCredentials credentials);
//    Future<StreamMetadataResult> getStreamMetadataAsync(String stream, UserCredentials credentials);
//    Future<RawStreamMetadataResult> getStreamMetadataAsRawBytesAsync(String stream, UserCredentials credentials); TODO

  /**
   * Sets the metadata for a stream.
   *
   * @param stream                    The name of the stream for which to set metadata.
   * @param expectedMetastreamVersion The expected version for the write to the metadata stream.
   * @param metadata                  A byte array representing the new metadata.
   * @param credentials               The optional user credentials to perform operation with
   * @return A {@link scala.concurrent.Future} representing the operation
   */
  Future<WriteResult> setStreamMetadata(
      String stream,
      ExpectedVersion expectedMetastreamVersion,
      byte[] metadata,
      UserCredentials credentials);

  /**
   * Reads the metadata for a stream as a byte array.
   *
   * @param stream      The name of the stream for which to read metadata.
   * @param credentials The optional user credentials to perform operation with
   * @return A {@link scala.concurrent.Future} containing the metadata as byte array.
   */
  Future<byte[]> getStreamMetadataBytes(String stream, UserCredentials credentials);

  /**
   * Creates a Source you can use to subscribe to a single event stream. Existing events from
   * event number onwards are read from the stream and presented to the user of
   * Source as if they had been pushed.
   *

   * Once the end of the stream is read the Source transparently (to the user)
   * switches to push new events as they are written.
   *

   * If events have already been received and resubscription from the same point
   * is desired, use the event number of the last event processed.
   *
   * @param stream                   The stream to subscribe to
   * @param fromEventNumberExclusive The event number from which to start, or null to read all events.
   * @param resolveLinkTos           Whether to resolve LinkTo events automatically
   * @param credentials              The optional user credentials to perform operation with
   * @param infinite                 Whether to subscribe to the future events upon reading all current
   * @return A {@link akka.stream.javadsl.Source} representing the stream
   */
   Source<Event, NotUsed> streamSource(
      String stream,
      EventNumber fromEventNumberExclusive,
      boolean resolveLinkTos,
      UserCredentials credentials,
      boolean infinite);

  /**
   * Creates a Source you can use to subscribes to all events. Existing events from position
   * onwards are read from the Event Store and presented to the user of
   * Source as if they had been pushed.
   *

   * Once the end of the stream is read the Source transparently (to the user)
   * switches to push new events as they are written.
   *

   * If events have already been received and resubscription from the same point
   * is desired, use the position representing the last event processed.
   *
   * @param fromPositionExclusive The position from which to start, or null to read all events
   * @param resolveLinkTos        Whether to resolve LinkTo events automatically
   * @param credentials           The optional user credentials to perform operation with
   * @param infinite              Whether to subscribe to the future events upon reading all current
   * @return A {@link akka.stream.javadsl.Source} representing all streams
   */
  Source<IndexedEvent, NotUsed> allStreamsSource(
      Position fromPositionExclusive,
      boolean resolveLinkTos,
      UserCredentials credentials,
      boolean infinite);

  /**
   * Asynchronously create a persistent subscription group on a stream
   *
   * @param stream      The name of the stream to create the persistent subscription on
   * @param groupName   The name of the group to create
   * @param settings    The {@link PersistentSubscriptionSettings} for the subscription, or null for defaults
   * @param credentials The credentials to be used for this operation
   * @return A {@link scala.concurrent.Future} representing the operation
   */
  Future<scala.Unit> createPersistentSubscription(
      String stream,
      String groupName,
      PersistentSubscriptionSettings settings,
      UserCredentials credentials);

  /**
   * Asynchronously update a persistent subscription group on a stream
   *
   * @param stream      The name of the stream to create the persistent subscription on
   * @param groupName   The name of the group to create
   * @param settings    The {@link PersistentSubscriptionSettings} for the subscription, or null for defaults
   * @param credentials The credentials to be used for this operation, or null for default
   * @return A {@link scala.concurrent.Future} representing the operation
   */
  Future<scala.Unit> updatePersistentSubscription(
      String stream,
      String groupName,
      PersistentSubscriptionSettings settings,
      UserCredentials credentials);

  /**
   * Asynchronously delete a persistent subscription group on a stream
   *
   * @param stream      The name of the stream to create the persistent subscription on
   * @param groupName   The name of the group to create
   * @param credentials The credentials to be used for this operation, or null for default
   * @return A {@link scala.concurrent.Future} representing the operation
   */
  Future<scala.Unit> deletePersistentSubscription(
      String stream,
      String groupName,
      UserCredentials credentials);
}


ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
null

### Remarks
null


Editing OilColor

<?php echo render('oilcolors/_form'); ?>

	<?php echo Html::anchor('oilcolors/view/'.$oilColor->id, 'View'); ?> |
	<?php echo Html::anchor('oilcolors', 'Back'); ?>


<?php declare(strict_types=1);

namespace Monolog\Handler;

use Monolog\Logger;
use Swift;
use Swift_Message;

/**
 * MandrillHandler uses cURL to send the emails to the Mandrill API
 *
 * @author Adam Nicholson <adamnicholson10@gmail.com>
 */
class MandrillHandler extends MailHandler
{
    /** @var Swift_Message */
    protected $message;
    /** @var string */
    protected $apiKey;

    /**
     * @psalm-param Swift_Message|callable(): Swift_Message $message
     *
     * @param string                 $apiKey  A valid Mandrill API key
     * @param callable|Swift_Message $message An example message for real messages, only the body will be replaced
     */
    public function __construct(string $apiKey, $message, $level = Logger::ERROR, bool $bubble = true)
    {
        parent::__construct($level, $bubble);

        if (!$message instanceof Swift_Message && is_callable($message)) {
            $message = $message();
        }
        if (!$message instanceof Swift_Message) {
            throw new \InvalidArgumentException('You must provide either a Swift_Message instance or a callable returning it');
        }
        $this->message = $message;
        $this->apiKey = $apiKey;
    }

    /**
     * {@inheritdoc}
     */
    protected function send(string $content, array $records): void
    {
        $mime = 'text/plain';
        if ($this->isHtmlBody($content)) {
            $mime = 'text/html';
        }

        $message = clone $this->message;
        $message->setBody($content, $mime);
        /** @phpstan-ignore-next-line */
        if (version_compare(Swift::VERSION, '6.0.0', '>=')) {
            $message->setDate(new \DateTimeImmutable());
        } else {
            /** @phpstan-ignore-next-line */
            $message->setDate(time());
        }

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, 'https://mandrillapp.com/api/1.0/messages/send-raw.json');
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
            'key' => $this->apiKey,
            'raw_message' => (string) $message,
            'async' => false,
        ]));

        Curl\Util::execute($ch);
    }
}


Tucnak pedestrian crossing


// # Ghost Editor
//
// Ghost Editor contains a set of modules which make up the editor component
// It manages the left and right panes, and all of the communication between them
// Including scrolling,

/*global document, $, _, Ghost */
(function () {
    'use strict';

    var Editor = function () {
        var self = this,
            $document = $(document),
        // Create all the needed editor components, passing them what they need to function
            markdown = new Ghost.Editor.MarkdownEditor(),
            uploadMgr = new Ghost.Editor.UploadManager(markdown),
            preview = new Ghost.Editor.HTMLPreview(markdown, uploadMgr),
            scrollHandler = new Ghost.Editor.ScrollHandler(markdown, preview),
            unloadDirtyMessage,
            handleChange,
            handleDrag;

        unloadDirtyMessage = function () {
            return '==============================\n\n' +
                'Hey there! It looks like you\'re in the middle of writing' +
                ' something and you haven\'t saved all of your content.' +
                '\n\nSave before you go!\n\n' +
                '==============================';
        };

        handleChange = function () {
            self.setDirty(true);
            preview.update();
        };

        handleDrag = function (e) {
            e.preventDefault();
        };

        // Public API
        _.extend(this, {
            enable: function () {
                // Listen for changes
                $document.on('markdownEditorChange', handleChange);

                // enable editing and scrolling
                markdown.enable();
                scrollHandler.enable();
            },

            disable: function () {
                // Don't listen for changes
                $document.off('markdownEditorChange', handleChange);

                // disable editing and scrolling
                markdown.disable();
                scrollHandler.disable();
            },

            // Get the markdown value from the editor for saving
            // Upload manager makes sure the upload markers are removed beforehand
            value: function () {
                return uploadMgr.value();
            },

            setDirty: function (dirty) {
                window.onbeforeunload = dirty ? unloadDirtyMessage : null;
            }
        });

         // Initialise
        $document.on('drop dragover', handleDrag);
        preview.update();
        this.enable();
    };

    Ghost.Editor = Ghost.Editor || {};
    Ghost.Editor.Main = Editor;
}());


<?php

declare(strict_types=1);

namespace whatwedo\TableBundle\Tests\App\Factory;

use whatwedo\TableBundle\Tests\App\Entity\Person;
use whatwedo\TableBundle\Tests\App\Repository\PersonRepository;
use Zenstruck\Foundry\ModelFactory;
use Zenstruck\Foundry\Proxy;
use Zenstruck\Foundry\RepositoryProxy;

/**
 * @method static       Person|Proxy createOne(array $attributes = [])
 * @method static       Person[]|Proxy[] createMany(int $number, $attributes = [])
 * @method static       Person|Proxy find($criteria)
 * @method static       Person|Proxy findOrCreate(array $attributes)
 * @method static       Person|Proxy first(string $sortedField = 'id')
 * @method static       Person|Proxy last(string $sortedField = 'id')
 * @method static       Person|Proxy random(array $attributes = [])
 * @method static       Person|Proxy randomOrCreate(array $attributes = [])
 * @method static       Person[]|Proxy[] all()
 * @method static       Person[]|Proxy[] findBy(array $attributes)
 * @method static       Person[]|Proxy[] randomSet(int $number, array $attributes = [])
 * @method static       Person[]|Proxy[] randomRange(int $min, int $max, array $attributes = [])
 * @method static       PersonRepository|RepositoryProxy repository()
 * @method Person|Proxy create($attributes = [])
 */
final class PersonFactory extends ModelFactory
{
    protected function getDefaults(): array
    {
        return [
            'name' => self::faker()->name(),
        ];
    }

    protected static function getClass(): string
    {
        return Person::class;
    }
}


package com.francetelecom.clara.cloud.presentation.applications;

import com.francetelecom.clara.cloud.core.service.exception.ObjectNotFoundException;
import com.francetelecom.clara.cloud.coremodel.Application;
import com.francetelecom.clara.cloud.presentation.common.AjaxFallbackCustomDataTable;
import com.francetelecom.clara.cloud.presentation.common.PageTemplate;
import com.francetelecom.clara.cloud.presentation.resource.CacheActivatedImage;
import com.francetelecom.clara.cloud.presentation.tools.ApplicationProvider;
import com.francetelecom.clara.cloud.presentation.tools.BusinessExceptionHandler;
import com.francetelecom.clara.cloud.presentation.tools.WicketSession;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.AjaxSelfUpdatingTimerBehavior;
import org.apache.wicket.ajax.markup.html.form.AjaxCheckBox;
import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator;
import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn;
import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.SubmitLink;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.model.*;
import org.apache.wicket.util.time.Duration;

import java.util.ArrayList;
import java.util.List;

/**
 * ApplicationsTablePanel
 * Panel which show the applications
 *
 * User: Thomas Escalle - tawe8231
 * Entity : FT/OLNC/RD/MAPS/MEP/MSE
 * Updated  : $LastChangedDate$
 * @author  : $Author$
 * @version : $Revision$
 */
public class ApplicationsTablePanel extends Panel {

    private static final long serialVersionUID = 527385503166750788L;

    //private static final transient org.slf4j.Logger logger = LoggerFactory.getLogger(ApplicationsTablePanel.class);

    AjaxFallbackCustomDataTable<Application, String> dataTable;

    CheckBox viewAllCheckBox;

    private ApplicationsPage parentPage;

    private List<Application> applicationsList;
    private Form<?> searchCriteriaForm;
    private String searchCriteria;

    private WebMarkupContainer refreshContainer;

    public ApplicationsTablePanel(String id) {
        super(id);
        initComponents();

    }

    private void initComponents() {
		refreshContainer = new WebMarkupContainer("refreshApplication");
		add(refreshContainer.setOutputMarkupId(true));

		}

    private StringResourceModel getStringResourceModel(java.lang.String key) {
        // BVA fix Localizer warning : cf. https://issues.apache.org/jira/browse/WICKET-990
        return new StringResourceModel(key, this, null);
    }

    private void initTable(){
        final List<IColumn<Application, String>> columns = new ArrayList<IColumn<Application, String>>();

        columns.add(new PropertyColumn<Application, String>(getStringResourceModel("portal.application.table.header.name"), "label", "label") {
            private static final long serialVersionUID = -5548238873027346512L;

            @Override
            public void populateItem(Item<ICellPopulator<Application>> cellItem, String id, IModel<Application> appIModel) {
                cellItem.add(new ApplicationDetailsLinkPanel(id, appIModel));
                cellItem.add(new AttributeAppender("title", appIModel.getObject().getLabel()));
            }

            @Override
            public String getCssClass() {
                return "label ellipsis";
            }
        });

        columns.add(new PropertyColumn<Application, String>(getStringResourceModel("portal.application.table.header.appCode"), "code", "code") {
			private static final long serialVersionUID = 2743741360422459728L;

			@Override
            public void populateItem(Item<ICellPopulator<Application>> item, String componentId, IModel<Application> rowModel) {
                super.populateItem(item, componentId, rowModel);
                item.add(new AttributeAppender("title", rowModel.getObject().getCode()));
            }

            @Override
            public String getCssClass() {
                return "label ellipsis";
            }
        });

        columns.add(new PropertyColumn<Application, String>(getStringResourceModel("portal.application.table.header.description"), "description", "description"));

        columns.add(new PropertyColumn<Application, String>(getStringResourceModel("portal.application.table.header.visibility"), "visibility", "visibility") {
 			private static final long serialVersionUID = -2362613895284301548L;

			@Override
            public void populateItem(Item<ICellPopulator<Application>> iCellPopulatorItem, String componentId, IModel<Application> appIModel) {
                iCellPopulatorItem.add(new ApplicationVisibilityPanel(componentId, appIModel));
            }

            @Override
            public String getCssClass() {
                return "actionShort actionCenter";
            }
        });

        columns.add(new AbstractColumn<Application, String>(getStringResourceModel("portal.application.table.header.actions")) {
            private static final long serialVersionUID = -2548831025324697929L;

            @Override
            public void populateItem(Item<ICellPopulator<Application>> iCellPopulatorItem, String componentId, IModel<Application> appIModel) {
                ApplicationActionPanel appActPanel = null;
                try {
                    appActPanel = new ApplicationActionPanel(componentId, appIModel, parentPage.getManageApplication().canBeDeleted(appIModel.getObject().getUID()));
                } catch (ObjectNotFoundException e) {
                    BusinessExceptionHandler handler = new BusinessExceptionHandler(parentPage);
                    handler.error(e);
                }
                iCellPopulatorItem.add(appActPanel);
            }

            @Override
            public String getCssClass() {
                return "actionShort actionCenter";
            }
        });

        //ApplicationProvider appProv = new ApplicationProvider(this, viewAllCheckBox.getModel(), parentPage.getManageApplication());
        ApplicationProvider appProv = new ApplicationProvider(searchCriteria, applicationsList);

        dataTable = new AjaxFallbackCustomDataTable<>("applicationsDataTable",columns,appProv, PageTemplate.ROWS_PER_PAGE);
        dataTable.add(new AjaxSelfUpdatingTimerBehavior(Duration.seconds(60)));
        addOrReplace(dataTable);
    }

    @Override
    protected void onBeforeRender() {

        this.parentPage = (ApplicationsPage) getPage();

        createSearchCriteriaForm();

        viewAllCheckBox = new AjaxCheckBox("allAppsCheckbox", new Model<Boolean>(WicketSession.get().getViewAll())) {
			private static final long serialVersionUID = -336651607302799133L;

			@Override
            protected void onUpdate(AjaxRequestTarget target) {
                WicketSession.get().setViewAll(getModelObject());
                getApplicationsFromDB();
                //
                initTable();
                refreshContainer.replace(dataTable);
                target.add(refreshContainer);

            }
        };
        searchCriteriaForm.addOrReplace(viewAllCheckBox);

        getApplicationsFromDB();

        initTable();
        refreshContainer.addOrReplace(dataTable) ;
        super.onBeforeRender();
    }

    private void getApplicationsFromDB() {
    	applicationsList = new ArrayList<Application>();
    	if (viewAllCheckBox.getModelObject()) {
    		applicationsList = parentPage.getManageApplication().findApplications();
        } else {
        	applicationsList = parentPage.getManageApplication().findMyApplications();
        }

    }

    private void createSearchCriteriaForm() {
    	searchCriteriaForm = new Form<Void>("searchCriteriaForm");
    	searchCriteriaForm.add(new CacheActivatedImage("imageHelp.searchField",  new ResourceModel("image.help").getObject()));
    	addOrReplace(searchCriteriaForm);
		searchCriteriaForm.add(new TextField<String>("searchCriteria", new PropertyModel<String>(this, "searchCriteria")));
		SubmitLink searchLink = new SubmitLink("searchLink");
		CacheActivatedImage imageSearch = new CacheActivatedImage("imageSearch",  new ResourceModel("image.help").getObject());
		searchLink.add(imageSearch);
		searchCriteriaForm.add(searchLink);
    }

}


import { Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ProfileComponent } from './profile/profile.component';
import { CallbackComponent } from './callback/callback.component';
// import { DashboardComponent }  from './dashboard/dashboard.component';
// import { BootstrapComponent }  from './bootstrap/bootstrap-component.component';
import { Error404Component }  from './errors/error404.component';

export const ROUTES: Routes = [
  { path: '', component: HomeComponent },
  { path: 'dashboard', component: Error404Component },
  { path: 'bootstrap/:id', component: Error404Component },
  { path: 'profile', component: ProfileComponent },
  { path: 'callback', component: CallbackComponent },
  { path: '**', redirectTo: '' }
];


/* 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.
 */

package org.activiti.engine.impl.persistence.entity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.activiti.engine.impl.EventSubscriptionQueryImpl;
import org.activiti.engine.impl.Page;
import org.activiti.engine.impl.persistence.AbstractManager;

/**
 * @author Daniel Meyer
 */
public class EventSubscriptionManager extends AbstractManager {

  /** keep track of subscriptions created in the current command */
  protected List<EventSubscriptionEntity> createdSignalSubscriptions = new ArrayList<EventSubscriptionEntity>();

  public void insert(EventSubscriptionEntity persistentObject) {
    super.insert(persistentObject);
    if(persistentObject instanceof SignalEventSubscriptionEntity) {
      createdSignalSubscriptions.add(persistentObject);
    }
  }

  public void deleteEventSubscription(EventSubscriptionEntity persistentObject) {
    getDbSqlSession().delete(persistentObject.getClass(), persistentObject.getId());
    if(persistentObject instanceof SignalEventSubscriptionEntity) {
      createdSignalSubscriptions.remove(persistentObject);
    }
  }

  public EventSubscriptionEntity findEventSubscriptionbyId(String id) {
    return (EventSubscriptionEntity) getDbSqlSession().selectOne("selectEventSubscription", id);
  }

  public long findEventSubscriptionCountByQueryCriteria(EventSubscriptionQueryImpl eventSubscriptionQueryImpl) {
    final String query = "selectEventSubscriptionCountByQueryCriteria";
    return (Long) getDbSqlSession().selectOne(query, eventSubscriptionQueryImpl);
  }

  @SuppressWarnings("unchecked")
  public List<EventSubscriptionEntity> findEventSubscriptionsByQueryCriteria(EventSubscriptionQueryImpl eventSubscriptionQueryImpl, Page page) {
    final String query = "selectEventSubscriptionByQueryCriteria";
    return getDbSqlSession().selectList(query, eventSubscriptionQueryImpl, page);
  }

  @SuppressWarnings("unchecked")
  public List<SignalEventSubscriptionEntity> findSignalEventSubscriptionsByEventName(String eventName) {
    final String query = "selectSignalEventSubscriptionsByEventName";
    Set<SignalEventSubscriptionEntity> selectList = new HashSet<SignalEventSubscriptionEntity>( getDbSqlSession().selectList(query, eventName));

    // add events created in this command (not visible yet in query)
    for (EventSubscriptionEntity entity : createdSignalSubscriptions) {
      if(entity instanceof SignalEventSubscriptionEntity
         && eventName.equals(entity.getEventName())) {
        selectList.add((SignalEventSubscriptionEntity) entity);
      }
    }

    return new ArrayList<SignalEventSubscriptionEntity>(selectList);
  }

  @SuppressWarnings("unchecked")
  public List<SignalEventSubscriptionEntity> findSignalEventSubscriptionsByExecution(String executionId) {
    final String query = "selectSignalEventSubscriptionsByExecution";
    Set<SignalEventSubscriptionEntity> selectList = new HashSet<SignalEventSubscriptionEntity>( getDbSqlSession().selectList(query, executionId));

    // add events created in this command (not visible yet in query)
    for (EventSubscriptionEntity entity : createdSignalSubscriptions) {
      if(entity instanceof SignalEventSubscriptionEntity
         && executionId.equals(entity.getExecutionId())) {
        selectList.add((SignalEventSubscriptionEntity) entity);
      }
    }

    return new ArrayList<SignalEventSubscriptionEntity>(selectList);
  }

  @SuppressWarnings("unchecked")
  public List<SignalEventSubscriptionEntity> findSignalEventSubscriptionsByNameAndExecution(String name, String executionId) {
    final String query = "selectSignalEventSubscriptionsByNameAndExecution";
    Map<String,String> params = new HashMap<String, String>();
    params.put("executionId", executionId);
    params.put("eventName", name);
    Set<SignalEventSubscriptionEntity> selectList = new HashSet<SignalEventSubscriptionEntity>( getDbSqlSession().selectList(query, params));

    // add events created in this command (not visible yet in query)
    for (EventSubscriptionEntity entity : createdSignalSubscriptions) {
      if(entity instanceof SignalEventSubscriptionEntity
              && executionId.equals(entity.getExecutionId())
              && name.equals(entity.getEventName())) {
        selectList.add((SignalEventSubscriptionEntity) entity);
      }
    }

    return new ArrayList<SignalEventSubscriptionEntity>(selectList);
  }

  public List<EventSubscriptionEntity> findEventSubscriptions(String executionId, String type) {
    final String query = "selectEventSubscriptionsByExecutionAndType";
    Map<String,String> params = new HashMap<String, String>();
    params.put("executionId", executionId);
    params.put("eventType", type);
    return getDbSqlSession().selectList(query, params);
  }

  public List<EventSubscriptionEntity> findEventSubscriptions(String executionId, String type, String activityId) {
    final String query = "selectEventSubscriptionsByExecutionTypeAndActivity";
    Map<String,String> params = new HashMap<String, String>();
    params.put("executionId", executionId);
    params.put("eventType", type);
    params.put("activityId", activityId);
    return getDbSqlSession().selectList(query, params);
  }

  public List<EventSubscriptionEntity> findEventSubscriptionsByConfiguration(String type, String configuration) {
    final String query = "selectEventSubscriptionsByConfiguration";
    Map<String,String> params = new HashMap<String, String>();
    params.put("eventType", type);
    params.put("configuration", configuration);
    return getDbSqlSession().selectList(query, params);
  }

  public List<EventSubscriptionEntity> findEventSubscriptionByName(String type, String eventName) {
    final String query = "selectEventSubscriptionsByName";
    Map<String,String> params = new HashMap<String, String>();
    params.put("eventType", type);
    params.put("eventName", eventName);
    return getDbSqlSession().selectList(query, params);
  }

  public MessageEventSubscriptionEntity findMessageStartEventSubscriptionByName(String messageName) {
    MessageEventSubscriptionEntity entity = (MessageEventSubscriptionEntity) getDbSqlSession().selectOne("selectMessageStartEventSubscriptionByName", messageName);
    return entity;
  }

}


"""
Various utilities for working with Python and Matplotlib
"""

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import os

from math import ceil, sqrt
from skimage.io import imread

def show_images(images,titles=None):
    """Display a list of images"""
    n_ims = len(images)
    if titles is None: titles = ['(%d)' % i for i in range(1,n_ims + 1)]
    fig = plt.figure()
    n = 1
    for image,title in zip(images, titles):
        a = fig.add_subplot(1,n_ims,n) # Make subplot
        if image.ndim == 2: # Is image grayscale?
            plt.gray() # Only place in this blog you can't replace 'gray' with 'grey'
        plt.imshow(image)
        a.set_title(title)
        n += 1
    fig.set_size_inches(np.array(fig.get_size_inches()) * n_ims)
    plt.show()

def tile_images(lst, size=None):
    """
    Given a list of images, display them in a tiled format.
    """
    num_plots = len(lst)
    if size is None:
        cols = ceil(sqrt(num_plots))
        rows  = ceil(num_plots/cols)
    else:
        rows, cols = size

    # Set up the figure
    fig, axes = plt.subplots(rows, cols)

    # Plot the images using `plt.imshow`
    for i, x in enumerate(lst):
        ax = axes[i]
        # If the element is a string, assume that it's a path
        if isinstance(x, str):
            try:
                img = imread(os.path.abspath(x))
                ax.imshow(img)
            except IOError:
                print("Unable to load image: %s" %x)
            except Exception as e:
                print(e)
        # Otherwise, attempt to load it as a numpy array
        else:
            try:
                img = np.array(x)
                ax.imshow(img)
            except Exception as e:
                print(e)

    # Show the images
    plt.show()

    # Return the fig and axes images, in case that is wanted
    return fig, axes


/*
 * 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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.contentwarehouse.v1.model;

/**
 * Saft named-entities info for a given topic.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the contentwarehouse API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class VideoContentSearchSaftEntityInfo extends com.google.api.client.json.GenericJson {

  /**
   * Representative canonical name for the entity.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String canonicalEntityName;

  /**
   * Score indicating the saliency (centrality) of this entity to the original_text.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Double entitySalience;

  /**
   * The type name, like "/saft/person", "/saft/art". See README.entity-types for the inventory of
   * SAFT type tags.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String entityTypeName;

  /**
   * Representative entity name mention extracted from original_text.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String mentionText;

  /**
   * SAFT Mention type.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String mentionType;

  /**
   * Freebase MID for entity if this the saft entity corresponds to a Webref KG mid. This field is
   * not always populated and is taken from FREEBASE_MID mid in EntityProfile in the saft entity
   * annotation.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String mid;

  /**
   * The original input text (e.g. the anchor text) where the saft entity annotation was run on.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String originalText;

  /**
   * Representative canonical name for the entity.
   * @return value or {@code null} for none
   */
  public java.lang.String getCanonicalEntityName() {
    return canonicalEntityName;
  }

  /**
   * Representative canonical name for the entity.
   * @param canonicalEntityName canonicalEntityName or {@code null} for none
   */
  public VideoContentSearchSaftEntityInfo setCanonicalEntityName(java.lang.String canonicalEntityName) {
    this.canonicalEntityName = canonicalEntityName;
    return this;
  }

  /**
   * Score indicating the saliency (centrality) of this entity to the original_text.
   * @return value or {@code null} for none
   */
  public java.lang.Double getEntitySalience() {
    return entitySalience;
  }

  /**
   * Score indicating the saliency (centrality) of this entity to the original_text.
   * @param entitySalience entitySalience or {@code null} for none
   */
  public VideoContentSearchSaftEntityInfo setEntitySalience(java.lang.Double entitySalience) {
    this.entitySalience = entitySalience;
    return this;
  }

  /**
   * The type name, like "/saft/person", "/saft/art". See README.entity-types for the inventory of
   * SAFT type tags.
   * @return value or {@code null} for none
   */
  public java.lang.String getEntityTypeName() {
    return entityTypeName;
  }

  /**
   * The type name, like "/saft/person", "/saft/art". See README.entity-types for the inventory of
   * SAFT type tags.
   * @param entityTypeName entityTypeName or {@code null} for none
   */
  public VideoContentSearchSaftEntityInfo setEntityTypeName(java.lang.String entityTypeName) {
    this.entityTypeName = entityTypeName;
    return this;
  }

  /**
   * Representative entity name mention extracted from original_text.
   * @return value or {@code null} for none
   */
  public java.lang.String getMentionText() {
    return mentionText;
  }

  /**
   * Representative entity name mention extracted from original_text.
   * @param mentionText mentionText or {@code null} for none
   */
  public VideoContentSearchSaftEntityInfo setMentionText(java.lang.String mentionText) {
    this.mentionText = mentionText;
    return this;
  }

  /**
   * SAFT Mention type.
   * @return value or {@code null} for none
   */
  public java.lang.String getMentionType() {
    return mentionType;
  }

  /**
   * SAFT Mention type.
   * @param mentionType mentionType or {@code null} for none
   */
  public VideoContentSearchSaftEntityInfo setMentionType(java.lang.String mentionType) {
    this.mentionType = mentionType;
    return this;
  }

  /**
   * Freebase MID for entity if this the saft entity corresponds to a Webref KG mid. This field is
   * not always populated and is taken from FREEBASE_MID mid in EntityProfile in the saft entity
   * annotation.
   * @return value or {@code null} for none
   */
  public java.lang.String getMid() {
    return mid;
  }

  /**
   * Freebase MID for entity if this the saft entity corresponds to a Webref KG mid. This field is
   * not always populated and is taken from FREEBASE_MID mid in EntityProfile in the saft entity
   * annotation.
   * @param mid mid or {@code null} for none
   */
  public VideoContentSearchSaftEntityInfo setMid(java.lang.String mid) {
    this.mid = mid;
    return this;
  }

  /**
   * The original input text (e.g. the anchor text) where the saft entity annotation was run on.
   * @return value or {@code null} for none
   */
  public java.lang.String getOriginalText() {
    return originalText;
  }

  /**
   * The original input text (e.g. the anchor text) where the saft entity annotation was run on.
   * @param originalText originalText or {@code null} for none
   */
  public VideoContentSearchSaftEntityInfo setOriginalText(java.lang.String originalText) {
    this.originalText = originalText;
    return this;
  }

  @Override
  public VideoContentSearchSaftEntityInfo set(String fieldName, Object value) {
    return (VideoContentSearchSaftEntityInfo) super.set(fieldName, value);
  }

  @Override
  public VideoContentSearchSaftEntityInfo clone() {
    return (VideoContentSearchSaftEntityInfo) super.clone();
  }

}


package org.openspaces.persistency.hibernate.iterator;

import com.gigaspaces.datasource.DataIterator;
import org.hibernate.CacheMode;
import org.hibernate.Criteria;
import org.hibernate.FlushMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Example;

import java.util.Iterator;

/**
 * A simple iterator that iterates over template object using Hibernate Criteria
 * by example.
 *
 * @author kimchy
 */
public class DefaultCriteriaByExampleDataIterator implements DataIterator {

    protected final Object template;

    protected final SessionFactory sessionFactory;

    protected Transaction transaction;

    protected Session session;

    private Iterator iterator;

    public DefaultCriteriaByExampleDataIterator(Object template, SessionFactory sessionFactory) {
        this.template = template;
        this.sessionFactory = sessionFactory;
    }

    public boolean hasNext() {
        if (iterator == null) {
            iterator = createIterator();
        }
        return iterator.hasNext();
    }

    public Object next() {
        return iterator.next();
    }

    public void remove() {
        throw new UnsupportedOperationException("remove not supported");
    }

    public void close() {
        try {
            if (transaction == null) {
                return;
            }
            transaction.commit();
        } finally {
            transaction = null;
            if (session != null && session.isOpen()) {
                session.close();
            }
        }
    }

    protected Iterator createIterator() {
        session = sessionFactory.openSession();
        transaction = session.beginTransaction();
        Example example = Example.create(template);
        Criteria criteria = session.createCriteria(template.getClass()).add(example);
        criteria.setCacheMode(CacheMode.IGNORE);
        criteria.setCacheable(false);
        criteria.setFlushMode(FlushMode.NEVER);
        return criteria.list().iterator();
    }
}


'use strict';

var gulp                = require('gulp'),
	gutil               = require('gulp-util'),
	livereload          = require('gulp-livereload'),
	notify              = require('gulp-notify'),
	postcss             = require('gulp-postcss'),
	rename              = require('gulp-rename'),
	sass                = require('gulp-sass'),
	sourcemaps          = require('gulp-sourcemaps');

gulp.task('styles', function() {
	return gulp.src(['src/scss/screen.scss', 'src/scss/ie.scss'])
		.pipe(sourcemaps.init())
		.pipe(sass())
		.on('error', notify.onError({
			icon:       'gulp/developer/icon-notify-styles.jpg',
			title:      'SCSS error',
			message:    '<%= error.message %>'
		}))
		.pipe(postcss([
			require('autoprefixer')({ browsers: [ 'last 3 versions' ]})
		]))
		.pipe(gutil.env.production ? require('gulp-cssnano')() : gutil.noop())
		.pipe(sourcemaps.write('.'))
		.pipe(gutil.env.production ? rename(function(path) {
			path.basename = path.extname === '.map' ?
				path.basename.replace(/\.(.*)$/, '.min.$1') :
			path.basename + '.min';
		}) : gutil.noop())
		.pipe(!gutil.env.production ? livereload() : gutil.noop())
		.pipe(gulp.dest('assets/css'))
});


package com.hazelcast.nio.serialization;

import java.io.IOException;

/**
 * Portable provides an alternative serialization method. Instead of relying on reflection, each Portable is
 * created by a registered {@link com.hazelcast.nio.serialization.PortableFactory}.
 *
 *

 *
 * Portable serialization has the following advantages:
 *

 *
Support multiple versions of the same object type.
 *     (See {@link com.hazelcast.config.SerializationConfig#setPortableVersion(int)})

 *
Fetching individual fields without having to rely on reflection.

 *
Querying and indexing support without de-serialization and/or reflection.

 *

 *
 * @see com.hazelcast.nio.serialization.PortableFactory
 * @see PortableWriter
 * @see PortableReader
 * @see ClassDefinition
 * @see com.hazelcast.nio.serialization.DataSerializable
 * @see com.hazelcast.nio.serialization.IdentifiedDataSerializable
 * @see com.hazelcast.config.SerializationConfig
 */

public interface Portable {

    /**
     * Returns PortableFactory ID for this portable class
     * @return factory ID
     */
    int getFactoryId();

    /**
     * Returns class identifier for this portable class. Class ID should be unique per PortableFactory.
     * @return class ID
     */
    int getClassId();

    /**
     * Serialize this portable object using PortableWriter
     *
     * @param writer PortableWriter
     * @throws IOException in case of any exceptional case
     */
    void writePortable(PortableWriter writer) throws IOException;

    /**
     * Read portable fields using PortableReader
     *
     * @param reader PortableReader
     * @throws IOException in case of any exceptional case
     */
    void readPortable(PortableReader reader) throws IOException;
}


---
uid: SolidEdgePart.Model.ResizeRounds
summary:
remarks:
---


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Class net.sf.jasperreports.web.util.WebResourceHandlersExtensionRegistryFactory (JasperReports 5.6.0 API)</title>
<meta name="date" content="2014-05-27">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
net.sf.jasperreports.web.util.WebResourceHandlersExtensionRegistryFactory

No usage of net.sf.jasperreports.web.util.WebResourceHandlersExtensionRegistryFactory

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

© 2001-2010 Jaspersoft Corporation www.jaspersoft.com


using System.ComponentModel;
using Windows.ApplicationModel.DataTransfer;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Xaml;
using AppStudio.DataProviders.LocalStorage;
using AppStudio.DataProviders.Html;
using NguyenAnNinhConfession.Sections;
using NguyenAnNinhConfession.ViewModels;
using AppStudio.Uwp;

namespace NguyenAnNinhConfession.Pages
{
    public sealed partial class AboutThisApp1ListPage : Page
    {
	    public ListViewModel ViewModel { get; set; }

        private DataTransferManager _dataTransferManager;
		public static readonly DependencyProperty HtmlContentProperty =
            DependencyProperty.Register("HtmlContent", typeof(string), typeof(AboutThisApp1ListPage), new PropertyMetadata(string.Empty));
        public AboutThisApp1ListPage()
        {
			this.ViewModel = ListViewModel.CreateNew(Singleton<AboutThisApp1Config>.Instance);

            this.InitializeComponent();

        }

        public string HtmlContent
        {
            get { return (string)GetValue(HtmlContentProperty); }
            set { SetValue(HtmlContentProperty, value); }
        }

        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            await this.ViewModel.LoadDataAsync();
			if (ViewModel.Items != null && ViewModel.Items.Count > 0)
			{
                HtmlContent = ViewModel.Items[0].Content;
            }
            _dataTransferManager = DataTransferManager.GetForCurrentView();
            _dataTransferManager.DataRequested += OnDataRequested;

            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            _dataTransferManager.DataRequested -= OnDataRequested;

            base.OnNavigatedFrom(e);
        }

        private void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs args)
        {
            ViewModel.ShareContent(args.Request);
        }
    }
}


package domain

import (
	"encoding/json"
	"flag"
	"fmt"
	"path/filepath"
	"testing"
	"time"

	"go-common/app/interface/main/app-resource/conf"

	. "github.com/smartystreets/goconvey/convey"
)

var (
	s *Service
)

func WithService(f func(s *Service)) func() {
	return func() {
		f(s)
	}
}

func init() {
	dir, _ := filepath.Abs("../../cmd/app-resource-test.toml")
	flag.Set("conf", dir)
	conf.Init()
	s = New(conf.Conf)
	time.Sleep(time.Second)
}

func TestDomain(t *testing.T) {
	Convey("get Domain data", t, WithService(func(s *Service) {
		res := s.Domain()
		result, _ := json.Marshal(res)
		fmt.Printf("test Domain (%v) \n", string(result))
		So(res, ShouldNotBeEmpty)
	}))
}


<?php
/**
 * vpopqmail
 *
 * @license http://opensource.org/licenses/MIT MIT
 */

interface MazelabVpopqmail_Model_Dataprovider_Interface_MailingList
{

    /**
     * deletes a certain mailing list
     *
     * @param MazelabVpopqmail_Model_ValueObject_MailingList $mailingList
     * @return boolean
     */
    public function deleteMailingList(MazelabVpopqmail_Model_ValueObject_MailingList $mailingList);

    /**
     * returns content of mailing list from given id
     *
     * @param string $id
     * @return array
     */
    public function getMailingList($id);

    /**
     * returns content of mailing list from given email
     *
     * @param string $email
     * @return array
     */
    public function getMailingListByEmail($email);

    /**
     * get all mailing lists
     *
     * @return array
     */
    public function getMailingLists();

    /**
     * returns all mailing lists of a certain domain
     *
     * @param string $id
     * @return array
     */
    public function getMailingListsByDomain($domainId);

    /**
     * saves given data set to a certain mailing list
     *
     * if id is not provided, it will create a new item
     *
     * @param string $mailingListId
     * @param array $data
     * @return string|false id of saved item
     */
    public function saveMailingList(array $data, $mailingListId = null);

}


#ifndef ALINOUS_RUNTIME_PARALLEL_CONCURRENTTASKEXEXUTOR_H_
#define ALINOUS_RUNTIME_PARALLEL_CONCURRENTTASKEXEXUTOR_H_
namespace alinous{namespace annotation{
class OneSource;
}}
namespace alinous {namespace runtime {namespace parallel {
class ThreadPool;}}}

namespace alinous {namespace runtime {namespace parallel {
class LaunchJoin;}}}

namespace alinous {namespace runtime {namespace parallel {
class IParallelTask;}}}

namespace alinous {namespace runtime {namespace parallel {
class ConcurrentTaskQueue;}}}

namespace java {namespace lang {
class InterruptedException;}}

namespace java {namespace util {
template <typename  T> class LinkedList;}}

namespace alinous {namespace lock {
class LockObject;}}

namespace alinous {namespace runtime {namespace parallel {
class AlinousThread;}}}

namespace alinous {namespace runtime {namespace parallel {
class ConcurrentTaskExexutor;}}}

namespace alinous {namespace runtime {namespace parallel {
class IThreadAction;}}}

namespace java {namespace lang {
class IObject;
}}

namespace alinous {
class ThreadContext;
}

namespace alinous {namespace runtime {namespace parallel {

using namespace ::alinous;
using namespace ::java::lang;
using ::java::util::Iterator;
using ::java::util::LinkedList;
using ::alinous::lock::LockObject;

class ConcurrentTaskExexutor final : public virtual IObject {
public:
	class FinalyzerEntryPoint;
	class LauncherEntryPoint;
	ConcurrentTaskExexutor(const ConcurrentTaskExexutor& base) = default;
public:
	ConcurrentTaskExexutor(ThreadPool* pool, ThreadContext* ctx) throw() ;
	void __construct_impl(ThreadPool* pool, ThreadContext* ctx) throw() ;
	virtual ~ConcurrentTaskExexutor() throw();
	virtual void __releaseRegerences(bool prepare, ThreadContext* ctx) throw();
private:
	LinkedList<ConcurrentTaskQueue>* queue;
	LinkedList<ConcurrentTaskQueue>* readyQueue;
	LockObject* sync;
	AlinousThread* finalizer;
	LaunchJoin* finalizerLaunchJoin;
	AlinousThread* launcher;
	LaunchJoin* launcherLaunchJoin;
	bool finalizerEnds;
	ConcurrentTaskQueue* lastTask;
	ThreadPool* pool;
public:
	void begin(ThreadContext* ctx);
	void startTask(IParallelTask* task, ThreadContext* ctx) throw() ;
	void flush(ThreadContext* ctx);
	void dispose(ThreadContext* ctx) throw() ;
private:
	void finalizeLoop(ThreadContext* ctx);
	void launcherLoop(ThreadContext* ctx);
	void asyncStart(ThreadContext* ctx);
public:

	class FinalyzerEntryPoint final : public IThreadAction, public virtual IObject {
	public:
		FinalyzerEntryPoint(const FinalyzerEntryPoint& base) = default;
	public:
		FinalyzerEntryPoint(ConcurrentTaskExexutor* exec, ThreadContext* ctx) throw() ;
		void __construct_impl(ConcurrentTaskExexutor* exec, ThreadContext* ctx) throw() ;
		virtual ~FinalyzerEntryPoint() throw();
		virtual void __releaseRegerences(bool prepare, ThreadContext* ctx) throw();
	private:
		ConcurrentTaskExexutor* executor;
	public:
		void execute(ThreadContext* ctx) throw()  final;
	public:
		static bool __init_done;
		static bool __init_static_variables();
	public:
		static void __cleanUp(ThreadContext* ctx);
	};

	class LauncherEntryPoint final : public IThreadAction, public virtual IObject {
	public:
		LauncherEntryPoint(const LauncherEntryPoint& base) = default;
	public:
		LauncherEntryPoint(ConcurrentTaskExexutor* exec, ThreadContext* ctx) throw() ;
		void __construct_impl(ConcurrentTaskExexutor* exec, ThreadContext* ctx) throw() ;
		virtual ~LauncherEntryPoint() throw();
		virtual void __releaseRegerences(bool prepare, ThreadContext* ctx) throw();
	private:
		ConcurrentTaskExexutor* exec;
	public:
		void execute(ThreadContext* ctx) throw()  final;
	public:
		static bool __init_done;
		static bool __init_static_variables();
	public:
		static void __cleanUp(ThreadContext* ctx);
	};

	static bool __init_done;
	static bool __init_static_variables();
public:
	static void __cleanUp(ThreadContext* ctx);
};

}}}

#endif /* end of ALINOUS_RUNTIME_PARALLEL_CONCURRENTTASKEXEXUTOR_H_ */


layout: post
title: Insertion sort on small arrays in merge sort
date: 2015-08-30 15:04
tags: CLRS Algorithms
---

2.1 Although merge sort runs in $$\Theta(n \lg n)$$ worst-case time and isnertion sort runs in $$\Theta(n^2)$$ worst-case time, the constant factors in insertion sort can make it faster in practice for small problem sizes on many machines. Thus, it makes sense to coarsen the leaves of the recursion by using insertion sort within merge sort when subproblems become sufficiently small. Consider a modification to merge sort in which $$n/k$$ sublists of length $$k$$ are sorted using insertion sort and then merged using the standard merging mechanism, where $$k$$ is a value to be determined.

1. Show that insertion sort can sort the $$n/k$$ sublists, each of length $$k$$, in $$\Theta(nk)$$ worst-case time.
We know that insertion sort runs in $$\Theta(n^2)$$ time where $$n$$ is the size of the list. Thus when the list is of size $$k$$, the worst case time is $$\Theta(k^2)$$. Repeating this $$n/k$$ times (once for each of the $$n/k$$ sublists), we get $$n/k\Theta(k^2)=\Theta(nk)$$.

2. Show how to merge the sublists in $$\Theta(n\lg(n/k))$$ worst-case time.
We merge sublists the exact same way as we did in regular mergesort. As before, there are $$n$$ elements at each level. Thus the merges cost $$\Theta(n)$$ at each level. To see how many levels there are we note that recursion bottoms out when the size of the list is less than $$k$$, thus the number of levels, $$l$$, satisfies $$n(\frac{1}{2}^l)\leq k \Rightarrow n\leq k2^l \Rightarrow n/k \leq 2^l \Rightarrow \lg(n/k) \leq l$$. Therefore $$l = \lceil\lg(n/k)\rceil$$ and we can merge sublists in $$\Theta(n\lg(n/k))$$ worst-case time.

3. Given that the modified algorithm runs in $$\Theta(nk + n\lg(n/k))$$ worst-case time, what is the largest value of $$k$$ as a function of $$n$$ for which the modified algorithm has the same running time as standard merge sort, in terms of $$\Theta$$ notation?
Merge sort runs in $$\Theta(n\lg n)$$ time. Thus for the modified algorithm to have a asymptotically faster run time, $$\Theta(nk + n\lg(n/k)) < \Theta(n\lg n) \Rightarrow max(nk, n\lg(n/k)) < n\lg n$$, we must have $$nk < n\lg n$$ and $$n\lg(n/k) < n\lg n$$. Therefore, $$1 < k < \lg n$$.
As $$nk$$ strictly increases with $$k$$ and $$n\lg(n/k)$$ strictly decreases with $$k$$, the lowest asymptotic running time occurs when $$k$$ is such that $$nk = n\lg(n/k)$$.

{% highlight python %}

def merge(left, right):
    ''' as before this function merges two lists, producing a new one '''
    sorted_keys  = list()
    while True:
        try:
            left_top = left[0]
            right_top = right[0]
        except IndexError:
            sorted_keys += left + right
            return sorted_keys
        if left_top < right_top:
            sorted_keys.append(left.pop(0))
        else:
            sorted_keys.append(right.pop(0))

def insertion_sort(keys):
    ''' in place insertion sort '''
    for i in xrange(1,len(keys)):
        value = keys[i]
        j = i - 1
        while j >= 0 and keys[j] > value:
            keys[j + 1] = keys[j]
            j -= 1
        keys[j + 1] = value

def modified_merge_sort(keys, k):
    if len(keys) <= k:
        insertion_sort(keys)
        return keys
    else:
        midpoint = len(keys) / 2
        left = modified_merge_sort(keys[:midpoint], k)
        right = modified_merge_sort(keys[midpoint:], k)
        return merge(left, right)

{% endhighlight %}


/* ########## PARA VISUALIZAR Y REGISTRAR PUBLICACIONES ########## */

/*Estilo en el título (centrar el texto)*/
.title-style{
	text-align: center;
}

/*Color para icono de borrado en autores*/
.btn-delete-color{
	color: #d9534f;
}

/*Espaciado superior e inferior en mensaje de alerta (no hay resultados de autor)*/
.spacing-text-alert{
	margin-top: 10px;
	margin-bottom: 10px;
}

/*Margen, espaciado y color para el formulario "Registrar autor"*/
.subform-autor{
	background-color: #dedede;
	padding: 15px;
	margin-bottom: 1em;
}

/*Decoración de fondo en cada año*/
.blockquote-decoration{
	border-left: 5px solid #666;
	background-color: #ddd;
}

/*Espacio para mostrar publicación con imagen
Se emplean publication-container, publication-cover y publication-info*/
.publication-container{ /*contenedor principal*/
	height: 305px;
	width: 100%;
	margin-bottom: 20px;
	position: relative; /*para alinear texto posteriormente*/
}
.publication-cover{ /*espacio para portada*/
	height: 100%;
	width: 100%;
	overflow: hidden;
	display: flex;
	justify-content: center;
	align-items: center;
	background-color: #333;
}
.publication-cover img{
	width: 100%;
}
.publication-info{ /*espacio para texto*/
	height: 30%;
	width: 100%;
	position: absolute;
	bottom: 0;
	font-size: 1.2em;
	text-align: center;
	background-color: rgba(0,0,0,0.5);
	color: #eee;
}

/*Definir tamaños, espacios y alineación de cada recuardo.
También se define el tamaño individual del título, autor, fecha*/
.publication-thumbnail{
	height: 305px;
	width: 100%;
	padding: 1em;
	margin: auto;
	margin-bottom: 20px;
	text-align: center;
}
.publication-title{
	font-size: 1.3em;
	font-weight: bold;
}
.publication-autor{
	font-size: 1em;
}
.publication-date{
	font-size: 1.2em;
}

/*Color de fondo y de texto si la publicación es un ARTICULO*/
.color-article{
	background: #133175;
	background: -webkit-linear-gradient(#133175, #0E4671);
	background: -o-linear-gradient(#133175, #0E4671);
	background: -moz-linear-gradient(#133175, #0E4671);
	background: linear-gradient(#133175, #0E4671);
}
.color-article-title{
	color: #F0A32F;
}
.color-article-autor{
	color: #FFF;
}
.color-article-date{
	color: #BBB;
}

/*Color de fondo y de texto si la publicación es un LIBRO*/
.color-book{
	background: #19197B;
	background: -webkit-linear-gradient(#19197B, #132F76);
	background: -o-linear-gradient(#19197B, #132F76);
	background: -moz-linear-gradient(#19197B, #132F76);
	background: linear-gradient(#19197B, #132F76);
}
.color-book-title{
	color: #F0A32F;
}
.color-book-autor{
	color: #FFF;
}
.color-book-date{
	color: #BBB;
}

/*Color de fondo y de texto si la publicación es un DOCUMENTAL*/
.color-documentary{
	background: #0E4671;
	background: -webkit-linear-gradient(#0E4671, #07666A);
	background: -o-linear-gradient(#0E4671, #07666A);
	background: -moz-linear-gradient(#0E4671, #07666A);
	background: linear-gradient(#0E4671, #07666A);
}
.color-documentary-title{
	color: #F0A32F;
}
.color-documentary-autor{
	color: #FFF;
}
.color-documentary-date{
	color: #BBB;
}

/*Color de fondo y de texto si la publicación es una PONENCIA*/
.color-lecture{
	background: #2C1479;
	background: -webkit-linear-gradient(#2C1479, #1B197A);
	background: -o-linear-gradient(#2C1479, #1B197A);
	background: -moz-linear-gradient(#2C1479, #1B197A);
	background: linear-gradient(#2C1479, #1B197A);
}
.color-lecture-title{
	color: #F0A32F;
}
.color-lecture-autor{
	color: #FFF;
}
.color-lecture-date{
	color: #BBB;
}

/*Color de fondo y de texto si la publicación es una PAGINA WEB*/
.color-website{
	background: #076969;
	background: -webkit-linear-gradient(#076969, #07774A);
	background: -o-linear-gradient(#076969, #07774A);
	background: -moz-linear-gradient(#076969, #07774A);
	background: linear-gradient(#076969, #07774A);
}
.color-website-title{
	color: #F0A32F;
}
.color-website-autor{
	color: #FFF;
}
.color-website-date{
	color: #BBB;
}

/*Color de fondo y de texto si la publicación no tiene un tipo definido*/
.color-default{
	background: #666;
	background: -webkit-linear-gradient(#666, #999);
	background: -o-linear-gradient(#666, #999);
	background: -moz-linear-gradient(#666, #999);
	background: linear-gradient(#666, #999);
}
.color-default-title{
	color: #EEE;
}
.color-default-autor{
	color: #FFF;
}
.color-default-date{
	color: #BBB;
}

/*Cada una de las propiedades de la publicación (en tamaño xs)*/
.row-property{
	margin-bottom: 0.5em;
	margin-top: 0.5em;
	padding-top: 0.5em;
	border-top-style: solid;
	border-top-color: rgba(0,0,0,0.1);
	border-top-width: 1px;
}
/*Imagen responsiva (max-width: 100% está en estilo de <img>)*/
.imagen-portada{
	max-height: 400px;
}

/*Estilo a usar en tamaño sm, md, lg*/
@media screen and (min-width: 768px){
	/*Se disminuye ligeramente el tamaño de fuente*/
	.publication-title{
		font-size: 1.2em;
	}
	.publication-autor{
		font-size: 0.9em;
	}
	.publication-date{
		font-size: 1em;
	}
}


package net.systran.platform.resources.client.model;

import net.systran.platform.resources.client.model.LiteCorpus;

import io.swagger.annotations.*;
import com.fasterxml.jackson.annotation.JsonProperty;

@ApiModel(description = "")
public class CorpusImportResponse  {

  private LiteCorpus corpus = null;

  /**
   **/
  @ApiModelProperty(required = true, value = "")
  @JsonProperty("corpus")
  public LiteCorpus getCorpus() {
    return corpus;
  }
  public void setCorpus(LiteCorpus corpus) {
    this.corpus = corpus;
  }

  @Override
  public String toString()  {
    StringBuilder sb = new StringBuilder();
    sb.append("class CorpusImportResponse {\n");

    sb.append("  corpus: ").append(corpus).append("\n");
    sb.append("}\n");
    return sb.toString();
  }
}


<?php

namespace Drupal\commerce\Element;

use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;

/**
 * Provides a trait for Commerce form elements.
 *
 * Allows form elements to use #commerce_element_submit, a substitute
 * for the #element_submit that's missing from Drupal core.
 *
 * Each form element using this trait should add the attachElementSubmit and
 * validateElementSubmit callbacks to their getInfo() methods.
 */
trait CommerceElementTrait {

  /**
   * Attaches the #commerce_element_submit functionality.
   *
   * @param array $element
   *   The form element being processed.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   * @param array $complete_form
   *   The complete form structure.
   *
   * @return array
   *   The processed form element.
   */
  public static function attachElementSubmit(array $element, FormStateInterface $form_state, array &$complete_form) {
    if (isset($complete_form['#commerce_element_submit_attached'])) {
      return $element;
    }
    // The #validate callbacks of the complete form run last.
    // That allows executeElementSubmitHandlers() to be completely certain that
    // the form has passed validation before proceeding.
    $complete_form['#validate'][] = [get_class(), 'executeElementSubmitHandlers'];
    $complete_form['#commerce_element_submit_attached'] = TRUE;

    return $element;
  }

  /**
   * Confirms that #commerce_element_submit handlers can be run.
   *
   * @param array $element
   *   The form element.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @throws \Exception
   *   Thrown if button-level #validate handlers are detected on the parent
   *   form, as a protection against buggy behavior.
   */
  public static function validateElementSubmit(array &$element, FormStateInterface $form_state) {
    // Button-level #validate handlers replace the form-level ones, which means
    // that executeElementSubmitHandlers() won't be triggered.
    if ($handlers = $form_state->getValidateHandlers()) {
      throw new \Exception('The current form must not have button-level #validate handlers');
    }
  }

  /**
   * Submits elements by calling their #commerce_element_submit callbacks.
   *
   * Form API has no #element_submit, requiring us to simulate it by running
   * the #commerce_element_submit handlers either in the last step of
   * validation, or the first step of submission. In this case it's the last
   * step of validation, allowing thrown exceptions to be converted into form
   * errors.
   *
   * @param array &$form
   *   The form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   */
  public static function executeElementSubmitHandlers(array &$form, FormStateInterface $form_state) {
    if (!$form_state->isSubmitted() || $form_state->hasAnyErrors()) {
      // The form wasn't submitted (#ajax in progress) or failed validation.
      return;
    }
    // A submit button might need to process only a part of the form.
    // For example, the "Apply coupon" button at checkout should apply coupons,
    // but not save the payment information. Use #limit_validation_errors
    // as a guideline for which parts of the form to submit.
    $triggering_element = $form_state->getTriggeringElement();
    if (isset($triggering_element['#limit_validation_errors']) && $triggering_element['#limit_validation_errors'] !== FALSE) {
      // #limit_validation_errors => [], the button cares about nothing.
      if (empty($triggering_element['#limit_validation_errors'])) {
        return;
      }

      foreach ($triggering_element['#limit_validation_errors'] as $limit_validation_errors) {
        $element = NestedArray::getValue($form, $limit_validation_errors);
        if (!$element) {
          // The element will be empty if #parents don't match #array_parents,
          // the case for IEF widgets. In that case just submit everything.
          $element = &$form;
        }
        self::doExecuteSubmitHandlers($element, $form_state);
      }
    }
    else {
      self::doExecuteSubmitHandlers($form, $form_state);
    }
  }

  /**
   * Calls the #commerce_element_submit callbacks recursively.
   *
   * @param array &$element
   *   The current element.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   */
  public static function doExecuteSubmitHandlers(array &$element, FormStateInterface $form_state) {
    // Recurse through all children.
    foreach (Element::children($element) as $key) {
      if (!empty($element[$key])) {
        static::doExecuteSubmitHandlers($element[$key], $form_state);
      }
    }

    // If there are callbacks on this level, run them.
    if (!empty($element['#commerce_element_submit'])) {
      foreach ($element['#commerce_element_submit'] as $callback) {
        call_user_func_array($callback, [&$element, &$form_state]);
      }
    }
  }

}


package com.google.devtools.j2objc;

import com.google.devtools.j2objc.util.ErrorUtil;
import com.google.devtools.j2objc.util.JdtParser;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Translation tool for generating Objective C source files from Java sources.
 * This tool is not intended to be a general purpose converter, but instead is
 * focused on what is needed for business logic libraries written in Java to
 * run natively on iOS.  In particular, no attempt is made to translate Java
 * UI framework code to any iOS frameworks.
 *
 * @author Tom Ball
 */
public class J2ObjC {

  static {
    // Always enable assertions in translator.
    ClassLoader loader = J2ObjC.class.getClassLoader();
    if (loader != null) {
      loader.setPackageAssertionStatus(J2ObjC.class.getPackage().getName(), true);
    }
  }

  private static final Logger logger = Logger.getLogger(J2ObjC.class.getName());

  private static void exit() {
    Options.deleteTemporaryDirectory();
    System.exit(ErrorUtil.errorCount());
  }

  public static String getFileHeader(String sourceFileName) {
    return String.format(Options.getFileHeader(), sourceFileName);
  }

  private static class JarFileLoader extends URLClassLoader {
    public JarFileLoader() {
      super(new URL[]{});
    }

    public void addJarFile(String path) throws MalformedURLException {
      String urlPath = "jar:file://" + path + "!/";
      addURL(new URL(urlPath));
    }
  }

  private static void initPlugins(String[] pluginPaths, String pluginOptionString)
      throws IOException {
    @SuppressWarnings("resource")
    JarFileLoader classLoader = new JarFileLoader();
    for (String path : pluginPaths) {
      if (path.endsWith(".jar")) {
        JarInputStream jarStream = null;
        try {
          jarStream = new JarInputStream(new FileInputStream(path));
          classLoader.addJarFile(new File(path).getAbsolutePath());

          JarEntry entry;
          while ((entry = jarStream.getNextJarEntry()) != null) {
            String entryName = entry.getName();
            if (!entryName.endsWith(".class")) {
              continue;
            }

            String className = entryName.replaceAll("/", "\\.").substring(
                0, entryName.length() - ".class".length());

            try {
              Class<?> clazz = classLoader.loadClass(className);
              if (Plugin.class.isAssignableFrom(clazz)) {
                Constructor<?> cons = clazz.getDeclaredConstructor();
                Plugin plugin = (Plugin) cons.newInstance();
                plugin.initPlugin(pluginOptionString);
                Options.getPlugins().add(plugin);
              }
            } catch (Exception e) {
              throw new IOException("plugin exception: ", e);
            }
          }
        } finally {
          if (jarStream != null) {
            jarStream.close();
          }
        }
      } else {
        logger.warning("Don't understand plugin path entry: " + path);
      }
    }
  }

  public static void error(Exception e) {
    logger.log(Level.SEVERE, "Exiting due to exception", e);
    System.exit(1);
  }

  private static void checkErrors() {
    int errors = ErrorUtil.errorCount();
    if (Options.treatWarningsAsErrors()) {
      errors += ErrorUtil.warningCount();
    }
    if (errors > 0) {
      System.exit(1);
    }
  }

  private static JdtParser createParser() {
    JdtParser parser = new JdtParser();
    parser.addClasspathEntries(Options.getClassPathEntries());
    parser.addClasspathEntries(Options.getBootClasspath());
    parser.addSourcepathEntries(Options.getSourcePathEntries());
    parser.setIncludeRunningVMBootclasspath(false);
    parser.setEncoding(Options.fileEncoding());
    parser.setIgnoreMissingImports(Options.ignoreMissingImports());
    parser.setEnableDocComments(Options.docCommentsEnabled());
    return parser;
  }

  /**
   * Entry point for tool.
   *
   * @param args command-line arguments: flags and source file names
   * @throws IOException
   */
  public static void main(String[] args) {
    if (args.length == 0) {
      Options.help(true);
    }
    String[] files = null;
    try {
      files = Options.load(args);
      if (files.length == 0) {
        Options.usage("no source files");
      }
    } catch (IOException e) {
      ErrorUtil.error(e.getMessage());
      System.exit(1);
    }

    try {
      initPlugins(Options.getPluginPathEntries(), Options.getPluginOptionString());
    } catch (IOException e) {
      error(e);
    }

    JdtParser parser = createParser();

    // Remove dead-code first, so modified file paths are replaced in the
    // translation list.
    DeadCodeProcessor deadCodeProcessor = DeadCodeProcessor.create(parser);
    if (deadCodeProcessor != null) {
      deadCodeProcessor.processFiles(Arrays.asList(files));
      checkErrors();
      files = deadCodeProcessor.postProcess().toArray(new String[0]);
    }

    TranslationProcessor translationProcessor = new TranslationProcessor(parser);
    translationProcessor.processFiles(Arrays.asList(files));
    translationProcessor.postProcess();
    checkErrors();

    exit();
  }
}


//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.1
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace ScrimpNet.Presentation.Demo.Properties {

    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")]
    internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {

        private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

        public static Settings Default {
            get {
                return defaultInstance;
            }
        }
    }
}


![Argüman.org](http://arguman.org/static/img/logo.png)
----
[Arguman.org](http://arguman.org) is an argument analysis and [mapping](https://en.wikipedia.org/wiki/Argument_map) platform.

## How it works

Users assert contentions to be discussed, supported, prooved or disprooved and argue with premises using because, but, or however conjuctions.

![image](https://cloud.githubusercontent.com/assets/182906/10586355/674acef0-76a4-11e5-9902-3dd7184cb0b3.png)

## Benefits

Critical thinking is the intellectually disciplined process of actively and skillfully conceptualizing, applying, analyzing, synthesizing, and/or evaluating information gathered from, or generated by, observation, experience, reflection, reasoning, or communication, as a guide to belief and action. In its exemplary form, it is based on universal intellectual values that transcend subject matter divisions: clarity, accuracy, precision, consistency, relevance, sound evidence, good reasons, depth, breadth, and fairness.

Basis of critical thinking is arguments. Assesment is done over  argument, argument premises, promotives and corruptives.

You may think argument mappings as visual hierarchy mappings.

Arguman.org’s aim is arguments to be mapped successfully by many users.

![](https://upload.wikimedia.org/wikipedia/commons/thumb/9/99/Whatley.png/800px-Whatley.png)

## Who are we

arguman.org is an open source project which developed by community, If you want to contribute technically or intellectually please don’t hesitate.

### Contributors

- Fatih Erikli
- Tuna Vargı
- Huseyin Mert
- Erdem Ozkol
- Aybars Badur
- Can Göktaş
- Bahattin Çiniç
- Murat Çorlu
- Cumhur Korkut
- Serdar Dalgıç
- Emir Karşıyakalı
- Ali Barın
- Halil Kaya
- A. Liva Cengiz
- Çağlar Bozkurt

## Additionally Thanks To

- Burak Arıkan
- Kadir Akkara Yardımcı


#ifndef RMLUI_CORE_LAYOUTLINEBOX_H
#define RMLUI_CORE_LAYOUTLINEBOX_H

#include "LayoutInlineBox.h"

namespace Rml {

class LayoutBlockBox;

/**
	@author Peter Curry
 */

class LayoutLineBox
{
public:
	LayoutLineBox(LayoutBlockBox* parent);
	~LayoutLineBox();

	/// Closes the line box, positioning all inline elements within it.
	/// @param overflow[in] The overflow box from a split inline box that caused this line to close. Leave this as nullptr if we closed naturally.
	/// @return If there was any overflow, this will be the last element generated by the spilling content. Otherwise, this will be nullptr.
	LayoutInlineBox* Close(UniquePtr<LayoutInlineBox> overflow = nullptr);

	/// Closes one of the line box's inline boxes.
	/// @param inline_box[in] The inline box to close. This should always be the line box's open box.
	void CloseInlineBox(LayoutInlineBox* inline_box);

	/// Attempts to add a new element to this line box. If it can't fit, or needs to be split, new line boxes will
	/// be created. The inline box for the final section of the element will be returned.
	/// @param element[in] The element to fit into this line box.
	/// @param box[in] The element's extents.
	/// @return The inline box for the element.
	LayoutInlineBox* AddElement(Element* element, const Box& box);

	/// Attempts to add a new inline box to this line. If it can't fit, or needs to be split, new line boxes will
	/// be created. The inline box for the final section of the element will be returned.
	/// @param box[in] The inline box to be added to the line.
	/// @return The final inline box.
	LayoutInlineBox* AddBox(UniquePtr<LayoutInlineBox> box);
	/// Adds an inline box as a chained hierarchy overflowing to this line. The chain will be extended into
	/// this line box.
	/// @param split_box[in] The box overflowed from a previous line.
	void AddChainedBox(LayoutInlineBox* chained_box);

	/// Returns the position of the line box, relative to its parent's block box's content area.
	/// @return The position of the line box.
	Vector2f GetPosition() const;
	/// Returns the position of the line box, relative to its parent's block box's offset parent.
	/// @return The relative position of the line box.
	Vector2f GetRelativePosition() const;
	/// Returns the dimensions of the line box.
	/// @return The dimensions of the line box.
	Vector2f GetDimensions() const;

	/// Returns the line box's open inline box.
	/// @return The line's open inline box, or nullptr if it currently has none.
	LayoutInlineBox* GetOpenInlineBox();
	/// Returns the line's containing block box.
	/// @return The line's block box.
	LayoutBlockBox* GetBlockBox();

	float GetBoxCursor() const;

	bool GetBaselineOfLastLine(float& baseline) const;

	void* operator new(size_t size);
	void operator delete(void* chunk, size_t size);

private:
	/// Appends an inline box to the end of the line box's list of inline boxes. Returns a pointer to the appended box.
	LayoutInlineBox* AppendBox(UniquePtr<LayoutInlineBox> box);

	using InlineBoxList = Vector< UniquePtr<LayoutInlineBox> >;

	// The block box containing this line.
	LayoutBlockBox* parent;

	// The top-left position of the line box; this is set when the first inline box is placed.
	Vector2f position;
	bool position_set;

	// The width and height of the line box; this is set when the line box is placed.
	Vector2f dimensions;
	bool wrap_content;

	// The horizontal cursor. This is where the next inline box will be placed along the line.
	float box_cursor;

	// The list of inline boxes in this line box. These line boxes may be parented to others in this list.
	InlineBoxList inline_boxes;
	// The open inline box; this is nullptr if all inline boxes are closed.
	LayoutInlineBox* open_inline_box;
};

} // namespace Rml
#endif


package me.tikitoo.androiddemo.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

import me.tikitoo.androiddemo.R;
import me.tikitoo.androiddemo.view.DrawView;

/**
 * Created by Tikitoo on 2015/12/22.
 */
public class DrawViewActivity extends Activity {

    private DrawView mDrawView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_view);
        mDrawView = (DrawView) findViewById(R.id.draw_view);
    }

    public void saveBtn(View view) {
        onSaveClicked(this, view);

    }

    public void onSaveClicked(final Context context, View view) {
        try {
            File file = new File(Environment.getExternalStorageDirectory(),
                    System.currentTimeMillis() + ".jpg");
            OutputStream outputStream = new FileOutputStream(file);
            mDrawView.saveBitmap(outputStream);
            outputStream.close();
/*
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_MEDIA_MOUNTED);
            intent.setData(Uri.fromFile(Environment.getExternalStorageDirectory()));
            sendBroadcast(intent);*/

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                Intent mediaScanIntent = new Intent(
                        Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri contentUri = Uri.fromFile(file);
                mediaScanIntent.setData(contentUri);
                this.sendBroadcast(mediaScanIntent);
            } else {
                sendBroadcast(new Intent(
                        Intent.ACTION_MEDIA_MOUNTED,
                        Uri.fromFile(Environment.getExternalStorageDirectory())));
            }
            showToast(context, "save success");
        } catch (Exception e) {
            showToast(context, "save failed");
            e.printStackTrace();
        }

    }

    private static void showToast(Context context, String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }

}