text:
/*global require*/
'use strict';

require.config({
    shim: {
        underscore: {
            exports: '_'
        },
        backbone: {
            deps: [
                'underscore',
                'jquery'
            ],
            exports: 'Backbone'
        },
        bootstrap: {
            deps: ['jquery'],
            exports: 'jquery'
        },
        facebook : {
            exports: 'FB'
        }
    },
    paths: {
        jquery: '../bower_components/jquery/jquery',
        backbone: '../bower_components/backbone/backbone',
        underscore: '../bower_components/underscore/underscore',
        text: '../bower_components/requirejs-text/text',
        bootstrap: 'vendor/bootstrap',
        facebook: '//connect.facebook.net/en_US/all',
        markercluster: 'vendor/markercluster'
    }
});

require([
    'routers/router',
    'jquery',
    'backbone',
    'bootstrap'
], function (Router, $, Backbone) {
    // ajax settings (sent cors cookies)
    $.ajaxSetup({ xhrFields: { withCredentials: true }, dataType: 'json'});
    new Router();
    Backbone.history.start();
    window.onresize = function(event) {
		setItems();
	}
    setItems();
});

function setItems() {
    console.log('set navigation');
    var windowHeight = $(window).height();
	var windowWidth = $(window).width();
    // start in landscape
    var orientation = 'landscape';
    var circleRadius = windowHeight * 0.475;

    // check device orientation
    if (windowWidth < windowHeight) {
        // change stuff if portrait mode
        orientation = 'portrait';
        circleRadius = windowWidth * 0.475;
    }
    console.log('screen orientation: '+orientation);

	// logo min-width offset
    var logoSize = windowHeight * 0.16;
    if (logoSize < 100) {
        logoSize = 100;
    }

    // buttonSize min-width offset
    var buttonSize = windowHeight * 0.08;
    if (buttonSize < 50) {
        buttonSize = 50;
    }

    // center circle in portrait and set button degrees
	var startLeftLogo;
	var startTopLogo;
    var startLeft;
    var startRight;
    var startTop;
    var startBottom;
	var degLogo;
    var degZoomPlus;
    var degZoomMinus;
    var degFbLogin;
    var degTwitterLogin;
    var degFriendsMap;
    var degHelp;
    if (orientation == 'portrait') {
        $('#app-content').css('padding-top', ((windowHeight/2) - circleRadius)+'px');
		startLeftLogo = ((windowWidth / 2) - logoSize);
		startTopLogo = (windowHeight/2) - logoSize;
        startLeft = ((windowWidth / 2) - buttonSize);
        startRight = (windowWidth / 2);
        startTop = (windowHeight/2) - buttonSize;
        startBottom = (windowHeight/2);
		degLogo = 115;
        degZoomPlus = 225;
        degZoomMinus = 240;
        degFbLogin = 90;
        // degTwitterLogin = 75;
        degFriendsMap = 60;
        degHelp = 40;
    } else {
        $('#app-content').css('padding-top', '2.5vh');
		startLeftLogo = ((windowWidth / 2) - logoSize);
		startTopLogo = (windowHeight * 0.025) + circleRadius - logoSize;
        startLeft = ((windowWidth / 2) - buttonSize);
        startRight = (windowWidth / 2);
        startTop = (windowHeight * 0.025) + circleRadius - buttonSize;
        startBottom = (windowHeight * 0.025) + circleRadius;
		degLogo = 140;
        degZoomPlus = 200;
        degZoomMinus = 212;
        degFbLogin = 55;
        degFriendsMap = 43;
        // degTwitterLogin = 43;
        degHelp = 22;
    }

    // set all buttons to correct position
    // y = sin(a) * r
    // x = cos(a) * r

    $('#logo').css('top', (startTopLogo + ((Math.sin(degLogo * Math.PI / 180) * circleRadius) * -1)));
    $('#logo').css('left', (startLeftLogo - ((Math.cos(degLogo * Math.PI / 180) * circleRadius) * -1)));

    $('#button-zoom-plus').css('top', (startBottom + ((Math.sin(degZoomPlus * Math.PI / 180) * circleRadius) * -1)));
    $('#button-zoom-plus').css('left', (startLeft - ((Math.cos(degZoomPlus * Math.PI / 180) * circleRadius) * -1)));

    $('#button-zoom-minus').css('top', (startBottom + ((Math.sin(degZoomMinus * Math.PI / 180) * circleRadius) * -1)));
    $('#button-zoom-minus').css('left', (startLeft - ((Math.cos(degZoomMinus * Math.PI / 180) * circleRadius) * -1)));

    $('#button-fb-login').css('top', (startTop + ((Math.sin(degFbLogin * Math.PI / 180) * circleRadius) * -1)));
    $('#button-fb-login').css('left', (startRight - ((Math.cos(degFbLogin * Math.PI / 180) * circleRadius) * -1)));

    // $('#button-twitter-login').css('top', (startTop + ((Math.sin(degTwitterLogin * Math.PI / 180) * circleRadius) * -1)));
    // $('#button-twitter-login').css('left', (startRight - ((Math.cos(degTwitterLogin * Math.PI / 180) * circleRadius) * -1)));

    $('#button-friends').css('top', (startTop + ((Math.sin(degFriendsMap * Math.PI / 180) * circleRadius) * -1)));
    $('#button-friends').css('left', (startRight - ((Math.cos(degFriendsMap * Math.PI / 180) * circleRadius) * -1)));

    $('#button-map').css('top', (startTop + ((Math.sin(degFriendsMap * Math.PI / 180) * circleRadius) * -1)));
    $('#button-map').css('left', (startRight - ((Math.cos(degFriendsMap * Math.PI / 180) * circleRadius) * -1)));

    $('#button-help').css('top', (startTop + ((Math.sin(degHelp * Math.PI / 180) * circleRadius) * -1)));
    $('#button-help').css('left', (startRight - ((Math.cos(degHelp * Math.PI / 180) * circleRadius) * -1)));
}


text:
package com.codepath.apps.CPTweetsM.fragments;

import android.os.Bundle;
import android.widget.Toast;

import com.codepath.apps.CPTweetsM.TwitterApplication;
import com.codepath.apps.CPTweetsM.models.Tweet;
import com.codepath.apps.CPTweetsM.network.TwitterClient;
import com.loopj.android.http.JsonHttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONObject;

import cz.msebera.android.httpclient.Header;

/**
 * Created by chmanish on 11/5/16.
 */
public class MentionsTimelineFragment extends TweetsListFragment{
    private TwitterClient client;

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        client = TwitterApplication.getRestClient(); //singleton client

        if (isOnline)
            // Retrieve from the network
            populateTimeline(false, true);
        else {

            Toast.makeText(getContext(), "Cannot retrieve mentions, since you are offline!", Toast.LENGTH_LONG).show();
        }
    }

    // Send an api request to get the timeline json
    // Fill the view by creating the tweet objects from the json
    @Override
    protected void populateTimeline(final boolean isRefresh, final boolean isFirstCall) {
        super.populateTimeline(isRefresh, isFirstCall);
        client.getMentionsTimeline(new JsonHttpResponseHandler(){
            // Success

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
                int curSize = adapter.getItemCount();
                tweets.addAll(Tweet.fromJSONArray(response));
                max_id = tweets.get(tweets.size()-1).getUid();

                adapter.notifyItemRangeInserted(curSize, (Tweet.fromJSONArray(response)).size());
                if (isRefresh)
                    swipeContainer.setRefreshing(false);
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {

            }
        }, max_id);
    }

}

redpajama_set_name: RedPajamaGithub


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections     #-}

module Data.Vhd
	( create
	, CreateParameters (..)
	, defaultCreateParameters
	, getInfo
	, snapshot
	, readData
	, readDataRange
	, writeDataRange
	, withVhd
	, module Data.Vhd.Types
	) where

import Control.Applicative
import Control.Monad
import Data.BitSet
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Internal as B
import qualified Data.ByteString.Unsafe as B
import Data.Maybe
import Data.Serialize
import Data.Time.Clock.POSIX
import Data.Vhd.Bat
import Data.Vhd.Block hiding (readData, readDataRange, writeDataRange)
import qualified Data.Vhd.Block as Block
import Data.Vhd.Checksum
import Data.Vhd.Geometry
import Data.Vhd.Node
import Data.Vhd.Types
import Data.Vhd.Utils
import Data.Word
import Foreign.C.String
import Foreign.C.Types
import Foreign.Ptr
import Prelude hiding (subtract)
import System.FilePath.Posix
import System.IO

data Vhd = Vhd
	{ vhdBlockCount :: VirtualBlockCount
	, vhdBlockSize  :: BlockByteCount
	, vhdNodes      :: [VhdNode]
	}

virtualSize :: Vhd -> VirtualByteCount
virtualSize vhd = fromIntegral (vhdBlockCount vhd) * fromIntegral (vhdBlockSize vhd)

withVhd :: FilePath -> (Vhd -> IO a) -> IO a
withVhd = withVhdInner [] where

	blockCount node = headerMaxTableEntries $ nodeHeader node
	blockSize  node = headerBlockSize       $ nodeHeader node
	diskType   node = footerDiskType        $ nodeFooter node

	withVhdInner accumulatedNodes filePath f =
		withVhdNode filePath $ \node ->
			if diskType node == DiskTypeDifferencing
				then withVhdInner (node : accumulatedNodes) (parentPath node) f
				else f $ Vhd
					-- TODO: require consistent block count and size across all nodes.
					{ vhdBlockCount = blockCount node
					, vhdBlockSize  = validateBlockSize $ blockSize  node
					, vhdNodes      = reverse $ node : accumulatedNodes
					}
		where parentPath node = resolveColocatedFilePath filePath p
			where ParentUnicodeName p = headerParentUnicodeName $ nodeHeader node

-- The VHD specification requires an unsigned 32-bit word to encode the
-- block size of a VHD.
--
-- However, this library provides:
--     a. operations to copy data from a block into a strict ByteString.
--     b. operations to copy data from a strict ByteString into a block.
--
-- Furthermore:
--     c. for all bytestrings b:   (length of b) ≤ (maxBound :: Int).
--     d. for some systems: (maxBound :: Word32) > (maxBound :: Int).
--
-- This opens the (very remote) possibility of subtle bugs on attempting
-- to open a VHD with (block size) > (maxBound :: Int).  Therefore, this
-- function fails fast on attempting to open such a VHD file.
--
validateBlockSize :: BlockByteCount -> BlockByteCount
validateBlockSize value =
	if integerValue > integerLimit
		then error
			( "Cannot open VHD file with block size " ++
			  "greater than upper bound of platform integer." )
		else value
	where
		integerValue = fromIntegral (value          ) :: Integer
		integerLimit = fromIntegral (maxBound :: Int) :: Integer

data CreateParameters = CreateParameters
	{ createBlockSize         :: BlockByteCount
	, createDiskType          :: DiskType
	, createParentTimeStamp   :: Maybe TimeStamp
	, createParentUnicodeName :: Maybe ParentUnicodeName
	, createParentUniqueId    :: Maybe UniqueId
	, createTimeStamp         :: Maybe TimeStamp
	, createUuid              :: Maybe UniqueId
	, createUseBatmap         :: Bool
	, createVirtualSize       :: VirtualByteCount
	} deriving (Show, Eq)

defaultCreateParameters = CreateParameters
	{ createBlockSize         = 2 * 1024 * 1024
	, createDiskType          = DiskTypeDynamic
	, createParentTimeStamp   = Nothing
	, createParentUnicodeName = Nothing
	, createParentUniqueId    = Nothing
	, createTimeStamp         = Nothing
	, createUuid              = Nothing
	, createUseBatmap         = False
	, createVirtualSize       = 0
	}

-- | Retrieves the header and footer from a VHD file.
getInfo :: FilePath -> IO (Either String (Header, Footer))
getInfo filePath = withFile filePath ReadMode $ \handle -> do
	footer <- decode <$> B.hGet handle 512
	header <- decode <$> B.hGet handle 1024
	case (footer, header) of
		(Left err, _)      -> return $ Left err
		(_, Left err)      -> return $ Left err
		(Right f, Right h) -> return $ Right (h, f)

-- | Creates an empty VHD file with the specified parameters.
create :: FilePath -> CreateParameters -> IO ()
create filePath createParams
	| createVirtualSize createParams == 0 = error "cannot create a 0-sized VHD"
	| otherwise                           = do
		nowUnixEpoch <- fromIntegral . fromEnum <$> getPOSIXTime
		let nowVhdEpoch = fromIntegral (nowUnixEpoch - y2k)
		uniqueid <- randomUniqueId
		create' filePath $ createParams
			{ createTimeStamp = Just $ maybe nowVhdEpoch id $ createTimeStamp createParams
			, createUuid      = Just $ maybe uniqueid    id $ createUuid      createParams
			}
	where
		y2k :: Word64
		y2k = 946684800 -- seconds from the unix epoch to the vhd epoch

create' :: FilePath -> CreateParameters -> IO ()
create' filePath createParams =

	withFile filePath WriteMode $ \handle -> do
		B.hPut handle $ encode footer
		B.hPut handle $ encode header
		hAlign handle (fromIntegral sectorLength)
		-- create a BAT with every entry initialized to 0xffffffff.
		B.hPut handle $ B.replicate (fromIntegral batSize) 0xff
		-- maybe create a batmap
		when (createUseBatmap createParams) $ do
			hAlign handle (fromIntegral sectorLength)
			headerPos <- hTell handle
			B.hPut handle $ encode $ BatmapHeader
				{ batmapHeaderCookie   = cookie "tdbatmap"
				, batmapHeaderOffset   = fromIntegral (headerPos + fromIntegral sectorLength)
				, batmapHeaderSize     = (maxTableEntries `div` 8) `divRoundUp` sectorLength
				, batmapHeaderVersion  = Version 1 2
				, batmapHeaderChecksum = 0xffffffff
				}
			hAlign handle (fromIntegral sectorLength)
			B.hPut handle $ B.replicate (fromIntegral (maxTableEntries `div` 8)) 0x0
		hAlign handle (fromIntegral sectorLength)
		B.hPut handle $ encode footer

	where
		virtualSize     = createVirtualSize createParams
		maxTableEntries = fromIntegral (virtualSize `divRoundUp` fromIntegral (createBlockSize createParams))
		batSize         = (maxTableEntries * 4) `roundUpToModulo` sectorLength
		batPadSize      = batSize - maxTableEntries * 4
		footerSize      = 512
		headerSize      = 1024

		footer = adjustFooterChecksum $ Footer
			{ footerCookie             = cookie "conectix"
			, footerIsTemporaryDisk    = False
			, footerFormatVersion      = Version 1 0
			, footerDataOffset         = footerSize
			, footerTimeStamp          = fromJust $ createTimeStamp createParams
			, footerCreatorApplication = creatorApplication "tap\0"
			, footerCreatorVersion     = if createUseBatmap createParams then Version 1 3 else Version 1 0
			, footerCreatorHostOs      = CreatorHostOsWindows
			, footerOriginalSize       = virtualSize
			, footerCurrentSize        = virtualSize
			, footerDiskGeometry       = diskGeometry (virtualSize `div` fromIntegral sectorLength)
			, footerDiskType           = createDiskType createParams
			, footerChecksum           = 0
			, footerUniqueId           = fromJust $ createUuid createParams
			, footerIsSavedState       = False
			}

		header = adjustHeaderChecksum $ Header
			{ headerCookie               = cookie "cxsparse"
			, headerDataOffset           = 0xffffffffffffffff
			, headerTableOffset          = footerSize + headerSize
			, headerVersion              = Version 1 0
			, headerMaxTableEntries      = maxTableEntries
			, headerBlockSize            = createBlockSize createParams
			, headerChecksum             = 0
			, headerParentUniqueId       = fromMaybe (uniqueId $ B.replicate 16 0) (createParentUniqueId createParams)
			, headerParentTimeStamp      = fromMaybe 0 (createParentTimeStamp createParams)
			, headerReserved1            = B.replicate 4 0
			, headerParentUnicodeName    = fromMaybe (parentUnicodeName "") (createParentUnicodeName createParams)
			, headerParentLocatorEntries = parentLocatorEntries $ replicate 8 (ParentLocatorEntry $ B.replicate 24 0)
			}

snapshot :: Vhd -> FilePath -> IO ()
snapshot parentVhd childFilePath = do
	create childFilePath $ CreateParameters
		{ createBlockSize         = vhdBlockSize parentVhd
		, createDiskType          = DiskTypeDifferencing
		, createParentTimeStamp   = Just $ footerTimeStamp   headNodeFooter
		, createParentUniqueId    = Just $ footerUniqueId    headNodeFooter
		, createParentUnicodeName = Just $ parentUnicodeName parentFilePath
		, createTimeStamp         = Nothing
		, createUuid              = Nothing
		, createUseBatmap         = hasBitmap headNodeBat
		, createVirtualSize       = virtualSize parentVhd
		}
		where
			headNode         = head $ vhdNodes parentVhd
			headNodeBat      = nodeBat      headNode
			headNodeFooter   = nodeFooter   headNode
			parentFilePath   = makeRelative (takeDirectory childFilePath) (nodeFilePath headNode)

-- | Reads data from the whole virtual address space of the given VHD.
readData :: Vhd -> IO BL.ByteString
readData vhd = readDataRange vhd 0 (virtualSize vhd)

-- | Reads data from the given virtual address range of the given VHD.
readDataRange :: Vhd -> VirtualByteAddress -> VirtualByteCount -> IO BL.ByteString
readDataRange vhd offset length =
	-- To do: modify this function to read sub-blocks where appropriate.
	if offset + length > virtualSize vhd
		then error "cannot read data past end of VHD."
		else fmap (trim . BL.fromChunks) (sequence blocks)
	where
		blocks     = map (readDataBlock vhd) [blockFirst .. blockLast]
		blockFirst = fromIntegral $ (offset             ) `div` blockSize
		blockLast  = fromIntegral $ (offset + length - 1) `div` blockSize
		blockSize  = fromIntegral $ vhdBlockSize vhd
		trim       = BL.take toTake . BL.drop toDrop
			where
				toTake = fromIntegral $ length
				toDrop = fromIntegral $ offset `mod` blockSize

-- | Writes data to the given virtual address of the given VHD.
writeDataRange :: Vhd -> VirtualByteAddress -> BL.ByteString -> IO ()
writeDataRange vhd offset content = write (fromIntegral offset) content where

	write offset content
		| offset > offsetMax = error "cannot write data past end of VHD."
		| BL.null content    = return ()
		| otherwise          = do
			sectorOffset <- lookupOrCreateBlock node (fromIntegral blockNumber)
			withBlock file (fromIntegral blockSize) sectorOffset $ \block -> do
				Block.writeDataRange block (fromIntegral blockOffset) chunk
				write offsetNext contentNext
				where
					blockNumber  = (fromIntegral $ offset `div` blockSize) :: VirtualBlockAddress
					blockOffset  = offset `mod` blockSize
					chunk        = B.concat $ BL.toChunks $ fst contentSplit
					chunkLength  = fromIntegral $ blockSize - (offset `mod` blockSize)
					contentSplit = BL.splitAt chunkLength content
					contentNext  = snd contentSplit
					offsetNext   = ((offset `div` blockSize) * blockSize) + blockSize

	bat       = nodeBat node
	file      = nodeFilePath node
	node      = head $ vhdNodes vhd
	offsetMax = virtualSize vhd
	blockSize = fromIntegral $ vhdBlockSize vhd

-- | Reads all available data from the given virtual block of the given VHD.
readDataBlock :: Vhd -> VirtualBlockAddress -> IO B.ByteString
readDataBlock vhd virtualBlockAddress =
	readDataBlockRange vhd virtualBlockAddress 0 ((vhdBlockSize vhd) `div` sectorLength)

-- | Reads data from the given sector range of the given virtual block of the given VHD.
readDataBlockRange :: Vhd -> VirtualBlockAddress -> BlockSectorAddress -> BlockSectorCount -> IO B.ByteString
readDataBlockRange vhd virtualBlockAddress sectorOffset sectorCount =
	B.create
		(fromIntegral $ sectorCount * sectorLength)
		(unsafeReadDataBlockRange vhd virtualBlockAddress sectorOffset sectorCount)

-- | Unsafely reads data from the given sector range of the given virtual block of the given VHD.
unsafeReadDataBlockRange :: Vhd -> VirtualBlockAddress -> BlockSectorAddress -> BlockSectorCount -> Ptr Word8 -> IO ()
unsafeReadDataBlockRange vhd virtualBlockAddress sectorOffset sectorCount resultPtr = buildResult where

	buildResult :: IO ()
	buildResult = do
		B.memset resultPtr 0 $ fromIntegral $ sectorCount * sectorLength
		copySectorsFromNodes sectorsToRead =<< nodeOffsets

	sectorsToRead = fromRange lo hi where
		lo = fromIntegral $ sectorOffset
		hi = fromIntegral $ sectorOffset + sectorCount

	nodeOffsets :: IO [(VhdNode, PhysicalSectorAddress)]
	nodeOffsets = fmap catMaybes $ mapM maybeNodeOffset $ vhdNodes vhd where
		maybeNodeOffset node = (fmap . fmap) (node, ) $
			lookupBlock (nodeBat node) virtualBlockAddress

	copySectorsFromNodes :: BitSet -> [(VhdNode, PhysicalSectorAddress)] -> IO ()
	copySectorsFromNodes sectorsRequested [] = return ()
	copySectorsFromNodes sectorsRequested (nodeOffset : tail) =
		if Data.BitSet.isEmpty sectorsRequested then return () else do
		sectorsMissing <- copySectorsFromNode sectorsRequested nodeOffset
		copySectorsFromNodes sectorsMissing tail

	copySectorsFromNode :: BitSet -> (VhdNode, PhysicalSectorAddress) -> IO BitSet
	copySectorsFromNode sectorsRequested (node, physicalSectorOfBlock) =
		withBlock (nodeFilePath node) (vhdBlockSize vhd)
			physicalSectorOfBlock $ copySectorsFromNodeBlock sectorsRequested

	copySectorsFromNodeBlock :: BitSet -> Block -> IO BitSet
	copySectorsFromNodeBlock sectorsRequested block = do
		sectorsPresentByteString <- Block.readBitmap block
		let sectorsPresent = fromByteString sectorsPresentByteString
		let sectorsMissing = sectorsRequested `subtract`  sectorsPresent
		let sectorsToCopy  = sectorsRequested `intersect` sectorsPresent
		mapM_ (copySectorFromNodeBlock block) (map fromIntegral $ toList sectorsToCopy)
		return sectorsMissing

	copySectorFromNodeBlock :: Block -> BlockSectorAddress -> IO ()
	copySectorFromNodeBlock block sectorToCopy =
		unsafeReadDataRange block sourceByteOffset sectorLength target where
			sourceByteOffset = sectorLength * (sectorToCopy               )
			targetByteOffset = sectorLength * (sectorToCopy - sectorOffset)
			target = plusPtr resultPtr $ fromIntegral $ targetByteOffset


text:
/*
 * STUB FOR RUNNING A CinderSketch
 * ON THE DESKTOP (OSX OR WINDOW)
 */

#include "chronotext/cinder/CinderApp.h"

#include "Sketch.h"

using namespace std;
using namespace ci;
using namespace app;
using namespace chr;

class Application : public CinderApp
{
public:
    Application();
    void prepareSettings(Settings *settings);
};

Application::Application()
{
    sketch = new Sketch(this);
}

void Application::prepareSettings(Settings *settings)
{
#if defined(CINDER_MAC) || defined(CINDER_MSW)
//  settings->setWindowSize(320, 480); // IPHONE
    settings->setWindowSize(640, 960); // IPHONE RETINA
//  settings->setWindowSize(768, 1024); // IPAD-1
//  settings->setWindowSize(480, 800); // ANDROID WVGA800
#endif
}

CINDER_APP_NATIVE(Application, RendererGl(RendererGl::AA_NONE))


text: export { WatsonHealth3DICa32 as default } from "../../../";


text:
mod bogus_attribute_types_1 {
    #[stable(feature = "a", since = "a", reason)] //~ ERROR incorrect meta item
    fn f1() { }

    #[stable(feature = "a", since, reason = "a")] //~ ERROR incorrect meta item
    fn f2() { }

    #[stable(feature, since = "a", reason = "a")] //~ ERROR incorrect meta item
    fn f3() { }

    #[stable(feature = "a", since = "a", reason(b))] //~ ERROR incorrect meta item
    fn f4() { }

    #[stable(feature = "a", since(b), reason = "a")] //~ ERROR incorrect meta item
    fn f5() { }

    #[stable(feature(b), since = "a", reason = "a")] //~ ERROR incorrect meta item
    fn f6() { }
}

mod bogus_attribute_types_2 {
    #[unstable] //~ ERROR incorrect stability attribute type
    fn f1() { }

    #[unstable = "a"] //~ ERROR incorrect stability attribute type
    fn f2() { }

    #[stable] //~ ERROR incorrect stability attribute type
    fn f3() { }

    #[stable = "a"] //~ ERROR incorrect stability attribute type
    fn f4() { }

    #[stable(feature = "a", since = "b")]
    #[deprecated] //~ ERROR incorrect stability attribute type
    fn f5() { }

    #[stable(feature = "a", since = "b")]
    #[deprecated = "a"] //~ ERROR incorrect stability attribute type
    fn f6() { }
}

mod missing_feature_names {
    #[unstable(since = "a", issue = "0")] //~ ERROR missing 'feature'
    fn f1() { }

    #[unstable(feature = "a")]
    fn f2() { } //~ ERROR need to point to an issue

    #[stable(since = "a")] //~ ERROR missing 'feature'
    fn f3() { }
}

mod missing_version {
    #[stable(feature = "a")] //~ ERROR missing 'since'
    fn f1() { }

    #[stable(feature = "a", since = "b")]
    #[deprecated(reason = "a")] //~ ERROR missing 'since'
    fn f2() { }
}

#[unstable(feature = "a", since = "b", issue = "0")]
#[stable(feature = "a", since = "b")]
fn multiple1() { } //~ ERROR multiple stability levels

#[unstable(feature = "a", since = "b", issue = "0")]
#[unstable(feature = "a", since = "b", issue = "0")]
fn multiple2() { } //~ ERROR multiple stability levels

#[stable(feature = "a", since = "b")]
#[stable(feature = "a", since = "b")]
fn multiple3() { } //~ ERROR multiple stability levels

#[stable(feature = "a", since = "b")]
#[deprecated(since = "b")]
#[deprecated(since = "b")]
fn multiple4() { } //~ ERROR multiple deprecated attributes
//~^ ERROR Invalid stability or deprecation version found

#[deprecated(since = "a")]
fn deprecated_without_unstable_or_stable() { } //~ ERROR deprecated attribute must be paired

fn main() { }


text:
package net.fortuna.ical4j.model.component;

import java.net.URISyntaxException;
import junit.framework.TestSuite;
import net.fortuna.ical4j.model.property.Attendee;
import net.fortuna.ical4j.model.property.Organizer;
import net.fortuna.ical4j.model.property.Uid;

/**
 * $Id: VToDoTest.java,v 1.8 2010/03/06 12:57:23 fortuna Exp $
 *
 * Created on: 25/11/2008
 *
 * @author fortuna
 */
public class VToDoTest extends CalendarComponentTest {

    /**
     * @param testMethod
     * @param component
     */
    public VToDoTest(String testMethod, VToDo component) {
        super(testMethod, component);
    }

    /**
     * @return
     */
    public static TestSuite suite() throws URISyntaxException {
        TestSuite suite = new TestSuite();

        VToDo td = new VToDo();
        suite.addTest(new VToDoTest("testIsCalendarComponent", td));

        // iCalendar validation
        suite.addTest(new VToDoTest("testValidationException", td));
        VToDo validTd = new VToDo();
        validTd.getProperties().add(new Uid("12"));
        suite.addTest(new VToDoTest("testValidation", validTd));

        // iTIP REPLY validation
        suite.addTest(new VToDoTest("testReplyValidationException", new VToDo()));
        VToDo replyTd = new VToDo();
        replyTd.getProperties().add(new Attendee("mailto:jane@example.com"));
        replyTd.getProperties().add(new Organizer("mailto:joe@example.com"));
        replyTd.getProperties().add(new Uid("12"));
        suite.addTest(new VToDoTest("testReplyValidation", replyTd));

        return suite;
    }

}


text: set (CTEST_PROJECT_NAME "Tutorial")


text:
// Copyright © 2017-2018 Andy Goryachev <andy@goryachev.com>
package goryachev.fx.edit.internal;
import goryachev.fx.util.FxPathBuilder;
import javafx.scene.shape.LineTo;
import javafx.scene.shape.MoveTo;
import javafx.scene.shape.PathElement;

/**
 * Selection Helper encapsulates the logic required to generate selection shapes.
 *
 * The goal is to find out which shapes correspond to the top-most and bottom-most
 * text rows (in the presence of wrapping).  These shapes should be added to selection as is.
 * The (possible) space in between would generate a single rectangular block that fills the
 * width of the container:
 *
 *	 ----***--***----
 *	 ****************
 *	 ****************
 *	 ----**----------
 *
 * This algorithm has a minor drawback where the top and bottom row selection may not go
 * to the left and right side of the container.  This is because I am too lazy to account
 * for RTL/LTR text and wrapping.
 */
public class SelectionHelper
{
	private final FxPathBuilder pathBuilder;
	private final double left;
	private final double right;
	private double topUp = Double.NaN;
	private double topDn = Double.NaN;
	private double botUp = Double.NaN;
	private double botDn = Double.NaN;

	public SelectionHelper(FxPathBuilder b, double left, double right)
	{
		this.pathBuilder = b;
		this.left = left;
		this.right = right;
	}

	public String toString()
	{
		return
			"topUp=" + topUp +
			" topDn=" + topDn +
			" botUp=" + botUp +
			" botDn=" + botDn;
	}

	public void process(PathElement[] elements)
	{
		for(PathElement em: elements)
		{
			double y = getY(em);
			setTop(y);
			setBottom(y);
		}
	}

	public void generateTop(PathElement[] elements)
	{
		boolean include = false;
		double y;
		for(PathElement em: elements)
		{
			if(em instanceof LineTo)
			{
				if(include)
				{
					pathBuilder.add(em);
				}
			}
			else if(em instanceof MoveTo)
			{
				y = getY(em);
				if((y == topUp) || (y == topDn))
				{
					pathBuilder.add(em);
					include = true;
				}
				else
				{
					include = false;
				}
			}
		}
	}

	public void generateMiddle()
	{
		if(Double.isNaN(topUp))
		{
			return;
		}

		if(botUp > topDn)
		{
			// only if the middle exists
			pathBuilder.moveto(left, topDn);
			pathBuilder.lineto(right, topDn);
			pathBuilder.lineto(right, botUp);
			pathBuilder.lineto(left, botUp);
			pathBuilder.lineto(left, topDn);
		}
	}

	public void generateBottom(PathElement[] elements)
	{
		boolean include = false;
		double y;
		for(PathElement em: elements)
		{
			if(em instanceof LineTo)
			{
				if(include)
				{
					pathBuilder.add(em);
				}
			}
			else if(em instanceof MoveTo)
			{
				y = getY(em);
				if((y == botUp) || (y == botDn))
				{
					pathBuilder.add(em);
					include = true;
				}
				else
				{
					include = false;
				}
			}
		}
	}

	protected double getY(PathElement em)
	{
		if(em instanceof LineTo)
		{
			LineTo m = (LineTo)em;
			return m.getY();
		}
		else if(em instanceof MoveTo)
		{
			MoveTo m = (MoveTo)em;
			return m.getY();
		}
		else
		{
			throw new Error("?" + em);
		}
	}

	protected void setTop(double y)
	{
		if(isSmaller(y, topUp))
		{
			if(isSmaller(topUp, topDn))
			{
				topDn = topUp;
			}
			topUp = y;
		}
		else if(isSmaller(y, topDn) && (y > topUp))
		{
			topDn = y;
		}
	}

	protected void setBottom(double y)
	{
		if(isLarger(y, botDn))
		{
			if(isLarger(botDn, botUp))
			{
				botUp = botDn;
			}
			botDn = y;
		}
		else if(isLarger(y, botUp) && (y < botDn))
		{
			botUp = y;
		}
	}

	protected boolean isSmaller(double y, double current)
	{
		if(Double.isNaN(y))
		{
			return false;
		}
		else if(Double.isNaN(current))
		{
			return true;
		}
		else if(y < current)
		{
			return true;
		}
		else
		{
			return false;
		}
	}

	protected boolean isLarger(double y, double current)
	{
		if(Double.isNaN(y))
		{
			return false;
		}
		else if(Double.isNaN(current))
		{
			return true;
		}
		else if(y > current)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
}


text:
package io.codekvast.javaagent.util;

import static io.codekvast.javaagent.util.ConfigUtils.expandVariables;
import static io.codekvast.javaagent.util.ConfigUtils.getBooleanValue;
import static io.codekvast.javaagent.util.ConfigUtils.getCommaSeparatedFileValues;
import static io.codekvast.javaagent.util.ConfigUtils.getEnvVarName;
import static io.codekvast.javaagent.util.ConfigUtils.getIntValue;
import static io.codekvast.javaagent.util.ConfigUtils.getNormalizedPackagePrefix;
import static io.codekvast.javaagent.util.ConfigUtils.getNormalizedPackages;
import static io.codekvast.javaagent.util.ConfigUtils.getStringValue;
import static io.codekvast.javaagent.util.ConfigUtils.getStringValue2;
import static io.codekvast.javaagent.util.ConfigUtils.getSystemPropertyName;
import static java.util.Arrays.asList;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
import static org.hamcrest.core.Is.is;

import io.codekvast.junit5.extensions.CaptureSystemOutput;
import io.codekvast.junit5.extensions.CaptureSystemOutput.OutputCapture;
import java.io.File;
import java.util.List;
import java.util.Optional;
import java.util.Properties;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;

@CaptureSystemOutput
public class ConfigUtilsTest {

  private static final String MY_PROP1 = ConfigUtilsTest.class.getName() + ".prop1";
  private static final String MY_PROP2 = ConfigUtilsTest.class.getName() + ".prop2";
  private static final String MY_PROP3 = ConfigUtilsTest.class.getName() + ".prop3";
  private static final String CODEKVAST_APP_VERSION = "codekvast.appVersion";

  @AfterEach
  public void afterTest() {
    System.getProperties().remove(MY_PROP1);
    System.getProperties().remove(MY_PROP2);
    System.getProperties().remove(MY_PROP3);
    System.getProperties().remove(CODEKVAST_APP_VERSION);
  }

  @Test
  public void should_compute_codekvast_prefixed_env_var_names() {
    assertThat(getEnvVarName("foo"), is("CODEKVAST_FOO"));
    assertThat(getEnvVarName("fooBarBaz"), is("CODEKVAST_FOO_BAR_BAZ"));
  }

  @Test
  public void should_compute_codekvast_prefixed_system_property_names() {
    assertThat(getSystemPropertyName("fooBar"), is("codekvast.fooBar"));
  }

  @Test
  public void testGetNormalizedPackagePrefix1() {
    assertThat(getNormalizedPackagePrefix("prefix....."), is("prefix"));
  }

  @Test
  public void testGetNormalizedPackagePrefix2() {
    assertThat(getNormalizedPackagePrefix("prefix."), is("prefix"));
  }

  @Test
  public void testGetNormalizedPackagePrefix3() {
    assertThat(getNormalizedPackagePrefix("prefix.foobar..."), is("prefix.foobar"));
  }

  @Test
  public void testGetNormalizedPackagePrefix4() {
    assertThat(getNormalizedPackagePrefix("prefix"), is("prefix"));
  }

  @Test
  public void testGetNormalizedPackagePrefix5() {
    assertThat(getNormalizedPackagePrefix("p"), is("p"));
  }

  @Test
  public void testGetNormalizedPackagePrefix6() {
    assertThat(getNormalizedPackagePrefix(""), is(""));
  }

  @Test
  public void testGetNormalizedPackages1() {
    assertThat(
        getNormalizedPackages("   com.acme... ; foo.bar..   "),
        equalTo(asList("com.acme", "foo.bar")));
  }

  @Test
  public void testGetNormalizedPackages2() {
    assertThat(
        getNormalizedPackages(",   , x, : y  ; : com.acme... , foo.bar..  , "),
        equalTo(asList("com.acme", "foo.bar", "x", "y")));
  }

  @Test
  public void should_expand_variables_with_braces() {
    // given
    System.setProperty(MY_PROP1, "XXX");
    System.setProperty(MY_PROP2, "YYY");
    String userVariableName;
    if (System.getProperty("os.name").startsWith(("Windows"))) {
      userVariableName = "$USERNAME";
    } else {
      userVariableName = "$USER";
    }
    Properties props = new Properties();
    props.setProperty(MY_PROP1, "XXX_from_props");
    props.setProperty(MY_PROP3, "ZZZ");

    // when
    String actual =
        expandVariables(
            props,
            userVariableName
                + " ${"
                + MY_PROP1
                + "} foo ${"
                + MY_PROP2
                + "} bar ${"
                + MY_PROP3
                + "}");

    // then
    assertThat(actual, is(System.getProperty("user.name") + " XXX foo YYY bar ZZZ"));
  }

  @Test
  public void should_expand_variables_without_braces() {
    // given
    System.setProperty(MY_PROP1, "XXX");
    System.setProperty(MY_PROP2, "YYY");
    String userVariableName;
    if (System.getProperty("os.name").startsWith(("Windows"))) {
      userVariableName = "$USERNAME";
    } else {
      userVariableName = "$USER";
    }
    Properties props = new Properties();
    props.setProperty(MY_PROP1, "XXX_from_props");
    props.setProperty(MY_PROP3, "ZZZ");

    // when
    String actual =
        expandVariables(
            props,
            userVariableName
                + " $"
                + MY_PROP1
                + " foo $"
                + MY_PROP2
                + " bar $"
                + MY_PROP3
                + "${user.name}baz");

    // then
    assertThat(
        actual,
        is(
            System.getProperty("user.name")
                + " XXX foo YYY bar ZZZ"
                + System.getProperty("user.name")
                + "baz"));
  }

  @Test
  public void should_detect_codekvast_system_properties() {
    System.setProperty(CODEKVAST_APP_VERSION, "sysprop-appVersion");

    Properties props = new Properties();
    props.setProperty("appVersion", "some-app-version");

    assertThat(
        expandVariables(props, "appVersion", "default-app-version"),
        is(Optional.of("sysprop-appVersion")));
  }

  @Test
  public void should_handle_missing_expansions(OutputCapture outputCapture) {
    assertThat(
        expandVariables(new Properties(), "foo $missingProp1 bar ${missing.prop2} baz"),
        is("foo $missingProp1 bar ${missing.prop2} baz"));

    outputCapture.expect(containsString("Unrecognized variable: $missingProp1"));
    outputCapture.expect(containsString("Unrecognized variable: ${missing.prop2}"));
  }

  @Test
  public void should_get_comma_separated_file_values() {
    List<File> files = getCommaSeparatedFileValues("   file1 , file2 ; file3 ");
    assertThat(files, contains(new File("file1"), new File("file2"), new File("file3")));
  }

  @Test
  public void should_getOptionalIntValue_when_present_value() {
    Properties props = new Properties();
    props.setProperty("key", "4711");
    assertThat(getIntValue(props, "key", 17), is(4711));
  }

  @Test
  public void should_getOptionalIntValue_when_missing_value() {
    assertThat(getIntValue(new Properties(), "key", 17), is(17));
  }

  @Test
  public void should_getBooleanValue_when_present_value() {
    Properties props = new Properties();
    props.setProperty("key", "false");
    assertThat(getBooleanValue(props, "key", true), is(false));
  }

  @Test
  public void should_getOptionalBooleanValue_when_missing_value() {
    assertThat(getBooleanValue(new Properties(), "key", true), is(true));
  }

  @Test
  public void should_return_empty_when_missing_string_value() {
    assertThat(getStringValue(new Properties(), "key"), is(Optional.empty()));
  }

  @Test
  public void should_return_empty_when_blank_string_value() {
    Properties props = new Properties();
    props.setProperty("key", " ");

    assertThat(getStringValue(new Properties(), "key"), is(Optional.empty()));
  }

  @Test
  public void should_getStringValue() {
    Properties props = new Properties();
    props.setProperty("key", "value");

    assertThat(getStringValue(props, "key"), is(Optional.of("value")));
  }

  @Test
  public void should_getStringValue2_key1() {
    Properties props = new Properties();
    props.setProperty("key", "value");

    assertThat(getStringValue2(props, "alternateKey", "key", "defaultValue"), is("value"));
  }

  @Test
  public void should_getStringValue2_key2() {
    Properties props = new Properties();
    props.setProperty("key", "value");

    assertThat(getStringValue2(props, "key", "alternateKey", "defaultValue"), is("value"));
  }

  @Test
  public void should_getStringValue2_default() {
    Properties props = new Properties();
    props.setProperty("somekey", "value");

    assertThat(getStringValue2(props, "key", "alternateKey", "defaultValue"), is("defaultValue"));
  }
}


text:
var _chop = require('underscore.string/chop');
var _curry = require('chickencurry').n;
var _reverse = require('reverse-arguments');

module.exports = _curry(_reverse(_chop), 2);


text:
The aim of Cygnite Framework is to make your application secure. You do not need to worry, all your POST, GET, COOKIE values are sanitize internally. Everything has been configured for you out of box.

###Sanitize Your String

Cygnite Framework sanitize, and do cross site filtering (XSS) recursively with single method **sanitize()**

```php
    use Cygnite\Common\Security;

    $security =Security::instance(
       function ($instance) {

            $instance->sanitize("Your Data to Sanitize");

            return $instance;
       }
    );

```
If you particularly want to remove javascript protocols from your string.

```php
   $security->removeJavaScriptProtocols();
```


text: const Coord2D Coord2D::OXY = Coord2D{};


text:
title: Composing Functions in JavaScript
date: 2014-01-19 00:00
author: Blake Embrey
template: article.jade
---

Composing multiple functions to create more complex ones is a common utility in any programming language. And the ability to construct functions in a way that is easily composable is a true talent, but it really shines with code maintenance and reuse. It's not uncommon to find huge applications composed of many, much smaller functions. Inspired by this pattern of extremely modular functions, I've been slowly migrating my programming style to allow for more composable and reusable functions.

To compose functions together, we will need to accept a list of functions for it to be made up from. Let's call the functions `a`, `b` and `c`. Now that we have the list of functions, we need to call each of them with the result of the next function. In JavaScript, we would do this with `a(b(c(x)))` - with `x` being the starting value. However, it would be much more useful to have something a little more reusable than this.

```javascript
var compose = function () {
  var fns = arguments;

  return function (result) {
    for (var i = fns.length - 1; i > -1; i--) {
      result = fns[i].call(this, result);
    }

    return result;
  };
};
```

The above function iterates over the function list (our arguments) in reverse - the last function to pass in is executed first. Given a single value as the initial input, it'll chain that value between every function call and return the final result. This allows us to do some really cool things.

```javascript
var number = compose(Math.round, parseFloat);

number('72.5'); //=> 73
```

## Sequence

Another utility I've seen about in some functional libraries is called [sequence](https://github.com/raganwald/allong.es#functional-composition). It's very similar to `compose`, except the arguments are executed in reverse. For example:

```javascript
var sequence = function () {
  var fns = arguments;

  return function (result) {
    for (var i = 0; i < fns.length; i++) {
      result = fns[i].call(this, result);
    }

    return result;
  };
};
```

However, we should make a note of the almost identical function signature to `compose`. Usually, seeing something like this should trigger a warning in your head to find some way to reuse previous functionality, instead of replicating it. In this example, we can reuse the `compose` function to write the `sequence` implementation.

```javascript
var __slice = Array.prototype.slice;

var sequence = function () {
  return compose.apply(this, __slice.call(arguments).reverse());
};
```


text:
@interface PDFDocumentSearch ()
@property (nonatomic, assign, readwrite) BOOL searching;
@property (nonatomic, assign) BOOL cancel;
@end

@implementation PDFDocumentSearch

- (instancetype)initWithDocument:(PDFDocument *)document
{
    self = [super init];
    if (self) {
        _document = document;
    }
    return self;
}

- (void)cancelSearch
{
    self.cancel = YES;
    while (self.searching) {
        [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0]];
    }
    self.cancel = NO;
}

- (void)doneSearching
{
    self.searching = NO;
}

- (void)searchWithString:(NSString *)keyword
{
    if (self.searching) {
        [self cancelSearch];
    }
    self.searching = YES;
    size_t numberOfPages = CGPDFDocumentGetNumberOfPages(self.document.CGPDFDocument);
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        for (int i = 1; i <= numberOfPages; i++) {
            if (self.cancel) {
                break;
            }
            [self searchWithString:keyword
                            atPage:i];
        }
        [self performSelectorOnMainThread:@selector(doneSearching)
                               withObject:nil
                            waitUntilDone:YES];
    });
}

- (void)searchWithString:(NSString *)keyword
                  atPage:(NSUInteger)index
{
    CGPDFPageRef page = CGPDFDocumentGetPage(self.document.CGPDFDocument, index);
    PDFPageScanner *scanner = [[PDFPageScanner alloc] initWithCGPDFPage:page];
    NSArray *contents = [scanner scanStringContents];
    NSString *text = [[contents grt_map:^(PDFRenderingCharacter *character) {
        return character.stringDescription;
    }] componentsJoinedByString:@""];
    NSRange range = [text rangeOfString:keyword options:NSCaseInsensitiveSearch];
    while (range.location != NSNotFound) {
        PDFDocumentSearchResult *result =
                [self searchResultWithCharacters:contents
                                           range:range
                                          atPage:index];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.delegate search:self
                    didFindString:result];
        });

        NSUInteger start = range.location + range.length;
        NSRange targetRange = NSMakeRange(start,
                                          text.length - start);
        range = [text rangeOfString:keyword
                            options:0
                              range:targetRange];
    }
}

- (PDFDocumentSearchResult *)searchResultWithCharacters:(NSArray *)characters
                                                  range:(NSRange)range
                                                 atPage:(NSUInteger)page
{
    const NSUInteger maxLength = 30;
    NSUInteger left = (maxLength - range.length) / 2;
    NSRange surroundingRange = range;
    if ((int)(surroundingRange.location - left) < 0) {
        surroundingRange.location = 0;
        surroundingRange.length = MIN(maxLength, characters.count);
    } else {
        surroundingRange.location = surroundingRange.location - left;
        surroundingRange.length = MIN(maxLength, characters.count - surroundingRange.location);
        if (surroundingRange.length < maxLength) {
            NSInteger location = surroundingRange.location - (maxLength - surroundingRange.length);
            if (location < 0) {
                location = 0;
            }
            surroundingRange.location = location;
            surroundingRange.length = characters.count - surroundingRange.location;
        }
    }

    NSString *text = [[[characters subarrayWithRange:surroundingRange] grt_map:^(PDFRenderingCharacter *character) {
        return character.stringDescription;
    }] componentsJoinedByString:@""];

    PDFDocumentSearchResult *result =
            [PDFDocumentSearchResult resultWithSurroundingText:text
                                                         range:NSMakeRange(range.location - surroundingRange.location, range.length)
                                                        atPage:page];
    return result;
}

@end


text:
using System;
using System.Threading.Tasks;
using Elasticsearch.Net;

namespace Nest
{
	public partial class ElasticClient
	{
		/// <inheritdoc />
		public ISearchResponse<T> Scroll<T>(IScrollRequest request) where T : class
		{
			return this.Dispatcher.Dispatch<IScrollRequest, ScrollRequestParameters, SearchResponse<T>>(
				request,
				(p, d) =>
				{
					string scrollId = p.ScrollId;
					p.ScrollId = null;
					return this.RawDispatch.ScrollDispatch<SearchResponse<T>>(p, scrollId);
				}
			);
		}
		/// <inheritdoc />
		public ISearchResponse<T> Scroll<T>(Func<ScrollDescriptor<T>, ScrollDescriptor<T>> scrollSelector) where T : class
		{
			return this.Dispatcher.Dispatch<ScrollDescriptor<T>, ScrollRequestParameters, SearchResponse<T>>(
				scrollSelector,
				(p, d) =>
				{
					string scrollId = p.ScrollId;
					p.ScrollId = null;
					return this.RawDispatch.ScrollDispatch<SearchResponse<T>>(p, scrollId);
				}
			);
		}

		/// <inheritdoc />
		public Task<ISearchResponse<T>> ScrollAsync<T>(IScrollRequest request) where T : class
		{
			return this.Dispatcher.DispatchAsync<IScrollRequest, ScrollRequestParameters, SearchResponse<T>, ISearchResponse<T>>(
				request,
				(p, d) =>
				{
					string scrollId = p.ScrollId;
					p.ScrollId = null;
					return this.RawDispatch.ScrollDispatchAsync<SearchResponse<T>>(p, scrollId);
				}
			);
		}

		/// <inheritdoc />
		public Task<ISearchResponse<T>> ScrollAsync<T>(Func<ScrollDescriptor<T>, ScrollDescriptor<T>> scrollSelector) where T : class
		{
			return this.Dispatcher.DispatchAsync<ScrollDescriptor<T>, ScrollRequestParameters, SearchResponse<T>, ISearchResponse<T>>(
				scrollSelector,
				(p, d) =>
				{
					string scrollId = p.ScrollId;
					p.ScrollId = null;
					return this.RawDispatch.ScrollDispatchAsync<SearchResponse<T>>(p, scrollId);
				}
			);
		}

		/// <inheritdoc />
		public IEmptyResponse ClearScroll(Func<ClearScrollDescriptor, ClearScrollDescriptor> clearScrollSelector)
		{
			return this.Dispatcher.Dispatch<ClearScrollDescriptor, ClearScrollRequestParameters, EmptyResponse>(
				clearScrollSelector,
				(p, d) =>
				{
					var body = PatchClearScroll(p);
					return this.RawDispatch.ClearScrollDispatch<EmptyResponse>(p, body);
				}
				);
		}

		/// <inheritdoc />
		public IEmptyResponse ClearScroll(IClearScrollRequest clearScrollRequest)
		{
			return this.Dispatcher.Dispatch<IClearScrollRequest, ClearScrollRequestParameters, EmptyResponse>(
				clearScrollRequest,
				(p, d) =>
				{
					var body = PatchClearScroll(p);
					return this.RawDispatch.ClearScrollDispatch<EmptyResponse>(p, body);
				}
				);
		}

		/// <inheritdoc />
		public Task<IEmptyResponse> ClearScrollAsync(Func<ClearScrollDescriptor, ClearScrollDescriptor> clearScrollSelector)
		{
			return this.Dispatcher.DispatchAsync<ClearScrollDescriptor, ClearScrollRequestParameters, EmptyResponse, IEmptyResponse>(
				clearScrollSelector,
				(p, d) =>
				{
					var body = PatchClearScroll(p);
					return this.RawDispatch.ClearScrollDispatchAsync<EmptyResponse>(p, body);
				}
			);
		}

		/// <inheritdoc />
		public Task<IEmptyResponse> ClearScrollAsync(IClearScrollRequest clearScrollRequest)
		{
			return this.Dispatcher.DispatchAsync<IClearScrollRequest, ClearScrollRequestParameters, EmptyResponse, IEmptyResponse>(
				clearScrollRequest,
				(p, d) =>
				{
					var body = PatchClearScroll(p);
					return this.RawDispatch.ClearScrollDispatchAsync<EmptyResponse>(p, body);
				}
			);
		}

		private static string PatchClearScroll(ElasticsearchPathInfo<ClearScrollRequestParameters> p)
		{
			string body = null;
			var scrollId = p.ScrollId;
			if (scrollId != null && scrollId != "_all")
			{
				p.ScrollId = null;
				body = scrollId;
			}
			return body;
		}
	}
}


text:
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>

/* local objects */
#include "error.h"
#include "aldl-io.h"
#include "loadconfig.h"
#include "useful.h"

void *remote_init(void *aldl_in) {
  aldl_conf_t *aldl = aldl_in;
  int ran_connected_script = 0;
  while(1) {

    /* loop throttling */
    sleep(1);

    /* exit entire program if this file is present ... */
    if(access("/etc/aldl/aldl-stop",F_OK) != -1) {
      exit(1);
    }

    /* if /etc/aldl/aldl-connected.sh exists, run it when buffered... */
    if(aldl->ready == 1 && ran_connected_script == 0) {
      if(access("/etc/aldl/aldl-connected.sh",X_OK) != -1) {
        system("/etc/aldl/aldl-connected.sh");
      }
      ran_connected_script = 1;
    }

    /* if connection drops after being connected, run aldl-disconnected.sh */
    if(ran_connected_script == 1 && get_connstate(aldl) > 10) {
      if(access("/etc/aldl/aldl-disconnected.sh",X_OK) != -1) {
        system("/etc/aldl/aldl-disconnected.sh");
      }
      ran_connected_script = 0;
    }
  }
  return NULL;
}


text:
FakeWifiNetworkConfigurationHandler::FakeWifiNetworkConfigurationHandler()
    : last_wifi_credentials_attachment_(
          WifiCredentialsAttachment(kDefaultId,
                                    kDefaultSecurityType,
                                    kDefaultSsid)) {}

FakeWifiNetworkConfigurationHandler::~FakeWifiNetworkConfigurationHandler() =
    default;

void FakeWifiNetworkConfigurationHandler::ConfigureWifiNetwork(
    const WifiCredentialsAttachment& wifi_credentials_attachment,
    chromeos::network_config::mojom::CrosNetworkConfig::ConfigureNetworkCallback
        callback) {
  ++num_configure_network_calls_;
  last_wifi_credentials_attachment_ = wifi_credentials_attachment;
  std::move(callback).Run(guid_, error_message_);
}

void FakeWifiNetworkConfigurationHandler::SetOutput(
    const absl::optional<std::string>& network_guid,
    const std::string& error_message) {
  guid_ = network_guid;
  error_message_ = error_message;
}


text:
package com.infinityworks.webapp.service;

import com.infinityworks.common.lang.Try;
import com.infinityworks.webapp.converter.WardSummaryConverter;
import com.infinityworks.webapp.domain.Constituency;
import com.infinityworks.webapp.domain.Role;
import com.infinityworks.webapp.domain.User;
import com.infinityworks.webapp.domain.Ward;
import com.infinityworks.webapp.error.NotAuthorizedFailure;
import com.infinityworks.webapp.error.NotFoundFailure;
import com.infinityworks.webapp.repository.ConstituencyRepository;
import com.infinityworks.webapp.repository.WardRepository;
import com.infinityworks.webapp.rest.dto.UserRestrictedWards;
import org.junit.Before;
import org.junit.Test;

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

import static com.google.common.collect.Sets.newHashSet;
import static com.infinityworks.webapp.testsupport.builder.ConstituencyBuilder.constituency;
import static com.infinityworks.webapp.testsupport.builder.UserBuilder.user;
import static com.infinityworks.webapp.testsupport.builder.WardBuilder.ward;
import static com.infinityworks.webapp.testsupport.matcher.TryFailureMatcher.isFailure;
import static com.infinityworks.webapp.testsupport.matcher.TrySuccessMatcher.isSuccess;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;

public class WardServiceTest {
    private ConstituencyRepository constituencyRepository;
    private WardService underTest;
    private WardRepository wardRepository;
    private UserService userService;
    private WardAssociationService wardAssociationService;

    @Before
    public void setUp() throws Exception {
        wardRepository = mock(WardRepository.class);
        constituencyRepository = mock(ConstituencyRepository.class);
        userService = mock(UserService.class);
        wardAssociationService = mock(WardAssociationService.class);
        underTest = new WardService(new WardSummaryConverter(), wardRepository, constituencyRepository, userService, wardAssociationService);
    }

    @Test
    public void returnsFailureIfUserDoesNotHavePermissionWhenGettingWardByCode() throws Exception {
        Ward w = ward().build();
        User user = user().withRole(Role.USER).build();
        given(wardRepository.findByCode(w.getCode())).willReturn(Collections.singletonList(w));

        Try<Ward> result = underTest.getByCode(w.getCode(), user);

        assertThat(result, isFailure(instanceOf(NotAuthorizedFailure.class)));
    }

    @Test
    public void returnsFailureIfWardNotFoundWhenGettingWardByCode() throws Exception {
        Ward w = ward().build();
        User user = user().withRole(Role.USER).withWards(newHashSet(w)).build();
        given(wardRepository.findByCode(w.getCode())).willReturn(Collections.emptyList());

        Try<Ward> result = underTest.getByCode(w.getCode(), user);

        assertThat(result, isFailure(instanceOf(NotFoundFailure.class)));
    }

    @Test
    public void returnsTheWardByCode() throws Exception {
        Ward ward = ward().build();
        User user = user().withRole(Role.USER).withWards(newHashSet(ward)).build();
        given(wardRepository.findByCode(ward.getCode())).willReturn(Collections.singletonList(ward));

        Try<Ward> result = underTest.getByCode(ward.getCode(), user);

        assertThat(result, isSuccess(equalTo(ward)));
    }

    @Test
    public void returnsTheWards() throws Exception {
        Constituency c = constituency().build();
        Set<Ward> wards = newHashSet(
                ward().withWardName("Willenhall").withConstituency(c).build(),
                ward().withWardName("Binley").withConstituency(c).build());
        c.setWards(wards);
        User u = user().withWards(wards).withConstituencies(newHashSet(c))
                .build();
        given(constituencyRepository.findOne(c.getId())).willReturn(c);

        Try<UserRestrictedWards> result = underTest.findByConstituency(c.getId(), u);

        List<Ward> restrictedWards = new ArrayList<>(result.get().getWards());
        assertThat(restrictedWards.get(1).getName(), is("Willenhall"));
        assertThat(restrictedWards.get(0).getName(), is("Binley"));
    }

    @Test
    public void returnsFailureIfConstituencyNotFound() throws Exception {
        User user = mock(User.class);
        Constituency c = constituency().build();
        given(constituencyRepository.findOne(c.getId())).willReturn(null);

        Try<UserRestrictedWards> result = underTest.findByConstituency(c.getId(), user);

        assertThat(result.isSuccess(), is(false));
    }
}


text:
<?php

namespace Application\Form\Element;

use Zend\Form\Element;
use Zend\Form\Element\Select;

class TextSearch extends Select
{
}


text:
const void* kUIViewIsScrollInputView = &kUIViewIsScrollInputView;
@implementation UIView (Extand)

- (BOOL) isScrollInputView
{
    return [objc_getAssociatedObject(self, kUIViewIsScrollInputView) boolValue];
}

- (void) setIsScrollInputView:(BOOL)isScrollInputView
{
    objc_setAssociatedObject(self, kUIViewIsScrollInputView, @(isScrollInputView), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end

@interface UIView (First)
@property (nonatomic, assign, readonly) BOOL isContaionsFirstResponse;
@end

@implementation UIView (First)

- (BOOL) isContaionsFirstResponse
{
    if (self.isFirstResponder) {
        return YES;
    }
    NSArray* subViews = [self.subviews copy];
    for (UIView* v in subViews) {
        if (v.isContaionsFirstResponse) {
            return YES;
        }
    }
    return NO;
}

@end

@interface MSInputScrollViewController () <UIGestureRecognizerDelegate>

@end

@implementation MSInputScrollViewController
- (void) dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (instancetype) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (!self) {
        return self;
    }
    _isKeyboardShowing = NO;
    return self;
}
- (void) keybordWillShow:(NSNotification*)nc
{
    _isKeyboardShowing = YES;
    CGRect rect = [nc.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGRect scrollRect = self.view.bounds;
    scrollRect.size.height = CGRectGetHeight(self.view.bounds) - rect.size.height;
    _scrollView.frame = scrollRect;
    [self reloadScrollContentSize];
    [self showFirstResponse];

}

- (void) showFirstResponse
{
    NSArray* subViews = [self.scrollView subviews];
    for (UIView* v in subViews) {
        if (!v.isScrollInputView) {
            continue;
        }
        if (v.hidden) {
            continue;
        }

        BOOL first = v.isContaionsFirstResponse;
        NSLog(@"is first %d", first);
        if (first) {
            [self.scrollView scrollRectToVisible:v.frame animated:YES];
            break;
        }
    }
}
- (void) reloadScrollContentSize
{
    CGFloat maxHeight = 0;
    NSArray* subViews = [self.scrollView subviews];
    for (UIView* v in subViews) {
        if (!v.isScrollInputView) {
            continue;
        }
        if (v.hidden) {
            continue;
        }
        maxHeight = MAX(maxHeight, CGRectGetMaxY(v.frame));
    }
    if (_isKeyboardShowing) {
        maxHeight += 20;
    }
    CGSize size = CGSizeMake(CGRectGetViewControllerWidth, CGRectGetViewControllerHeight);
    size.height = MAX(maxHeight, CGRectGetHeight(_scrollView.frame));
    _scrollView.contentSize = size;
}
- (void) keybordWillHide:(NSNotification*)nc
{
    _isKeyboardShowing = NO;
    CGRect scrollRect = self.view.bounds;
    _scrollView.frame = scrollRect;
    [self reloadScrollContentSize];
    [self.scrollView scrollRectToVisible:CGRectZero animated:YES];
}

- (void) viewDidLoad
{
    [super viewDidLoad];
	[self setAutomaticallyAdjustsScrollViewInsets:NO];
    self.view.backgroundColor = [UIColor whiteColor];
    _scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:_scrollView];
    _scrollView.contentSize = self.view.bounds.size;

    UITapGestureRecognizer* tapG = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleHideKeyboardTap:)];
    tapG.numberOfTapsRequired = 1;
    tapG.numberOfTouchesRequired = 1;
    tapG.delegate = self;
    [self.view addGestureRecognizer:tapG];

}

- (void) handleHideKeyboardTap:(UITapGestureRecognizer*)tapG
{
    if (tapG.state == UIGestureRecognizerStateRecognized) {
        NSArray* subViews = self.scrollView.subviews;
        CGPoint point = [tapG locationInView:self.scrollView];
        for (UIView* v in subViews) {
            if (CGRectContainsPoint(v.frame, point)) {
                return;
            }
        }
        for (UIView* v in subViews) {
            if ([v respondsToSelector:@selector(resignFirstResponder)]) {
                [v resignFirstResponder];
            }
        }
    }
}
- (void) viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
}

- (BOOL) gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    NSArray* subViews = [self.scrollView subviews];
    CGPoint point = [gestureRecognizer locationInView:self.scrollView];
    for (UIView* v in subViews) {
        if (CGRectContainsPoint(v.frame, point)) {
            return NO;
        }
    }
    return YES;
}

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    _scrollView.frame = self.view.bounds;
    [self reloadScrollContentSize];
}
- (void) viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keybordWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keybordWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void) viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
@end


text:
var exec = require('child_process').exec;
var path = require('path');
var fs = require('fs');
var tap = require('tap');

function getContent(testName) {
  return fs.readFileSync(path.join(__dirname, 'expected', testName)).toString();
}

tap.test('make2tap CLI', function(test){
  test.plan(4);

  test.test('Basic', function(test){

    test.plan(3);
    exec('cat basic | ../bin.js', {
      cwd: __dirname
    }, function(error, stdout, stderr){
      test.equal(error, null, 'exists without error');
      test.equal('', stderr, 'do not output on stderr');
      test.equal(stdout, getContent('basic'), 'outputs expected TAP');
    });
  });

  test.test('With comments', function(test){

    test.plan(3);
    exec('cat comments | ../bin.js', {
      cwd: __dirname
    }, function(error, stdout, stderr){
      test.equal(error, null, 'exists without error');
      test.equal('', stderr, 'do not output on stderr');
      test.equal(stdout, getContent('comments'), 'outputs expected TAP');
    });
  });

  test.test('Proper make integration', function(test){

    test.plan(3);
    exec('make clean compile 2>&1 | ../bin.js', {
      cwd: __dirname
    }, function(error, stdout, stderr){
      test.equal(error, null, 'exists without error');
      test.equal('', stderr, 'do not output on stderr');
      test.equal(stdout, getContent('integration'), 'outputs expected TAP');
    });
  });

  test.test('Error handling', function(test){

    test.plan(8);
    exec('make break 2>&1 | ../bin.js', {
      cwd: __dirname
    }, function(error, stdout, stderr){
      test.notEqual(error, null, 'exits with error');
      test.equal('', stderr, 'do not output on stderr');
      test.ok(stdout.indexOf('# Successful task') >= 0, 'outputs successful steps');
      test.ok(stdout.indexOf('ok 1 - This works fine') >= 0, 'outputs sucessful tests');
      test.ok(stdout.startsWith(getContent('error')), 'contains expected TAP');
      test.ok(stdout.indexOf('thiswillbreak') >= 0, 'outputs original stderr');
      test.ok(stdout.indexOf('1..3') >= 0, 'has proper test count');
    });

    test.test('when the first intput is an error', function(test){
      test.plan(4);
      exec('make break-direct 2>&1 | ../bin.js', {
        cwd: __dirname
      }, function(error, stdout, stderr){
        test.notEqual(error, null, 'exits with error');
        test.equal('', stderr, 'do not output on stderr');
        test.ok(stdout.indexOf('thiswillbreak') >= 0, 'outputs original stderr');
        test.ok(stdout.indexOf('1..0') >= 0, 'has proper test count');
      });
    })
  });
});


text:
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="DAS-features-test-suite" parallel="false">
    <parameter name="useDefaultListeners" value="false"/>
    <test name="das-tests" preserve-order="true" parallel="false">
        <packages>
            <package name="org.wso2.das.integration.tests.jsapi.analytics"/>
        </packages>
    </test>
    <!--<test name="global-purging" preserve-order="true" parallel="false">-->
        <!--<packages>-->
            <!--<package name="org.wso2.das4is.integration.tests.globalpurging"/>-->
        <!--</packages>-->
    <!--</test>-->
    <test name="is-analytics" preserve-order="true" parallel="false">
        <packages>
            <package name="org.wso2.das4is.integration.tests.is"/>
        </packages>
    </test>
</suite>


text:
package groovy.transform;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Marker interface used to indicate that the property names of the annotated parameter
 * represent valid key names when using named arguments and that the property types
 * are applicable for type checking purposes.
 *
 * @since 2.5.0
 */
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.PARAMETER)
public @interface NamedDelegate {
}


text:
    <input hidden type="checkbox" id="menu-visible" value="1"/>

        {{ trans('header.menu') }}

            {{ trans('header.search.label') }}

            Treasures

        {{ Form::open([
                'method' => 'GET',
                'route' => ['search', App::getLocale()],
                'class' => 'header3__search',
                'role' => 'search',
                'id' => 'search',
                'itemprop' => 'potentialAction',
                'itemscope',
                'itemtype' => 'http://schema.org/SearchAction'
            ]) }}
        <meta itemprop="target" content="{{ URL::route('search', App::getLocale() ) }}?q={q}"/>
        {{ Form::text( 'q', null, [
            'class' => 'header3__search__input',
            'placeholder' => trans( 'header.search.placeholder' ),
            'aria-label' => trans( 'header.search.label' ),
            'id' => 'q',
            'autocomplete' => 'off',
            'accesskey' => 'f',
            'itemprop' => 'query-input' ])
        }}
        {{ Form::submit( trans( 'header.search.label' ), [ 'class' => 'header3__search__submit', 'tabindex' => '-1' ]) }}
        {{ Form::close() }}

        {{ trans('header.items') }}
        {{ trans('header.achievements') }}
        {{ trans('skin.breadcrumb') }}
        {{--            {{ trans('skill.breadcrumb') }}
        --}}{{ trans('profession.breadcrumb') }}
        {{ trans('trait.breadcrumb') }}
        {{ trans('specialization.breadcrumb') }}
        {{ trans('mount.breadcrumb') }}
        {{ trans('header.wvw') }}

        {{ trans('header.search.items') }}

        {{ trans('header.search.recent') }}


text:
package events

import (
	"sync"
	"testing"
	"time"

	"github.com/google/uuid"
	"github.com/stretchr/testify/assert"
)

type testPayload struct {
	Message string
}

type testCase struct {
	str  Stream
	name string
}

func TestStream(t *testing.T) {
	tcs := []testCase{}

	stream, err := NewStream()
	assert.Nilf(t, err, "NewStream should not return an error")
	assert.NotNilf(t, stream, "NewStream should return a stream object")
	tcs = append(tcs, testCase{str: stream, name: "memory"})

	for _, tc := range tcs {
		t.Run(tc.name, func(t *testing.T) {
			runTestStream(t, tc.str)
		})
	}

}

func runTestStream(t *testing.T, stream Stream) {
	// TestMissingTopic will test the topic validation on publish
	t.Run("TestMissingTopic", func(t *testing.T) {
		err := stream.Publish("", nil)
		assert.Equalf(t, err, ErrMissingTopic, "Publishing to a blank topic should return an error")
	})

	// TestConsumeTopic will publish a message to the test topic. The subscriber will subscribe to the
	// same test topic.
	t.Run("TestConsumeTopic", func(t *testing.T) {
		payload := &testPayload{Message: "HelloWorld"}
		metadata := map[string]string{"foo": "bar"}

		// create the subscriber
		evChan, err := stream.Consume("test")
		assert.Nilf(t, err, "Consume should not return an error")

		// setup the subscriber async
		var wg sync.WaitGroup

		go func() {
			timeout := time.NewTimer(time.Millisecond * 250)

			select {
			case event, _ := <-evChan:
				assert.NotNilf(t, event, "The message was nil")
				assert.Equal(t, event.Metadata, metadata, "Metadata didn't match")

				var result testPayload
				err = event.Unmarshal(&result)
				assert.Nil(t, err, "Error decoding result")
				assert.Equal(t, result, *payload, "Payload didn't match")

				wg.Done()
			case <-timeout.C:
				t.Fatalf("Event was not recieved")
			}
		}()

		err = stream.Publish("test", payload, WithMetadata(metadata))
		assert.Nil(t, err, "Publishing a valid message should not return an error")
		wg.Add(1)

		// wait for the subscriber to recieve the message or timeout
		wg.Wait()
	})

	// TestConsumeGroup will publish a message to a random topic. Two subscribers will then consume
	// the message from the firehose topic with different queues. The second subscriber will be registered
	// after the message is published to test durability.
	t.Run("TestConsumeGroup", func(t *testing.T) {
		topic := uuid.New().String()
		payload := &testPayload{Message: "HelloWorld"}
		metadata := map[string]string{"foo": "bar"}

		// create the first subscriber
		evChan1, err := stream.Consume(topic)
		assert.Nilf(t, err, "Consume should not return an error")

		// setup the subscriber async
		var wg sync.WaitGroup

		go func() {
			timeout := time.NewTimer(time.Millisecond * 250)

			select {
			case event, _ := <-evChan1:
				assert.NotNilf(t, event, "The message was nil")
				assert.Equal(t, event.Metadata, metadata, "Metadata didn't match")

				var result testPayload
				err = event.Unmarshal(&result)
				assert.Nil(t, err, "Error decoding result")
				assert.Equal(t, result, *payload, "Payload didn't match")

				wg.Done()
			case <-timeout.C:
				t.Fatalf("Event was not recieved")
			}
		}()

		err = stream.Publish(topic, payload, WithMetadata(metadata))
		assert.Nil(t, err, "Publishing a valid message should not return an error")
		wg.Add(2)

		// create the second subscriber
		evChan2, err := stream.Consume(topic,
			WithGroup("second_queue"),
			WithOffset(time.Now().Add(time.Minute*-1)),
		)
		assert.Nilf(t, err, "Consume should not return an error")

		go func() {
			timeout := time.NewTimer(time.Second * 1)

			select {
			case event, _ := <-evChan2:
				assert.NotNilf(t, event, "The message was nil")
				assert.Equal(t, event.Metadata, metadata, "Metadata didn't match")

				var result testPayload
				err = event.Unmarshal(&result)
				assert.Nil(t, err, "Error decoding result")
				assert.Equal(t, result, *payload, "Payload didn't match")

				wg.Done()
			case <-timeout.C:
				t.Fatalf("Event was not recieved")
			}
		}()

		// wait for the subscriber to recieve the message or timeout
		wg.Wait()
	})

	t.Run("AckingNacking", func(t *testing.T) {
		ch, err := stream.Consume("foobarAck", WithAutoAck(false, 5*time.Second))
		assert.NoError(t, err, "Unexpected error subscribing")
		assert.NoError(t, stream.Publish("foobarAck", map[string]string{"foo": "message 1"}))
		assert.NoError(t, stream.Publish("foobarAck", map[string]string{"foo": "message 2"}))

		ev := <-ch
		ev.Ack()
		ev = <-ch
		nacked := ev.ID
		ev.Nack()
		select {
		case ev = <-ch:
			assert.Equal(t, ev.ID, nacked, "Nacked message should have been received again")
			assert.NoError(t, ev.Ack())
		case <-time.After(7 * time.Second):
			t.Fatalf("Timed out waiting for message to be put back on queue")
		}

	})

	t.Run("Retries", func(t *testing.T) {
		ch, err := stream.Consume("foobarRetries", WithAutoAck(false, 5*time.Second), WithRetryLimit(1))
		assert.NoError(t, err, "Unexpected error subscribing")
		assert.NoError(t, stream.Publish("foobarRetries", map[string]string{"foo": "message 1"}))

		ev := <-ch
		id := ev.ID
		ev.Nack()
		ev = <-ch
		assert.Equal(t, id, ev.ID, "Nacked message should have been received again")
		ev.Nack()
		select {
		case ev = <-ch:
			t.Fatalf("Unexpected event received")
		case <-time.After(7 * time.Second):
		}

	})

	t.Run("InfiniteRetries", func(t *testing.T) {
		ch, err := stream.Consume("foobarRetriesInf", WithAutoAck(false, 2*time.Second))
		assert.NoError(t, err, "Unexpected error subscribing")
		assert.NoError(t, stream.Publish("foobarRetriesInf", map[string]string{"foo": "message 1"}))

		count := 0
		id := ""
		for {
			select {
			case ev := <-ch:
				if id != "" {
					assert.Equal(t, id, ev.ID, "Nacked message should have been received again")
				}
				id = ev.ID
			case <-time.After(3 * time.Second):
				t.Fatalf("Unexpected event received")
			}

			count++
			if count == 11 {
				break
			}
		}

	})

	t.Run("twoSubs", func(t *testing.T) {
		ch1, err := stream.Consume("foobarTwoSubs1", WithAutoAck(false, 5*time.Second))
		assert.NoError(t, err, "Unexpected error subscribing to topic 1")
		ch2, err := stream.Consume("foobarTwoSubs2", WithAutoAck(false, 5*time.Second))
		assert.NoError(t, err, "Unexpected error subscribing to topic 2")

		assert.NoError(t, stream.Publish("foobarTwoSubs2", map[string]string{"foo": "message 1"}))
		assert.NoError(t, stream.Publish("foobarTwoSubs1", map[string]string{"foo": "message 1"}))

		wg := sync.WaitGroup{}
		wg.Add(2)
		go func() {
			ev := <-ch1
			assert.Equal(t, "foobarTwoSubs1", ev.Topic, "Received message from unexpected topic")
			wg.Done()
		}()
		go func() {
			ev := <-ch2
			assert.Equal(t, "foobarTwoSubs2", ev.Topic, "Received message from unexpected topic")
			wg.Done()
		}()
		wg.Wait()
	})
}


text:
package io.dockstore.webservice.helpers;

import com.google.common.collect.Sets;
import io.dockstore.webservice.CustomWebApplicationException;
import io.dockstore.webservice.core.Alias;
import io.dockstore.webservice.core.User;
import io.dockstore.webservice.core.Workflow;
import io.dockstore.webservice.core.WorkflowVersion;
import io.dockstore.webservice.jdbi.WorkflowDAO;
import io.dockstore.webservice.jdbi.WorkflowVersionDAO;
import io.dockstore.webservice.resources.AliasableResourceInterface;
import io.dockstore.webservice.resources.AuthenticatedResourceInterface;
import java.util.Arrays;
import java.util.Optional;
import java.util.Set;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class AliasHelper {

    private static final Logger LOG = LoggerFactory.getLogger(AliasHelper.class);

    private AliasHelper() {
    }

    /**
     * Finds a workflow and returns the workflow id based on a workflow version id.
     *
     * @param workflowDAO Workflow data access object
     * @param workflowVersionId the id of the workflow version
     * @return workflow or throws an exception if the workflow cannot be found
     */
    public static Workflow getWorkflow(WorkflowDAO workflowDAO, long workflowVersionId) {
        Optional<Workflow> workflow = workflowDAO.getWorkflowByWorkflowVersionId(workflowVersionId);
        if (!workflow.isPresent()) {
            LOG.error("Could not get workflow based on workflow version id " + workflowVersionId);
            throw new CustomWebApplicationException("Could not get workflow based on workflow version id " + workflowVersionId, HttpStatus.SC_NOT_FOUND);
        }
        return workflow.get();
    }

    /**
     * Gets the Workflow Version object via a Workflow Version ID
     * and checks that the Workflow exists and that the
     * user is authorized to update it
     * @param authenticatedResourceInterface interface to check users and entries
     * @param workflowDAO Workflow data access object
     * @param workflowVersionDAO Workflow Version data access object
     * @param user user authenticated to update the workflow
     * @param workflowVersionId the id of the workflow version
     * @return the workflow version
     */
    public static WorkflowVersion getAndCheckWorkflowVersionResource(AuthenticatedResourceInterface authenticatedResourceInterface, WorkflowDAO workflowDAO,
            WorkflowVersionDAO workflowVersionDAO, User user, Long workflowVersionId) {
        final WorkflowVersion workflowVersion = workflowVersionDAO.findById(workflowVersionId);
        if (workflowVersion == null) {
            LOG.error("Could not find workflow version using the workflow version id: " + workflowVersionId);
            throw new CustomWebApplicationException("Workflow version not found when searching with id: " + workflowVersionId, HttpStatus.SC_BAD_REQUEST);
        }

        Workflow workflow = getWorkflow(workflowDAO, workflowVersionId);
        authenticatedResourceInterface.checkCanWrite(user, workflow);
        return workflowVersion;
    }

    /**
     * Add aliases to a Workflow Version
     * and check that they are valid before adding them:
     * Only works for owner of the entry
     * If blockFormat false, then no limit on format
     * @param authenticatedResourceInterface interface to check users and entries
     * @param workflowDAO Workflow data access object
     * @param workflowVersionDAO Workflow Version data access object
     * @param user user authenticated to issue a DOI for the workflow
     * @param id the id of the Entry
     * @param aliases a comma separated string of aliases
     * @param blockFormat if true don't allow specific formats
     * @return the Workflow Version
     */
    public static WorkflowVersion addWorkflowVersionAliasesAndCheck(AuthenticatedResourceInterface authenticatedResourceInterface, WorkflowDAO workflowDAO,
            WorkflowVersionDAO workflowVersionDAO, User user, Long id, String aliases, boolean blockFormat) {
        WorkflowVersion workflowVersion = getAndCheckWorkflowVersionResource(authenticatedResourceInterface, workflowDAO, workflowVersionDAO, user, id);
        Set<String> oldAliases = workflowVersion.getAliases().keySet();
        Set<String> newAliases = Sets.newHashSet(Arrays.stream(aliases.split(",")).map(String::trim).toArray(String[]::new));

        AliasableResourceInterface.checkAliases(newAliases, user, blockFormat);

        Set<String> duplicateAliasesToAdd = Sets.intersection(newAliases, oldAliases);
        if (!duplicateAliasesToAdd.isEmpty()) {
            String dupAliasesString = String.join(", ", duplicateAliasesToAdd);
            throw new CustomWebApplicationException("Aliases " + dupAliasesString + " already exist; please use unique aliases",
                    HttpStatus.SC_BAD_REQUEST);
        }

        newAliases.forEach(alias -> workflowVersion.getAliases().put(alias, new Alias()));
        return workflowVersion;
    }
}


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

<title>FollowManagerAdapter</title>
<meta name="date" content="2017-12-04">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.example.habittracker2017

Class FollowManagerAdapter

java.lang.Object

android.widget.BaseAdapter

com.example.habittracker2017.FollowManagerAdapter

All Implemented Interfaces:

android.widget.Adapter, android.widget.ListAdapter, android.widget.SpinnerAdapter

public class FollowManagerAdapter
extends android.widget.BaseAdapter
implements android.widget.ListAdapter

Activities the viewHistory does, subclass of fragment

Since:

1.0

See Also:

BaseAdapter

Field Summary

Fields inherited from interface android.widget.Adapter

IGNORE_ITEM_VIEW_TYPE, NO_SELECTION

Constructor Summary

Constructors

Constructor and Description

FollowManagerAdapter(java.util.ArrayList<java.lang.String> list,
                    android.content.Context context)

Constructor  for FollowManagerAdapter

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

int
getCount()

java.lang.String
getItem(int pos)

long
getItemId(int pos)

android.view.View
getView(int position,
       android.view.View convertView,
       android.view.ViewGroup parent)

Methods inherited from class android.widget.BaseAdapter

areAllItemsEnabled, getAutofillOptions, getDropDownView, getItemViewType, getViewTypeCount, hasStableIds, isEmpty, isEnabled, notifyDataSetChanged, notifyDataSetInvalidated, registerDataSetObserver, setAutofillOptions, unregisterDataSetObserver

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Methods inherited from interface android.widget.ListAdapter

areAllItemsEnabled, isEnabled

Methods inherited from interface android.widget.Adapter

getAutofillOptions, getItemViewType, getViewTypeCount, hasStableIds, isEmpty, registerDataSetObserver, unregisterDataSetObserver

Constructor Detail

FollowManagerAdapter

public FollowManagerAdapter(java.util.ArrayList<java.lang.String> list,
                            android.content.Context context)

Constructor  for FollowManagerAdapter

Parameters:

list -

context -

Method Detail

getCount

public int getCount()

Specified by:

getCount in interface android.widget.Adapter

getItem

public java.lang.String getItem(int pos)

Specified by:

getItem in interface android.widget.Adapter

getItemId

public long getItemId(int pos)

Specified by:

getItemId in interface android.widget.Adapter

getView

public android.view.View getView(int position,
                                 android.view.View convertView,
                                 android.view.ViewGroup parent)

Specified by:

getView in interface android.widget.Adapter

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<polymer-element name="commits-panel-sk">
  <template>

      Buildbot Percent Complete: {{percent | userPercent}}%

      <template repeat="{{c in commitinfo}}">

          {{c.author}}
          {{c.commit_time | humanize}}
          {{c.hash | trunc}}
          {{c.message}}

      </template>

  </template>

</polymer-element>


text:
FROM toubiweb/node-core:8.1

MAINTAINER Nicolas Toublanc <n.toublanc@gmail.com>

# create "dev" user without password
RUN adduser --disabled-password --gecos '' dev
# allow user to go sudo
RUN adduser dev sudo
RUN echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers

# set default docker user
USER dev

# set default working directory
WORKDIR /app


text:
<?php

namespace Moip\Resource;

use stdClass;

class Webhook extends MoipResource
{
    /**
     * Initialize a new instance.
     */
    public function initialize()
    {
        $this->data = new stdClass();
    }

    /**
     * Get webhook id.
     *
     * @return string The webhook id.
     */
    public function getId()
    {
        return $this->getIfSet('id');
    }

    /**
     * Get resource id.
     *
     * @return string The webhook id.
     */
    public function getResourceId()
    {
        return $this->getIfSet('resourceId');
    }

    /**
     * Get event.
     *
     * @return string event.
     */
    public function getEvent()
    {
        return $this->getIfSet('event');
    }

    /**
     * Get url.
     *
     * @return string url.
     */
    public function getUrl()
    {
        return $this->getIfSet('url');
    }

    /**
     * Get webhook status.
     *
     * @return string webhook status.
     */
    public function getStatus()
    {
        return $this->getIfSet('status');
    }

    /**
     * Mount structure of Webhook.
     *
     * @param \stdClass $response
     *
     * @return \Moip\Resource\Webhook Webhook
     */
    protected function populate(stdClass $response)
    {
        $webhook = clone $this;
        $webhook->data = new stdClass();

        $webhook->data->id = $response->id;
        $webhook->data->event = $response->event;
        $webhook->data->url = $response->url;
        $webhook->data->resourceId = $response->resourceId;
        $webhook->data->status = $response->status;

        return $webhook;
    }
}


text:
package org.liuxy.rentcar.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.liuxy.rentcar.dao.UserDao;
import org.liuxy.rentcar.entity.AdminUser;
import org.liuxy.rentcar.entity.User;

public class AdminDaoImpl extends BaseDao implements UserDao {

	public AdminDaoImpl() {

	}

	@Override
	public User getUserByUser(User user) {

		AdminUser adminUser = null;

		if (user instanceof AdminUser) {

			String sql = "SELECT adminId, adminName, adminPwd FROM AdminUsers WHERE adminName = ? AND adminPwd = ?";
			ResultSet rs = this.dataQuery(sql, ((AdminUser) user).getAdminName(), ((AdminUser) user).getAdminPwd());

			try {
				// 必须要用next()类似迭代器
				while (rs.next()){
					if (rs.getString("adminName").equals(((AdminUser) user).getAdminName())
							&& rs.getString("adminPwd").equals(((AdminUser) user).getAdminPwd())) {
						adminUser = new AdminUser(rs.getInt("adminId"), rs.getString("adminName"));
					}
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}finally {
				this.closeAll();
			}
		}

		return adminUser;
	}

	@Override
	public int addUserByUser(User user) {

		String sql = "insert into AdminUsers(adminName, adminPwd) values(?, ?)";
		if (user instanceof AdminUser) {
			return this.dataUpdate(sql, ((AdminUser) user).getAdminName(), ((AdminUser) user).getAdminPwd());
		} else {
			return 0;
		}
	}

	@Override
	public int delUser(User user) {

		String sql = "DELETE FROM AdminUsers WHERE adminId = ?";
		if (user instanceof AdminUser) {
			return this.dataUpdate(sql, ((AdminUser) user).getAdminId());
		} else {
			return 0;
		}
	}

	@Override
	public int updateUser(User user) {

		String sql = "UPDATE AdminUsers SET adminName = ?, adminPwd = ? WHERE adminId = ?;";
		if (user instanceof AdminUser) {
			return this.dataUpdate(sql, ((AdminUser) user).getAdminName(), ((AdminUser) user).getAdminPwd(), ((AdminUser) user).getAdminId());
		} else {
			return 0;
		}
	}

}


text:
<?php

namespace ZendTest\Filter\Compress;

use Zend\Filter\Compress\Tar as TarCompression;

/**
 * @category   Zend
 * @package    Zend_Filter
 * @subpackage UnitTests
 * @group      Zend_Filter
 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class TarTest extends \PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        if (!class_exists('Archive_Tar')) {
            try {
                \Zend\Loader::loadClass('Archive_Tar');
            } catch (\Zend\Loader\Exception $e) {
                $this->markTestSkipped('This filter needs PEARs Archive_Tar');
            }
        }

        $files = array(
            dirname(__DIR__) . '/_files/zipextracted.txt',
            dirname(__DIR__) . '/_files/_compress/Compress/First/Second/zipextracted.txt',
            dirname(__DIR__) . '/_files/_compress/Compress/First/Second',
            dirname(__DIR__) . '/_files/_compress/Compress/First/zipextracted.txt',
            dirname(__DIR__) . '/_files/_compress/Compress/First',
            dirname(__DIR__) . '/_files/_compress/Compress/zipextracted.txt',
            dirname(__DIR__) . '/_files/_compress/Compress',
            dirname(__DIR__) . '/_files/_compress/zipextracted.txt',
            dirname(__DIR__) . '/_files/_compress',
            dirname(__DIR__) . '/_files/compressed.tar'
        );

        foreach($files as $file) {
            if (file_exists($file)) {
                if (is_dir($file)) {
                    rmdir($file);
                } else {
                    unlink($file);
                }
            }
        }

        if (!file_exists(dirname(__DIR__) . '/_files/Compress/First/Second')) {
            mkdir(dirname(__DIR__) . '/_files/Compress/First/Second', 0777, true);
            file_put_contents(dirname(__DIR__) . '/_files/Compress/First/Second/zipextracted.txt', 'compress me');
            file_put_contents(dirname(__DIR__) . '/_files/Compress/First/zipextracted.txt', 'compress me');
            file_put_contents(dirname(__DIR__) . '/_files/Compress/zipextracted.txt', 'compress me');
        }
    }

    public function tearDown()
    {
        $files = array(
            dirname(__DIR__) . '/_files/zipextracted.txt',
            dirname(__DIR__) . '/_files/_compress/Compress/First/Second/zipextracted.txt',
            dirname(__DIR__) . '/_files/_compress/Compress/First/Second',
            dirname(__DIR__) . '/_files/_compress/Compress/First/zipextracted.txt',
            dirname(__DIR__) . '/_files/_compress/Compress/First',
            dirname(__DIR__) . '/_files/_compress/Compress/zipextracted.txt',
            dirname(__DIR__) . '/_files/_compress/Compress',
            dirname(__DIR__) . '/_files/_compress/zipextracted.txt',
            dirname(__DIR__) . '/_files/_compress',
            dirname(__DIR__) . '/_files/compressed.tar'
        );

        foreach($files as $file) {
            if (file_exists($file)) {
                if (is_dir($file)) {
                    rmdir($file);
                } else {
                    unlink($file);
                }
            }
        }

        if (!file_exists(dirname(__DIR__) . '/_files/Compress/First/Second')) {
            mkdir(dirname(__DIR__) . '/_files/Compress/First/Second', 0777, true);
            file_put_contents(dirname(__DIR__) . '/_files/Compress/First/Second/zipextracted.txt', 'compress me');
            file_put_contents(dirname(__DIR__) . '/_files/Compress/First/zipextracted.txt', 'compress me');
            file_put_contents(dirname(__DIR__) . '/_files/Compress/zipextracted.txt', 'compress me');
        }
    }

    /**
     * Basic usage
     *
     * @return void
     */
    public function testBasicUsage()
    {
        $filter  = new TarCompression(
            array(
                'archive'  => dirname(__DIR__) . '/_files/compressed.tar',
                'target'   => dirname(__DIR__) . '/_files/zipextracted.txt'
            )
        );

        $content = $filter->compress('compress me');
        $this->assertEquals(dirname(__DIR__) . DIRECTORY_SEPARATOR . '_files'
                            . DIRECTORY_SEPARATOR . 'compressed.tar', $content);

        $content = $filter->decompress($content);
        $this->assertEquals(dirname(__DIR__) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR, $content);
        $content = file_get_contents(dirname(__DIR__) . '/_files/zipextracted.txt');
        $this->assertEquals('compress me', $content);
    }

    /**
     * Setting Options
     *
     * @return void
     */
    public function testTarGetSetOptions()
    {
        $filter = new TarCompression();
        $this->assertEquals(
            array(
                'archive' => null,
                'target'  => '.',
                'mode'    => null),
            $filter->getOptions()
        );

        $this->assertEquals(null, $filter->getOptions('archive'));

        $this->assertNull($filter->getOptions('nooption'));
        $filter->setOptions(array('nooptions' => 'foo'));
        $this->assertNull($filter->getOptions('nooption'));

        $filter->setOptions(array('archive' => 'temp.txt'));
        $this->assertEquals('temp.txt', $filter->getOptions('archive'));
    }

    /**
     * Setting Archive
     *
     * @return void
     */
    public function testTarGetSetArchive()
    {
        $filter = new TarCompression();
        $this->assertEquals(null, $filter->getArchive());
        $filter->setArchive('Testfile.txt');
        $this->assertEquals('Testfile.txt', $filter->getArchive());
        $this->assertEquals('Testfile.txt', $filter->getOptions('archive'));
    }

    /**
     * Setting Target
     *
     * @return void
     */
    public function testTarGetSetTarget()
    {
        $filter = new TarCompression();
        $this->assertEquals('.', $filter->getTarget());
        $filter->setTarget('Testfile.txt');
        $this->assertEquals('Testfile.txt', $filter->getTarget());
        $this->assertEquals('Testfile.txt', $filter->getOptions('target'));

        try {
            $filter->setTarget('/unknown/path/to/file.txt');
            $this->fail('Exception expected');
        } catch(\Zend\Filter\Exception $e) {
            $this->assertContains('does not exist', $e->getMessage());
        }
    }

    /**
     * Setting Archive
     *
     * @return void
     */
    public function testTarCompressToFile()
    {
        $filter  = new TarCompression(
            array(
                'archive'  => dirname(__DIR__) . '/_files/compressed.tar',
                'target'   => dirname(__DIR__) . '/_files/zipextracted.txt'
            )
        );
        file_put_contents(dirname(__DIR__) . '/_files/zipextracted.txt', 'compress me');

        $content = $filter->compress(dirname(__DIR__) . '/_files/zipextracted.txt');
        $this->assertEquals(dirname(__DIR__) . DIRECTORY_SEPARATOR . '_files'
                            . DIRECTORY_SEPARATOR . 'compressed.tar', $content);

        $content = $filter->decompress($content);
        $this->assertEquals(dirname(__DIR__) . DIRECTORY_SEPARATOR . '_files' . DIRECTORY_SEPARATOR, $content);
        $content = file_get_contents(dirname(__DIR__) . '/_files/zipextracted.txt');
        $this->assertEquals('compress me', $content);
    }

    /**
     * Compress directory to Filename
     *
     * @return void
     */
    public function testTarCompressDirectory()
    {
        $filter  = new TarCompression(
            array(
                'archive'  => dirname(__DIR__) . '/_files/compressed.tar',
                'target'   => dirname(__DIR__) . '/_files/_compress'
            )
        );
        $content = $filter->compress(dirname(__DIR__) . '/_files/Compress');
        $this->assertEquals(dirname(__DIR__) . DIRECTORY_SEPARATOR . '_files'
                            . DIRECTORY_SEPARATOR . 'compressed.tar', $content);
    }

    /**
     * testing toString
     *
     * @return void
     */
    public function testTarToString()
    {
        $filter = new TarCompression();
        $this->assertEquals('Tar', $filter->toString());
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Juel, Bihangtill K. Svenska Vetensk. -Akad. Handl. , Afd. 3 27(no. 16): 7 (1902)

#### Original name
Taphridium Lagerh. & Juel

### Remarks
null


text:
<!DOCTYPE html>
<html>
  <head>

    <script src="../jspsych.js"></script>
    <script src="../plugins/jspsych-instructions.js"></script>
    <link rel="stylesheet" href="../css/jspsych.css"></link>
  </head>

  <script>

  var trial = {
    type: 'instructions',
    pages: [
      'Welcome to the experiment. Click next to begin.',
      'This is the second page of instructions.',
      'This is the final page.'
    ],
    show_clickable_nav: true
  }

  jsPsych.init({
    timeline: [trial],
    on_finish: function(){ jsPsych.data.displayData(); }
  });

  </script>
</html>


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import injectSheet from 'react-jss';
import classNames from 'classnames';
import { Container, FixedBox } from '../../flexBoxLayout';

const styles = {
  menu: {
    backgroundColor: props => props.backgroundColor,
    textAlign: 'center',
  },

  // popup aniamtion
  item: {
    backgroundColor: props => props.itemUnselectedBgColor,
    color: props => props.itemUnselectedColor,
    fontSize: props => props.fontSize,
    height: props => props.itemHeight,
    lineHeight: props => props.itemHeight,
    margin: props => `${props.margin} 0`,
  },

  selected: {
    backgroundColor: props => props.itemSelectedBgColor,
    color: props => props.itemSelectedColor,
  },
};

/**
 *  An Popup modal from bottom
 *
 */
class SideMenu extends Component {
    static propTypes = {
      items: PropTypes.array,
      selected: PropTypes.number,
      fontSize: PropTypes.string,
      itemHeight: PropTypes.string,
      margin: PropTypes.string,
      backgroundColor: PropTypes.string,
      itemUnselectedBgColor: PropTypes.string,
      itemUnselectedColor: PropTypes.string,
      itemSelectedBgColor: PropTypes.string,
      itemSelectedColor: PropTypes.string,
      handleItemClick: PropTypes.func,
    };

    static defaultProps = {
      selected: 0,
      fontSize: '0.32rem',
      itemHeight: '0.60rem',
      margin: '0.12rem',
      backgroundColor: 'transparent',
      itemUnselectedBgColor: 'transparent',
      itemUnselectedColor: '#ddc597',
      itemSelectedBgColor: '#3b1410',
      itemSelectedColor: '#996a48',
    }

    render() {
      const { classes } = this.props;
      const that = this;
      return (
        <Container direction="v" className={classes.menu}>
          {
                    this.props.items.map((item, index) => {
                        const cls = classNames(classes.item, {
                            [classes.selected]: index === this.props.selected,
                        });
                        return (
                          <FixedBox className={cls} onClick={() => { that.props.handleItemClick(index); }} key={index}>
                            {item.menu}
                          </FixedBox>
                        );
                    })
                }
        </Container>
      );
    }
}

export default injectSheet(styles)(SideMenu);