text:
<?php

namespace OpenCloud\Tests\ObjectStore\Resource;

use Guzzle\Http\Message\Response;
use OpenCloud\Common\Constants\Size;
use OpenCloud\Tests\ObjectStore\ObjectStoreTestCase;

class ContainerTest extends ObjectStoreTestCase
{
    private function getFilePath()
    {
        $path = '/tmp/php_sdk_test_file';
        if (!file_exists($path)) {
            file_put_contents($path, '.');
        }
        return $path;
    }

    public function test_Services()
    {
        $this->assertInstanceOf(
            'OpenCloud\ObjectStore\CDNService',
            $this->container->getCDNService()
        );
    }

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

        $this->assertEquals('foo', $container->getName());
        $this->assertEquals('5', $container->getObjectCount());
        $this->assertEquals('3846773', $container->getBytesUsed());
        $this->assertFalse($container->hasLogRetention());

        $cdn = $container->getCdn();
        $this->assertInstanceOf('OpenCloud\ObjectStore\Resource\CDNContainer', $cdn);
        $this->assertEquals('tx82a6752e00424edb9c46fa2573132e2c', $cdn->getTransId());
        $this->assertFalse($cdn->hasLogRetention());
        $this->assertTrue($cdn->isCdnEnabled());

        $this->assertEquals(
            'https://83c49b9a2f7ad18250b3-346eb45fd42c58ca13011d659bfc1ac1.ssl.cf0.rackcdn.com',
            $cdn->getCdnSslUri()
        );
        $this->assertEquals(
            'http://081e40d3ee1cec5f77bf-346eb45fd42c58ca13011d659bfc1ac1.r49.cf0.rackcdn.com',
            $cdn->getCdnUri()
        );
        $this->assertEquals('259200', $cdn->getTtl());
        $this->assertEquals(
            'http://084cc2790632ccee0a12-346eb45fd42c58ca13011d659bfc1ac1.r49.stream.cf0.rackcdn.com',
            $cdn->getCdnStreamingUri()
        );
    }

    /**
     * @expectedException OpenCloud\Common\Exceptions\NoNameError
     */
    public function test_Bad_Name_Url()
    {
        $container = $this->container;
        $container->name = '';

        $container->getUrl();
    }

    /**
     * @expectedException OpenCloud\Common\Exceptions\CdnNotAvailableError
     */
    public function test_NonCDN_Container()
    {
        $this->addMockSubscriber($this->makeResponse(null, 200));
        $this->addMockSubscriber($this->makeResponse(null, 404));

        $container = $this->service->getContainer('foo');
        $container->getCdn();
    }

    public function test_Delete()
    {
        $container = $this->container;
        $this->addMockSubscriber($this->makeResponse('[]', 200));
        $container->delete(true);
    }

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

        $this->addMockSubscriber($this->makeResponse('[{"name":"test_obj_1","hash":"4281c348eaf83e70ddce0e07221c3d28","bytes":14,"content_type":"application\/octet-stream","last_modified":"2009-02-03T05:26:32.612278"},{"name":"test_obj_2","hash":"b039efe731ad111bc1b0ef221c3849d0","bytes":64,"content_type":"application\/octet-stream","last_modified":"2009-02-03T05:26:32.612278"}]', 200));

        $list = $container->objectList();
        $this->assertInstanceOf(self::COLLECTION_CLASS, $list);
        $this->assertEquals('test_obj_1', $list->first()->getName());
    }

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

        $this->assertInstanceOf(
            'Guzzle\Http\Message\Response',
            $container->enableLogging()
        );

        $this->assertInstanceOf(
            'Guzzle\Http\Message\Response',
            $container->disableLogging()
        );

        $this->assertInstanceOf(
            'Guzzle\Http\Message\Response',
            $container->getCdn()->setStaticIndexPage('index.html')
        );

        $this->assertInstanceOf(
            'Guzzle\Http\Message\Response',
            $container->getCdn()->setStaticErrorPage('error.html')
        );

        $this->assertInstanceOf(
            'Guzzle\Http\Message\Response',
            $container->disableCdn()
        );

        $container->enableCdn(500);
    }

    public function test_Get_Object()
    {
        $this->addMockSubscriber($this->makeResponse('b0dffe8254d152d8fd28f3c5e0404a10'));
        $object = $this->container->getObject('foobar');

        $this->assertInstanceOf('OpenCloud\ObjectStore\Resource\DataObject', $object);
        $this->assertEquals(
            'b0dffe8254d152d8fd28f3c5e0404a10',
            (string) $object->getContent()
        );
        $this->assertEquals('foobar', $object->getName());
    }

    /**
     * @expectedException \OpenCloud\ObjectStore\Exception\ObjectNotFoundException
     */
    public function test_Get_Object_404()
    {
        $this->addMockSubscriber(new Response(404));
        $this->container->getObject('foobar');
    }

    /**
     * @expectedException \Guzzle\Http\Exception\BadResponseException
     */
    public function test_Get_Object_500()
    {
        $this->addMockSubscriber(new Response(500));
        $this->container->getObject('foobar');
    }

    /**
     * @expectedException OpenCloud\Common\Exceptions\InvalidArgumentError
     */
    public function test_Upload_Multiple_Fails_Without_Name()
    {
        $container = $this->container;
        $container->uploadObjects(array(
            array('path' => '/foo')
        ));
    }

    /**
     * @expectedException OpenCloud\Common\Exceptions\InvalidArgumentError
     */
    public function test_Upload_Multiple_Fails_With_No_Data()
    {
        $container = $this->container;
        $container->uploadObjects(array(
            array('name' => 'test', 'baz' => 'something')
        ));
    }

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

        $responses = $container->uploadObjects(array(
            array('name' => 'test', 'body' => 'FOOBAR')
        ));
        $this->assertInstanceOf('Guzzle\Http\Message\Response', $responses[0]);

        $container->uploadObjects(array(
            array('name' => 'test', 'path' => $this->getFilePath())
        ));
    }

    public function test_Upload()
    {
        $this->assertInstanceOf(
            'OpenCloud\ObjectStore\Resource\DataObject',
            $this->container->uploadObject('foobar', 'data')
        );
    }

    public function test_Large_Upload()
    {
        $options = array(
            'name' => 'new_object',
            'path' => $this->getFilePath(),
            'metadata' => array('author' => 'Jamie'),
            'partSize' => Size::MB * 20,
            'concurrency' => 3,
            'progress' => function($options) {
                var_dump($options);
            }
        );

        $container = $this->container;
        $container->setupObjectTransfer($options);
    }

    public function test_Large_Upload_With_Body()
    {
        $options = array(
            'name' => 'new_object',
            'body' => 'foo'
        );

        $container = $this->container;
        $container->setupObjectTransfer($options);
    }

    /**
     * @expectedException OpenCloud\Common\Exceptions\InvalidArgumentError
     */
    public function test_Large_Upload_Fails_Without_Name()
    {
        $options = array(
            'path' => '/foo'
        );

        $container = $this->container;
        $container->setupObjectTransfer($options);
    }

    /**
     * @expectedException OpenCloud\Common\Exceptions\InvalidArgumentError
     */
    public function test_Large_Upload_Fails_Without_Entity()
    {
        $options = array(
            'name' => 'new_object',
            'path' => '/' . rand(1,9999)
        );

        $container = $this->container;
        $container->setupObjectTransfer($options);
    }

    public function test_Metadata()
    {
        $metadata = $this->container->getMetadata();

        $this->assertEquals('Whaling', $metadata->getProperty('Subject'));
        $this->assertEquals(
            $this->container->getMetadata()->getProperty('Subject'),
            $metadata->getProperty('Subject')
        );

        $response = $this->container->unsetMetadataItem('Subject');
    }

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

        $this->assertInstanceOf('Guzzle\Http\Message\Response', $container->setCountQuota(50));
        $this->assertInstanceOf('Guzzle\Http\Message\Response', $container->setBytesQuota(50 * 1024));

        $this->assertEquals(50, $container->getCountQuota());
        $this->assertEquals(50 * 1024, $container->getBytesQuota());
    }

    /**
     * @mockFile Object_Metadata
     */
    public function test_Partial_Object()
    {
        $object = $this->container->getPartialObject('test.foo');

        $this->assertEquals('', (string) $object->getContent());
        $this->assertNotNull($object->getLastModified());
    }
}


text:
package org.apache.flink.streaming.performance.legacy.general;

import java.io.File;
import java.io.FileNotFoundException;

import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class WordCountPerformanceForwardMain {

	public static void main(String[] args) {

		if (args != null && args.length == 11) {
			try {
				boolean runOnCluster = args[0].equals("cluster");
				String sourcePath = args[1];
				String csvPath = args[2];
				String jarPath = args[3];
				String host = args[4];
				int port = Integer.valueOf(args[5]);

				if (!(new File(sourcePath)).exists()) {
					throw new FileNotFoundException();
				}

				int clusterSize = Integer.valueOf(args[6]);
				int sourceSize = Integer.valueOf(args[7]);
				int splitterSize = Integer.valueOf(args[8]);
				int counterSize = Integer.valueOf(args[9]);
				int sinkSize = Integer.valueOf(args[10]);

				StreamExecutionEnvironment env;
				if (runOnCluster) {
					env = StreamExecutionEnvironment.createRemoteEnvironment(
							host, port, clusterSize,
							jarPath);
				} else {
					env = StreamExecutionEnvironment.createLocalEnvironment(clusterSize);
				}

				@SuppressWarnings("unused")
				DataStream<Tuple2<String, Integer>> dataStream = env
						.readTextFile(sourcePath).setParallelism(sourceSize).forward()
						.flatMap(new WordCountPerformanceSplitter()).setParallelism(splitterSize)
							.groupBy(0)
						.map(new WordCountPerformanceCounter()).setParallelism(counterSize).forward()
						.addSink(new WordCountPerformanceSink(args, csvPath))
							.setParallelism(sinkSize);

				try {
					env.execute();
				} catch (Exception e) {
					e.printStackTrace();
				}
			} catch (NumberFormatException e) {
				printUsage();
			} catch (FileNotFoundException e) {
				printUsage();
			}
		} else {
			printUsage();
		}
	}

	private static void printUsage() {
		System.out
				.println("USAGE:\n run <local/cluster> <source path> <csv path> <jar path> <number of workers> <spout parallelism> <splitter parallelism> <counter parallelism> <sink parallelism>");
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php

declare(strict_types=1);

namespace Gmo\Beanstalk\Queue;

use Bolt\Common\Exception\ParseException;
use Bolt\Common\Serialization;
use Gmo\Beanstalk\Exception\JobPushException;
use Gmo\Beanstalk\Exception\JobTooBigException;
use Gmo\Beanstalk\Exception\RangeException;
use Gmo\Beanstalk\Job\Job;
use Gmo\Beanstalk\Job\NullJob;
use Gmo\Beanstalk\Job\UnserializableJob;
use Gmo\Beanstalk\Log\JobProcessor;
use Gmo\Beanstalk\Queue\Response\JobStats;
use Gmo\Beanstalk\Queue\Response\ServerStats;
use Gmo\Beanstalk\Queue\Response\TubeStats;
use Gmo\Beanstalk\Tube\Tube;
use Gmo\Beanstalk\Tube\TubeCollection;
use Pheanstalk;
use Psr\Log\LoggerAwareTrait;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;

/**
 * Queue manages jobs in tubes and provides stats about jobs.
 */
class Queue implements QueueInterface
{
    use LoggerAwareTrait;

    /** @var Pheanstalk\Pheanstalk */
    protected $pheanstalk;
    /** @var JobProcessor */
    protected $logProcessor;

    /**
     * Sets up a new Queue.
     *
     * @param string          $host
     * @param int             $port
     * @param LoggerInterface $logger [Optional] Default: NullLogger
     */
    public function __construct($host = 'localhost', $port = 11300, LoggerInterface $logger = null)
    {
        $this->setLogger($logger ?: new NullLogger());
        $this->pheanstalk = new Pheanstalk\Pheanstalk($host, $port);
        $this->logProcessor = new JobProcessor();
    }

    public function setJobProcessor(JobProcessor $processor): void
    {
        $this->logProcessor = $processor;
    }

    //region Tube Control

    public function push($tube, $data, $priority = null, $delay = null, $ttr = null)
    {
        $priority = $priority ?: static::DEFAULT_PRIORITY;
        if ($priority < 0 || $priority > 4294967295) {
            throw new RangeException("Priority must be between 0 and 4294967295. Given: $priority");
        }
        try {
            $data = Serialization::dump($data);

            return $this->pheanstalk->putInTube(
                $tube,
                $data,
                $priority,
                $delay ?: static::DEFAULT_DELAY,
                $ttr ?: static::DEFAULT_TTR
            );
        } catch (Pheanstalk\Exception $e) {
            if ($e->getMessage() === Pheanstalk\Response::RESPONSE_JOB_TOO_BIG) {
                throw new JobTooBigException($tube, $data, $e);
            }
            throw new JobPushException($tube, $data, $e);
        }
    }

    public function reserve($tube, $timeout = null, $stopWatching = false)
    {
        try {
            $job = $this->pheanstalk->reserveFromTube($tube, $timeout);
            if ($stopWatching) {
                $this->pheanstalk->watchOnly(Pheanstalk\PheanstalkInterface::DEFAULT_TUBE);
            }
            if (!$job) {
                $this->logProcessor->setCurrentJob(null);

                return new NullJob();
            }

            return $this->createJob($job);
        } catch (Pheanstalk\Exception\ClientException $e) {
            $this->logProcessor->setCurrentJob(null);

            return new NullJob();
        }
    }

    public function kickTube($tube, $num = -1)
    {
        $this->pheanstalk->useTube($tube);
        $kicked = 0;

        $stats = $this->statsTube($tube);
        if ($stats->buriedJobs() > 0) {
            $numToKick = $num > 0 ? min($num, $stats->buriedJobs()) : $stats->buriedJobs();
            $kicked += $this->pheanstalk->kick($numToKick);
            $num -= $numToKick;
            if ($num === 0) {
                return $kicked;
            }
        }
        $numToKick = $num > 0 ? $num : $stats->delayedJobs();
        $kicked += $this->pheanstalk->kick($numToKick);

        return $kicked;
    }

    public function peekJob($jobId)
    {
        try {
            $job = $this->pheanstalk->peek($jobId);
        } catch (Pheanstalk\Exception\ServerException $e) {
            return new NullJob();
        }

        return $this->createJob($job);
    }

    public function peekReady($tube)
    {
        return $this->peek($tube, 'Ready');
    }

    public function peekBuried($tube)
    {
        return $this->peek($tube, 'Buried');
    }

    public function peekDelayed($tube)
    {
        return $this->peek($tube, 'Delayed');
    }

    private function peek($tube, $state)
    {
        try {
            $job = $this->pheanstalk->{"peek$state"}($tube);
        } catch (Pheanstalk\Exception\ServerException $e) {
            return new NullJob();
        }

        return $this->createJob($job);
    }

    public function deleteReadyJobs($tube, $num = -1)
    {
        return $this->deleteJobs('Ready', $tube, $num);
    }

    public function deleteBuriedJobs($tube, $num = -1)
    {
        return $this->deleteJobs('Buried', $tube, $num);
    }

    public function deleteDelayedJobs($tube, $num = -1)
    {
        return $this->deleteJobs('Delayed', $tube, $num);
    }

    private function deleteJobs($state, $tube, $numberToDelete)
    {
        $numberDeleted = 0;
        while ($numberToDelete !== 0) {
            $job = $this->{"peek$state"}($tube);
            if ($this->isNullJob($job)) {
                break;
            }
            $this->delete($job);
            ++$numberDeleted;
            --$numberToDelete;
        }

        return $numberDeleted;
    }

    public function pause($tube, $delay)
    {
        $this->pheanstalk->pauseTube($tube, $delay);
    }

    /** @inheritdoc */
    public function statsTube($tube)
    {
        /** @var Pheanstalk\Response\ArrayResponse $response */
        $response = $this->pheanstalk->statsTube($tube);
        $stats = TubeStats::from($response);

        return $stats;
    }

    //endregion

    //region Job Control

    public function release(Job $job, $priority = null, $delay = null)
    {
        if ($this->isNullJob($job)) {
            return;
        }
        $priority = $priority ?: Pheanstalk\Pheanstalk::DEFAULT_PRIORITY;
        $delay = $delay ?: Pheanstalk\Pheanstalk::DEFAULT_DELAY;
        $this->pheanstalk->release($job, $priority, $delay);
    }

    public function bury(Job $job, $priority = null)
    {
        if ($this->isNullJob($job)) {
            return;
        }
        $priority = $priority ?: Pheanstalk\Pheanstalk::DEFAULT_PRIORITY;
        $this->pheanstalk->bury($job, $priority);
    }

    public function delete($job)
    {
        if ($this->isNullJob($job)) {
            return;
        }
        try {
            $this->pheanstalk->delete($job);
        } catch (Pheanstalk\Exception\ServerException $e) {
            $this->logger->notice('Error deleting job', ['exception' => $e]);
        }
    }

    public function kickJob($job)
    {
        if ($this->isNullJob($job)) {
            return;
        }
        $this->pheanstalk->kickJob($job);
    }

    /** @inheritdoc */
    public function statsJob($job)
    {
        try {
            /** @var Pheanstalk\Response\ArrayResponse $stats */
            $stats = $this->pheanstalk->statsJob($job);
        } catch (Pheanstalk\Exception\ServerException $e) {
            $stats = ['id' => -1];
        }

        return JobStats::from($stats);
    }

    public function touch(Job $job)
    {
        if ($this->isNullJob($job)) {
            return;
        }
        $this->pheanstalk->touch($job);
    }

    //endregion

    public function tube($name)
    {
        return new Tube($name, $this);
    }

    public function tubes()
    {
        $tubeNames = $this->pheanstalk->listTubes();
        sort($tubeNames);

        $tubes = new TubeCollection();
        foreach ($tubeNames as $name) {
            if ($name === Pheanstalk\PheanstalkInterface::DEFAULT_TUBE) {
                continue;
            }
            $tubes[$name] = new Tube($name, $this);
        }

        return $tubes;
    }

    /** @inheritdoc */
    public function statsAllTubes()
    {
        return $this->tubes()->map(function ($i, Tube $tube) {
            return $tube->stats();
        });
    }

    /** @inheritdoc */
    public function statsServer()
    {
        /** @var Pheanstalk\Response\ArrayResponse $stats */
        $stats = $this->pheanstalk->stats();

        return ServerStats::from($stats);
    }

    protected function createJob(Pheanstalk\Job $job)
    {
        try {
            $data = Serialization::parse($job->getData());
            $job = new Job($job->getId(), $data, $this);
        } catch (ParseException $e) {
            $job = new UnserializableJob($job->getId(), $job->getData(), $this, $e);
        }
        $this->logProcessor->setCurrentJob($job);

        return $job;
    }

    protected function isNullJob(Job $job)
    {
        return $job instanceof NullJob || $job->getId() === -1;
    }
}


text:
module Refinery
  module Reports
    class Image < Refinery::Core::BaseModel

      belongs_to :report

      attr_accessible :photo, :report_id, :photo_cache

      mount_uploader :photo, PhotoUploader
    end
  end
end


text:
from __future__ import absolute_import
from .sense_hat import SenseHat, SenseHat as AstroPi
from .stick import (
    SenseStick,
    InputEvent,
    DIRECTION_UP,
    DIRECTION_DOWN,
    DIRECTION_LEFT,
    DIRECTION_RIGHT,
    DIRECTION_MIDDLE,
    ACTION_PRESSED,
    ACTION_RELEASED,
    ACTION_HELD,
    )

__version__ = '2.2.0'


text:
package com.worldstream.client.conn;

import java.io.IOException;
import java.util.logging.Logger;

import com.worldstream.client.messages.Message;
import com.worldstream.client.messages.ServerMessage;

/**
 * Manages the connection between the client and the sever
 * @author Drem Darios
 *
 */
public class ConnectionManager
{
    private static final Logger LOG = Logger.getLogger("manager");
    /**
     * The connection between the server and client
     */
    private Connection connection;

    /**
     * Creates a new ConnectionManager to manage the connection
     * between the server and client. If the connection is not open already, this
     * will attempt to open the connection.
     *
     */
    public ConnectionManager(Connection connection)
    {
        this.connection = connection;
        if(!connection.isConnected())
        {
            try
            {
                connection.open();
            }
            catch (IOException e)
            {
                LOG.severe("Could not open connection.");
                e.printStackTrace();
            }
        }
    }

    /**
     * Sends a message to the server. To get the reply see getMessage()
     *
     * @param message - The message object holding the message to send
     */
    public void sendMessage(Message message)
    {
        ClientStream outputStream = connection.getStream();

        try
        {
            outputStream.write(message.getMessage());
        }
        catch (IOException e)
        {
            LOG.warning("Could not send message.");
            e.printStackTrace();
        }
    }

    /**
     * Returns the message from the server. If no request to the server has been
     * made, a blank message will be returned.
     *
     * @return The latest Message returned from the server
     */
    public Message getMessage()
    {
        ClientStream stream = connection.getStream();
        return new ServerMessage(stream.getReply());
    }

    /**
     * Closes the connection to the server.
     */
    public void closeConnection()
    {
        try
        {
            connection.close();
        }
        catch (IOException e)
        {
            LOG.severe("Could not close connection.");
            e.printStackTrace();
        }
    }
}


text:
# Example promise

Check the [code folder](https://github.com/MatthijsKamstra/haxejs/tree/master/docs/10promise/code) for more comments.

If you want an extra explanation about Promise just visite the [about](about.md) page.

_The code used in this example can be found [here](https://github.com/MatthijsKamstra/haxejs/tree/master/docs/10promise/code)._

## How to start

Create a folder named **foobar** (please use a better name; any name will do) and create folders **bin** and **src**.
See example below:

```
+ foobar
	+ bin
	+ src
        - Main.hx
	- build.hxml
```

## First example

This example is the first I would check out.
It's originally from: <https://www.toptal.com/javascript/javascript-promises>

The complete code for you to try (without installing Haxe):

    Try Haxe !

Because we copy/paste the original code from the example, we need to add two imports

```
import js.Browser.*;   // to make sure console.log works
import js.Promise;     // and the Promise
```

> The promise constructor takes one argument, a callback with two parameters, resolve and reject. Do something within the callback, perhaps async, then call resolve if everything worked, otherwise call reject. Like `throw` in plain old JavaScript, it's customary, but not required, to reject with an Error object.

```
var promise = new Promise(function(resolve, reject) {
    // do a thing, possibly async, then..
    if (/* everything turned out fine */) {
        resolve("Stuff worked!");
    } else {
        reject(Error("It broke"));
    }
});
```

And this is how to use the promise

```
promise.then(function(result) {
    console.log(result); // "Stuff worked!"
}, function(err) {
    console.log(err); // Error: "It broke"
});
```

You can always just [copy/paste](code/src/Main01.hx) the code into your favorite editor and save it in the `src` folder.

## Second example

This example is the next version of the first example
It's originally from: <https://www.toptal.com/javascript/javascript-promises>

    Try Haxe !

This example will let you roll (a maximum off) 3 times. If you roll a 6 it will stop rolling.
If not it will continue till it does. Unless you roll more then 3 times. Then it will just mention that you were not able to roll a 6.

The `tossASix` function creates the promise. And it will `fulfill` when `n` is a 6. Lower then a 6 will trigger a `reject`.

```
tossASix()
    .then(null, logAndTossAgain)   // Roll first time
    .then(null, logAndTossAgain)   // Roll second time
    .then(logSuccess, logFailure); // Roll third and last time
```

This is how we use the promise. The `tossASix` returns the promise. It's possible to chain a couple of `.then`.
In this example, if there is no `logSuccess` (`null`), the `logAndTossAgain` will create a promise again.
But if there is a `logSuccess` it will skip "then" and show that response.

You can always just [copy/paste](code/src/Main02.hx) the code into your favorite editor and save it in the `src` folder.

## Third example

This example is from: <https://developers.google.com/web/fundamentals/getting-started/primers/promises>
And the [Nasa Example](../06nasa/example.md)

    Try Haxe !

Usually you can just copy/paste pure JavaScript examples and with little to no adjustments it will work!

In this case it will not work:

```
get('story.json').then(function(response) {
    console.log("Success!", response);
}).catch(function(error) {
    console.log("Failed!", error);
});
```

`catch` is an Haxe keyword, so you can't use that.
So in this case `catch` is replace with `catchError`

```
getDataNASA(url).then(function(response) {
    console.log("Success!", response);
}).catchError(function(error) {
    console.error("Failed!", error);
});

```

Just remember that `.catchError` (or the original `.catch`) syntactic sugar is for `.then(null, function(error) {}) ... ` but more readable.

```
get('story.json').then(function(response) {
    console.log("Success!", response);
}).then(null, function(error) {
    console.log("Failed!", error);
});
```

Works the same.

The original example works a little bit different because it loads a local file, you can find that example [here](code/src/Main03.hx).

This example can be [copy/paste](code/src/Main.hx) into your favorite editor and save it in the `src` folder.

## index.html

the html is not that exciting, so we can keep that the same for all examples and check out the console info

```

<html>
<head>
	<title>Haxe JS - Promise example</title></head>
<body>

<!-- Your Haxe compiled script -->
<script type="text/javascript" src="example.js"></script>

</body>
</html>

```

## The Haxe build file, build.hxml

There are a lot of different arguments that you are able to pass to the Haxe compiler.
These arguments can also be placed into a text file of one per line with the extension hxml. This file can then be passed directly to the Haxe compiler as a build script.

```
# // build.hxml
-cp src
-main Main
-js bin/example.js
-dce full
```

## Build js with Haxe

To finish and see what we have, build the file and see the result

1. Open your terminal
2. `cd ` to the correct folder where you have saved the `build.hxml`
3. type `haxe build.hxml`
4. press enter

You could build everything directly in the terminal.

```
haxe -cp src -main Main -js bin/example.js -dce full
```

It will have the same result


text:
namespace {

// The avatar ends 2 px above the bottom of the tabstrip (which, given the
// way the tabstrip draws its bottom edge, will appear like a 1 px gap to the
// user).
const int kAvatarBottomSpacing = 2;
// There are 2 px on each side of the avatar (between the frame border and
// it on the left, and between it and the tabstrip on the right).
const int kAvatarSideSpacing = 2;
// Space between left edge of window and tabstrip.
const int kTabstripLeftSpacing = 0;
// Space between right edge of tabstrip and maximize button.
const int kTabstripRightSpacing = 10;
// Height of the shadow of the content area, at the top of the toolbar.
const int kContentShadowHeight = 1;
// Space between top of window and top of tabstrip for tall headers, such as
// for restored windows, apps, etc.
const int kTabstripTopSpacingTall = 7;
// Space between top of window and top of tabstrip for short headers, such as
// for maximized windows, pop-ups, etc.
const int kTabstripTopSpacingShort = 0;
// Height of the shadow in the tab image, used to ensure clicks in the shadow
// area still drag restored windows.  This keeps the clickable area large enough
// to hit easily.
const int kTabShadowHeight = 4;

// Space between right edge of tabstrip and caption buttons when using the
// alternate caption button style.
const int kTabstripRightSpacingAlternateCaptionButtonStyle = 0;
// Space between top of window and top of tabstrip for short headers when using
// the alternate caption button style.
const int kTabstripTopSpacingShortAlternateCaptionButtonStyle = 4;

}  // namespace

///////////////////////////////////////////////////////////////////////////////
// BrowserNonClientFrameViewAsh, public:

// static
const char BrowserNonClientFrameViewAsh::kViewClassName[] =
    "BrowserNonClientFrameViewAsh";

BrowserNonClientFrameViewAsh::BrowserNonClientFrameViewAsh(
    BrowserFrame* frame, BrowserView* browser_view)
    : BrowserNonClientFrameView(frame, browser_view),
      caption_button_container_(NULL),
      window_icon_(NULL),
      frame_painter_(new ash::FramePainter) {
}

BrowserNonClientFrameViewAsh::~BrowserNonClientFrameViewAsh() {
}

void BrowserNonClientFrameViewAsh::Init() {
  caption_button_container_ = new ash::FrameCaptionButtonContainerView(frame(),
      ash::FrameCaptionButtonContainerView::MINIMIZE_ALLOWED);
  AddChildView(caption_button_container_);

  // Initializing the TabIconView is expensive, so only do it if we need to.
  if (browser_view()->ShouldShowWindowIcon()) {
    window_icon_ = new TabIconView(this);
    window_icon_->set_is_light(true);
    AddChildView(window_icon_);
    window_icon_->Update();
  }

  // Create incognito icon if necessary.
  UpdateAvatarInfo();

  // Frame painter handles layout.
  frame_painter_->Init(frame(), window_icon_, caption_button_container_);
}

///////////////////////////////////////////////////////////////////////////////
// BrowserNonClientFrameView overrides:

gfx::Rect BrowserNonClientFrameViewAsh::GetBoundsForTabStrip(
    views::View* tabstrip) const {
  if (!tabstrip)
    return gfx::Rect();

  // When the tab strip is painted in the immersive fullscreen light bar style,
  // the caption buttons and the avatar button are not visible. However, their
  // bounds are still used to compute the tab strip bounds so that the tabs have
  // the same horizontal position when the tab strip is painted in the immersive
  // light bar style as when the top-of-window views are revealed.
  TabStripInsets insets(GetTabStripInsets(false));
  return gfx::Rect(insets.left, insets.top,
                   std::max(0, width() - insets.left - insets.right),
                   tabstrip->GetPreferredSize().height());
}

BrowserNonClientFrameView::TabStripInsets
BrowserNonClientFrameViewAsh::GetTabStripInsets(bool force_restored) const {
  int left = avatar_button() ? kAvatarSideSpacing +
      browser_view()->GetOTRAvatarIcon().width() + kAvatarSideSpacing :
      kTabstripLeftSpacing;
  int extra_right = ash::switches::UseAlternateFrameCaptionButtonStyle() ?
      kTabstripRightSpacingAlternateCaptionButtonStyle :
      kTabstripRightSpacing;
  int right = frame_painter_->GetRightInset() + extra_right;
  return TabStripInsets(NonClientTopBorderHeight(force_restored), left, right);
}

int BrowserNonClientFrameViewAsh::GetThemeBackgroundXInset() const {
  return frame_painter_->GetThemeBackgroundXInset();
}

void BrowserNonClientFrameViewAsh::UpdateThrobber(bool running) {
  if (window_icon_)
    window_icon_->Update();
}

///////////////////////////////////////////////////////////////////////////////
// views::NonClientFrameView overrides:

gfx::Rect BrowserNonClientFrameViewAsh::GetBoundsForClientView() const {
  int top_height = NonClientTopBorderHeight(false);
  return frame_painter_->GetBoundsForClientView(top_height, bounds());
}

gfx::Rect BrowserNonClientFrameViewAsh::GetWindowBoundsForClientBounds(
    const gfx::Rect& client_bounds) const {
  int top_height = NonClientTopBorderHeight(false);
  return frame_painter_->GetWindowBoundsForClientBounds(top_height,
                                                        client_bounds);
}

int BrowserNonClientFrameViewAsh::NonClientHitTest(const gfx::Point& point) {
  int hit_test = frame_painter_->NonClientHitTest(this, point);

  // See if the point is actually within the avatar menu button or within
  // the avatar label.
  if (hit_test == HTCAPTION && ((avatar_button() &&
       avatar_button()->GetMirroredBounds().Contains(point)) ||
      (avatar_label() && avatar_label()->GetMirroredBounds().Contains(point))))
      return HTCLIENT;

  // When the window is restored we want a large click target above the tabs
  // to drag the window, so redirect clicks in the tab's shadow to caption.
  if (hit_test == HTCLIENT &&
      !(frame()->IsMaximized() || frame()->IsFullscreen())) {
    // Convert point to client coordinates.
    gfx::Point client_point(point);
    View::ConvertPointToTarget(this, frame()->client_view(), &client_point);
    // Report hits in shadow at top of tabstrip as caption.
    gfx::Rect tabstrip_bounds(browser_view()->tabstrip()->bounds());
    if (client_point.y() < tabstrip_bounds.y() + kTabShadowHeight)
      hit_test = HTCAPTION;
  }
  return hit_test;
}

void BrowserNonClientFrameViewAsh::GetWindowMask(const gfx::Size& size,
                                                  gfx::Path* window_mask) {
  // Aura does not use window masks.
}

void BrowserNonClientFrameViewAsh::ResetWindowControls() {
  // Hide the caption buttons in immersive fullscreen when the tab light bar
  // is visible because it's confusing when the user hovers or clicks in the
  // top-right of the screen and hits one.
  bool button_visibility = !UseImmersiveLightbarHeaderStyle();
  caption_button_container_->SetVisible(button_visibility);

  caption_button_container_->ResetWindowControls();
}

void BrowserNonClientFrameViewAsh::UpdateWindowIcon() {
  if (window_icon_)
    window_icon_->SchedulePaint();
}

void BrowserNonClientFrameViewAsh::UpdateWindowTitle() {
  if (!frame()->IsFullscreen())
    frame_painter_->SchedulePaintForTitle(BrowserFrame::GetTitleFont());
}

///////////////////////////////////////////////////////////////////////////////
// views::View overrides:

void BrowserNonClientFrameViewAsh::OnPaint(gfx::Canvas* canvas) {
  if (!ShouldPaint())
    return;

  if (UseImmersiveLightbarHeaderStyle()) {
    PaintImmersiveLightbarStyleHeader(canvas);
    return;
  }

  // The primary header image changes based on window activation state and
  // theme, so we look it up for each paint.
  int theme_frame_image_id = GetThemeFrameImageId();
  int theme_frame_overlay_image_id = GetThemeFrameOverlayImageId();

  ui::ThemeProvider* theme_provider = GetThemeProvider();
  ash::FramePainter::Themed header_themed = ash::FramePainter::THEMED_NO;
  if (theme_provider->HasCustomImage(theme_frame_image_id) ||
      (theme_frame_overlay_image_id != 0 &&
       theme_provider->HasCustomImage(theme_frame_overlay_image_id))) {
    header_themed = ash::FramePainter::THEMED_YES;
  }

  if (frame_painter_->ShouldUseMinimalHeaderStyle(header_themed))
    theme_frame_image_id = IDR_AURA_WINDOW_HEADER_BASE_MINIMAL;

  frame_painter_->PaintHeader(
      this,
      canvas,
      ShouldPaintAsActive() ?
          ash::FramePainter::ACTIVE : ash::FramePainter::INACTIVE,
      theme_frame_image_id,
      theme_frame_overlay_image_id);
  if (browser_view()->ShouldShowWindowTitle())
    frame_painter_->PaintTitleBar(this, canvas, BrowserFrame::GetTitleFont());
  if (browser_view()->IsToolbarVisible())
    PaintToolbarBackground(canvas);
  else
    PaintContentEdge(canvas);
}

void BrowserNonClientFrameViewAsh::Layout() {
  frame_painter_->LayoutHeader(this, UseShortHeader());
  if (avatar_button())
    LayoutAvatar();
  BrowserNonClientFrameView::Layout();
}

const char* BrowserNonClientFrameViewAsh::GetClassName() const {
  return kViewClassName;
}

bool BrowserNonClientFrameViewAsh::HitTestRect(const gfx::Rect& rect) const {
  if (!views::View::HitTestRect(rect)) {
    // |rect| is outside BrowserNonClientFrameViewAsh's bounds.
    return false;
  }
  // If the rect is outside the bounds of the client area, claim it.
  // TODO(tdanderson): Implement View::ConvertRectToTarget().
  gfx::Point rect_in_client_view_coords_origin(rect.origin());
  View::ConvertPointToTarget(this, frame()->client_view(),
      &rect_in_client_view_coords_origin);
  gfx::Rect rect_in_client_view_coords(
      rect_in_client_view_coords_origin, rect.size());
  if (!frame()->client_view()->HitTestRect(rect_in_client_view_coords))
    return true;

  // Otherwise, claim |rect| only if it is above the bottom of the tabstrip in
  // a non-tab portion.
  TabStrip* tabstrip = browser_view()->tabstrip();
  if (!tabstrip || !browser_view()->IsTabStripVisible())
    return false;

  gfx::Point rect_in_tabstrip_coords_origin(rect.origin());
  View::ConvertPointToTarget(this, tabstrip,
      &rect_in_tabstrip_coords_origin);
  gfx::Rect rect_in_tabstrip_coords(rect_in_tabstrip_coords_origin,
      rect.size());

  if (rect_in_tabstrip_coords.bottom() > tabstrip->GetLocalBounds().bottom()) {
    // |rect| is below the tabstrip.
    return false;
  }

  if (tabstrip->HitTestRect(rect_in_tabstrip_coords)) {
    // Claim |rect| if it is in a non-tab portion of the tabstrip.
    // TODO(tdanderson): Pass |rect_in_tabstrip_coords| instead of its center
    // point to TabStrip::IsPositionInWindowCaption() once
    // GetEventHandlerForRect() is implemented.
    return tabstrip->IsPositionInWindowCaption(
        rect_in_tabstrip_coords.CenterPoint());
  }

  // We claim |rect| because it is above the bottom of the tabstrip, but
  // not in the tabstrip. In particular, the window controls are right of
  // the tabstrip.
  return true;
}

void BrowserNonClientFrameViewAsh::GetAccessibleState(
    ui::AccessibleViewState* state) {
  state->role = ui::AccessibilityTypes::ROLE_TITLEBAR;
}

gfx::Size BrowserNonClientFrameViewAsh::GetMinimumSize() {
  return frame_painter_->GetMinimumSize(this);
}

void BrowserNonClientFrameViewAsh::OnThemeChanged() {
  BrowserNonClientFrameView::OnThemeChanged();
  frame_painter_->OnThemeChanged();
}

///////////////////////////////////////////////////////////////////////////////
// chrome::TabIconViewModel overrides:

bool BrowserNonClientFrameViewAsh::ShouldTabIconViewAnimate() const {
  // This function is queried during the creation of the window as the
  // TabIconView we host is initialized, so we need to NULL check the selected
  // WebContents because in this condition there is not yet a selected tab.
  content::WebContents* current_tab = browser_view()->GetActiveWebContents();
  return current_tab ? current_tab->IsLoading() : false;
}

gfx::ImageSkia BrowserNonClientFrameViewAsh::GetFaviconForTabIconView() {
  views::WidgetDelegate* delegate = frame()->widget_delegate();
  if (!delegate)
    return gfx::ImageSkia();
  return delegate->GetWindowIcon();
}

///////////////////////////////////////////////////////////////////////////////
// BrowserNonClientFrameViewAsh, private:

int BrowserNonClientFrameViewAsh::NonClientTopBorderHeight(
    bool force_restored) const {
  if (force_restored)
    return kTabstripTopSpacingTall;
  if (!ShouldPaint() || UseImmersiveLightbarHeaderStyle())
    return 0;
  // Windows with tab strips need a smaller non-client area.
  if (browser_view()->IsTabStripVisible()) {
    if (UseShortHeader()) {
      if (ash::switches::UseAlternateFrameCaptionButtonStyle())
        return kTabstripTopSpacingShortAlternateCaptionButtonStyle;
      return kTabstripTopSpacingShort;
    }
    return kTabstripTopSpacingTall;
  }
  // For windows without a tab strip (popups, etc.) ensure we have enough space
  // to see the window caption buttons.
  return caption_button_container_->bounds().bottom() - kContentShadowHeight;
}

bool BrowserNonClientFrameViewAsh::UseShortHeader() const {
  // Restored browser -> tall header
  // Maximized browser -> short header
  // Fullscreen browser, no immersive reveal -> hidden or super short light bar
  // Fullscreen browser, immersive reveal -> short header
  // Popup&App window -> tall header
  // Panels use short header and are handled via ash::PanelFrameView.
  // Dialogs use short header and are handled via ash::CustomFrameViewAsh.
  Browser* browser = browser_view()->browser();
  switch (browser->type()) {
    case Browser::TYPE_TABBED:
      return frame()->IsMaximized() || frame()->IsFullscreen();
    case Browser::TYPE_POPUP:
      return false;
    default:
      NOTREACHED();
      return false;
  }
}

bool BrowserNonClientFrameViewAsh::UseImmersiveLightbarHeaderStyle() const {
  ImmersiveModeController* immersive_controller =
      browser_view()->immersive_mode_controller();
  return immersive_controller->IsEnabled() &&
      !immersive_controller->IsRevealed() &&
      !immersive_controller->ShouldHideTabIndicators();
}

void BrowserNonClientFrameViewAsh::LayoutAvatar() {
  DCHECK(avatar_button());
  gfx::ImageSkia incognito_icon = browser_view()->GetOTRAvatarIcon();

  int avatar_bottom = GetTabStripInsets(false).top +
      browser_view()->GetTabStripHeight() - kAvatarBottomSpacing;
  int avatar_restored_y = avatar_bottom - incognito_icon.height();
  int avatar_y = (frame()->IsMaximized() || frame()->IsFullscreen()) ?
      NonClientTopBorderHeight(false) + kContentShadowHeight :
      avatar_restored_y;

  // Hide the incognito icon in immersive fullscreen when the tab light bar is
  // visible because the header is too short for the icognito icon to be
  // recognizable.
  bool avatar_visible = !UseImmersiveLightbarHeaderStyle();
  int avatar_height = avatar_visible ? avatar_bottom - avatar_y : 0;

  gfx::Rect avatar_bounds(kAvatarSideSpacing,
                          avatar_y,
                          incognito_icon.width(),
                          avatar_height);
  avatar_button()->SetBoundsRect(avatar_bounds);
  avatar_button()->SetVisible(avatar_visible);
}

bool BrowserNonClientFrameViewAsh::ShouldPaint() const {
  if (!frame()->IsFullscreen())
    return true;

  // There is nothing to paint for traditional (tab) fullscreen.
  ImmersiveModeController* immersive_controller =
      browser_view()->immersive_mode_controller();
  if (!immersive_controller->IsEnabled())
    return false;

  // Need to paint during an immersive fullscreen reveal or when the immersive
  // light bar is visible.
  return immersive_controller->IsRevealed() ||
      !immersive_controller->ShouldHideTabIndicators();
}

void BrowserNonClientFrameViewAsh::PaintImmersiveLightbarStyleHeader(
    gfx::Canvas* canvas) {
  // The light bar header is not themed because theming it does not look good.
  gfx::ImageSkia* frame_image = GetThemeProvider()->GetImageSkiaNamed(
      IDR_AURA_WINDOW_HEADER_BASE_MINIMAL);
  canvas->TileImageInt(*frame_image, 0, 0, width(), frame_image->height());
}

void BrowserNonClientFrameViewAsh::PaintToolbarBackground(gfx::Canvas* canvas) {
  gfx::Rect toolbar_bounds(browser_view()->GetToolbarBounds());
  if (toolbar_bounds.IsEmpty())
    return;
  gfx::Point toolbar_origin(toolbar_bounds.origin());
  View::ConvertPointToTarget(browser_view(), this, &toolbar_origin);
  toolbar_bounds.set_origin(toolbar_origin);

  int x = toolbar_bounds.x();
  int w = toolbar_bounds.width();
  int y = toolbar_bounds.y();
  int h = toolbar_bounds.height();

  // Gross hack: We split the toolbar images into two pieces, since sometimes
  // (popup mode) the toolbar isn't tall enough to show the whole image.  The
  // split happens between the top shadow section and the bottom gradient
  // section so that we never break the gradient.
  int split_point = kFrameShadowThickness * 2;
  int bottom_y = y + split_point;
  ui::ThemeProvider* tp = GetThemeProvider();
  int bottom_edge_height = h - split_point;

  canvas->FillRect(gfx::Rect(x, bottom_y, w, bottom_edge_height),
                   tp->GetColor(ThemeProperties::COLOR_TOOLBAR));

  // Paint the main toolbar image.  Since this image is also used to draw the
  // tab background, we must use the tab strip offset to compute the image
  // source y position.  If you have to debug this code use an image editor
  // to paint a diagonal line through the toolbar image and ensure it lines up
  // across the tab and toolbar.
  gfx::ImageSkia* theme_toolbar = tp->GetImageSkiaNamed(IDR_THEME_TOOLBAR);
  canvas->TileImageInt(
      *theme_toolbar,
      x + GetThemeBackgroundXInset(),
      bottom_y - GetTabStripInsets(false).top,
      x, bottom_y,
      w, theme_toolbar->height());

  // The content area line has a shadow that extends a couple of pixels above
  // the toolbar bounds.
  const int kContentShadowHeight = 2;
  gfx::ImageSkia* toolbar_top = tp->GetImageSkiaNamed(IDR_TOOLBAR_SHADE_TOP);
  canvas->TileImageInt(*toolbar_top,
                       0, 0,
                       x, y - kContentShadowHeight,
                       w, split_point + kContentShadowHeight + 1);

  // Draw the "lightening" shade line around the edges of the toolbar.
  gfx::ImageSkia* toolbar_left = tp->GetImageSkiaNamed(IDR_TOOLBAR_SHADE_LEFT);
  canvas->TileImageInt(*toolbar_left,
                       0, 0,
                       x + kClientEdgeThickness,
                       y + kClientEdgeThickness + kContentShadowHeight,
                       toolbar_left->width(), theme_toolbar->height());
  gfx::ImageSkia* toolbar_right =
      tp->GetImageSkiaNamed(IDR_TOOLBAR_SHADE_RIGHT);
  canvas->TileImageInt(*toolbar_right,
                       0, 0,
                       w - toolbar_right->width() - 2 * kClientEdgeThickness,
                       y + kClientEdgeThickness + kContentShadowHeight,
                       toolbar_right->width(), theme_toolbar->height());

  // Draw the content/toolbar separator.
  canvas->FillRect(
      gfx::Rect(x + kClientEdgeThickness,
                toolbar_bounds.bottom() - kClientEdgeThickness,
                w - (2 * kClientEdgeThickness),
                kClientEdgeThickness),
      ThemeProperties::GetDefaultColor(
          ThemeProperties::COLOR_TOOLBAR_SEPARATOR));
}

void BrowserNonClientFrameViewAsh::PaintContentEdge(gfx::Canvas* canvas) {
  canvas->FillRect(gfx::Rect(0, caption_button_container_->bounds().bottom(),
                             width(), kClientEdgeThickness),
      ThemeProperties::GetDefaultColor(
          ThemeProperties::COLOR_TOOLBAR_SEPARATOR));
}

int BrowserNonClientFrameViewAsh::GetThemeFrameImageId() const {
  bool is_incognito = browser_view()->IsOffTheRecord() &&
                      !browser_view()->IsGuestSession();
  if (browser_view()->IsBrowserTypeNormal()) {
    // Use the standard resource ids to allow users to theme the frames.
    if (ShouldPaintAsActive()) {
      return is_incognito ?
          IDR_THEME_FRAME_INCOGNITO : IDR_THEME_FRAME;
    }
    return is_incognito ?
        IDR_THEME_FRAME_INCOGNITO_INACTIVE : IDR_THEME_FRAME_INACTIVE;
  }
  // Never theme app and popup windows.
  if (ShouldPaintAsActive()) {
    return is_incognito ?
        IDR_AURA_WINDOW_HEADER_BASE_INCOGNITO_ACTIVE :
        IDR_AURA_WINDOW_HEADER_BASE_ACTIVE;
  }
  return is_incognito ?
      IDR_AURA_WINDOW_HEADER_BASE_INCOGNITO_INACTIVE :
      IDR_AURA_WINDOW_HEADER_BASE_INACTIVE;
}

int BrowserNonClientFrameViewAsh::GetThemeFrameOverlayImageId() const {
  ui::ThemeProvider* tp = GetThemeProvider();
  if (tp->HasCustomImage(IDR_THEME_FRAME_OVERLAY) &&
      browser_view()->IsBrowserTypeNormal() &&
      !browser_view()->IsOffTheRecord()) {
    return ShouldPaintAsActive() ?
        IDR_THEME_FRAME_OVERLAY : IDR_THEME_FRAME_OVERLAY_INACTIVE;
  }
  return 0;
}


text:
package com.github.cnlinjie.infrastructure.dao.nativesql;

import com.github.cnlinjie.infrastructure.dao.Page;
import com.github.cnlinjie.infrastructure.dao.PageParams;
import com.github.cnlinjie.infrastructure.dao.hibernate.QueryUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.NativeQuery;
import org.hibernate.query.Query;
import org.hibernate.transform.Transformers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigInteger;
import java.util.List;
import java.util.Map;

/**
 * @author Linjie
 * @date 2015/10/1.
 */
public class NativeSqlDaoImpl implements INativeSqlDao {

    private static Logger logger = LoggerFactory.getLogger(NativeSqlDaoImpl.class);
    protected SessionFactory sessionFactory;
    private boolean useCurrentSession = true;

    public NativeSqlDaoImpl() {
    }

    /**
     * 获取Hibernate SessionFactory
     *
     * @return {@link org.hibernate.SessionFactory}
     */
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    /**
     * 设置Hibernate sessionFactory
     *
     * @param sessionFactory
     */
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    /**
     * 取得当前Session.
     *
     * @return {@link org.hibernate.Session}
     */
    public Session getSession() {
        if (useCurrentSession) {
            return sessionFactory.getCurrentSession();
        } else {
            return sessionFactory.openSession();
        }
    }

    /**
     * 设置查询参数
     *
     * @param query
     * @param values
     */
    protected Query setParameters(Query query, Object... values) {
        if (ArrayUtils.isEmpty(values)) {
            return query;
        }
        for (Integer i = 0; i < values.length; i++) {
            query.setParameter(i, values[i]);
        }
        return query;
    }

    protected Long getCountRow(String sql, Object... args) {
        BigInteger o = (BigInteger) setParameters(createSQLQuery(getTotalSql(sql)), args).uniqueResult();
        return o.longValue();
    }

    protected Long getCountRow(String sql, Map<String, Object> args) {
        BigInteger o = (BigInteger) createSQLQuery(getTotalSql(sql)).setProperties(args).uniqueResult();
        return o.longValue();
    }

    protected String getTotalSql(String sql) {
        String countSql = "select count(*) ";
        String upperSql = sql.toUpperCase();
        int start = upperSql.indexOf("FROM");
        int end = sql.length();
        countSql += sql.substring(start, end);
        logger.debug(countSql);
        return countSql;
    }

    protected NativeQuery createSQLQuery(String sql) {
        return this.getSession().createSQLQuery(sql);
    }

    public <X> X sqlUniqueValue(String sql, Object... args) {
        X x = (X) setParameters(createSQLQuery(sql), args).uniqueResult();
        return x;
    }

    public <X> X sqlUniqueValue(String sql, Map<String, Object> args) {
        X x = (X) createSQLQuery(sql)
                .setProperties(args).uniqueResult();
        return x;
    }

    public Object[] sqlUniqueObject(String sql, Object... args) {
        return sqlListObjects(sql, args).get(0);
    }

    public Object[] sqlUniqueObject(String sql, Map<String, Object> args) {
        return sqlListObjects(sql, args).get(0);
    }

    public <X> X sqlUniqueBean(String sql, Class<? extends X> transferClass, Object... args) {
        X x = (X) setParameters(createSQLQuery(sql), args)
                .setResultTransformer(Transformers.aliasToBean(transferClass))
                .uniqueResult();
        return x;
    }

    public <X> X sqlUniqueBean(String sql, Class<? extends X> transferClass, Map<String, Object> args) {
        X x = (X) createSQLQuery(sql)
                .setProperties(args)
                .setResultTransformer(Transformers.aliasToBean(transferClass))
                .uniqueResult();
        return x;
    }

    public List<Object[]> sqlListObjects(String sql, Object... args) {
        List<Object[]> list = setParameters(createSQLQuery(sql), args).list();
        return list;
    }

    public List<Object[]> sqlListObjects(String sql, Map<String, Object> args) {
        List<Object[]> list = createSQLQuery(sql).setProperties(args).list();
        return list;
    }

    @Override
    public <X> List<X> sqlListX(String sql, Object... args) {
        List<X> list = createSQLQuery(sql).setProperties(args).list();
        return list;
    }

    @Override
    public <X> List<X> sqlListX(String sql, Map<String, Object> args) {
        List<X> list = createSQLQuery(sql).setProperties(args).list();
        return list;
    }

    public Page<Object[]> sqlPageObjects(String sql, PageParams pageParams, Object... args) {
        List list = setParameters(createSQLQuery(sql), args)
                .setFirstResult(pageParams.getStartRowByInt())
                .setMaxResults(pageParams.getPageSize())
                .list();
        Long totalCount = getCountRow(sql, args);
        Page<Object[]> page = new Page<Object[]>(list, totalCount, pageParams.getPageIndex(), pageParams.getPageSize());
        return page;
    }

    public Page<Object[]> sqlPageObjects(String sql, PageParams pageParams, Map<String, Object> args) {
        List list = createSQLQuery(sql)
                .setProperties(args)
                .setFirstResult(pageParams.getStartRowByInt())
                .setMaxResults(pageParams.getPageSize())
                .list();
        Long totalCount = getCountRow(sql, args);
        Page<Object[]> page = new Page<Object[]>(list, totalCount, pageParams.getPageIndex(), pageParams.getPageSize());
        return page;
    }

    public <X> List<X> sqlListBeans(String sql, Class<? extends X> transferClass, Object... args) {
        List<X> list = setParameters(createSQLQuery(sql), args)
                .setResultTransformer(Transformers.aliasToBean(transferClass))
                .list();
        return list;
    }

    public <X> List<X> sqlListBeans(String sql, Class<? extends X> transferClass, Map<String, Object> args) {
        List<X> list = createSQLQuery(sql).setProperties(args)
                .setResultTransformer(Transformers.aliasToBean(transferClass))
                .list();
        return list;
    }

    public <X> Page<X> sqlPageBeans(String sql, Class<? extends X> transferClass, PageParams pageParams, Object... args) {

        List<X> list = setParameters(createSQLQuery(sql), args)
                .setFirstResult(pageParams.getStartRowByInt())
                .setMaxResults(pageParams.getPageSize())
                .setResultTransformer(Transformers.aliasToBean(transferClass))
                .list();

        Long totalCount = getCountRow(sql, args);
        Page<X> page = new Page<X>(list, totalCount, pageParams.getPageIndex(), pageParams.getPageSize());
        return page;
    }

    public <X> Page<X> sqlPageBeans(String sql, Class<? extends X> transferClass, PageParams pageParams, Map<String, Object> args) {
        List<X> list =
                createSQLQuery(sql)
                        .setResultTransformer(Transformers.aliasToBean(transferClass))
                        .setFirstResult(pageParams.getStartRowByInt())
                        .setMaxResults(pageParams.getPageSize())
                        .setProperties(args)
                        .list();
        Long totalCount = getCountRow(sql, args);
        Page<X> page = new Page<X>(list, totalCount, pageParams.getPageIndex(), pageParams.getPageSize());
        return page;
    }

    public List<Map<String, Object>> sqlListMaps(String sql, Object... args) {
        List<Map<String, Object>> list =
                setParameters(createSQLQuery(sql), args)
                        .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP)
                        .list();
        return list;
    }

    public List<Map<String, Object>> sqlListMaps(String sql, Map<String, Object> args) {

        List<Map<String, Object>> list =
                createSQLQuery(sql)
                        .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP)
                        .setProperties(args)
                        .list();
        return list;

    }

    public List<Map<String, Object>> sqlListMaps(String sql, String[] fields, Object... args) {
        List<Object[]> list =
                setParameters(createSQLQuery(sql), args)
                        .list();
        List<Map<String, Object>> maps = QueryUtil.arraysToMaps(
                list, fields
        );
        return maps;
    }

    public List<Map<String, Object>> sqlListMaps(String sql, String[] fields, Map<String, Object> args) {
        List<Object[]> list =
                createSQLQuery(sql)
                        .setProperties(args)
                        .list();
        List<Map<String, Object>> maps = QueryUtil.arraysToMaps(
                list, fields
        );
        return maps;
    }

    public Page<Map<String, Object>> sqlPageMaps(String sql, PageParams pageParams, Object... args) {

        List<Map<String, Object>> list =
                setParameters(createSQLQuery(sql), args)
                        .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP)
                        .setFirstResult(pageParams.getStartRowByInt())
                        .setMaxResults(pageParams.getPageSize())
                        .list();
        Long totalCount = getCountRow(sql, args);
        Page<Map<String, Object>> page = new Page<Map<String, Object>>(list, totalCount, pageParams.getPageIndex(), pageParams.getPageSize());
        return page;
    }

    public Page<Map<String, Object>> sqlPageMaps(String sql, PageParams pageParams, Map<String, Object> args) {

        List<Map<String, Object>> list =
                createSQLQuery(sql)
                        .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP)
                        .setFirstResult(pageParams.getStartRowByInt())
                        .setMaxResults(pageParams.getPageSize())
                        .setProperties(args)
                        .list();
        Long totalCount = getCountRow(sql, args);
        Page<Map<String, Object>> page = new Page<Map<String, Object>>(list, totalCount, pageParams.getPageIndex(), pageParams.getPageSize());
        return page;
    }

    public Page<Map<String, Object>> sqlPageMaps(String sql, PageParams pageParams, String[] fields, Object... args) {
        List<Object[]> list =
                setParameters(createSQLQuery(sql), args)
                        .setFirstResult(pageParams.getStartRowByInt())
                        .setMaxResults(pageParams.getPageSize())
                        .list();
        Long totalCount = getCountRow(sql, args);
        List<Map<String, Object>> maps = QueryUtil.arraysToMaps(list, fields);
        Page<Map<String, Object>> page = new Page<Map<String, Object>>(maps, totalCount, pageParams.getPageIndex(), pageParams.getPageSize());
        return page;
    }

    public Page<Map<String, Object>> sqlPageMaps(String sql, PageParams pageParams, String[] fields, Map<String, Object> args) {
        List<Object[]> list =
                createSQLQuery(sql)
                        .setFirstResult(pageParams.getStartRowByInt())
                        .setMaxResults(pageParams.getPageSize())
                        .setProperties(args)
                        .list();
        Long totalCount = getCountRow(sql, args);
        List<Map<String, Object>> maps = QueryUtil.arraysToMaps(list, fields);
        Page<Map<String, Object>> page = new Page<Map<String, Object>>(maps, totalCount, pageParams.getPageIndex(), pageParams.getPageSize());
        return page;
    }

    public int sqlExecute(String sql, Object... args) {
        int i = setParameters(createSQLQuery(sql), args)
                .executeUpdate();
        return i;
    }

    public int sqlExecute(String sql, Map<String, Object> args) {
        int i = createSQLQuery(sql)
                .setProperties(args)
                .executeUpdate();
        return i;
    }
}


text:
package org.jetbrains.plugins.scala.codeInspection

import com.intellij.openapi.util.TextRange
import com.intellij.psi.util.CachedValueProvider.Result
import com.intellij.psi.util.{CachedValueProvider, CachedValuesManager, PsiTreeUtil}
import com.intellij.psi.{PsiClass, PsiElement, PsiMethod, PsiType}
import org.jetbrains.plugins.scala.codeInspection.InspectionsUtil.isExpressionOfType
import org.jetbrains.plugins.scala.debugger.evaluation.ScalaEvaluatorBuilderUtil
import org.jetbrains.plugins.scala.extensions._
import org.jetbrains.plugins.scala.lang.psi.ScalaPsiUtil
import org.jetbrains.plugins.scala.lang.psi.api.base.patterns.ScCaseClauses
import org.jetbrains.plugins.scala.lang.psi.api.base.{ScLiteral, ScReferenceElement}
import org.jetbrains.plugins.scala.lang.psi.api.expr._
import org.jetbrains.plugins.scala.lang.psi.api.statements.params.ScParameter
import org.jetbrains.plugins.scala.lang.psi.api.statements.{ScFunction, ScFunctionDefinition, ScValue, ScVariable}
import org.jetbrains.plugins.scala.lang.psi.api.toplevel.typedef.{ScMember, ScObject}
import org.jetbrains.plugins.scala.lang.psi.api.{InferUtil, ScalaRecursiveElementVisitor}
import org.jetbrains.plugins.scala.lang.psi.impl.ScalaPsiElementFactory
import org.jetbrains.plugins.scala.lang.psi.types._
import org.jetbrains.plugins.scala.lang.psi.types.api.{FunctionType, JavaArrayType}
import org.jetbrains.plugins.scala.lang.psi.types.result._
import org.jetbrains.plugins.scala.lang.refactoring.util.ScalaNamesUtil
import org.jetbrains.plugins.scala.lang.resolve.ScalaResolveResult
import org.jetbrains.plugins.scala.project.ProjectPsiElementExt
import org.jetbrains.plugins.scala.project.ScalaLanguageLevel.Scala_2_9
import org.jetbrains.plugins.scala.settings.ScalaApplicationSettings

import scala.annotation.tailrec

/**
 * @author Nikolay.Tropin
 */
package object collections {
  def likeCollectionClasses: Array[String] = ScalaApplicationSettings.getInstance().getLikeCollectionClasses
  def likeOptionClasses: Array[String] = ScalaApplicationSettings.getInstance().getLikeOptionClasses

  val monadicMethods = Set("map", "flatMap", "filter", "withFilter")
  val foldMethodNames = Set("foldLeft", "/:", "foldRight", ":\\", "fold")
  val reduceMethodNames = Set("reduce", "reduceLeft", "reduceRight")

  def invocation(methodName: String) = new Qualified(methodName == _)
  def invocation(methodNames: Set[String]) = new Qualified(methodNames.contains)

  def unqualifed(methodName: String) = new Unqualified(methodName == _)

  private[collections] val `.exists` = invocation("exists").from(likeCollectionClasses)
  private[collections] val `.forall` = invocation("forall").from(likeCollectionClasses)
  private[collections] val `.filter` = invocation("filter").from(likeCollectionClasses)
  private[collections] val `.filterNot` = invocation("filterNot").from(likeCollectionClasses)
  private[collections] val `.map` = invocation("map").from(likeCollectionClasses)
  private[collections] val `.headOption` = invocation("headOption").from(likeCollectionClasses)
  private[collections] val `.lastOption` = invocation("lastOption").from(likeCollectionClasses)
  private[collections] val `.head` = invocation("head").from(likeCollectionClasses)
  private[collections] val `.last` = invocation("last").from(likeCollectionClasses)
  private[collections] val `.sizeOrLength` = invocation(Set("size", "length")).from(likeCollectionClasses)
  private[collections] val `.find` = invocation("find").from(likeCollectionClasses)
  private[collections] val `.contains` = invocation("contains").from(likeCollectionClasses)
  private[collections] val `.flatten` = invocation("flatten").from(likeCollectionClasses)
  private[collections] val `.flatMap` = invocation("flatMap").from(likeCollectionClasses)
  private[collections] val `.collect` = invocation("collect").from(likeCollectionClasses)

  private[collections] val `.isDefined` = invocation(Set("isDefined", "nonEmpty")).from(likeOptionClasses)
  private[collections] val `.isEmptyOnOption` = invocation("isEmpty").from(likeOptionClasses)
  private[collections] val `.isEmpty` = invocation("isEmpty").from(likeCollectionClasses)
  private[collections] val `.nonEmpty` = invocation("nonEmpty").from(likeCollectionClasses)

  private[collections] val `.fold` = invocation(foldMethodNames).from(likeCollectionClasses)
  private[collections] val `.foldLeft` = invocation(Set("foldLeft", "/:")).from(likeCollectionClasses)
  private[collections] val `.reduce` = invocation(reduceMethodNames).from(likeCollectionClasses)
  private[collections] val `.getOrElse` = invocation("getOrElse").from(likeOptionClasses)
  private[collections] val `.get` = invocation("get").from(likeOptionClasses)
  private[collections] val `.getOnMap` = invocation("get").from(likeCollectionClasses).ref(checkResolveToMap)
  private[collections] val `.mapOnOption` = invocation("map").from(likeOptionClasses).ref(checkScalaVersion)
  private[collections] val `.sort` = invocation(Set("sortWith", "sortBy", "sorted")).from(likeCollectionClasses)
  private[collections] val `.sorted` = invocation("sorted").from(likeCollectionClasses)
  private[collections] val `.sortBy` = invocation("sortBy").from(likeCollectionClasses)
  private[collections] val `.reverse` = invocation("reverse").from(likeCollectionClasses)
  private[collections] val `.iterator` = invocation("iterator").from(likeCollectionClasses)
  private[collections] val `.apply` = invocation("apply")
  private[collections] val `.zip` = invocation("zip").from(likeCollectionClasses)
  private[collections] val `.indices` = invocation("indices").from(likeCollectionClasses)
  private[collections] val `.take` = invocation("take").from(likeCollectionClasses)
  private[collections] val `.drop` = invocation("drop").from(likeCollectionClasses)
  private[collections] val `.sameElements` = invocation("sameElements").from(likeCollectionClasses)
  private[collections] val `.corresponds` = invocation("corresponds").from(likeCollectionClasses)

  private[collections] val `.to` = invocation("to").from(Array("RichInt", "RichChar", "RichLong", "RichDouble", "RichFloat").map("scala.runtime." + _))

  private[collections] val `!=` = invocation("!=")
  private[collections] val `==` = invocation(Set("==", "equals"))
  private[collections] val `>` = invocation(">")
  private[collections] val `>=` = invocation(">=")
  private[collections] val `!` = invocation(Set("!", "unary_!"))
  private[collections] val `-` = invocation("-")
  private[collections] val `+` = invocation("+")

  private[collections] val `.toCollection` = new Qualified(name => name.startsWith("to") && name != "toString").from(likeCollectionClasses)
  private[collections] val `.toSet` = invocation("toSet").from(likeCollectionClasses)
  private[collections] val `.toIterator` = invocation("toIterator").from(likeCollectionClasses)

  private[collections] val `.lift` = invocation("lift").from(Array("scala.PartialFunction"))

  private[collections] val `.monadicMethod` = invocation(monadicMethods).from(likeCollectionClasses)

  object scalaNone {
    def unapply(expr: ScExpression): Boolean = {
      expr match {
        case ResolvesTo(obj: ScObject) if obj.qualifiedName == "scala.None" => true
        case _ => false
      }
    }
  }

  object scalaSome {
    def unapply(expr: ScExpression): Option[ScExpression] = expr match {
      case MethodRepr(_, _, Some(ref), Seq(e)) if ref.refName == "Some" =>
        ref.resolve() match {
          case m: ScMember if m.containingClass.qualifiedName == "scala.Some" => Some(e)
          case _ => None
        }
      case _ => None
    }
  }

  object scalaOption {
    def unapply(expr: ScExpression): Option[ScExpression] = expr match {
      case MethodRepr(_, _, Some(ref), Seq(e)) if ref.refName == "Option" =>
        ref.resolve() match {
          case m: ScMember if m.containingClass.qualifiedName == "scala.Option" => Some(e)
          case _ => None
        }
      case _ => None
    }
  }

  object IfStmt {
    def unapply(expr: ScExpression): Option[(ScExpression, ScExpression, ScExpression)] = {
      expr match {
        case ScIfStmt(Some(c), Some(stripped(tb)), Some(stripped(eb))) => Some(c, tb, eb)
        case _ => None
      }
    }
  }

  object literal {
    def unapply(expr: ScExpression): Option[String] = {
      expr match {
        case lit: ScLiteral => Some(lit.getText)
        case _ => None
      }
    }
  }

  object returnsBoolean {
    def unapply(expr: ScExpression): Boolean = {
      import expr.projectContext

      expr.`type`() match {
        case Right(result) =>
          result match {
            case FunctionType(returnType, _) => returnType.conforms(api.Boolean)
            case _ => false
          }
        case _ => false
      }
    }
  }

  object binaryOperation {
    def unapply(expr: ScExpression): Option[String] = {
      val operRef = stripped(expr) match {
        case ScFunctionExpr(Seq(x, y), Some(result)) =>
          def checkResolve(left: ScExpression, right: ScExpression) = (stripped(left), stripped(right)) match {
            case (leftRef: ScReferenceExpression, rightRef: ScReferenceExpression) =>
              Set(leftRef.resolve(), rightRef.resolve()) equals Set(x, y)
            case _ => false
          }
          stripped(result) match {
            case ScInfixExpr(left, oper, right) if checkResolve(left, right) => Some(oper)
            case ScMethodCall(refExpr: ScReferenceExpression, Seq(left, right)) if checkResolve(left, right) => Some(refExpr)
            case _ => None
          }
        case ScInfixExpr(underscore(), oper, underscore()) => Some(oper)
        case ScMethodCall(refExpr: ScReferenceExpression, Seq(underscore(), underscore()))  => Some(refExpr)
        case _ => None
      }
      operRef.map(_.refName)
    }
  }

  class BinaryOperationOnParameterAndExprTemplate(operName: String) {
    def unapply(expr: ScExpression): Option[ScExpression] = {
      stripped(expr) match {
        case ScFunctionExpr(Seq(x), Some(result)) =>
          stripped(result) match {
            case ScInfixExpr(left, oper, right) if oper.refName == operName =>
              (stripped(left), stripped(right)) match {
                case (leftRef: ScReferenceExpression, rightExpr)
                  if leftRef.resolve() == x && isIndependentOf(rightExpr, x) =>
                  Some(rightExpr)
                case (leftExpr: ScExpression, rightRef: ScReferenceExpression)
                  if rightRef.resolve() == x && isIndependentOf(leftExpr, x) =>
                  Some(leftExpr)
                case _ => None
              }
            case _ => None
          }
        case ScInfixExpr(underscore(), oper, right) if oper.refName == operName => Some(right)
        case ScInfixExpr(left, oper, underscore()) if oper.refName == operName => Some(left)
        case _ => None
      }
    }
  }

  private[collections] val `x == ` = new BinaryOperationOnParameterAndExprTemplate("==")
  private[collections] val `x != ` = new BinaryOperationOnParameterAndExprTemplate("!=")

  object andCondition {
    def unapply(expr: ScExpression): Option[ScExpression] = {
      stripped(expr) match {
        case ScFunctionExpr(Seq(x, y), Some(result)) =>
          stripped(result) match {
            case ScInfixExpr(left, oper, right) if oper.refName == "&&" =>
              (stripped(left), stripped(right)) match {
                case (leftRef: ScReferenceExpression, right: ScExpression)
                  if leftRef.resolve() == x && isIndependentOf(right, x) =>
                  val secondArgName = y.getName
                  val funExprText = secondArgName + " => " + right.getText
                  Some(ScalaPsiElementFactory.createExpressionWithContextFromText(funExprText, expr.getContext, expr))
                case _ => None
              }
            case _ => None
          }
        case ScInfixExpr(underscore(), oper, right) if oper.refName == "&&" => Some(right)
        case _ => None
      }
    }
  }

  class ParameterlessCallOnParameterTemplate(name: String) {
    def unapply(expr: ScExpression): Boolean = {
      stripped(expr) match {
        case ScFunctionExpr(Seq(x), Some(result)) =>
          stripped(result) match {
            case MethodRepr(_, Some(ResolvesTo(`x`)), Some(ref), Seq()) if ref.refName == name => true
            case _ => false
          }
        case MethodRepr(_, Some(underscore()), Some(ref), Seq()) if ref.refName == name => true
        case _ => false
      }
    }
  }

  private[collections] val `_._1` = new ParameterlessCallOnParameterTemplate("_1")
  private[collections] val `_._2` = new ParameterlessCallOnParameterTemplate("_2")

  object underscore {
    def unapply(expr: ScExpression): Boolean = {
      stripped(expr) match {
        case ScParenthesisedExpr(underscore()) => true
        case typed: ScTypedStmt if typed.expr.isInstanceOf[ScUnderscoreSection] => true
        case und: ScUnderscoreSection if und.bindingExpr.isEmpty => true
        case _ => false
      }
    }
  }

  def invocationText(qual: ScExpression, methName: String, args: ScExpression*): String = {
    def argsText = argListText(args)

    if (qual == null) {
      val argsText = argListText(args)
      s"$methName$argsText"
    } else {
      val qualText = qual.getText
      qual match {
        case _ childOf ScInfixExpr(`qual`, _, _) if args.size == 1 =>
          s"${qual.getText} $methName ${args.head.getText}"
        case _: ScInfixExpr => s"($qualText).$methName$argsText"
        case _ => s"$qualText.$methName$argsText"
      }

    }
  }

  def invocationText(negation: Boolean, qual: ScExpression, methName: String, args: ScExpression*): String = {
    val baseText = invocationText(qual, methName, args: _*)
    qual match {
      case _ if !negation => baseText
      case _ childOf ScInfixExpr(`qual`, _, _) => s"!($baseText)"
      case _ => s"!$baseText"
    }
  }

  def argListText(args: Seq[ScExpression]): String = {
    args match {
      case Seq(p: ScParenthesisedExpr) => p.getText
      case Seq(b @ ScBlock(_: ScFunctionExpr)) => b.getText
      case Seq(ScBlock(stmt: ScBlockStatement)) => s"(${stmt.getText})"
      case Seq(b: ScBlock) => b.getText
      case Seq((_: ScFunctionExpr) childOf (b: ScBlockExpr)) => b.getText
      case Seq(other) => s"(${other.getText})"
      case seq if seq.size > 1 => seq.map(_.getText).mkString("(", ", ", ")")
      case _ => ""
    }
  }

  private def checkResolveToMap(memberRef: ScReferenceElement): Boolean = memberRef.resolve() match {
    case m: ScMember => Option(m.containingClass).exists(_.name.toLowerCase.contains("map"))
    case _ => false
  }

  private def checkScalaVersion(elem: PsiElement): Boolean = { //there is no Option.fold in Scala 2.9
    elem.scalaLanguageLevel.forall(_ > Scala_2_9)
  }

  def implicitParameterExistsFor(methodName: String, baseExpr: ScExpression): Boolean = {
    val expression = ScalaPsiElementFactory.createExpressionWithContextFromText(s"${baseExpr.getText}.$methodName", baseExpr.getContext, baseExpr)
    implicitParameterExistsFor(expression)
  }

  def implicitParameterExistsFor(expr: ScExpression): Boolean = {
    if (expr == null) false
    else expr.findImplicitParameters match {
      case Some(Seq(srr: ScalaResolveResult)) if srr.element.name == InferUtil.notFoundParameterName => false
      case Some(Seq(_: ScalaResolveResult, _*)) => true
      case _ => false
    }
  }

  @tailrec
  def stripped(expr: ScExpression): ScExpression = {
    expr match {
      case ScParenthesisedExpr(inner) => stripped(inner)
      case ScBlock(inner: ScExpression) => stripped(inner)
      case _ => expr
    }
  }

  object stripped {
    def unapply(expr: ScExpression): Option[ScExpression] = Some(stripped(expr))
  }

  def isIndependentOf(expr: ScExpression, parameter: ScParameter): Boolean = {
    var result = true
    val name = parameter.getName
    val visitor = new ScalaRecursiveElementVisitor() {
      override def visitReferenceExpression(ref: ScReferenceExpression) {
        if (ref.refName == name && ref.resolve() == parameter) result = false
        super.visitReferenceExpression(ref)
      }
    }
    expr.accept(visitor)
    result
  }

  def checkResolve(expr: ScExpression, patterns: Array[String]): Boolean = {
    Option(expr).collect {
      case ref: ScReferenceExpression => ref.resolve()
    }.flatMap {
      case obj: ScObject => Some(obj)
      case member: ScMember => Option(member.containingClass)
      case _ => None
    }.exists {
      qualifiedNameFitToPatterns(_, patterns)
    }
  }

  def isOfClassFrom(expr: ScExpression, patterns: Array[String]): Boolean =
    expr.`type`().toOption.exists(isOfClassFrom(_, patterns))

  def isOfClassFrom(`type`: ScType, patterns: Array[String]): Boolean =
    `type`.tryExtractDesignatorSingleton.extractClass.exists(qualifiedNameFitToPatterns(_, patterns))

  private def qualifiedNameFitToPatterns(clazz: PsiClass, patterns: Array[String]) =
    Option(clazz).flatMap(c => Option(c.qualifiedName))
      .exists(ScalaNamesUtil.nameFitToPatterns(_, patterns, strict = false))

  def isOption(`type`: ScType): Boolean = isOfClassFrom(`type`, likeOptionClasses)

  def isOption(expr: ScExpression): Boolean = isOfClassFrom(expr, likeOptionClasses)

  def isArray(expr: ScExpression): Boolean = expr match {
    case Typeable(JavaArrayType(_)) => true
    case _ => isOfClassFrom(expr, Array("scala.Array"))
  }

  def isSet(expr: ScExpression): Boolean = isExpressionOfType("scala.collection.GenSetLike", expr)

  def isSeq(expr: ScExpression): Boolean = isExpressionOfType("scala.collection.GenSeqLike", expr)

  def isIndexedSeq(expr: ScExpression): Boolean = isExpressionOfType("scala.collection.IndexedSeqLike", expr)

  def isMap(expr: ScExpression): Boolean = isExpressionOfType("scala.collection.GenMapLike", expr)

  def isSortedSet(expr: ScExpression): Boolean = isExpressionOfType("scala.collection.SortedSetLike", expr)

  def isSortedMap(expr: ScExpression): Boolean = isExpressionOfType("scala.collection.SortedMapLike", expr)

  def isIterator(expr: ScExpression): Boolean = isExpressionOfType("scala.collection.Iterator", expr)

  private val sideEffectsCollectionMethods = Set("append", "appendAll", "clear", "insert", "insertAll",
    "prepend", "prependAll", "reduceToSize", "remove", "retain",
    "transform", "trimEnd", "trimStart", "update",
    "push", "pushAll", "pop", "dequeue", "dequeueAll", "dequeueFirst", "enqueue",
    "next")

  private class SideEffectsProvider(expr: ScExpression) extends CachedValueProvider[Seq[ScExpression]] {
    override def compute(): Result[Seq[ScExpression]] = Result.create(computeExprsWithSideEffects(expr), expr)

    private def computeExprsWithSideEffects(expr: ScExpression): Seq[ScExpression] = {

      def isSideEffectCollectionMethod(ref: ScReferenceExpression): Boolean = {
        val refName = ref.refName
        (refName.endsWith("=") || refName.endsWith("=:") || sideEffectsCollectionMethods.contains(refName)) &&
                checkResolve(ref, Array("scala.collection.mutable._", "scala.collection.Iterator"))
      }

      def isSetter(ref: ScReferenceExpression): Boolean = {
        ref.refName.startsWith("set") || ref.refName.endsWith("_=")
      }

      def hasUnitReturnType(ref: ScReferenceExpression): Boolean = {
        ref match {
          case MethodRepr(Typeable(FunctionType(_, _)), _, _, _) => false
          case ResolvesTo(fun: ScFunction) => fun.hasUnitResultType
          case ResolvesTo(m: PsiMethod) => m.getReturnType == PsiType.VOID
          case _ => false
        }
      }

      object definedOutside {
        def unapply(ref: ScReferenceElement): Option[PsiElement] = ref match {
          case ResolvesTo(elem: PsiElement) if !PsiTreeUtil.isAncestor(expr, elem, false) => Some(elem)
          case _ => None
        }
      }

      val predicate: (PsiElement) => Boolean = {
        case `expr` => true
        case (ScFunctionExpr(_, _) | (_: ScCaseClauses)) childOf `expr` => true
        case (e: ScExpression) childOf `expr` if ScUnderScoreSectionUtil.underscores(e).nonEmpty => true
        case _: ScFunctionDefinition => false
        case elem: PsiElement => !ScalaEvaluatorBuilderUtil.isGenerateClass(elem)
      }

      val sameLevelIterator = expr.depthFirst(predicate).filter(predicate)

      sameLevelIterator.collect {
        case assign @ ScAssignStmt(definedOutside(ScalaPsiUtil.inNameContext(_: ScVariable)), _) =>
          assign
        case assign @ ScAssignStmt(mc @ ScMethodCall(definedOutside(_), _), _) if mc.isUpdateCall =>
          assign
        case infix @ ScInfixExpr(definedOutside(ScalaPsiUtil.inNameContext(_: ScVariable)), _, _) if infix.isAssignmentOperator =>
          infix
        case MethodRepr(itself, Some(definedOutside(ScalaPsiUtil.inNameContext((_ : ScVariable | _: ScValue)))), Some(ref), _)
          if isSideEffectCollectionMethod(ref) || isSetter(ref) || hasUnitReturnType(ref) => itself
        case MethodRepr(itself, None, Some(ref @ definedOutside(_)), _) if hasUnitReturnType(ref) => itself
      }.toSeq
    }
  }

  def exprsWithSideEffects(expr: ScExpression): Seq[ScExpression] = CachedValuesManager.getCachedValue(expr, new SideEffectsProvider(expr))

  def hasSideEffects(expr: ScExpression): Boolean = exprsWithSideEffects(expr).nonEmpty

  def rightRangeInParent(expr: ScExpression, parent: ScExpression): TextRange = {
    if (expr == parent) return TextRange.create(0, expr.getTextLength)

    val endOffset = parent.getTextRange.getEndOffset

    val startOffset = expr match {
      case _ childOf ScInfixExpr(`expr`, op, _) => op.nameId.getTextOffset
      case _ childOf (ref @ ScReferenceExpression.withQualifier(`expr`)) => ref.nameId.getTextOffset
      case _ => expr.getTextRange.getEndOffset
    }
    TextRange.create(startOffset, endOffset).shiftRight( - parent.getTextOffset)
  }

  @tailrec
  def refNameId(expr: ScExpression): Option[PsiElement] = stripped(expr) match {
    case MethodRepr(_: ScMethodCall, Some(base), None, _) => refNameId(base)
    case MethodRepr(_, _,Some(ref), _) => Some(ref.nameId)
    case _ => None
  }

  implicit class PsiElementRange(val elem: PsiElement) extends AnyVal {
    def start: Int = elem.getTextRange.getStartOffset
    def end: Int = elem.getTextRange.getEndOffset
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<sect1 id="zend.service.slideshare">
    <title>Zend_Service_SlideShare</title>

    <para>
        Die <classname>Zend_Service_SlideShare</classname> wird verwendet um mit dem
        <ulink url="http://www.slideshare.net/">slideshare.net</ulink> Web Service für das
        Online-Hosten von Slideshows zu interagieren. Mit dieser Komponente kann eine Slideshow
        die in dieser Website gehostet wird in einer Website eingebettet und sogar neue
        Slideshows zum eigenen Account hochgeladen werden.
    </para>

    <sect2 id="zend.service.slideshare.basicusage">
        <title>Mit Zend_Service_SlideShare beginnen</title>

        <para>
            Um die <classname>Zend_Service_SlideShare</classname> Komponente zu verwenden muß zuerst
            ein Account auf den slideshare.net Servern erstellt werden (mehr Informationen können
            <ulink url="http://www.slideshare.net/developers/">hier</ulink> gefunden werden) um
            einen <acronym>API</acronym> Schlüssel, Benutzername, Passwort und einen geteilten
            geheimen Wert zu erhalten -- diese werden alle benötigt um die
            <classname>Zend_Service_SlideShare</classname> Komponente zu verwenden.
        </para>

        <para>
            Sobald ein Account erstellt wurde, kann die
            <classname>Zend_Service_SlideShare</classname> Komponente verwendet werden durch die
            Erstellung eines <classname>Zend_Service_SlideShare</classname> Objektes und dem
            anbieten dieser Werte wie anbei gezeigt:
        </para>

        <programlisting language="php"><![CDATA[
// Erstellt eine neue Instanz der Komponente
$ss = new Zend_Service_SlideShare('APIKEY',
                                  'SHAREDSECRET',
                                  'USERNAME',
                                  'PASSWORD');
]]></programlisting>
    </sect2>

    <sect2 id="zend.service.slideshare.slideshowobj">
        <title>Das SlideShow Objekt</title>

        <para>
            Alle Slideshows in der <classname>Zend_Service_SlideShare</classname> werden
            repräsentiert durch die Verwendung des
            <classname>Zend_Service_SlideShare_SlideShow</classname> Objektes (sowohl beim Empfangen
            als auch beim Hochladen neuer Slideshows). Zur Referenz ist eine Pseudo-Code Version
            dieser Klasse anbei zu sehen.
        </para>

        <programlisting language="php"><![CDATA[
class Zend_Service_SlideShare_SlideShow {

    /**
     * Empfängt den Ort der Slideshow
     */
    public function getLocation() {
        return $this->_location;
    }

    /**
     * Erhält das Transcript für die Slideshow
     */
    public function getTranscript() {
        return $this->_transcript;
    }

    /**
     * Fügt ein Tag zu der Slideshow hinzu
     */
    public function addTag($tag) {
        $this->_tags[] = (string)$tag;
        return $this;
    }

    /**
     * Setzt die Tags für die Slideshow
     */
    public function setTags(Array $tags) {
        $this->_tags = $tags;
        return $this;
    }

    /**
     * Erhält alle Tags die mit der Slideshow assoziiert sind
     */
    public function getTags() {
        return $this->_tags;
    }

    /**
     * Setzt den Dateinamen im Lokalen Filesystem der Slideshow
     * (für das Hochladen einer neuen Slideshow)
     */
    public function setFilename($file) {
        $this->_slideShowFilename = (string)$file;
        return $this;
    }

    /**
     * Empfängt den Dateinamen auf dem lokalen Dateisystem der Slideshow
     * die hochgeladen werden soll
     */
    public function getFilename() {
        return $this->_slideShowFilename;
    }

    /**
     * Empfängt die ID für die Slideshow
     */
    public function getId() {
        return $this->_slideShowId;
    }

    /**
     * Empfängt den eingebetteten HTML Code für die Slideshow
     */
    public function getEmbedCode() {
        return $this->_embedCode;
    }

    /**
     * Empfängt die Thumbnail URi für die Slideshow
     */
    public function getThumbnailUrl() {
        return $this->_thumbnailUrl;
    }

    /**
     * Setzt den Titel für die Slideshow
     */
    public function setTitle($title) {
        $this->_title = (string)$title;
        return $this;
    }

    /**
     * Empfängt den Titel der Slideshow
     */
    public function getTitle() {
        return $this->_title;
    }

    /**
     * Setzt die Beschreibung für die Slideshow
     */
    public function setDescription($desc) {
        $this->_description = (string)$desc;
        return $this;
    }

    /**
     * Empfängt die Beschreibung der Slideshow
     */
    public function getDescription() {
        return $this->_description;
    }

    /**
     * Erhält den nummerischen Status der Slideshow auf dem Server
     */
    public function getStatus() {
        return $this->_status;
    }

    /**
     * Erhält die textuelle Beschreibung des Status der Slideshow
     * auf dem Server
     */
    public function getStatusDescription() {
        return $this->_statusDescription;
    }

    /**
     * Erhält den permanenten Link der Slideshow
     */
    public function getPermaLink() {
        return $this->_permalink;
    }

    /**
     * Erhält die Anzahl der Aufrufe der Slideshow
     */
    public function getNumViews() {
        return $this->_numViews;
    }
}
]]></programlisting>

        <note>
            <para>
                Die obige Pseudo-Klasse zeigt nur die Methoden welche von End-Benutzer
                Entwicklern verwendet werden sollten. Andere vorhandene Methoden sind
                intern für die Komponente.
            </para>
        </note>

        <para>
            Wenn die <classname>Zend_Service_SlideShare</classname> Komponente verwendet wird, wird
            diese Daten Klasse sehr oft verwendet um nachzusehen oder neue Slideshows zu oder
            von einem Webservice hinzuzufügen.
        </para>
    </sect2>

    <sect2 id="zend.service.slideshare.getslideshow">
        <title>Empfangen einer einzelnen Slideshow</title>

        <para>
            Die einfachste Verwendung der <classname>Zend_Service_SlideShare</classname> Komponente
            ist der Empfang einer einzelnen Slideshow durch die Slideshow ID die von der
            slideshare.net Anwendung angeboten wird und kann durch den Aufruf der
            <methodname>getSlideShow()</methodname> auf einem
            <classname>Zend_Service_SlideShare</classname> Objekt und der Verwendung des
            resultierenden <classname>Zend_Service_SlideShare_SlideShow</classname> Objektes wie
            gezeigt durchgeführt werden.
        </para>

        <programlisting language="php"><![CDATA[
// Erstellt eine neue Instanz der Komponente
$ss = new Zend_Service_SlideShare('APIKEY',
                                  'SHAREDSECRET',
                                  'USERNAME',
                                  'PASSWORD');

$slideshow = $ss->getSlideShow(123456);

print "Slide Show Titel: {$slideshow->getTitle()}
\n";
print "Anzahl an Besuchen: {$slideshow->getNumViews()}
\n";
]]></programlisting>
    </sect2>

    <sect2 id="zend.service.slideshare.getslideshowlist">
        <title>Empfangen von Gruppen von Slideshows</title>

        <para>
            Wenn die spezielle ID einer Slideshow die einen interessiert und die man empfangen will
            nicht kennt, kann man auch Gruppen von Slideshows empfangen durch Verwendung einer der
            drei Methoden:
        </para>

        <itemizedlist mark="opencircle">
            <listitem>
                <para>
                    <emphasis>Slideshows von einem speziellen Account</emphasis>
                </para>

                <para>
                    Slideshows können von einem speziellen Account empfangen werden durch
                    Verwendung der <methodname>getSlideShowsByUsername()</methodname> Methode und
                    der Angabe des Benutzernamens von dem die Slideshow empfangen werden soll
                </para>
            </listitem>

            <listitem>
                <para>
                    <emphasis>Slideshows mit einem speziellen Tag</emphasis>
                </para>

                <para>
                    Slideshows können empfangen werden wenn Sie ein oder mehrere spezielle Tags
                    enthalten durch die Verwendung der <methodname>getSlideShowsByTag()</methodname>
                    Methode und der Angabe von ein oder mehreren Tags welche der Slideshow
                    zugeordnet sein müssen um Sie zu empfangen
                </para>
            </listitem>

            <listitem>
                <para>
                    <emphasis>Slideshows durch Gruppen</emphasis>
                </para>

                <para>
                    Man kann Slideshows empfangen welche Mitglied einer speziellen Gruppe sind
                    durch Verwendung der <methodname>getSlideShowsByGroup()</methodname> Methode und
                    der Angabe des Namens der Gruppe welcher die Slideshow angehören muß um Sie zu
                    Empfangen
                </para>
            </listitem>
        </itemizedlist>

        <para>
            Jede der obigen Methoden des Empfangens mehrerer Slideshows zeigt das ein ähnlicher
            Ansatz verwendet wird. Ein Beispiel der Verwendung jeder Methode wird anbei gezeigt:
        </para>

        <programlisting language="php"><![CDATA[
// Erstellt eine neue Instanz der Komponente
$ss = new Zend_Service_SlideShare('APIKEY',
                                  'SHAREDSECRET',
                                  'USERNAME',
                                  'PASSWORD');

$starting_offset = 0;
$limit = 10;

// Empfängt die ersten 10 jeden Typs
$ss_user = $ss->getSlideShowsByUser('username', $starting_offset, $limit);
$ss_tags = $ss->getSlideShowsByTag('zend', $starting_offset, $limit);
$ss_group = $ss->getSlideShowsByGroup('mygroup', $starting_offset, $limit);

// Durch die Slideshows iterieren
foreach($ss_user as $slideshow) {
   print "Slide Show Titel: {$slideshow->getTitle}
\n";
}
]]></programlisting>
    </sect2>

    <sect2 id="zend.service.slideshare.caching">
        <title>Zend_Service_SlideShare Caching Policy</title>

        <para>
            Standardmäßig cached <classname>Zend_Service_SlideShare</classname> jede Anfrage an den
            Webservice automatisch in das Dateisystem (Standardpfad <filename>/tmp</filename>) für
            12 Stunden. Wenn man das Verhalten ändern will, muß eine eigenes <link
                linkend="zend.cache">Zend_Cache</link> Objekt durch Verwendung der
            <methodname>setCacheObject()</methodname> Methode angegeben werden wie anbei gezeigt:
        </para>

        <programlisting language="php"><![CDATA[
$frontendOptions = array(
                        'lifetime' => 7200,
                        'automatic_serialization' => true);
$backendOptions  = array(
                        'cache_dir' => '/webtmp/');

$cache = Zend_Cache::factory('Core',
                             'File',
                             $frontendOptions,
                             $backendOptions);

$ss = new Zend_Service_SlideShare('APIKEY',
                                  'SHAREDSECRET',
                                  'USERNAME',
                                  'PASSWORD');
$ss->setCacheObject($cache);

$ss_user = $ss->getSlideShowsByUser('username', $starting_offset, $limit);
]]></programlisting>
    </sect2>

    <sect2 id="zend.service.slideshare.httpclient">
        <title>Das Verhalten des HTTP Clients ändern</title>

        <para>
            Wenn das Verhalten des <acronym>HTTP</acronym> Clients, aus welchen Gründen auch immer,
            geändert werden soll wenn eine Anfrage an den Webservice durchgeführt wird, kann das
            durch die Erstellung einer eigenen Instanz eines <classname>Zend_Http_Client</classname>
            Objektes durchgeführt werden (siehe <link linkend="zend.http">Zend_Http</link>). Das ist
            zum Beispiel nützlich wenn es gewünscht ist das Timeout für die Verbindung auf etwas
            anderes als den Standardwert zu setzen wie anbei gezeigt:
        </para>

        <programlisting language="php"><![CDATA[
$client = new Zend_Http_Client();
$client->setConfig(array('timeout' => 5));

$ss = new Zend_Service_SlideShare('APIKEY',
                                  'SHAREDSECRET',
                                  'USERNAME',
                                  'PASSWORD');
$ss->setHttpClient($client);
$ss_user = $ss->getSlideShowsByUser('username', $starting_offset, $limit);
]]></programlisting>
    </sect2>
</sect1>


text:
This is a prototype app for photon emission control, management, and data aggregation.

 The purpose of this application is to test connectivity to the photon device,
        read data from the devices sensors, and to control the device's functional aspects.
        To learn more visit: {{landingPage.photonSiteLink}}