text:
import { placements as rcPlacements } from 'rc-tooltip/lib/placements';

const autoAdjustOverflowEnabled = {
  adjustX: 1,
  adjustY: 1,
};

const autoAdjustOverflowDisabled = {
  adjustX: 0,
  adjustY: 0,
};

const targetOffset = [0, 0];

export interface AdjustOverflow {
  adjustX?: 0 | 1;
  adjustY?: 0 | 1;
}

export interface PlacementsConfig {
  arrowWidth?: number;
  horizontalArrowShift?: number;
  verticalArrowShift?: number;
  arrowPointAtCenter?: boolean;
  autoAdjustOverflow?: any;
}

export function getOverflowOptions(autoAdjustOverflow: any) {
  if (typeof autoAdjustOverflow === 'boolean') {
    return autoAdjustOverflow ? autoAdjustOverflowEnabled : autoAdjustOverflowDisabled;
  }
  return {
    ...autoAdjustOverflowDisabled,
    ...autoAdjustOverflow,
  };
}

export default function getPlacements(config: PlacementsConfig = {}) {
  const { arrowWidth = 5, horizontalArrowShift = 16, verticalArrowShift = 12, autoAdjustOverflow = true } = config;
  const placementMap: any = {
    left: {
      points: ['cr', 'cl'],
      offset: [-4, 0],
    },
    right: {
      points: ['cl', 'cr'],
      offset: [4, 0],
    },
    top: {
      points: ['bc', 'tc'],
      offset: [0, -4],
    },
    bottom: {
      points: ['tc', 'bc'],
      offset: [0, 4],
    },
    topLeft: {
      points: ['bl', 'tc'],
      offset: [-(horizontalArrowShift + arrowWidth), -4],
    },
    leftTop: {
      points: ['tr', 'cl'],
      offset: [-4, -(verticalArrowShift + arrowWidth)],
    },
    topRight: {
      points: ['br', 'tc'],
      offset: [horizontalArrowShift + arrowWidth, -4],
    },
    rightTop: {
      points: ['tl', 'cr'],
      offset: [4, -(verticalArrowShift + arrowWidth)],
    },
    bottomRight: {
      points: ['tr', 'bc'],
      offset: [horizontalArrowShift + arrowWidth, 4],
    },
    rightBottom: {
      points: ['bl', 'cr'],
      offset: [4, verticalArrowShift + arrowWidth],
    },
    bottomLeft: {
      points: ['tl', 'bc'],
      offset: [-(horizontalArrowShift + arrowWidth), 4],
    },
    leftBottom: {
      points: ['br', 'cl'],
      offset: [-4, verticalArrowShift + arrowWidth],
    },
  };
  Object.keys(placementMap).forEach(key => {
    placementMap[key] = config.arrowPointAtCenter ? {
      ...placementMap[key],
      overflow: getOverflowOptions(autoAdjustOverflow),
      targetOffset,
    } : {
      ...rcPlacements[key],
      overflow: getOverflowOptions(autoAdjustOverflow),
    };
  });
  return placementMap;
}


text:
from webcomix.comic import Comic
from webcomix.search import discovery
from webcomix.tests.fake_websites.fixture import (
    one_webpage_searchable_uri,
    three_webpages_uri,
    three_webpages_classes_uri,
)

def test_search_searchable_website(mocker, three_webpages_classes_uri):
    expected = Comic(
        "Blindsprings",
        three_webpages_classes_uri,
        "//*[contains(translate(@class, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz'), 'comic')]//@src",
        "//*[contains(translate(@class, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz'), 'next')]//@href",
    )
    mocker.patch("webcomix.search.possible_image_xpath", ["comic"])
    mocker.patch("webcomix.search.possible_next_page_xpath", ["next"])
    mocker.patch("webcomix.search.possible_tags_image", ["*"])
    mocker.patch("webcomix.search.possible_tags_next", ["*"])
    mocker.patch("webcomix.search.possible_attributes_image", ["@class"])
    mocker.patch("webcomix.search.possible_attributes_next", ["@class"])
    mocker.patch("webcomix.util.check_first_pages")
    comic, result = discovery("Blindsprings", three_webpages_classes_uri)

    three_webpages_classes_folder = three_webpages_classes_uri.strip("1.html")

    assert result == [
        {
            "page": 1,
            "url": three_webpages_classes_uri,
            "image_urls": [three_webpages_classes_folder + "1.jpeg"],
            "alt_text": None,
        },
        {
            "page": 2,
            "url": three_webpages_classes_folder + "2.html",
            "image_urls": [three_webpages_classes_folder + "2.jpeg"],
            "alt_text": None,
        },
        {
            "page": 3,
            "url": three_webpages_classes_folder + "3.html",
            "image_urls": [three_webpages_classes_folder + "3.jpeg"],
            "alt_text": None,
        },
    ]

    assert comic.start_url == expected.start_url
    assert comic.next_page_selector == expected.next_page_selector
    assert comic.comic_image_selector == expected.comic_image_selector

def test_search_unsearchable_website(mocker, three_webpages_uri):
    mocker.patch("webcomix.search.possible_image_xpath", ["comic"])
    mocker.patch("webcomix.search.possible_next_page_xpath", ["next"])
    mocker.patch("webcomix.search.possible_tags_image", ["*"])
    mocker.patch("webcomix.search.possible_tags_next", ["*"])
    mocker.patch("webcomix.search.possible_attributes_image", ["@class"])
    mocker.patch("webcomix.search.possible_attributes_next", ["@class"])

    assert discovery("test", three_webpages_uri) == (None, None)

def test_can_stop_searching(mocker, three_webpages_classes_uri):
    mocker.patch("webcomix.search.possible_image_xpath", ["comic"])
    mocker.patch("webcomix.search.possible_next_page_xpath", ["next"])
    mocker.patch("webcomix.search.possible_tags_image", ["div"])
    mocker.patch("webcomix.search.possible_tags_next", ["div"])
    mocker.patch("webcomix.search.possible_attributes_image", ["@rel"])
    mocker.patch("webcomix.search.possible_attributes_next", ["@class"])
    exit_called = mocker.patch("sys.exit")
    mocker.patch("webcomix.comic.Comic.verify_xpath", side_effect=KeyboardInterrupt)
    result = discovery("test", three_webpages_classes_uri)
    assert exit_called.call_count == 1
    assert result == (None, None)

def test_can_find_single_page_correctly_while_searching(
    mocker, one_webpage_searchable_uri
):
    mocker.patch("webcomix.search.possible_image_xpath", ["image"])
    mocker.patch("webcomix.search.possible_next_page_xpath", ["next"])
    mocker.patch("webcomix.search.possible_tags_image", ["*"])
    mocker.patch("webcomix.search.possible_tags_next", ["*"])
    mocker.patch("webcomix.search.possible_attributes_image", ["@class"])
    mocker.patch("webcomix.search.possible_attributes_next", ["."])

    comic, result = discovery("test", one_webpage_searchable_uri, single_page=True)

    validation = comic.verify_xpath()

    assert len(result) == 1
    assert result == validation
    assert len(result[0]["image_urls"]) == 2

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Webforge\CmsBundle;

use Gaufrette\Filesystem;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Webforge\CmsBundle\Media\Manager;

class MediaControllerTest extends \Webforge\Testing\WebTestCase
{
    use \Webforge\Testing\TestTrait;

    protected function setupEmpty()
    {
        $client = self::makeClient($this->credentials['petra']);

        $this->loadAliceFixtures(
            array(
                'users'
            ),
            $client
        );

        $this->emptyFileSystemAndCache($client);

        return $client;
    }

    public function testMediaControllerReturnsTheEmptyStructure()
    {
        $client = $this->setupEmpty();

        $this->sendJsonRequest($client, 'GET', '/cms/media');

        $this->assertJsonResponse(200, $client)
            ->property('root')
            ->property('type', 'ROOT')->end()
            ->property('items')->isArray()->length(0);
    }

    public function testImagesAndOtherStuffSaving()
    {
        $client = $this->setupEmpty();

        $json = $this->getDropboxFiles();
        $this->sendJsonRequest($client, 'POST', '/cms/media/dropbox', $json);

        $dsc03281Key = $this->assertJsonResponse(201, $client)
            ->property('root')
            ->property('type', 'ROOT')->end()
            ->property('items')->isArray()
            ->key(0)
            ->property('name', '2016-03-27')->end()
            ->property('type', 'directory')->end()
            ->property('items')->isArray()
            ->key(0)
            ->property('name', 'dsc03281.jpg')->end()
            ->property('url')->isNotEmpty()->end()
            ->property('isExisting')->is(true)->end()
            ->property('thumbnails')->isObject()
            ->property('sm')
            ->property('orientation')->is('landscape')->end()
            ->property('isPortrait')->is(false)->end()
            ->property('isLandscape')->is(true)->end()
            ->property('width')->is($this->greaterThan(0))->end()
            ->property('height')->is($this->greaterThan(0))->end()
            ->property('url')->contains('fit')->contains('dsc03281.jpg')->end()
            ->end()
            ->property('xs')
            ->property('name')->is('xs')->end()
            ->end()
            ->end()
            ->property('key')->isNotEmpty()->get();

        $filesystem = $this->getFilesystem($client);
        $this->assertTrue($filesystem->has($dsc03281Key));

        $this->assertDatabaseBinaries($client, [
            $dsc03281Key => true
        ]);
    }

    public function testImageBatchDeleting()
    {
        $client = $this->setupEmpty();

        $keys = $this->storeFiles($client, [
            'test-image.png' => 'tapire.png',
            'something/test-image2.png' => 'mini-single.png'
        ]);

        $json = (object)['keys' => $keys];

        $this->sendJsonRequest($client, 'DELETE', '/cms/media', $json);
        $this->assertJsonResponse(200, $client)
            ->property('root')
            ->property('type', 'ROOT')->end()
            ->property('items')->isArray()->length(0);

        // this is a very internal test
        $filesystem = $this->getFilesystem($client);
        $this->assertFalse($filesystem->has($keys[0]));
        $this->assertFalse($filesystem->has($keys[1]));

        $this->assertDatabaseBinaries($client, []);
    }

    public function testExistingImagesWillBeOverwritten_AndNoticed_whenUploadedPerDropbox()
    {
        $client = $this->setupEmpty();

        list($key1, $oldKey) = $this->storeFiles($client, [
            'folder/tapire.png' => 'tapire.png',
            'folder/mini-single.png' => 'tapire.png'
        ]);

        $json = $this->getDropboxFiles();
        $uploadUrl = $json->dropboxFiles[0]->link;
        $json->dropboxFiles[0]->name = 'mini-single.png';
        $json->path = '/folder/';
        $this->sendJsonRequest($client, 'POST', '/cms/media/dropbox', $json);

        $this->assertJsonResponse(201, $client)
            ->property('warnings')->isArray()->length(1)
                ->key(0)->contains('folder/mini-single.png')->contains('existiert')->contains('überschrieben')->end()
            ->end()
            ->property('root')
                ->property('items')->isArray()->end()
            ->end();

        $manager = $client->getContainer()->get('webforge.media.manager');
        /** @var Manager $manager */
        $binary = $manager->findFileByPath('folder/mini-single.png');

        $this->assertTrue(
            file_get_contents($uploadUrl) === file_get_contents($manager->getStreamUrl($binary)),
            'the file should be overwritten from the uploaded dropbox url contents (contents do not equal from streams)'
        );

        $this->assertNotEquals($oldKey, $binary->getMediaFileKey(), 'the key should have changed, because thumbnails caching should reset');
        $this->assertFalse($this->getFilesystem($client)->has($oldKey), 'the old image file should be deleted');
    }

    public function testThatImagesWithBadNamesWillBeUrlified()
    {
        $client = $this->setupEmpty();

        $json = $this->getDropboxFiles();
        $json->dropboxFiles[0]->name = '20140825-IMGP4127_Käernten superpilß.jpg';
        $json->path = '/folder2/';
        $this->sendJsonRequest($client, 'POST', '/cms/media/dropbox', $json);

        $this->assertJsonResponse(201, $client)
            ->property('root')
            ->property('items')->isArray()
                ->key(0)
                    ->property('name', 'folder2')->end()
                    ->property('items')->isArray()
                        ->key(0)->property('name', '20140825-imgp4127-kaeernten-superpilss.jpg');
    }

    public function testMovingASingleFileFromOneToAnotherDirectory()
    {
        $client = $this->setupEmpty();

        $this->storeFiles($client, [
            'folder1/folder2/tapire.png' => 'tapire.png',
            'other/mini.png' => 'mini-single.png'
        ]);

        $this->sendJsonRequest($client, 'POST', '/cms/media/move', (object)[
            'sources' => ["other/mini.png"],
            'target' => 'folder1/folder2/'
        ]);

        $response = $this->assertJsonResponse(200, $client);

        $this->assertMediaFiles($response, [
            'folder1/folder2/tapire.png',
            'folder1/folder2/mini.png'
        ]);
    }

    public function testMovingCompleteFolderToAnother()
    {
        $client = $this->setupEmpty();

        $this->storeFiles($client, [
            'folder1/folder2/tapire.png' => 'tapire.png',
            'folder1/mini.png' => 'mini-single.png'
        ]);

        $this->sendJsonRequest($client, 'POST', '/cms/media/move', (object)[
            'sources' => ["folder1"],
            'target' => 'otherroot/'
        ]);

        $response = $this->assertJsonResponse(200, $client);

        $this->assertMediaFiles($response, [
            'otherroot/folder1/folder2/tapire.png',
            'otherroot/folder1/mini.png'
        ]);
    }

    public function testRenamingAFolderInPath()
    {
        $client = $this->setupEmpty();

        $keys = $this->storeFiles($client, [
            'folder1/folder2/tapire.png' => 'tapire.png',
            'folder1/mini.png' => 'mini-single.png'
        ]);

        $this->sendJsonRequest($client, 'POST', '/cms/media/rename', (object)[
            'path' => "folder1/",
            'name' => 'tapire'
        ]);

        $response = $this->assertJsonResponse(200, $client);

        $this->assertMediaFiles($response, [
            'tapire/folder2/tapire.png',
            'tapire/mini.png'
        ]);
    }

    public function testRenamingAfile()
    {
        $client = $this->setupEmpty();

        $keys = $this->storeFiles($client, [
            'folder1/mini.png' => 'mini-single.png'
        ]);

        $this->sendJsonRequest($client, 'POST', '/cms/media/rename', (object)[
            'path' => "folder1/mini.png",
            'name' => 'mini-360px.png'
        ]);

        $response = $this->assertJsonResponse(200, $client);

        $this->assertMediaFiles($response, [
            'folder1/mini-360px.png'
        ]);

        $binaries = $client->getContainer()->get('webforge.media.manager')->findFiles($keys);
        $this->assertEquals('mini-360px.png', $binaries[0]->getMediaName(), 'name in entity should be changed as well');
    }

    public function testRenamingAfileWithoutNameMakesNoSense()
    {
        $client = $this->setupEmpty();

        $keys = $this->storeFiles($client, [
            'folder1/mini.png' => 'mini-single.png'
        ]);

        $this->sendJsonRequest($client, 'POST', '/cms/media/rename', (object)[
            'path' => "folder1/mini.png",
            'name' => ''
        ]);

        $this->assertJsonResponse(400, $client)
            ->property('validation')
            ->property('errors')
            ->isArray()->length(1)
            ->key(0)
            ->property('field')
            ->property('path', 'name')->end();
    }

    public function testUploadingFilesConventional()
    {
        $client = $this->setupEmpty();

        $file = $this->getResourceImage('background.jpg');
        $photo = new UploadedFile(
            (string)$file,
            'background.jpg',
            'image/jpeg',
            123
        );

        $client->request(
            'POST',
            '/cms/media/upload?thumbnails[]=xs',
            array('path' => 'uploaded/2017/02/'),
            array('files' => [$photo])
        );

        $response = $this->assertJsonResponse(201, $client)
            ->property('warnings')->isArray()->length(0)->end()
            ->property('files')->isArray()->length(1)
                ->key(0)
                    ->property('thumbnails')
                        ->property('xs')->end()
                    ->end()
                    ->property('url')->end()
                ->end();

        $this->sendJsonRequest($client, 'GET', '/cms/media');
        $response = $this->assertJsonResponse(200, $client);

        $this->assertMediaFiles($response, [
            'uploaded/2017/02/background.jpg'
        ]);
    }

    public function testUploadingAlreadyExistingFilesConventional()
    {
        $client = $this->setUpEmpty();

        $keys = $this->storeFiles($client, [
            '/2016-03-27/DSC03281.JPG' => 'background.jpg'
        ]);

        $file = $this->getResourceImage('mini-single.png');
        $photo = new UploadedFile(
            (string) $file,
            'DSC03281.JPG',
            'image/jpeg'
        );

        $client->request(
            'POST',
            '/cms/media/upload',
            array('path' => '/2016-03-27'),
            array('files' => [$photo])
        );

        $this->assertJsonResponse(201, $client)
            ->property('warnings')->isArray()->length(1)->end()
            ->property('files')->isArray()->length(1)
                ->key(0)
                    ->property('name', 'dsc03281.jpg');

        $this->sendJsonRequest($client, 'GET', '/cms/media');
        $response = $this->assertJsonResponse(200, $client);

        $this->assertMediaFiles($response, [
            '2016-03-27/dsc03281.jpg'
        ]);
    }

    public function testGetWithThumbnailsFilter()
    {
        $client = $this->setUpEmpty();
        $json = $this->getDropboxFiles();
        $this->sendJsonRequest($client, 'POST', '/cms/media/dropbox', $json);

        $this->sendJsonRequest($client, 'GET', '/cms/media?thumbnails[]=xs');

        $response = $this->assertJsonResponse(200, $client);

        $thumbnails = $response->property('root')
            ->property('items')->key(0)
                ->property('items')->key(0)
                    ->property('thumbnails')
                        ->property('xs')->isObject()->end()
                    ->get();

        $this->assertEquals(['xs'], array_keys((array)$thumbnails), 'only xs thumbnails should be generated');
    }

    private function assertMediaFiles($response, array $flatFiles)
    {
        $root = $response->property('root')
            ->property('items')->end()
            ->get();

        // do the tree => flat conversion (Tiefensuche)
        $files = [];
        $stack = [$root];
        $path = [];
        while (count($stack) > 0) {
            $item = array_pop($stack);

            if ($item->type === 'directory' || $item->type === 'ROOT') {
                foreach ($item->items as $child) {
                    $stack[] = $child;
                }

                if ($item->type === 'directory') {
                    $path[] = $item->name;
                }
            } else {
                $files[] = $f = implode('/', $path).'/'.$item->name;
            }
        }

        $this->assertArrayEquals($flatFiles, $files);
    }

    private function assertDatabaseBinaries($client, array $files)
    {
        $dc = $client->getContainer()->get('dc');

        $binaries = $dc->getRepository('Binary')->findAll();
        $actualBinaries = array();

        foreach ($binaries as $binary) {
            $actualBinaries[] = $binary->getMediaFileKey();
        }

        $this->assertArrayEquals(array_keys($files), $actualBinaries, 'gaufretteKeys from Binaries in Database:');
    }

    private function getDropboxFiles()
    {
        // normally link is something like: https://dl.dropboxusercontent.com/1/view/hhkjprs3c7kxk98/Theo%20Family/2016-04-07%20Besuch%20Judith%2C%20Martin%20und%20Marlene/DSC03281.JPG
        // we fake it here to a local url
        $json = $this->parseJSON(
            <<<'JSON'
{
  "dropboxFiles": [
    {
      "isDir": false,
      "link": "%hostUrl%/assets/img/mini-single.png",
      "name": "DSC03281.JPG",
      "thumbnailLink": "https://api-content.dropbox.com/r11/t/AAA217oe69t24DpE6JGjbftPxAjLMBlPRyX2On6_ot1FhA/12/886689/jpeg/_/0/4/DSC03281.JPG/CKGPNiACIAcoAigH/hhkjprs3c7kxk98/AABbOb3Ey4HiK9oLYO6InxRsa/DSC03281.JPG?bounding_box=75&mode=fit",
      "is_dir": false,
      "bytes": 2089395,
      "icon": "https://www.dropbox.com/static/images/icons64/page_white_picture.png"
    }
  ],
  "path": "/2016-03-27/"
}
JSON
        );

        $json->dropboxFiles[0]->link = str_replace(
            '%hostUrl%',
            getenv('SYMFONY_BASEURL'),
            $json->dropboxFiles[0]->link
        );

        return $json;
    }

    protected function getResourceImage($filename)
    {
        return $GLOBALS['env']['root']->sub('Resources/img/')->getFile($filename);
    }

    protected function emptyFileSystemAndCache($client)
    {
        $filesystem = $client->getContainer()->get('knp_gaufrette.filesystem_map')->get('cms_media');

        foreach ($filesystem->keys() as $key) {
            $filesystem->delete($key);
        }
    }

    protected function getFilesystem($client) : Filesystem
    {
        return $client->getContainer()->get('knp_gaufrette.filesystem_map')->get('cms_media');
    }

    protected function storeFiles($client, array $files)
    {

        // this is a shortcut to insert binaries, we could query the mediaController dropboxUpload everytime (or use another web request here, or use fixtures) which would be cleaner
        $manager = $client->getContainer()->get('webforge.media.manager');
        $manager->beginTransaction();

        $keys = array();
        foreach ($files as $targetPath => $source) {
            $targetPath = '/'.$targetPath;
            $targetName = mb_substr($targetPath, strrpos($targetPath, '/') + 1);
            $targetPath = mb_substr($targetPath, 0, strrpos($targetPath, '/'));

            $entity = $manager->addFile($targetPath, $targetName, $this->getResourceImage($source)->getContents());
            $keys[] = $entity->getMediaFileKey();
        }

        $manager->commitTransaction();
        return $keys;
    }
}


text:
package com.francetelecom.clara.cloud.paas.activation.v1.async;

public class RetryContext {

	private int retryCount;

    public RetryContext(int retryCount) {
		super();
		this.retryCount = retryCount;
	}

	public int getRetryCount() {
		return retryCount;
	}

	public void setRetryCount(int retryCount) {
		this.retryCount = retryCount;
	}

}


text:
<?php

namespace pharext;

/**
 * Command interface
 */
interface Command
{
	/**
	 * Argument error
	 */
	const EARGS = 1;
	/**
	 * Build error
	 */
	const EBUILD = 2;
	/**
	 * Signature error
	 */
	const ESIGN = 3;
	/**
	 * Extract/unpack error
	 */
	const EEXTRACT = 4;
	/**
	 * Install error
	 */
	const EINSTALL = 5;

	/**
	 * Retrieve command line arguments
	 * @return pharext\Cli\Args
	 */
	public function getArgs();

	/**
	 * Print debug message
	 * @param string $fmt
	 * @param string ...$args
	 */
	public function debug($fmt);

	/**
	 * Print info
	 * @param string $fmt
	 * @param string ...$args
	 */
	public function info($fmt);

	/**
	 * Print warning
	 * @param string $fmt
	 * @param string ...$args
	 */
	public function warn($fmt);

	/**
	 * Print error
	 * @param string $fmt
	 * @param string ...$args
	 */
	public function error($fmt);

	/**
	 * Execute the command
	 * @param int $argc command line argument count
	 * @param array $argv command line argument list
	 */
	public function run($argc, array $argv);
}


text:
from matplotlib import pyplot as plt
import numpy as np
import pymc as pm

from IPython.core.pylabtools import figsize

def main():
    figsize(12.5, 3.5)
    np.set_printoptions(precision=3, suppress=True)
    challenger_data = np.genfromtxt("challenger_data.csv", skip_header=1,
                                    usecols=[1, 2], missing_values="NA",
                                    delimiter=",")
    # drop the NA values
    challenger_data = challenger_data[~np.isnan(challenger_data[:, 1])]

    # plot it, as a function of temperature (the first column)
    print "Temp (F), O-Ring failure?"
    print challenger_data

    plt.scatter(challenger_data[:, 0], challenger_data[:, 1], s=75, color="k",
                alpha=0.5)
    plt.yticks([0, 1])
    plt.ylabel("Damage Incident?")
    plt.xlabel("Outside temperature (Fahrenheit)")
    plt.title("Defects of the Space Shuttle O-Rings vs temperature")
    plt.show()

if __name__ == '__main__':
    main()


text:
package com.intellij.openapi.roots.ui.configuration.actions;

import com.intellij.CommonBundle;
import com.intellij.ide.DeleteProvider;
import com.intellij.ide.TitledHandler;
import com.intellij.ide.projectView.ProjectView;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.*;
import com.intellij.openapi.module.impl.LoadedModuleDescriptionImpl;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectBundle;
import com.intellij.openapi.roots.ModifiableRootModel;
import com.intellij.openapi.roots.ModuleOrderEntry;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.OrderEntry;
import com.intellij.openapi.roots.impl.ModifiableModelCommitter;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.NlsContexts;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.project.ProjectKt;
import com.intellij.projectImport.ProjectAttachProcessor;
import com.intellij.util.PathUtilRt;
import com.intellij.util.PlatformUtils;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;

import java.nio.file.Path;
import java.util.*;
import java.util.stream.Collectors;

public class ModuleDeleteProvider  implements DeleteProvider, TitledHandler  {
  @Override
  public boolean canDeleteElement(@NotNull DataContext dataContext) {
    final Module[] modules = LangDataKeys.MODULE_CONTEXT_ARRAY.getData(dataContext);
    List<UnloadedModuleDescription> unloadedModules = ProjectView.UNLOADED_MODULES_CONTEXT_KEY.getData(dataContext);
    return modules != null && !containsPrimaryModule(modules) || unloadedModules != null && !unloadedModules.isEmpty();
  }

  private static boolean containsPrimaryModule(Module[] modules) {
    if (!ProjectAttachProcessor.canAttachToProject()) {
      return !PlatformUtils.isIntelliJ();
    }

    for (Module module : modules) {
      String moduleFile = module.getModuleFilePath();
      Project project = module.getProject();
      if (!ProjectKt.isDirectoryBased(project)) {
        continue;
      }

      Path ideaDir = ProjectKt.getStateStore(project).getDirectoryStorePath();
      if (ideaDir != null && PathUtilRt.getParentPath(moduleFile).equals(FileUtil.toSystemIndependentName(ideaDir.toString()))) {
        return true;
      }
    }
    return false;
  }

  @Override
  public void deleteElement(@NotNull DataContext dataContext) {
    final Project project = CommonDataKeys.PROJECT.getData(dataContext);
    assert project != null;

    List<ModuleDescription> moduleDescriptions = new ArrayList<>();
    final Module[] modules = LangDataKeys.MODULE_CONTEXT_ARRAY.getData(dataContext);
    if (modules != null) {
      moduleDescriptions.addAll(ContainerUtil.map(modules, LoadedModuleDescriptionImpl::new));
    }
    List<UnloadedModuleDescription> unloadedModules = ProjectView.UNLOADED_MODULES_CONTEXT_KEY.getData(dataContext);
    if (unloadedModules != null) {
      moduleDescriptions.addAll(unloadedModules);
    }

    String names = StringUtil.join(moduleDescriptions, description -> "'" + description.getName() + "'", ", ");
    int ret = Messages.showOkCancelDialog(getConfirmationText(names, moduleDescriptions.size()), getActionTitle(), CommonBundle.message("button.remove"), CommonBundle.getCancelButtonText(), Messages.getQuestionIcon());
    if (ret != Messages.OK) return;
    CommandProcessor.getInstance().executeCommand(project, () -> {
      final Runnable action = () -> {
        final ModuleManager moduleManager = ModuleManager.getInstance(project);
        final Module[] currentModules = moduleManager.getModules();
        final ModifiableModuleModel modifiableModuleModel = moduleManager.getModifiableModel();
        final Map<Module, ModifiableRootModel> otherModuleRootModels = new HashMap<>();
        Set<String> moduleNamesToDelete = moduleDescriptions.stream().map(ModuleDescription::getName).collect(Collectors.toSet());
        for (final Module otherModule : currentModules) {
          if (!moduleNamesToDelete.contains(otherModule.getName())) {
            otherModuleRootModels.put(otherModule, ModuleRootManager.getInstance(otherModule).getModifiableModel());
          }
        }
        removeDependenciesOnModules(moduleNamesToDelete, otherModuleRootModels.values());
        if (modules != null) {
          for (final Module module : modules) {
            for (ProjectAttachProcessor processor : ProjectAttachProcessor.EP_NAME.getExtensionList()) {
              processor.beforeDetach(module);
            }
            modifiableModuleModel.disposeModule(module);
          }
        }
        final ModifiableRootModel[] modifiableRootModels = otherModuleRootModels.values().toArray(new ModifiableRootModel[0]);
        ModifiableModelCommitter.multiCommit(modifiableRootModels, modifiableModuleModel);
        if (unloadedModules != null) {
          moduleManager.removeUnloadedModules(unloadedModules);
        }
      };
      ApplicationManager.getApplication().runWriteAction(action);
    }, ProjectBundle.message("module.remove.command"), null);
  }

  private static @NlsContexts.DialogMessage String getConfirmationText(String names, int numberOfModules) {
    if (ProjectAttachProcessor.canAttachToProject()) {
      return ProjectBundle.message("project.remove.confirmation.prompt", names, numberOfModules);
    }
    return ProjectBundle.message("module.remove.confirmation.prompt", names, numberOfModules);
  }

  @Override
  public String getActionTitle() {
    return ProjectAttachProcessor.canAttachToProject() ? ProjectBundle.message("action.text.remove.from.project.view")
                                                       : ProjectBundle.message("action.text.remove.module");
  }

  public static void removeModule(@NotNull final Module moduleToRemove,
                                  @NotNull Collection<? extends ModifiableRootModel> otherModuleRootModels,
                                  @NotNull final ModifiableModuleModel moduleModel) {
    removeDependenciesOnModules(Collections.singleton(moduleToRemove.getName()), otherModuleRootModels);
    moduleModel.disposeModule(moduleToRemove);
  }

  private static void removeDependenciesOnModules(@NotNull Set<String> moduleNamesToRemove,
                                                  @NotNull Collection<? extends ModifiableRootModel> otherModuleRootModels) {
    for (final ModifiableRootModel modifiableRootModel : otherModuleRootModels) {
      final OrderEntry[] orderEntries = modifiableRootModel.getOrderEntries();
      for (final OrderEntry orderEntry : orderEntries) {
        if (orderEntry instanceof ModuleOrderEntry && moduleNamesToRemove.contains(((ModuleOrderEntry)orderEntry).getModuleName())) {
          modifiableRootModel.removeOrderEntry(orderEntry);
        }
      }
    }
  }
}


text:
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';

import { AdminComponent } from './admin.component';
import { newElectionComponent } from './new-election/new-election.component';
// Import HttpClientModule from @angular/common/http
import {HttpClientModule} from '@angular/common/http';

import {
    MatInputModule,
    MatSortModule,
    MatButtonModule,
    MatCheckboxModule,
    MatCardModule,
    MatPaginatorModule,
    MatTableModule,
    MatTabsModule,
    MatStepperModule,
    MatNativeDateModule,
    MatDatepickerModule,
    MatListModule,
    MatExpansionModule,
    MatRadioModule,
    MatGridListModule
} from '@angular/material';

@NgModule({
    declarations: [
        AdminComponent,
        newElectionComponent
    ],
    imports: [
        BrowserModule,
        BrowserAnimationsModule,
        FormsModule,
        MatInputModule,
        MatButtonModule,
        MatCheckboxModule,
        MatCardModule,
        /** Election table modules */
        MatTabsModule,
        MatTableModule,
        MatSortModule,
        MatTabsModule,
        MatPaginatorModule,
        /** Create new election modules */
        MatStepperModule,
        ReactiveFormsModule,
        MatNativeDateModule,
        MatDatepickerModule,
        MatListModule,
        MatExpansionModule,
        MatRadioModule,
        MatGridListModule,
        //http module
        HttpClientModule,
    ],
    exports: [
        AdminComponent,
        /** Election table modules */
        MatTableModule,
    ],
    providers: [],
    bootstrap: [AdminComponent]
})
export class AdminModule {
}


text:
const webpack = require('webpack');
const path = require('path');

module.exports = (opts) => {

    const plugins = opts.prod ? [
        new webpack.optimize.UglifyJsPlugin({
            compress: {warnings: false},
            output: {comments: false}
        })
    ] : [
        new webpack.ProvidePlugin({
            THREE: 'three'
        }),
        new webpack.HotModuleReplacementPlugin()
    ];

    return {
        context: path.join(__dirname, 'src/scripts'),
        entry: [
            './index.js'
        ],
        output: {
            path: path.join(__dirname, 'dist'),
            publicPath: '',
            filename: 'scripts/app.js'
        },
        plugins,
        module: {
            noParse: [
                path.join(__dirname, 'node_modules', 'three')
            ],
            preLoaders: [{
                test: /\.jsx?$/,
                loader: 'eslint',
                include: path.join(__dirname, 'src/scripts')
            }],
            loaders: [{
                test: /\.jsx?$/,
                loader: 'babel',
                include: path.join(__dirname, 'src/scripts')
            }, {
                test: /\.(glsl|vert|frag)$/,
                loader: 'webpack-glsl'
            }, {
                test: /\.json$/,
                loader: 'json'
            }]
        },
        eslint: {emitWarning: true},
        debug: !opts.prod,

        devtool: opts.prod ? undefined : 'cheap-source-map'
    };
};


text:
<?php

namespace IdeasBucket\Common\Swiftmailer\Transport;

use GuzzleHttp\ClientInterface;
use Swift_Mime_Message;

/**
 * Class MandrillTransport.
 *
 * @see https://github.com/laravel/framework/blob/5.3/LICENSE.md
 */
class Mandrill extends AbstractTransport
{
    /**
     * Guzzle client instance.
     *
     * @var \GuzzleHttp\ClientInterface
     */
    protected $client;

    /**
     * The Mandrill API key.
     *
     * @var string
     */
    protected $key;

    /**
     * Create a new Mandrill transport instance.
     *
     * @param  \GuzzleHttp\ClientInterface  $client
     * @param  string  $key
     */
    public function __construct(ClientInterface $client, $key)
    {
        $this->client = $client;
        $this->key = $key;
    }

    /**
     * {@inheritdoc}
     */
    public function send(Swift_Mime_Message $message, &$failedRecipients = null)
    {
        $this->beforeSendPerformed($message);

        $data = [
            'key' => $this->key,
            'to' => $this->getToAddresses($message),
            'raw_message' => $message->toString(),
            'async' => true,
        ];

        if (version_compare(ClientInterface::VERSION, '6') === 1) {

            $options = ['form_params' => $data];

        } else {

            $options = ['body' => $data];

        }

        $this->client->post('https://mandrillapp.com/api/1.0/messages/send-raw.json', $options);

        $this->sendPerformed($message);

        return $this->numberOfRecipients($message);
    }

    /**
     * Get all the addresses this message should be sent to.
     *
     * Note that Mandrill still respects CC, BCC headers in raw message itself.
     *
     * @param  \Swift_Mime_Message $message
     * @return array
     */
    protected function getToAddresses(Swift_Mime_Message $message)
    {
        $to = [];

        if ($message->getTo()) {

            $to = array_merge($to, array_keys($message->getTo()));

        }

        if ($message->getCc()) {

            $to = array_merge($to, array_keys($message->getCc()));

        }

        if ($message->getBcc()) {

            $to = array_merge($to, array_keys($message->getBcc()));

        }

        return $to;
    }

    /**
     * Get the API key being used by the transport.
     *
     * @return string
     */
    public function getKey()
    {
        return $this->key;
    }

    /**
     * Set the API key being used by the transport.
     *
     * @param  string  $key
     * @return string
     */
    public function setKey($key)
    {
        return $this->key = $key;
    }
}


text:
package com.tectonica.jonix.unify.base.onix3;

import com.tectonica.jonix.onix3.Contributor;
import com.tectonica.jonix.onix3.Product;
import com.tectonica.jonix.unify.base.BaseContributor;
import com.tectonica.jonix.unify.base.BaseContributors;
import com.tectonica.jonix.unify.base.util.Helper;

import java.util.List;

/**
 * ONIX3 concrete implementation for {@link BaseContributors}
 *
 * @author Zach Melamed
 */
public class BaseContributors3 extends BaseContributors {
    private static final long serialVersionUID = 1L;

    private final transient List<Contributor> contributors;

    private final transient BaseFactory3 factory;

    public BaseContributors3(Product product) {
        this(product, BaseFactory3.DEFAULT);
    }

    public BaseContributors3(Product product, BaseFactory3 factory) {
        this.factory = factory;
        contributors = product.descriptiveDetail().contributors();
    }

    public BaseContributors3(com.tectonica.jonix.onix3.Collection collection) {
        this(collection, BaseFactory3.DEFAULT);
    }

    public BaseContributors3(com.tectonica.jonix.onix3.Collection collection, BaseFactory3 factory) {
        this.factory = factory;
        contributors = collection.contributors();
    }

    @Override
    protected List<BaseContributor> initialize() {
        List<BaseContributor> list = Helper.createList(contributors, factory.baseContributorFactory);
        sortBySequence(list);
        return list;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<section xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="zend.gdata.exception"><title>Catching Gdata Exceptions</title>

    <para>
        The <classname>Zend_Gdata_App_Exception</classname> class is a base class
        for exceptions thrown by <classname>Zend_Gdata</classname>. You can catch any exception
        thrown by <classname>Zend_Gdata</classname> by catching
        <classname>Zend_Gdata_App_Exception</classname>.
    </para>

    <programlisting language="php"><![CDATA[
try {
    $client =
        Zend_Gdata_ClientLogin::getHttpClient($username, $password);
} catch(Zend_Gdata_App_Exception $ex) {
    // Report the exception to the user
    die($ex->getMessage());
}
]]></programlisting>

    <para>
        The following exception subclasses are used by <classname>Zend_Gdata</classname>:

        <itemizedlist>
            <listitem>
                <para>
                    <classname>Zend_Gdata_App_AuthException</classname>
                    indicates that the user's account credentials were not valid.
                </para>
            </listitem>

            <listitem>
                <para>
                    <classname>Zend_Gdata_App_BadMethodCallException</classname>
                    indicates that a method was called for a service
                    that does not support the method. For example,
                    the CodeSearch service does not support <methodname>post()</methodname>.
                </para>
            </listitem>

            <listitem>
                <para>
                    <classname>Zend_Gdata_App_HttpException</classname>
                    indicates that an <acronym>HTTP</acronym> request was not successful.
                    Provides the ability to get the full <classname>Zend_Http_Response</classname>
                    object to determine the exact cause of the failure in
                    cases where <command>$e->getMessage()</command> does not provide
                    enough details.
                </para>
            </listitem>

            <listitem>
                <para>
                    <classname>Zend_Gdata_App_InvalidArgumentException</classname>
                    is thrown when the application provides a value that
                    is not valid in a given context. For example,
                    specifying a Calendar visibility value of "banana",
                    or fetching a Blogger feed without specifying
                    any blog name.
                </para>
            </listitem>

            <listitem>
                <para>
                    <classname>Zend_Gdata_App_CaptchaRequiredException</classname>
                    is thrown when a ClientLogin attempt receives a
                    <trademark>CAPTCHA</trademark> challenge from the
                    authentication service. This exception contains a token
                    ID and a <acronym>URL</acronym> to a <trademark>CAPTCHA</trademark>
                    challenge image. The image is a visual puzzle that
                    should be displayed to the user. After
                    collecting the user's response to the challenge
                    image, the response can be included with the next
                    ClientLogin attempt.The user can alternatively be
                    directed to this website:
                    <uri xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="https://www.google.com/accounts/DisplayUnlockCaptcha">https://www.google.com/accounts/DisplayUnlockCaptcha</uri>
                    Further information can be found in the
                    <link linkend="zend.gdata.clientlogin">ClientLogin documentation</link>.
                </para>
            </listitem>
        </itemizedlist>
    </para>

    <para>
        You can use these exception subclasses to handle specific exceptions
        differently. See the <acronym>API</acronym> documentation for information on which
        exception subclasses are thrown by which methods in <classname>Zend_Gdata</classname>.
    </para>

    <programlisting language="php"><![CDATA[
try {
    $client = Zend_Gdata_ClientLogin::getHttpClient($username,
                                                    $password,
                                                    $service);
} catch(Zend_Gdata_App_AuthException $authEx) {
    // The user's credentials were incorrect.
    // It would be appropriate to give the user a second try.
    ...
} catch(Zend_Gdata_App_HttpException $httpEx) {
    // Google Data servers cannot be contacted.
    die($httpEx->getMessage);}
]]></programlisting>
</section>


text:
package org.sagebionetworks.repo.model.jdo;

import java.io.IOException;

import org.sagebionetworks.repo.model.Annotations;
import org.sagebionetworks.repo.model.UnmodifiableXStream;

public class AnnotationUtils {
	private static final UnmodifiableXStream X_STREAM = UnmodifiableXStream.builder()
			.omitField(Annotations.class, "id")
			.omitField(Annotations.class, "etag")
			.alias("annotations", Annotations.class)
			.build();

	/**
	 * Convert the passed annotations to a compressed (zip) byte array
	 * @param dto
	 * @return compressed annotations
	 * @throws IOException
	 */
	public static byte[] compressAnnotationsV1(Annotations dto) throws IOException{
		return JDOSecondaryPropertyUtils.compressObject(X_STREAM, dto == null || dto.isEmpty() ? null : dto);
	}

	/**
	 * Read the compressed (zip) byte array into the Annotations.
	 * @param zippedBytes
	 * @return the resurrected Annotations
	 * @throws IOException
	 */
	public static Annotations decompressedAnnotationsV1(byte[] zippedBytes) throws IOException{
		Object o = JDOSecondaryPropertyUtils.decompressObject(X_STREAM, zippedBytes);
		if (o==null) return new Annotations();
		return (Annotations) o;
	}

}


text:
function alreadyInit {
    httpCode=`curl --output /dev/null --silent --head --write-out '%{http_code}\n' http://$COUCHBASE_HOST:8091/pools/default`
    if [ "$httpCode" == "200" ] || [ "$httpCode" == "401" ]; then
        echo "Couchbase server at $COUCHBASE_HOST:8091 was already initialized"
        return 0
    fi
    return 1
}

function initCluster {
    curl -sS -X POST -o /dev/null $COUCHBASE_HOST:8091/pools/default \
         -d "memoryQuota=$COUCHBASE_MEMORY_QUOTA" \
         -d "indexMemoryQuota=$COUCHBASE_INDEX_MEMORY_QUOTA" \
         -d "ftsMemoryQuota=$COUCHBASE_INDEX_MEMORY_QUOTA" &&
        curl -sS -X POST -o /dev/null $COUCHBASE_HOST:8091/node/controller/setupServices -d "services=kv,index,n1ql,fts" &&
        curl -sS -X POST -o /dev/null $COUCHBASE_HOST:8091/settings/indexes -d "storageMode=forestdb" &&
        curl -sS -X POST -o /dev/null $COUCHBASE_HOST:8091/settings/web \
             -u Administrator:password \
             -d "username=$COUCHBASE_USERNAME" \
             -d "password=$COUCHBASE_PASSWORD" \
             -d "port=SAME"
}

here=`cd $(dirname $BASH_SOURCE); pwd`
. $here/cb-cli-common.sh

readCommonEnv

COUCHBASE_INIT_SERVICES=data,index,query,fts
if [ -z "$COUCHBASE_MEMORY_QUOTA" ]; then
    COUCHBASE_MEMORY_QUOTA=1024
fi

if [ -z "$COUCHBASE_INDEX_MEMORY_QUOTA" ]; then
    COUCHBASE_INDEX_MEMORY_QUOTA=256
fi

echo "COUCHBASE_HOST: $COUCHBASE_HOST:8091"
echo "COUCHBASE_USERNAME: $COUCHBASE_USERNAME"
echo "COUCHBASE_PASSWORD: ${COUCHBASE_PASSWORD:0:4}******"
echo "COUCHBASE_MEMORY_QUOTA: $COUCHBASE_MEMORY_QUOTA"
echo "COUCHBASE_INDEX_MEMORY_QUOTA: $COUCHBASE_INDEX_MEMORY_QUOTA"

if ! $here/cb-cli-check-connect.sh; then
    exit 1
fi
if alreadyInit; then
    exit 0
fi
/opt/couchbase/bin/couchbase-cli node-init \
                                 -c $COUCHBASE_HOST:8091 -u Administrator -p password \
                                 --node-init-data-path=/opt/couchbase/var/lib/couchbase/data \
                                 --node-init-index-path=/opt/couchbase/var/lib/couchbase/data &&
    initCluster


text:
'use strict';

import React, { Component } from 'react';
import { Link, browserHistory } from 'react-router';
import { FormattedMessage } from 'react-intl';
import translate from 'app/global/helper/translate';

import { Modal, message, Button } from 'antd';
import _ from 'lodash';

import ModalHeader from 'app/components/productivity/modal/Header';
import CardTabGeneral from 'app/components/productivity/modal/General';
import CardTabTodoList from 'app/components/productivity/modal/Todo';
import CardTabMeta from 'app/components/productivity/modal/Meta';

class PublicShowCard extends Component {

	constructor(props) {
		super(props);
		this.state = {
			tab: 'default',
		};
		this.handleCancel = this.handleCancel.bind(this);
		this.setActiveTab = this.setActiveTab.bind(this);
	}

	handleCancel() {
		browserHistory.push(`/public/boards/${this.props.params.id}`);
	}

	setActiveTab(tab) {
		this.setState({ tab: tab || 'default' });
	}

	render() {

		const list = _.filter( this.props.data.publicBoard.lists, { cards: [ {id: this.props.params.card_id} ] } )[0];

		if ( ! list ) {
			setTimeout( () => {
				message.error( translate('messages.card.show.error') );
				this.handleCancel();
			}, 50);
			return

;
		}

		const card = _.find( list.cards, { id: this.props.params.card_id } );

		return (
			<Modal
				wrapClassName="modal__primary"
				visible={ true }
				maskClosable={ false }
				onCancel={ this.handleCancel }
				footer={[]}
			>

				<ModalHeader
					title={ card.title }
					subtitle={
<FormattedMessage id="card.show.heading.sub" defaultMessage="In list" /> { list.title }
 }
					editable={ true }
					data={ card }
					editable={ false }
				/>

						{ this.state.tab === 'default' && <CardTabGeneral public={ true } data={ card } /> }
						{ this.state.tab === 'todo' && <CardTabTodoList public={ true } data={ card } /> }
						{ this.state.tab === 'meta' && <CardTabMeta public={ true } data={ card } /> }

							<Button
								size="small"
								type="primary"
								onClick={ () => { this.setActiveTab('default') } }
								disabled={ this.state.tab === 'default' }
								><FormattedMessage id="card.show.tab.general" defaultMessage="General" /></Button>
							<Button
								size="small"
								type="primary"
								onClick={ () => { this.setActiveTab('todo') } }
								disabled={ this.state.tab === 'todo' }
								><FormattedMessage id="card.show.tab.todo" defaultMessage="Todo List" /></Button>
							<Button
								size="small"
								type="primary"
								onClick={ () => { this.setActiveTab('meta') } }
								disabled={ this.state.tab === 'meta' }
								><FormattedMessage id="card.show.tab.meta" defaultMessage="Meta Details" /></Button>

			</Modal>
		);

	}

}

export default PublicShowCard;


text:
<?php

namespace Vagonero\Git\Command;

use Vagonero\Git\Command;
use Vagonero\Git\Exception\GitException;

/**
 * Provide content or type and size information for repository objects - `git cat-file`
 *
 * @author Kazuyuki Hayashi <hayashi@valnur.net>
 */
class CatCommand extends Command
{

    /**
     * Returns the contents of blob object
     *
     * ``` php
     * $git = new Vagonero\Git\Git();
     * $git->setRepository('/path/to/repo');
     * $contents = $git->cat->blob('e69de29bb2d1d6434b8b29ae775ad8');
     * ```
     *
     * @param string $object The name of the blob object to show
     *
     * @throws GitException
     * @return string
     */
    public function blob($object)
    {
        $process = $this->git->getProcessBuilder()
            ->add('cat-file')
            ->add('blob')
            ->add($object)
            ->getProcess();

        return $this->git->run($process);
    }

    /**
     * Returns the object type identified by **$object**
     *
     * ``` php
     * $git = new Vagonero\Git\Git();
     * $git->setRepository('/path/to/repo');
     * $type = $git->cat->type('e69de29bb2d1d6434b8b29ae775ad8');
     * ```
     *
     * @param string $object The name of the object to show
     *
     * @throws GitException
     * @return string
     */
    public function type($object)
    {
        $process = $this->git->getProcessBuilder()
            ->add('cat-file')
            ->add('-t')
            ->add($object)
            ->getProcess();

        return trim($this->git->run($process));
    }

    /**
     * Returns the object size identified by **$object**
     *
     * ``` php
     * $git = new Vagonero\Git\Git();
     * $git->setRepository('/path/to/repo');
     * $type = $git->cat->size('e69de29bb2d1d6434b8b29ae775ad8');
     * ```
     *
     * @param string $object The name of the object to show
     *
     * @throws GitException
     * @return string
     */
    public function size($object)
    {
        $process = $this->git->getProcessBuilder()
            ->add('cat-file')
            ->add('-s')
            ->add($object)
            ->getProcess();

        return trim($this->git->run($process));
    }

}


text:
class Marble < ActiveRecord::Base
  belongs_to :bucket

  fastapi_standard_interface [:id, :color, :radius, :bucket]
  fastapi_standard_interface_nested [:id, :color, :radius]

  fastapi_default_filters(color__not: 'clear')
end


text:
<?php
namespace Naloader;

use Symfony\Component\DomCrawler\Crawler;

/**
 * Class Novel
 * @package Naloader
 */
class Novel
{
    /**
     * the novel top page url.
     * @var string
     */
    public $url;

    /**
     * @var string
     */
    public $title;

    /**
     * @var Author
     */
    public $author;

    /**
     * @var string
     */
    public $textDownloadTopUrl;

    /**
     * @var array
     */
    public $chapters;

    /**
     * Novel constructor.
     * @param $url
     * @param null $html
     * @throws \Exception
     */
    public function __construct($url, $html = null) {
        if (!Naloader::isValidNovelUrl($url)) {
            throw new \Exception("invalid novel url: $url");
        }
        $this->url = $url;
    }

    /**
     * crawl novel top page
     */
    public function crawl() {
        $client = Naloader::getHttpClient($this->url);
        $crawler = $client->request('GET', $this->url);
        $this->parseFromCrawler($crawler);
    }

    /**
     * parse novel top html
     * @param $url
     * @param $html
     */
    public function parseFromHtml($url, $html) {
        $this->url = $url;
        $crawler = new Crawler(null, $this->url);
        $crawler->addContent($html);
        $this->parseFromCrawler($crawler);
    }

    /**
     * parse crawler object of novel top html
     * @param Crawler $crawler
     */
    public function parseFromCrawler(Crawler $crawler) {
        $this->title = Naloader::unescapeText($crawler->filter('p.novel_title')->first()->text());

        $authorNode = $crawler->filter('div.novel_writername')->first();
        $authorUrl = $crawler->filter('div#novel_footer a')->first()->attr('href');
        $this->author = new Author($authorUrl);
        $authorName = trim($authorNode->text());
        $authorName = mb_substr($authorName, 3, null, 'utf-8'); // "作者:"
        $this->author->name = Naloader::unescapeText($authorName);

        $crawler->filter('ul.undernavi a')->each(function(Crawler $node) {
            $linkUrl = $node->attr('href');
            if (strpos($linkUrl, 'txtdownload') !== false) {
                $this->textDownloadTopUrl = $linkUrl;
            }
        });

        $this->chapters = [];
        $crawler->filter('div.index_box dl.novel_sublist2')->each(function (Crawler $itemNode) {
            $chapter = new Chapter($this, $itemNode);
            $this->chapters[] = $chapter;
        });
        if (empty($this->chapters)) {
            $contentNode = $crawler->filter('div#novel_honbun')->first();
            $chapter = new Chapter($this, $contentNode);
            $this->chapters[] = $chapter;
        }
    }

    /**
     * convert text download top url to text download url
     * @return string
     */
    public function getTextDownloadUrl() {
        return str_replace('/top/', '/dlstart/', $this->textDownloadTopUrl);
    }
}


text:
package org.vitrivr.cineast.core.data.providers;

import org.vitrivr.cineast.core.extraction.decode.subtitle.SubtitleItem;

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

public interface SubtitleItemProvider {

	public default List<SubtitleItem> getSubtitleItems(){
	   return new ArrayList<>(0);
	}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ZAsteroids.World.Effects.ExplosionSmoke;
using Microsoft.Xna.Framework;

namespace ZitaAsteria.MenuSystem.World
{
    /// <summary>
    /// The shield for the satellite - some overrides to do the animation.
    /// </summary>
    public class Shield : SceneObject
    {
        #region Public Properties
        /// <summary>
        /// Used to manage the volume of the sounds.
        /// </summary>
        public float Radius { get { return this._cdBoundingSphere.Radius; } }
        #endregion

        #region Private Fields
        /// <summary>
        /// The current axial rotations.
        /// </summary>
        Vector3 _rotations = new Vector3();
        /// <summary>
        /// The rotational velocity.
        /// </summary>
        Vector3 _rotationalVelRadS = 0.1f * 3.14159f * Vector3.One;
        #endregion
        public Shield()
        {
        }

        public override void Initialize()
        {
            base.Initialize();

            //Load the model.
            this.Model = WorldContent.menuSystemContent.ShieldModel;
            this.Alpha = 1f;
            this.IsAdditiveBlending = true;
            this.IsZTransparent = true;

            //Set the bounding sphere
            this._cdBoundingSphere = new BoundingSphere(this.Location, this.Model.Meshes[0].BoundingSphere.Radius);

        }

        public override void DieEffect(Microsoft.Xna.Framework.Vector3 locationOfCollision)
        {
            base.DieEffect(locationOfCollision);
            IncendiaryExplosionACE expl = new IncendiaryExplosionACE(locationOfCollision, Vector3.Zero);
            expl.Initialize();
            expl.AddChildrenToMenuContainer();
            MenuContainer.CompoundEffects.Add(expl);
        }

        public override void Update(Microsoft.Xna.Framework.GameTime gameTime)
        {
            base.Update(gameTime);

            //Update the rotations
            _rotations += _rotationalVelRadS * (float)gameTime.ElapsedGameTime.TotalSeconds;

            //Saving the accuracy.
            while (_rotations.X > 2.0f * Math.PI) _rotations.X -= 2.0f * (float)Math.PI;
            while (_rotations.Y > 2.0f * Math.PI) _rotations.Y -= 2.0f * (float)Math.PI;
            while (_rotations.Z > 2.0f * Math.PI) _rotations.Z -= 2.0f * (float)Math.PI;
        }

        /// <summary>
        /// Override and draw the three components.
        /// </summary>
        /// <param name="inBlack"></param>
        public override void Draw(bool inBlack)
        {
            //Draw it three times with the different axes
            SceneRotation = new Vector3(_rotations.X,0,0);
            base.Draw(inBlack);
            //SceneRotation = new Vector3(_rotations.Y, 0, 0);
            //base.Draw(inBlack);
            //SceneRotation = new Vector3(0,_rotations.X, 0);
            //base.Draw(inBlack);
            //SceneRotation = new Vector3(0,-_rotations.X, 0);
            //base.Draw(inBlack);
            //SceneRotation = new Vector3(0,0,_rotations.Z);
            //base.Draw(inBlack);
        }
    }
}


text:
/**
 * FREEdealista Style sheet.
 *
 * @author: Jorge Vas Moreno <info@freedealista.com>
 * @author: Google Maps
 * @version: 1.0
 *
 */

/* Eric Meyer's reset
	http://meyerweb.com/eric/tools/css/reset/
	v2.0b1 | 201101 */

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, figcaption, figure,
footer, header, hgroup, menu, nav, section, summary,
time, mark, audio, video {
	margin: 0;
	padding: 0;
	border: 0;
	outline: 0;
	font-size: 100%;
	font: inherit;
	vertical-align: baseline;
}

a { margin: 0; padding: 0; font-size: 100%; vertical-align: baseline; background: transparent; }

/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
	display: block;
}
body {
	line-height: 1;
}
ol, ul {
	list-style: none;
}
blockquote, q {
	quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
	content: '';
	content: none;
}

:focus {
	outline: none;
}

ins {
	text-decoration: none;
}
del {
	text-decoration: line-through;
}

table {
	border-collapse: collapse;
	border-spacing: 0;
}
/* Meyer's reset ends here */

/* base.css, part of YUI's CSS Foundation */
h1,h2,h3 {
	/* top & bottom margin based on font size */
	margin: 1em 0;
}
h1,h2,h3,h4,h5,h6,strong {
	/*bringing boldness back to headers and the strong element*/
	font-weight: bold;
}
abbr,acronym {
	/*indicating to users that more info is available */
	border-bottom: 1px dotted #000;
	cursor: help;
}
em {
	/*bringing italics back to the em element*/
	font-style: italic;
}
blockquote,ul,ol,dl {
	/*giving blockquotes and lists room to breath*/
	margin: 1em;
}
ol,ul,dl {
	/*bringing lists on to the page with breathing room */
	margin-left: 2em;
}
ol li {
	/*giving OL's LIs generated numbers*/
	list-style: decimal outside;
}
ul li {
	/*giving UL's LIs generated disc markers*/
	list-style: disc outside;
}
dl dd {
	/*giving UL's LIs generated numbers*/
	margin-left: 1em;
}
th,td {
	/*borders and padding to make the table readable*/
	border: 1px solid #000;
	padding: .5em;
}
th {
	/*distinguishing table headers from data cells*/
	font-weight: bold;
	text-align: center;
}
caption {
	/*coordinated marking to match cell's padding*/
	margin-bottom: .5em;
	/*centered so it doesn't blend in to other content*/
	text-align: center;
}
p,fieldset,table {
	/*so things don't run into each other*/
	margin-bottom: 1em;
}
/* base.css ends here */

body {
	font-family: Verdana, Geneva, sans-serif;
	font-size: 62.5%;
	color: #222;
}

h1 {
	font-size: 1.8em;
}
h2 {
	font-size: 1.6em;
}
h3 {
	font-size: 1.4em;
}

h1,h2,h3,h4,h5,h6 {
	font-family: 'Lucida Sans Unicode', 'Lucida Grande', sans-serif;
}

#map-canvas {
	height: 500px;
}

.slider-amount {
	border: 0;
	color: #06c;
	font-weight: bold;
}

#home {
	display: table;
}

#hd1 {
	border-bottom: 2em solid #6699ff;
	height: 11em;
}

#hd1 #hlogo {
	float: left;
	height: 90px;
	margin-top: 10px;
	width: 368px;
}

#hlogo a {
	background-position: 0 0;
	background-image: url(/img/logo.png);
	display: block;
	float: left;
	height: 90px;
	text-indent: -999999em;
	width: 368px;
}

#hd1 #search {
	float: left;
	margin-top: 10px;
	padding: 28px 0 20px 5px;
}

#address{
	border: 1px solid #ddd;
	font-family: 'Lucida Sans Unicode', 'Lucida Grande', sans-serif;
	padding: 0.4em;
	width: 22.4em;
	-moz-border-radius: 4px;
	-webkit-border-radius: 4px;
	border-radius: 4px;
	font-weight: bold;
}

#main {
	margin-left: 40em;
}

aside {
	left: 0;
	position: absolute;
	top: 13em;
	width: 40em;
}

aside fieldset {
	padding: 2em 2em 0 2em;
	margin: 0;
}

#propertyList {
	padding: 0 2em;
	overflow: auto;
}

#loading {
	background: url(/img/preloader.gif) #fff no-repeat 38em 0.5em;
	/* for IE */
	filter:alpha(opacity=80);
	/* CSS3 standard */
	opacity:0.8;
	position: absolute;
	top: 0;
	left: 0;
	width: 40em;
}

.formUiContainer {
	margin-bottom: 2em;
}

.facebook-share {
	height: 4em;
	width: 36em;
}

#agencyContainer .ui-state-active,
#agencyContainer .ui-widget-content .ui-state-active,
#agencyContainer .ui-widget-header .ui-state-active {
	background-image: url('/css/custom-jquery-ui/images/ui-bg_glass_65_0066cc_1x400.png');
	background-color: #06c;
}

.property {
	outline: 1px solid #ddd;
	border-top: 1px solid #fff;
	border-left: 1px solid #c06;
	padding: 0.5em 1em;
	background: #f0f0f0;
	margin: 0.1em 0.1em 0.5em;
}

.property.agency {
	border-left: 1px solid #06c;
}

#map-canvas .property {
	margin: 1px;
}

.property a {
	text-decoration: none;
	font-weight: bold;
	color: #06c;
}

.property a:visited {
	color: #7ac;
}

.property a:hover {
	color: #c06;
}

.property .pic {
	float: left;
	margin-top: 0.5em;
}

.property .pic img {
	width: 64px;
}

.property .content {
	margin-left: 74px;
	min-height: 64px;
}

.property .content h2,
.property .content p {
	margin: 0;
	line-height: 1.4em;
}

.property .content .old {
	color: #999;
}


text:
package com.appleframework.data.hbase.myrecord.test.special;

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

import junit.framework.Assert;

import org.junit.Test;

import com.appleframework.data.hbase.exception.SimpleHBaseException;
import com.appleframework.data.hbase.myrecord.MyRecord;
import com.appleframework.data.hbase.myrecord.MyRecordRowKey;
import com.appleframework.data.hbase.myrecord.MyRecordTestBase;

/**
 * @author xinzhi
 */
public class TestSpecial extends MyRecordTestBase {

    //var parameter should have value.
    @Test(expected = SimpleHBaseException.class)
    public void nullParaValue() {
        addHql("select where name less #name#");
        Map<String, Object> para = new HashMap<String, Object>();
        simpleHbaseClient.findObjectList(new MyRecordRowKey(0),
                new MyRecordRowKey(100), MyRecord.class, TestHqlId, para);
    }

    //constant parameter should have value.
    @Test(expected = SimpleHBaseException.class)
    public void nullParaConstant() {
        addHql("select where age less \"\"");
        Map<String, Object> para = new HashMap<String, Object>();
        simpleHbaseClient.findObjectList(new MyRecordRowKey(0),
                new MyRecordRowKey(100), MyRecord.class, TestHqlId, para);
    }

    @Test
    public void cannotHandleNegative() {
        putSlim("id=0,age=100");
        putSlim("id=1,age=0");
        putSlim("id=2,age=-100");

        addHql("select where age greaterequal \"0\"");
        List<MyRecord> myRecordList = simpleHbaseClient.findObjectList(
                new MyRecordRowKey(0), new MyRecordRowKey(100), MyRecord.class,
                TestHqlId, null);
        //should be 2, but result is 3.
        Assert.assertTrue(myRecordList.size() == 3);
    }
}


text:
import SelectionPhase from './selector-phase';
import ExtractionPhase from './extraction-phase';
import PostProcessPhase from './post-process-phase';
import OutputPhase from './output-phase';
import PhaseManager from './phase-manager';

export {
    SelectionPhase, ExtractionPhase, PostProcessPhase, OutputPhase, PhaseManager
};


text:
//
//  M80Dispatch.h
//  WeChatPlugin
//
//  Created by amao on 2017/6/9.
//  Copyright © 2017年 xiangwangfeng. All rights reserved.
//

#ifndef M80Dispatch_h
#define M80Dispatch_h

static void M80MainAsync(dispatch_block_t block)
{
    if ([NSThread isMainThread])
    {
        block();
    }
    else
    {
        dispatch_async(dispatch_get_main_queue(), block);
    }
}

#endif /* M80Dispatch_h */


text:
<?php

namespace PHPUnit\Runner;

use PHPUnit\Framework\TestCase;
use PHPUnit\Util\PHP\AbstractPhpProcess;

class PhptTestCaseTest extends TestCase
{
    private const EXPECT_CONTENT = <<<EOF
--TEST--
EXPECT test
--FILE--
<?php echo "Hello PHPUnit!"; ?>
--EXPECT--
Hello PHPUnit!
EOF;

    private const EXPECTF_CONTENT = <<<EOF
--TEST--
EXPECTF test
--FILE--
<?php echo "Hello PHPUnit!"; ?>
--EXPECTF--
Hello %s!
EOF;

    private const EXPECTREGEX_CONTENT = <<<EOF
--TEST--
EXPECTREGEX test
--FILE--
<?php echo "Hello PHPUnit!"; ?>
--EXPECTREGEX--
Hello [HPU]{4}[nit]{3}!
EOF;

    private const FILE_SECTION = <<<EOF
<?php echo "Hello PHPUnit!"; ?>

EOF;

    /**
     * @var string
     */
    private $dirname;

    /**
     * @var string
     */
    private $filename;

    /**
     * @var PhptTestCase
     */
    private $testCase;

    /**
     * @var AbstractPhpProcess|\PHPUnit\Framework\MockObject\MockObject
     */
    private $phpProcess;

    protected function setUp(): void
    {
        $this->dirname  = \sys_get_temp_dir();
        $this->filename = $this->dirname . '/phpunit.phpt';
        \touch($this->filename);

        $this->phpProcess = $this->getMockForAbstractClass(AbstractPhpProcess::class, [], '', false);
        $this->testCase   = new PhptTestCase($this->filename, $this->phpProcess);
    }

    protected function tearDown(): void
    {
        @\unlink($this->filename);

        $this->phpProcess = null;
        $this->testCase   = null;
    }

    public function testShouldRunFileSectionAsTest(): void
    {
        $this->setPhpContent($this->ensureCorrectEndOfLine(self::EXPECT_CONTENT));

        $fileSection = '<?php echo "Hello PHPUnit!"; ?>' . PHP_EOL;

        $this->phpProcess
             ->expects($this->once())
             ->method('runJob')
             ->with($fileSection)
             ->will($this->returnValue(['stdout' => '', 'stderr' => '']));

        $this->testCase->run();
    }

    public function testRenderFileSection(): void
    {
        $this->setPhpContent($this->ensureCorrectEndOfLine(
            <<<EOF
--TEST--
Something to decribe it
--FILE--
<?php echo __DIR__ . __FILE__; ?>
--EXPECT--
Something
EOF
        ));

        $renderedCode = "<?php echo '" . $this->dirname . "' . '" . $this->filename . "'; ?>" . PHP_EOL;

        $this->phpProcess
             ->expects($this->once())
             ->method('runJob')
             ->with($renderedCode)
             ->will($this->returnValue(['stdout' => '', 'stderr' => '']));

        $this->testCase->run();
    }

    public function testRenderSkipifSection(): void
    {
        $phptContent = self::EXPECT_CONTENT . PHP_EOL;
        $phptContent .= '--SKIPIF--' . PHP_EOL;
        $phptContent .= "<?php echo 'skip: ' . __FILE__; ?>" . PHP_EOL;

        $this->setPhpContent($phptContent);

        $renderedCode = "<?php echo 'skip: ' . '" . $this->filename . "'; ?>" . PHP_EOL;

        $this->phpProcess
             ->expects($this->at(0))
             ->method('runJob')
             ->with($renderedCode)
             ->will($this->returnValue(['stdout' => '', 'stderr' => '']));

        $this->testCase->run();
    }

    public function testShouldRunSkipifSectionWhenExists(): void
    {
        $skipifSection = '<?php /** Nothing **/ ?>' . PHP_EOL;

        $phptContent = self::EXPECT_CONTENT . PHP_EOL;
        $phptContent .= '--SKIPIF--' . PHP_EOL;
        $phptContent .= $skipifSection;

        $this->setPhpContent($phptContent);

        $this->phpProcess
             ->expects($this->at(0))
             ->method('runJob')
             ->with($skipifSection)
             ->will($this->returnValue(['stdout' => '', 'stderr' => '']));

        $this->testCase->run();
    }

    public function testShouldNotRunTestSectionIfSkipifSectionReturnsOutputWithSkipWord(): void
    {
        $skipifSection = '<?php echo "skip: Reason"; ?>' . PHP_EOL;

        $phptContent = self::EXPECT_CONTENT . PHP_EOL;
        $phptContent .= '--SKIPIF--' . PHP_EOL;
        $phptContent .= $skipifSection;

        $this->setPhpContent($phptContent);

        $this->phpProcess
             ->expects($this->once())
             ->method('runJob')
             ->with($skipifSection)
             ->will($this->returnValue(['stdout' => 'skip: Reason', 'stderr' => '']));

        $this->testCase->run();
    }

    public function testShouldRunCleanSectionWhenDefined(): void
    {
        $cleanSection = '<?php unlink("/tmp/something"); ?>' . PHP_EOL;

        $phptContent = self::EXPECT_CONTENT . PHP_EOL;
        $phptContent .= '--CLEAN--' . PHP_EOL;
        $phptContent .= $cleanSection;

        $this->setPhpContent($phptContent);

        $this->phpProcess
             ->expects($this->at(1))
             ->method('runJob')
             ->with($cleanSection);

        $this->testCase->run();
    }

    public function testShouldThrowsAnExceptionWhenPhptFileIsEmpty(): void
    {
        $this->setPhpContent('');

        $this->expectException(Exception::class);
        $this->expectExceptionMessage('Invalid PHPT file');

        $this->testCase->run();
    }

    public function testShouldThrowsAnExceptionWhenFileSectionIsMissing(): void
    {
        $this->setPhpContent(
            <<<EOF
--TEST--
Something to decribe it
--EXPECT--
Something
EOF
        );

        $this->expectException(Exception::class);
        $this->expectExceptionMessage('Invalid PHPT file');

        $this->testCase->run();
    }

    public function testShouldThrowsAnExceptionWhenThereIsNoExpecOrExpectifOrExpecregexSectionInPhptFile(): void
    {
        $this->setPhpContent(
            <<<EOF
--TEST--
Something to decribe it
--FILE--
<?php
echo "Hello world!\n";
?>
EOF
        );

        $this->expectException(Exception::class);
        $this->expectExceptionMessage('Invalid PHPT file');

        $this->testCase->run();
    }

    public function testShouldValidateExpectSession(): void
    {
        $this->setPhpContent(self::EXPECT_CONTENT);

        $this->phpProcess
             ->expects($this->once())
             ->method('runJob')
             ->with(self::FILE_SECTION)
             ->will($this->returnValue(['stdout' => 'Hello PHPUnit!', 'stderr' => '']));

        $result = $this->testCase->run();

        $this->assertTrue($result->wasSuccessful());
    }

    public function testShouldValidateExpectfSession(): void
    {
        $this->setPhpContent(self::EXPECTF_CONTENT);

        $this->phpProcess
             ->expects($this->once())
             ->method('runJob')
             ->with(self::FILE_SECTION)
             ->will($this->returnValue(['stdout' => 'Hello PHPUnit!', 'stderr' => '']));

        $result = $this->testCase->run();

        $this->assertTrue($result->wasSuccessful());
    }

    public function testShouldValidateExpectregexSession(): void
    {
        $this->setPhpContent(self::EXPECTREGEX_CONTENT);

        $this->phpProcess
             ->expects($this->once())
             ->method('runJob')
             ->with(self::FILE_SECTION)
             ->will($this->returnValue(['stdout' => 'Hello PHPUnit!', 'stderr' => '']));

        $result = $this->testCase->run();

        $this->assertTrue($result->wasSuccessful());
    }

    /**
     * Defines the content of the current PHPT test.
     *
     * @param string $content
     */
    private function setPhpContent($content): void
    {
        \file_put_contents($this->filename, $content);
    }

    /**
     * Ensures the correct line ending is used for comparison
     *
     * @param string $content
     *
     * @return string
     */
    private function ensureCorrectEndOfLine($content)
    {
        return \strtr(
            $content,
            [
                "\r\n" => PHP_EOL,
                "\r"   => PHP_EOL,
                "\n"   => PHP_EOL
            ]
        );
    }
}