text:
{-# LANGUAGE TemplateHaskell, OverloadedStrings #-}

module SecondTransfer.Test.DecoySession where

import           Control.Concurrent
import           Control.Concurrent.STM.TMVar
import           Control.Concurrent.STM.TChan
import           Control.Exception
import           Control.Lens                     (view, (^.), over)
import qualified Control.Lens                     as L
import           Control.Monad.STM                (atomically)

import qualified Network.HTTP2                    as NH2
import qualified Network.HPACK                    as HP

import qualified Data.ByteString                  as B
import qualified Data.ByteString.Lazy             as LB
import qualified Data.ByteString.Builder          as Bu
import qualified Data.Sequence                    as Sq
import           Data.Sequence                    ( (<|), (|>), ViewL(..), Seq )

import           SecondTransfer.Http2
import           SecondTransfer.Types
import           SecondTransfer.Http2.Session
import           SecondTransfer.Sessions.Config
import           SecondTransfer.Sessions.Internal
import           SecondTransfer.Http2.Framer
import           SecondTransfer.MainLoop.Internal
import           Debug.Trace

-- "Internal imports"
import           SecondTransfer.MainLoop.CoherentWorker (defaultEffects)

data DataContinuityEngine = DataContinuityEngine {
    _incoming_DCE :: Seq B.ByteString
    }

L.makeLenses ''DataContinuityEngine

emptyDCE :: DataContinuityEngine
emptyDCE =  DataContinuityEngine  Sq.empty

dceAddData :: DataContinuityEngine -> B.ByteString -> DataContinuityEngine
dceAddData dce moredata | B.length moredata > 0 = over incoming_DCE ( |>  moredata ) dce
dceAddData dce moredata | otherwise             = dce

tryGetThisManyData :: DataContinuityEngine -> Int -> Maybe (DataContinuityEngine, B.ByteString)
tryGetThisManyData dce n = let
    go_result = go n "" (dce ^. incoming_DCE)
    go :: Int -> Bu.Builder -> Seq B.ByteString -> Maybe (Seq B.ByteString, Bu.Builder)
    go n bld seq  | Sq.EmptyL <- Sq.viewl seq, n > 0   = Nothing
                  | Sq.EmptyL <- Sq.viewl seq, n == 0  = Just (seq, bld)
                  | lead :< rest <- Sq.viewl seq, n > B.length lead    = go (n - B.length lead) (bld `mappend` Bu.byteString lead) rest
                  | lead :< rest <- Sq.viewl seq, n == B.length lead   = Just ( rest, bld `mappend` Bu.byteString lead)
                  | lead :< rest <- Sq.viewl seq, n < B.length lead    = let
                      (tk, lv) = B.splitAt n lead
                      in Just ( lv <| rest, bld `mappend`  Bu.byteString tk  )
  in case go_result of
    Just (new_dce, bld ) -> Just
        (DataContinuityEngine new_dce,  LB.toStrict . Bu.toLazyByteString $ bld )

    Nothing -> Nothing

dceIsEmpty :: DataContinuityEngine -> Bool
dceIsEmpty dce = Sq.null $ dce ^. incoming_DCE

dceGetAllData :: DataContinuityEngine -> (DataContinuityEngine, B.ByteString)
dceGetAllData dce = (emptyDCE, all_together)
  where
    all_together = LB.toStrict . Bu.toLazyByteString .  L.foldMapOf (incoming_DCE . L.folded) Bu.byteString $ dce

data DecoySession = DecoySession {
    _inputDataChannel     :: TChan B.ByteString
    ,_outputDataChannel   :: TChan B.ByteString
    ,_sessionThread       :: ThreadId
    ,_remainingOutputBit  :: TMVar B.ByteString
    ,_nh2Settings         :: NH2.Settings
    ,_sessionThrowed      :: TMVar Bool
    ,_waiting             :: TMVar ThreadId
    ,_encodeHeadersHere   :: TMVar HP.DynamicTable
    ,_decodeHeadersHere   :: TMVar HP.DynamicTable

    ,_incomingData        :: TMVar DataContinuityEngine
    ,_clientState         :: ClientState
    -- Execute this when you want to use a powerfull client session
    ,_startClientSessionCallback :: IO ClientState
    }

L.makeLenses ''DecoySession

-- errorsSessionConfig :: MVar Bool -> SessionsConfig
-- errorsSessionConfig mvar = set (sessionsCallbacks . reportErrorCallback_SC)
--      (Just $ setError mvar) defaultSessionsConfig

-- | Creates a IOCallbacks where "pullAction" reads from input_data_channel and where
--   "pushData" writes to output_data_channel.
channelsToIOCallbacks :: TChan B.ByteString -> TChan B.ByteString -> TMVar DataContinuityEngine -> IOCallbacks
channelsToIOCallbacks input_data_channel output_data_channel incoming_data_tmvar =
  let
    push_action  :: PushAction
    push_action lazy_bs  =  atomically $
        writeTChan output_data_channel $ LB.toStrict lazy_bs

    pull_action  :: PullAction
    pull_action byte_count = atomically $ do
        incoming_data <- takeTMVar incoming_data_tmvar
        let
            go dce = let
                maybe_stuff = tryGetThisManyData dce byte_count
                in case maybe_stuff of
                    Nothing -> do
                        new_data <- readTChan input_data_channel
                        let
                            new_dce = dceAddData dce new_data
                        go new_dce

                    Just (new_bce, bs) -> do
                        putTMVar incoming_data_tmvar new_bce
                        return bs
        go incoming_data

    best_effort_pull_action :: BestEffortPullAction
    best_effort_pull_action can_block = atomically $ do
        incoming_data <- takeTMVar incoming_data_tmvar
        if dceIsEmpty incoming_data
          then
            if can_block
              then do
                -- Wait for the next item
                new_data <- readTChan input_data_channel
                -- Leave the empty thing alone
                putTMVar incoming_data_tmvar incoming_data
                return new_data
              else do
                putTMVar incoming_data_tmvar incoming_data
                return ""
          else do
              let
                  (new_dce, all_together) = dceGetAllData incoming_data
              putTMVar incoming_data_tmvar new_dce
              return all_together

    close_action :: CloseAction
    close_action =  return ()
  in
    IOCallbacks {
       _pushAction_IOC = push_action,
       _pullAction_IOC = pull_action,
       _closeAction_IOC = close_action,
       _bestEffortPullAction_IOC = best_effort_pull_action
       }

-- Supposed to be an HTTP/2 attendant
createDecoySession :: Attendant -> IO DecoySession
createDecoySession attendant = do
    input_data_channel  <- newTChanIO
    output_data_channel <- newTChanIO
    incoming_data_tmvar  <- newTMVarIO emptyDCE
    reverse_data_tmvar <- newTMVarIO emptyDCE
    session_throwed_tmvar <- newTMVarIO False
    client_state <- makeClientState
    client_sessions_context <- makeSessionsContext defaultSessionsConfig
    let
        attendant_callbacks = channelsToIOCallbacks input_data_channel output_data_channel incoming_data_tmvar
        client_callbacks = channelsToIOCallbacks output_data_channel input_data_channel reverse_data_tmvar
        start_client_session_callback :: IO ClientState
        start_client_session_callback = do
            -- Connection info is not used anyway with client cases
            wrapSession (ClientState_SP client_state) client_sessions_context (error "no-connection_data")  client_callbacks
            return client_state

    dtable_for_encoding <- HP.newDynamicTableForEncoding 4096
    dtable_for_encoding_mvar <- newTMVarIO dtable_for_encoding
    dtable_for_decoding <- HP.newDynamicTableForDecoding 4096
    dtable_for_decoding_mvar <- newTMVarIO dtable_for_decoding

    waiting_mvar <- newEmptyTMVarIO

    thread_id <- forkIO $ catch
        (do
            attendant nullConnectionData  attendant_callbacks
        )
        ((\ e -> do
            putStrLn $ "Exception: " ++ (show e)
            maybe_waiting <- atomically $ tryReadTMVar waiting_mvar
            case maybe_waiting of
                Just thread_id -> throwTo thread_id e
                Nothing -> return ()
        ):: SomeException -> IO ())

    remaining_output_bit <- newTMVarIO ""
    let session = DecoySession {
        _inputDataChannel  = input_data_channel,
        _outputDataChannel = output_data_channel,
        _sessionThread     = thread_id,
        _remainingOutputBit= remaining_output_bit,
        _nh2Settings       = NH2.defaultSettings,
        _waiting           = waiting_mvar,
        _encodeHeadersHere = dtable_for_encoding_mvar,
        _decodeHeadersHere = dtable_for_decoding_mvar,
        _incomingData      = incoming_data_tmvar,
        _sessionThrowed    = session_throwed_tmvar,
        _clientState       = client_state,
        _startClientSessionCallback = start_client_session_callback
        }
    return session

-- Tell when we are done with a decision
sessionIsUndone :: DecoySession -> IO Bool
sessionIsUndone session = error "NotImplemented"

-- Send a frame to a session
sendFrameToSession :: DecoySession -> (NH2.EncodeInfo, NH2.FramePayload) -> IO ()
sendFrameToSession session (encode_info, frame_payload) = do
    let
        bs_list = NH2.encodeFrameChunks encode_info frame_payload
        input_data_channel = session ^. inputDataChannel

    atomically $
        mapM_
            (writeTChan input_data_channel) bs_list

-- Read a frame from a session... if possible. It will block
-- until the frame comes out, but should fail if there is
-- an exception and/or the session is closed.
recvFrameFromSession :: DecoySession ->  IO (Maybe NH2.Frame)
recvFrameFromSession decoy_session = do
    let
        output_data_channel = decoy_session ^. outputDataChannel
        remaining_output_bit_mvar = decoy_session ^. remainingOutputBit
        pull_action =  readTChan output_data_channel
        settings = decoy_session ^. nh2Settings
        waiting_for_read = decoy_session ^. waiting
    my_thread_id <- myThreadId
    packet <- atomically $ do
        {-# SCC aT #-} putTMVar waiting_for_read my_thread_id
        remaining_output_bit <- {-# SCC bT #-}  takeTMVar remaining_output_bit_mvar
        (packet, rest) <-  {-# SCC cT #-}  readNextChunkAndContinue http2FrameLength remaining_output_bit pull_action
        {-# SCC dT #-} putTMVar remaining_output_bit_mvar rest
        {-# SCC eT #-} takeTMVar waiting_for_read
        return packet
    let
        error_or_frame = NH2.decodeFrame settings packet
    case error_or_frame of
        Left   _      -> return Nothing
        Right  frame  -> return $ Just frame

-- Reads all frames from a session and assembles a response. Notice that this is a buggy hack,
-- because continuation frames and such are not considered.
-- T
-- readResponseFromSession :: DecoySession -> NH2.StreamId -> IO (Headers, B.ByteString, [NH2.Frame])

-- Encode headers to send to the session
-- TODO: There is an important bug here... we are using the default encoding
-- strategy everywhere
encodeHeadersForSession :: DecoySession -> Headers -> IO B.ByteString
encodeHeadersForSession decoy_session headers =
    do
        let
            mv = decoy_session ^. encodeHeadersHere
        dtable <- atomically $ takeTMVar mv
        (dtable', bs ) <- HP.encodeHeader HP.defaultEncodeStrategy dtable headers
        atomically $ putTMVar mv dtable'
        return bs

-- Decode headers to receive them from the session
decodeHeadersForSession :: DecoySession -> B.ByteString -> IO Headers
decodeHeadersForSession decoy_session bs =  do
    let
        mv = decoy_session ^. decodeHeadersHere
    dtable <- atomically $ takeTMVar mv
    (dtable', headers) <- HP.decodeHeader dtable bs
    atomically $ putTMVar mv dtable'
    return headers

-- Send raw data to a session
sendRawDataToSession :: DecoySession -> B.ByteString -> IO ()
sendRawDataToSession decoy_session data_to_send = do
    let
        input_data_channel = decoy_session ^. inputDataChannel
        waiting_for_write = decoy_session ^. waiting

    thread_id <- myThreadId
    atomically $ do
        putTMVar waiting_for_write thread_id
        writeTChan input_data_channel data_to_send
        takeTMVar waiting_for_write
    return ()

-- Send a headers frame to the session that ends the stream...
performRequestSimple :: DecoySession -> Int -> Headers -> IO ()
performRequestSimple decoy_session stream_id headers = do
    headers_data <- encodeHeadersForSession decoy_session headers
    let
        frame = NH2.HeadersFrame
            Nothing  -- No priority
            headers_data
        frame_data_ei = NH2.EncodeInfo {
            NH2.encodeFlags = NH2.setEndStream . NH2.setEndHeader $ NH2.defaultFlags,
            NH2.encodeStreamId = stream_id,
            NH2.encodePadding = Nothing
            }

    sendFrameToSession decoy_session (frame_data_ei,frame)

-- Read raw data from a session. Normally blocks until data be available.
-- It returns Nothing when the session is to be considered finished.
recvRawDataFromSession :: DecoySession -> IO (Maybe B.ByteString)
recvRawDataFromSession decoy_session = error "NotImplemented"


text:
'use strict';

var should = require('should'),
	request = require('supertest'),
	app = require('../../server'),
	mongoose = require('mongoose'),
	User = mongoose.model('User'),
	Feedback = mongoose.model('Feedback'),
	agent = request.agent(app);

/**
 * Globals
 */
var credentials, user, feedback;

/**
 * Feedback routes tests
 */
describe('Feedback CRUD tests', function() {
	beforeEach(function(done) {
		// Create user credentials
		credentials = {
			username: 'username',
			password: 'password'
		};

		// Create a new user
		user = new User({
			firstName: 'Full',
			lastName: 'Name',
			displayName: 'Full Name',
			email: 'test@test.com',
			username: credentials.username,
			password: credentials.password,
			provider: 'local'
		});

		// Save a user to the test db and create new Feedback
		user.save(function() {
			feedback = {
				name: 'Feedback Name'
			};

			done();
		});
	});

	it('should be able to save Feedback instance if logged in', function(done) {
		agent.post('/auth/signin')
			.send(credentials)
			.expect(200)
			.end(function(signinErr, signinRes) {
				// Handle signin error
				if (signinErr) done(signinErr);

				// Get the userId
				var userId = user.id;

				// Save a new Feedback
				agent.post('/feedbacks')
					.send(feedback)
					.expect(200)
					.end(function(feedbackSaveErr, feedbackSaveRes) {
						// Handle Feedback save error
						if (feedbackSaveErr) done(feedbackSaveErr);

						// Get a list of Feedbacks
						agent.get('/feedbacks')
							.end(function(feedbacksGetErr, feedbacksGetRes) {
								// Handle Feedback save error
								if (feedbacksGetErr) done(feedbacksGetErr);

								// Get Feedbacks list
								var feedbacks = feedbacksGetRes.body;

								// Set assertions
								(feedbacks[0].user._id).should.equal(userId);
								(feedbacks[0].name).should.match('Feedback Name');

								// Call the assertion callback
								done();
							});
					});
			});
	});

	it('should not be able to save Feedback instance if not logged in', function(done) {
		agent.post('/feedbacks')
			.send(feedback)
			.expect(401)
			.end(function(feedbackSaveErr, feedbackSaveRes) {
				// Call the assertion callback
				done(feedbackSaveErr);
			});
	});

	it('should not be able to save Feedback instance if no name is provided', function(done) {
		// Invalidate name field
		feedback.name = '';

		agent.post('/auth/signin')
			.send(credentials)
			.expect(200)
			.end(function(signinErr, signinRes) {
				// Handle signin error
				if (signinErr) done(signinErr);

				// Get the userId
				var userId = user.id;

				// Save a new Feedback
				agent.post('/feedbacks')
					.send(feedback)
					.expect(400)
					.end(function(feedbackSaveErr, feedbackSaveRes) {
						// Set message assertion
						(feedbackSaveRes.body.message).should.match('Please fill Feedback name');

						// Handle Feedback save error
						done(feedbackSaveErr);
					});
			});
	});

	it('should be able to update Feedback instance if signed in', function(done) {
		agent.post('/auth/signin')
			.send(credentials)
			.expect(200)
			.end(function(signinErr, signinRes) {
				// Handle signin error
				if (signinErr) done(signinErr);

				// Get the userId
				var userId = user.id;

				// Save a new Feedback
				agent.post('/feedbacks')
					.send(feedback)
					.expect(200)
					.end(function(feedbackSaveErr, feedbackSaveRes) {
						// Handle Feedback save error
						if (feedbackSaveErr) done(feedbackSaveErr);

						// Update Feedback name
						feedback.name = 'WHY YOU GOTTA BE SO MEAN?';

						// Update existing Feedback
						agent.put('/feedbacks/' + feedbackSaveRes.body._id)
							.send(feedback)
							.expect(200)
							.end(function(feedbackUpdateErr, feedbackUpdateRes) {
								// Handle Feedback update error
								if (feedbackUpdateErr) done(feedbackUpdateErr);

								// Set assertions
								(feedbackUpdateRes.body._id).should.equal(feedbackSaveRes.body._id);
								(feedbackUpdateRes.body.name).should.match('WHY YOU GOTTA BE SO MEAN?');

								// Call the assertion callback
								done();
							});
					});
			});
	});

	it('should be able to get a list of Feedbacks if not signed in', function(done) {
		// Create new Feedback model instance
		var feedbackObj = new Feedback(feedback);

		// Save the Feedback
		feedbackObj.save(function() {
			// Request Feedbacks
			request(app).get('/feedbacks')
				.end(function(req, res) {
					// Set assertion
					res.body.should.be.an.Array.with.lengthOf(1);

					// Call the assertion callback
					done();
				});

		});
	});

	it('should be able to get a single Feedback if not signed in', function(done) {
		// Create new Feedback model instance
		var feedbackObj = new Feedback(feedback);

		// Save the Feedback
		feedbackObj.save(function() {
			request(app).get('/feedbacks/' + feedbackObj._id)
				.end(function(req, res) {
					// Set assertion
					res.body.should.be.an.Object.with.property('name', feedback.name);

					// Call the assertion callback
					done();
				});
		});
	});

	it('should be able to delete Feedback instance if signed in', function(done) {
		agent.post('/auth/signin')
			.send(credentials)
			.expect(200)
			.end(function(signinErr, signinRes) {
				// Handle signin error
				if (signinErr) done(signinErr);

				// Get the userId
				var userId = user.id;

				// Save a new Feedback
				agent.post('/feedbacks')
					.send(feedback)
					.expect(200)
					.end(function(feedbackSaveErr, feedbackSaveRes) {
						// Handle Feedback save error
						if (feedbackSaveErr) done(feedbackSaveErr);

						// Delete existing Feedback
						agent.delete('/feedbacks/' + feedbackSaveRes.body._id)
							.send(feedback)
							.expect(200)
							.end(function(feedbackDeleteErr, feedbackDeleteRes) {
								// Handle Feedback error error
								if (feedbackDeleteErr) done(feedbackDeleteErr);

								// Set assertions
								(feedbackDeleteRes.body._id).should.equal(feedbackSaveRes.body._id);

								// Call the assertion callback
								done();
							});
					});
			});
	});

	it('should not be able to delete Feedback instance if not signed in', function(done) {
		// Set Feedback user
		feedback.user = user;

		// Create new Feedback model instance
		var feedbackObj = new Feedback(feedback);

		// Save the Feedback
		feedbackObj.save(function() {
			// Try deleting Feedback
			request(app).delete('/feedbacks/' + feedbackObj._id)
			.expect(401)
			.end(function(feedbackDeleteErr, feedbackDeleteRes) {
				// Set message assertion
				(feedbackDeleteRes.body.message).should.match('User is not logged in');

				// Handle Feedback error error
				done(feedbackDeleteErr);
			});

		});
	});

	afterEach(function(done) {
		User.remove().exec();
		Feedback.remove().exec();
		done();
	});
});

redpajama_set_name: RedPajamaGithub


text:
import * as assert from 'assert';
import { isWindows } from 'vs/base/common/platform';
import { URI } from 'vs/base/common/uri';
import { Selection } from 'vs/editor/common/core/selection';
import { SelectionBasedVariableResolver, CompositeSnippetVariableResolver, ModelBasedVariableResolver, ClipboardBasedVariableResolver, TimeBasedVariableResolver } from 'vs/editor/contrib/snippet/snippetVariables';
import { SnippetParser, Variable, VariableResolver } from 'vs/editor/contrib/snippet/snippetParser';
import { TextModel } from 'vs/editor/common/model/textModel';
import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';

suite('Snippet Variables Resolver', function () {

	let model: TextModel;
	let resolver: VariableResolver;

	setup(function () {
		model = TextModel.createFromString([
			'this is line one',
			'this is line two',
			'    this is line three'
		].join('\n'), undefined, undefined, URI.parse('file:///foo/files/text.txt'));

		resolver = new CompositeSnippetVariableResolver([
			new ModelBasedVariableResolver(model),
			new SelectionBasedVariableResolver(model, new Selection(1, 1, 1, 1)),
		]);
	});

	teardown(function () {
		model.dispose();
	});

	function assertVariableResolve(resolver: VariableResolver, varName: string, expected: string) {
		const snippet = new SnippetParser().parse(`$${varName}`);
		const variable = <Variable>snippet.children[0];
		variable.resolve(resolver);
		if (variable.children.length === 0) {
			assert.equal(undefined, expected);
		} else {
			assert.equal(variable.toString(), expected);
		}
	}

	test('editor variables, basics', function () {
		assertVariableResolve(resolver, 'TM_FILENAME', 'text.txt');
		assertVariableResolve(resolver, 'something', undefined);
	});

	test('editor variables, file/dir', function () {

		assertVariableResolve(resolver, 'TM_FILENAME', 'text.txt');
		if (!isWindows) {
			assertVariableResolve(resolver, 'TM_DIRECTORY', '/foo/files');
			assertVariableResolve(resolver, 'TM_FILEPATH', '/foo/files/text.txt');
		}

		resolver = new ModelBasedVariableResolver(
			TextModel.createFromString('', undefined, undefined, URI.parse('http://www.pb.o/abc/def/ghi'))
		);
		assertVariableResolve(resolver, 'TM_FILENAME', 'ghi');
		if (!isWindows) {
			assertVariableResolve(resolver, 'TM_DIRECTORY', '/abc/def');
			assertVariableResolve(resolver, 'TM_FILEPATH', '/abc/def/ghi');
		}

		resolver = new ModelBasedVariableResolver(
			TextModel.createFromString('', undefined, undefined, URI.parse('mem:fff.ts'))
		);
		assertVariableResolve(resolver, 'TM_DIRECTORY', '');
		assertVariableResolve(resolver, 'TM_FILEPATH', 'fff.ts');

	});

	test('editor variables, selection', function () {

		resolver = new SelectionBasedVariableResolver(model, new Selection(1, 2, 2, 3));
		assertVariableResolve(resolver, 'TM_SELECTED_TEXT', 'his is line one\nth');
		assertVariableResolve(resolver, 'TM_CURRENT_LINE', 'this is line two');
		assertVariableResolve(resolver, 'TM_LINE_INDEX', '1');
		assertVariableResolve(resolver, 'TM_LINE_NUMBER', '2');

		resolver = new SelectionBasedVariableResolver(model, new Selection(2, 3, 1, 2));
		assertVariableResolve(resolver, 'TM_SELECTED_TEXT', 'his is line one\nth');
		assertVariableResolve(resolver, 'TM_CURRENT_LINE', 'this is line one');
		assertVariableResolve(resolver, 'TM_LINE_INDEX', '0');
		assertVariableResolve(resolver, 'TM_LINE_NUMBER', '1');

		resolver = new SelectionBasedVariableResolver(model, new Selection(1, 2, 1, 2));
		assertVariableResolve(resolver, 'TM_SELECTED_TEXT', undefined);

		assertVariableResolve(resolver, 'TM_CURRENT_WORD', 'this');

		resolver = new SelectionBasedVariableResolver(model, new Selection(3, 1, 3, 1));
		assertVariableResolve(resolver, 'TM_CURRENT_WORD', undefined);

	});

	test('TextmateSnippet, resolve variable', function () {
		const snippet = new SnippetParser().parse('"$TM_CURRENT_WORD"', true);
		assert.equal(snippet.toString(), '""');
		snippet.resolveVariables(resolver);
		assert.equal(snippet.toString(), '"this"');

	});

	test('TextmateSnippet, resolve variable with default', function () {
		const snippet = new SnippetParser().parse('"${TM_CURRENT_WORD:foo}"', true);
		assert.equal(snippet.toString(), '"foo"');
		snippet.resolveVariables(resolver);
		assert.equal(snippet.toString(), '"this"');
	});

	test('More useful environment variables for snippets, #32737', function () {

		assertVariableResolve(resolver, 'TM_FILENAME_BASE', 'text');

		resolver = new ModelBasedVariableResolver(
			TextModel.createFromString('', undefined, undefined, URI.parse('http://www.pb.o/abc/def/ghi'))
		);
		assertVariableResolve(resolver, 'TM_FILENAME_BASE', 'ghi');

		resolver = new ModelBasedVariableResolver(
			TextModel.createFromString('', undefined, undefined, URI.parse('mem:.git'))
		);
		assertVariableResolve(resolver, 'TM_FILENAME_BASE', '.git');

		resolver = new ModelBasedVariableResolver(
			TextModel.createFromString('', undefined, undefined, URI.parse('mem:foo.'))
		);
		assertVariableResolve(resolver, 'TM_FILENAME_BASE', 'foo');
	});

	function assertVariableResolve2(input: string, expected: string, varValue?: string) {
		const snippet = new SnippetParser().parse(input)
			.resolveVariables({ resolve(variable) { return varValue || variable.name; } });

		const actual = snippet.toString();
		assert.equal(actual, expected);
	}

	test('Variable Snippet Transform', function () {

		const snippet = new SnippetParser().parse('name=${TM_FILENAME/(.*)\\..+$/$1/}', true);
		snippet.resolveVariables(resolver);
		assert.equal(snippet.toString(), 'name=text');

		assertVariableResolve2('${ThisIsAVar/([A-Z]).*(Var)/$2/}', 'Var');
		assertVariableResolve2('${ThisIsAVar/([A-Z]).*(Var)/$2-${1:/downcase}/}', 'Var-t');
		assertVariableResolve2('${Foo/(.*)/${1:+Bar}/img}', 'Bar');

		//https://github.com/Microsoft/vscode/issues/33162
		assertVariableResolve2('export default class ${TM_FILENAME/(\\w+)\\.js/$1/g}', 'export default class FooFile', 'FooFile.js');

		assertVariableResolve2('${foobarfoobar/(foo)/${1:+FAR}/g}', 'FARbarFARbar'); // global
		assertVariableResolve2('${foobarfoobar/(foo)/${1:+FAR}/}', 'FARbarfoobar'); // first match
		assertVariableResolve2('${foobarfoobar/(bazz)/${1:+FAR}/g}', 'foobarfoobar'); // no match, no else
		// assertVariableResolve2('${foobarfoobar/(bazz)/${1:+FAR}/g}', ''); // no match

		assertVariableResolve2('${foobarfoobar/(foo)/${2:+FAR}/g}', 'barbar'); // bad group reference
	});

	test('Snippet transforms do not handle regex with alternatives or optional matches, #36089', function () {

		assertVariableResolve2(
			'${TM_FILENAME/^(.)|(?:-(.))|(\\.js)/${1:/upcase}${2:/upcase}/g}',
			'MyClass',
			'my-class.js'
		);

		// no hyphens
		assertVariableResolve2(
			'${TM_FILENAME/^(.)|(?:-(.))|(\\.js)/${1:/upcase}${2:/upcase}/g}',
			'Myclass',
			'myclass.js'
		);

		// none matching suffix
		assertVariableResolve2(
			'${TM_FILENAME/^(.)|(?:-(.))|(\\.js)/${1:/upcase}${2:/upcase}/g}',
			'Myclass.foo',
			'myclass.foo'
		);

		// more than one hyphen
		assertVariableResolve2(
			'${TM_FILENAME/^(.)|(?:-(.))|(\\.js)/${1:/upcase}${2:/upcase}/g}',
			'ThisIsAFile',
			'this-is-a-file.js'
		);

		// KEBAB CASE
		assertVariableResolve2(
			'${TM_FILENAME_BASE/([A-Z][a-z]+)([A-Z][a-z]+$)?/${1:/downcase}-${2:/downcase}/g}',
			'capital-case',
			'CapitalCase'
		);

		assertVariableResolve2(
			'${TM_FILENAME_BASE/([A-Z][a-z]+)([A-Z][a-z]+$)?/${1:/downcase}-${2:/downcase}/g}',
			'capital-case-more',
			'CapitalCaseMore'
		);
	});

	test('Add variable to insert value from clipboard to a snippet #40153', function () {

		let readTextResult: string;
		const clipboardService = new class implements IClipboardService {
			_serviceBrand: any;
			readText(): string { return readTextResult; }
			_throw = () => { throw new Error(); };
			writeText = this._throw;
			readFindText = this._throw;
			writeFindText = this._throw;
			writeResources = this._throw;
			readResources = this._throw;
			hasResources = this._throw;
		};
		let resolver = new ClipboardBasedVariableResolver(clipboardService, 1, 0);

		readTextResult = undefined;
		assertVariableResolve(resolver, 'CLIPBOARD', undefined);

		readTextResult = null;
		assertVariableResolve(resolver, 'CLIPBOARD', undefined);

		readTextResult = '';
		assertVariableResolve(resolver, 'CLIPBOARD', undefined);

		readTextResult = 'foo';
		assertVariableResolve(resolver, 'CLIPBOARD', 'foo');

		assertVariableResolve(resolver, 'foo', undefined);
		assertVariableResolve(resolver, 'cLIPBOARD', undefined);
	});

	test('Add variable to insert value from clipboard to a snippet #40153', function () {

		let readTextResult: string;
		let resolver: VariableResolver;
		const clipboardService = new class implements IClipboardService {
			_serviceBrand: any;
			readText(): string { return readTextResult; }
			_throw = () => { throw new Error(); };
			writeText = this._throw;
			readFindText = this._throw;
			writeFindText = this._throw;
			writeResources = this._throw;
			readResources = this._throw;
			hasResources = this._throw;
		};

		resolver = new ClipboardBasedVariableResolver(clipboardService, 1, 2);
		readTextResult = 'line1';
		assertVariableResolve(resolver, 'CLIPBOARD', 'line1');
		readTextResult = 'line1\nline2\nline3';
		assertVariableResolve(resolver, 'CLIPBOARD', 'line1\nline2\nline3');

		readTextResult = 'line1\nline2';
		assertVariableResolve(resolver, 'CLIPBOARD', 'line2');
		readTextResult = 'line1\nline2';
		resolver = new ClipboardBasedVariableResolver(clipboardService, 0, 2);
		assertVariableResolve(resolver, 'CLIPBOARD', 'line1');
	});

	function assertVariableResolve3(resolver: VariableResolver, varName: string) {
		const snippet = new SnippetParser().parse(`$${varName}`);
		const variable = <Variable>snippet.children[0];

		assert.equal(variable.resolve(resolver), true, `${varName} failed to resolve`);
	}

	test('Add time variables for snippets #41631, #43140', function () {

		const resolver = new TimeBasedVariableResolver;

		assertVariableResolve3(resolver, 'CURRENT_YEAR');
		assertVariableResolve3(resolver, 'CURRENT_YEAR_SHORT');
		assertVariableResolve3(resolver, 'CURRENT_MONTH');
		assertVariableResolve3(resolver, 'CURRENT_DATE');
		assertVariableResolve3(resolver, 'CURRENT_HOUR');
		assertVariableResolve3(resolver, 'CURRENT_MINUTE');
		assertVariableResolve3(resolver, 'CURRENT_SECOND');
		assertVariableResolve3(resolver, 'CURRENT_DAY_NAME');
		assertVariableResolve3(resolver, 'CURRENT_DAY_NAME_SHORT');
		assertVariableResolve3(resolver, 'CURRENT_MONTH_NAME');
		assertVariableResolve3(resolver, 'CURRENT_MONTH_NAME_SHORT');
	});

	test('creating snippet - format-condition doesn\'t work #53617', function () {

		const snippet = new SnippetParser().parse('${TM_LINE_NUMBER/(10)/${1:?It is:It is not}/} line 10', true);
		snippet.resolveVariables({ resolve() { return '10'; } });
		assert.equal(snippet.toString(), 'It is line 10');

		snippet.resolveVariables({ resolve() { return '11'; } });
		assert.equal(snippet.toString(), 'It is not line 10');
	});
});


text:
class GpioException(BaseException):
    pass

class Gpio(object):
    # https://sourceforge.net/p/raspberry-gpio-python/code/ci/default/tree/source/common.h
    # https://sourceforge.net/p/raspberry-gpio-python/code/ci/default/tree/source/c_gpio.h
    MODE_UNKNOWN = -1
    BOARD = 10
    BCM = 11
    OUT = 0
    IN = 1
    LOW = 0
    HIGH = 1

    def __init__(self):
        # start of with None to avoid .fake's import before patching done
        self.hw = None
        self.numbering = self.MODE_UNKNOWN
        self.modes = {}
        self.pins = {}

    def cleanup(self, pin=None):
        # resets any setup'ed pins to input with no pud
        if pin is not None:
            del self.modes[pin]
            del self.pins[pin]
        self.modes = {}
        self.pins = {}
        # reset hardware, numbering?

    def setmode(self, mode):
        """Set pin numbering mode"""
        self.numbering = mode
        # ?? self.hw._setmode(mode)

    def setup(self, pin, mode, initial=None, pull_up_down=None):
        """Set mode for each pin (in/out, etc)"""
        # TODO verify possible modes
        self.modes[pin] = mode
        # TODO look at RPi.GPIO to see if anything else done here
        # assume the pin starts as low (may not be accurate)
        if initial is None:
            initial = self.LOW
        self._set(pin, initial)

    # Called by Adafruit API
    def output_pins(self, pinnums_to_bools):
        """Given a dict of pinnum:val, set multiple pins"""
        for (pin, value) in pinnums_to_bools.items():
            self._set(pin, value)

    # Called by Adafruit and RPLCD API
    def output(self, pin, value):
        """Given a pin number set it to value"""
        self._set(pin, value)

    def _set(self, pin, value):
        """Not in RPi.GPIO, manages Fake state and triggers HW"""
        if pin not in self.modes:
            raise GpioException('Pin %s not setup' % pin)
        if self.modes[pin] != self.OUT:
            raise GpioException('Attempt to IN and OUT pin')
        if value not in [self.LOW, self.HIGH]:
            # TODO handle PWM
            raise GpioException('Unhandled pin value %s' % value)
        self.pins[pin] = value
        if self.hw is None:
            raise GpioException('No fake HW has been attached')
        self.hw._set(pin, value)

###############################
# Other unimplemented functions

# carp if any pin you set has different mode (or anything other than input)
# could be bad cleanup, or multiple simultaneous GPIO instances
# def setwarnings(mode):

# return function/mode of pin, can be:
# INPUT, OUTPUT, SPI, I2C, HARD_PWM, SERIAL, UNKNOWN
# def gpio_function(pin):

# read value of pin (opposite of output)
# def input(pin):

# create a PWM obj for pin
# def PWM(pin, frequency):


text:
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
            ×
        </button>
        Adjustment - # <?php echo $empadjustments->ID; ?>

    <?php echo form_open($action = site_url('adjustmentlead/update'), $attributes = array('id' => 'filedadjustment',
    'name' => 'filedadjustment', 'role' => 'form')); ?>
        <?php echo form_hidden('id', $empadjustments->ID); ?>

Type

            <?php echo form_dropdown('adjustments',
            $this->config->item('adjustments'),
            $empadjustments->Type,
            'class="form-control" id="adjustments"'); ?>

Date

        <?php echo form_input(array(
            'name' => 'dateoccurred',
            'id' => 'dateoccurred',
            'class' => 'form-control',
            'value' => convert_date($empadjustments->DateOccurred, 'Y-m-d')
        )); ?>

Payday

        <?php echo form_dropdown('paydays',
                $this->config->item('paydays'),
                $payday,
                'class="form-control" id="paydays"'); ?>

Remarks

        <?php echo form_textarea(array(
            'name' => 'remarks',
            'id' => 'remarks',
            'class' => 'form-control',
            'value' => strip_quotes($empadjustments->Remarks)
        )); ?>

        <?php echo form_button(array(
            'class' => 'btn btn-default',
            'data-dismiss' => 'modal',
            'content' => 'Close'
        )); ?>
        <?php if ($empadjustments->Status == 0): ?>
            <?php if ($empadjustments->Type == 0 || $empadjustments->Type == 1): ?>
                <?php if (isset($empadjustments->SecurityNotes) && isset($empadjustments->SecurityID)): ?>
                    <?php echo form_submit(array(
                        'name' => 'btnapproveadj',
                        'value' => 'Approve',
                        'class' => 'btn btn-success'
                    )); ?>
                <?php else: ?>
                    <?php echo form_submit(array(
                        'name' => 'btnapproveadj',
                        'value' => 'Approve',
                        'class' => 'btn btn-success',
                        'disabled' => "disabled"
                    )); ?>
                 <?php endif; ?>
            <?php else: ?>
                <?php echo form_submit(array(
                    'name' => 'btnapproveadj',
                    'value' => 'Approve',
                    'class' => 'btn btn-success'
                )); ?>
            <?php endif; ?>
            <?php echo form_submit(array(
                'name' => 'btndeclineadj',
                'value' => 'Decline',
                'class' => 'btn btn-danger'
            )); ?>
        <?php endif; ?>

    <?php echo form_close(); ?>


text:
package gaffer.function.simple.filter;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;

import gaffer.exception.SerialisationException;
import gaffer.function.FilterFunction;
import gaffer.function.FilterFunctionTest;
import gaffer.function.Function;
import gaffer.jsonserialisation.JSONSerialiser;
import org.junit.Test;

public class RegexTest extends FilterFunctionTest {
    @Test
    public void shouldAccepValidValue() {
        // Given
        final Regex filter = new Regex("te[a-d]{3}st");

        // When
        boolean accepted = filter.isValid("teaadst");

        // Then
        assertTrue(accepted);
    }

    @Test
    public void shouldRejectInvalidValue() {
        // Given
        final Regex filter = new Regex("fa[a-d]{3}il");

        // When
        boolean accepted = filter.isValid("favcdil");

        // Then
        assertFalse(accepted);
    }

    @Test
    public void shouldClone() {
        // Given
        final Regex filter = new Regex();

        // When
        final Regex clonedFilter = filter.statelessClone();

        // Then
        assertNotSame(filter, clonedFilter);
    }

    @Test
    public void shouldJsonSerialiseAndDeserialise() throws SerialisationException {
        // Given
        final Regex filter = new Regex("test");

        // When
        final String json = new String(new JSONSerialiser().serialise(filter, true));

        // Then
        assertEquals(String.format("{%n" +
                "  \"class\" : \"gaffer.function.simple.filter.Regex\",%n" +
                "  \"value\" : {%n"
                + "    \"java.util.regex.Pattern\" : \"test\"%n"
                + "  }%n" +
                "}"), json);

        // When 2
        final Regex deserialisedFilter = new JSONSerialiser().deserialise(json.getBytes(), Regex.class);

        // Then 2
        assertEquals(filter.getControlValue().pattern(), deserialisedFilter.getControlValue().pattern());
        assertNotNull(deserialisedFilter);
    }

    @Override
    protected FilterFunction getInstance() {
        return new Regex("[a-zA-Z]{1,12}");
    }

    @Override
    protected Class<? extends Function> getFunctionClass() {
        return Regex.class;
    }

}


text:
/// <reference path="../../_references.ts"/>

module powerbitests {
    import EphemeralStorageService = powerbi.EphemeralStorageService;

    describe('Ephemeral Storage Service', () => {
        it('get with existing key retrieves data', () => {
            let storage = new EphemeralStorageService();

            storage.setData('key', 'value');

            let value = storage.getData('key');

            expect(value).toBe('value');
        });

        it('get with non-existing key returns null', () => {
            let storage = new EphemeralStorageService();

            storage.setData('key1', 'value');

            let value = storage.getData('key2');

            expect(value == null).toBeTruthy();
        });

        it('cache is cleared after interval', (done) => {
            let timeout = 10;
            let storage = new EphemeralStorageService(timeout);

            storage.setData('key', 'value');

            setTimeout(() => {

                // cache should be cleared by now
                let value = storage.getData('key');
                expect(value == null).toBeTruthy();
                done();
            }, timeout + 10);
        });
    });
}


text:
#include <stdlib.h>
#include <libopencm3/usb/usbd.h>
#include <libopencm3/usb/cdc.h>
#include <libopencm3/stm32/st_usbfs.h>
#include "cdcacm.h"

static usbd_device* device;
static volatile int configured = 0;

int CdcAcmIsConfigured()
{
	return configured;
}

static const struct usb_device_descriptor dev = {
	.bLength = USB_DT_DEVICE_SIZE,
	.bDescriptorType = USB_DT_DEVICE,
	.bcdUSB = 0x0200,
	.bDeviceClass = USB_CLASS_CDC,
	.bDeviceSubClass = 0,
	.bDeviceProtocol = 0,
	.bMaxPacketSize0 = 64,
	.idVendor = 0x0483,
	.idProduct = 0x5740,
	.bcdDevice = 0x0200,
	.iManufacturer = 1,
	.iProduct = 2,
	.iSerialNumber = 3,
	.bNumConfigurations = 1,
};

/*
 * This notification endpoint isn't implemented. According to CDC spec its
 * optional, but its absence causes a NULL pointer dereference in Linux
 * cdc_acm driver.
 */
static const struct usb_endpoint_descriptor comm_endp[] = {{
	.bLength = USB_DT_ENDPOINT_SIZE,
	.bDescriptorType = USB_DT_ENDPOINT,
	.bEndpointAddress = 0x83,
	.bmAttributes = USB_ENDPOINT_ATTR_INTERRUPT,
	.wMaxPacketSize = 16,
	.bInterval = 255,
}};

static const struct usb_endpoint_descriptor data_endp[] = {{
	.bLength = USB_DT_ENDPOINT_SIZE,
	.bDescriptorType = USB_DT_ENDPOINT,
	.bEndpointAddress = 0x01,
	.bmAttributes = USB_ENDPOINT_ATTR_BULK,
	.wMaxPacketSize = 64,
	.bInterval = 1,
}, {
	.bLength = USB_DT_ENDPOINT_SIZE,
	.bDescriptorType = USB_DT_ENDPOINT,
	.bEndpointAddress = 0x82,
	.bmAttributes = USB_ENDPOINT_ATTR_BULK,
	.wMaxPacketSize = 64,
	.bInterval = 1,
}};

static const struct {
	struct usb_cdc_header_descriptor header;
	struct usb_cdc_call_management_descriptor call_mgmt;
	struct usb_cdc_acm_descriptor acm;
	struct usb_cdc_union_descriptor cdc_union;
} __attribute__((packed)) cdcacm_functional_descriptors = {
	.header = {
		.bFunctionLength = sizeof(struct usb_cdc_header_descriptor),
		.bDescriptorType = CS_INTERFACE,
		.bDescriptorSubtype = USB_CDC_TYPE_HEADER,
		.bcdCDC = 0x0110,
	},
	.call_mgmt = {
		.bFunctionLength =
			sizeof(struct usb_cdc_call_management_descriptor),
		.bDescriptorType = CS_INTERFACE,
		.bDescriptorSubtype = USB_CDC_TYPE_CALL_MANAGEMENT,
		.bmCapabilities = 0,
		.bDataInterface = 1,
	},
	.acm = {
		.bFunctionLength = sizeof(struct usb_cdc_acm_descriptor),
		.bDescriptorType = CS_INTERFACE,
		.bDescriptorSubtype = USB_CDC_TYPE_ACM,
		.bmCapabilities = 0,
	},
	.cdc_union = {
		.bFunctionLength = sizeof(struct usb_cdc_union_descriptor),
		.bDescriptorType = CS_INTERFACE,
		.bDescriptorSubtype = USB_CDC_TYPE_UNION,
		.bControlInterface = 0,
		.bSubordinateInterface0 = 1,
	 }
};

// Communication Class Interface
static const struct usb_interface_descriptor comm_iface[] = {{
	.bLength = USB_DT_INTERFACE_SIZE,
	.bDescriptorType = USB_DT_INTERFACE,
	.bInterfaceNumber = 0,
	.bAlternateSetting = 0,
	.bNumEndpoints = 1,
	.bInterfaceClass = USB_CLASS_CDC,
	.bInterfaceSubClass = USB_CDC_SUBCLASS_ACM,
	.bInterfaceProtocol = USB_CDC_PROTOCOL_AT,
	.iInterface = 0,

	.endpoint = comm_endp,

	.extra = &cdcacm_functional_descriptors,
	.extralen = sizeof(cdcacm_functional_descriptors)
}};

// Data Class Interface
static const struct usb_interface_descriptor data_iface[] = {{
	.bLength = USB_DT_INTERFACE_SIZE,
	.bDescriptorType = USB_DT_INTERFACE,
	.bInterfaceNumber = 1,
	.bAlternateSetting = 0,
	.bNumEndpoints = 2,
	.bInterfaceClass = USB_CLASS_DATA,
	.bInterfaceSubClass = 0,
	.bInterfaceProtocol = 0,
	.iInterface = 0,

	.endpoint = data_endp,
}};

static const struct usb_interface ifaces[] = {{
	.num_altsetting = 1,
	.altsetting = comm_iface,
}, {
	.num_altsetting = 1,
	.altsetting = data_iface,
}};

static const struct usb_config_descriptor config = {
	.bLength = USB_DT_CONFIGURATION_SIZE,
	.bDescriptorType = USB_DT_CONFIGURATION,
	.wTotalLength = 0,
	.bNumInterfaces = 2,
	.bConfigurationValue = 1,
	.iConfiguration = 0,
	.bmAttributes = 0x80,
	.bMaxPower = 0x32,

	.interface = ifaces,
};

static char serial_no[9];

static const char *usb_strings[] = {
	"AHTOXA",
	"USB-LED matrix",
	"HELLO-1234",
//	serial_no,
};

/* Buffer to be used for control requests. */
uint8_t usbd_control_buffer[128];

static int cdcacm_control_request(usbd_device *usbd_dev, struct usb_setup_data *req, uint8_t **buf,
		uint16_t *len, void (**complete)(usbd_device *usbd_dev, struct usb_setup_data *req))
{
	(void)complete;
	(void)buf;
	(void)usbd_dev;

	switch(req->bRequest)
	{

	case USB_CDC_REQ_SET_CONTROL_LINE_STATE:
		configured = req->wValue;
		return USBD_REQ_HANDLED;

	case USB_CDC_REQ_SET_LINE_CODING:
		if(*len < sizeof(struct usb_cdc_line_coding))
			return USBD_REQ_NOTSUPP;

		return USBD_REQ_HANDLED;
	}
	return USBD_REQ_NOTSUPP;
}

static void cdcacm_data_rx_cb(usbd_device *usbd_dev, uint8_t ep)
{
	(void)ep;

	uint8_t buf[64];
	size_t len = usbd_ep_read_packet(usbd_dev, 0x01, buf, 64);
	if (len)
		CdcAcmDataReceived(buf, len);
}

static void cdcacm_sof_cb()
{
	CdcAcmSofReceived();
}

static void cdcacm_reset_cb()
{
	configured = 0;
	CdcResetEvent();
}

static void cdcacm_suspend_cb()
{
	configured = 0;
	*USB_CNTR_REG |= USB_CNTR_FSUSP;
	CdcSuspendEvent();
}

static void cdcacm_resume_cb()
{
	*USB_CNTR_REG &= ~USB_CNTR_FSUSP;
	CdcResumeEvent();
}

static void cdcacm_set_config(usbd_device *usbd_dev, uint16_t wValue)
{
	(void)wValue;

	usbd_ep_setup(usbd_dev, 0x01, USB_ENDPOINT_ATTR_BULK, 64, cdcacm_data_rx_cb);
	usbd_ep_setup(usbd_dev, 0x82, USB_ENDPOINT_ATTR_BULK, 64, NULL);
	usbd_ep_setup(usbd_dev, 0x83, USB_ENDPOINT_ATTR_INTERRUPT, 16, NULL);

	usbd_register_control_callback(
				usbd_dev,
				USB_REQ_TYPE_CLASS | USB_REQ_TYPE_INTERFACE,
				USB_REQ_TYPE_TYPE | USB_REQ_TYPE_RECIPIENT,
				cdcacm_control_request);

	usbd_register_sof_callback(usbd_dev, cdcacm_sof_cb);
	usbd_register_reset_callback(usbd_dev, cdcacm_reset_cb);
	usbd_register_suspend_callback(usbd_dev, cdcacm_suspend_cb);
	usbd_register_resume_callback(usbd_dev, cdcacm_resume_cb);
}

int CdcAcmSendData(char * buf, int size)
{
	for (int i = 0; i < 100000; ++i)
		if (usbd_ep_write_packet(device, 0x82, buf, size))
			return 1;
	return 0;
}

void CdcAcmPoll()
{
	usbd_poll(device);
}

void CdcAcmInit(void)
{
	FillSerialNumber(serial_no);
	device = usbd_init(
			&st_usbfs_v1_usb_driver,
			&dev,
			&config,
			usb_strings,
			3,
			usbd_control_buffer,
			sizeof(usbd_control_buffer)
			);
	usbd_register_set_config_callback(device, cdcacm_set_config);
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Cicinobolus limonii Dejeva

### Remarks
null


text:
pub mod semantic;
pub mod types;


text:
#include <linux/fs.h>
#include <linux/mm.h>
#include <linux/time.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/file.h>
#include <linux/bitops.h>
#include <linux/interrupt.h>
#include <linux/spinlock.h>
#include <linux/rcupdate.h>
#include <linux/workqueue.h>

struct fdtable_defer {
	spinlock_t lock;
	struct work_struct wq;
	struct timer_list timer;
	struct fdtable *next;
};

/*
 * We use this list to defer free fdtables that have vmalloced
 * sets/arrays. By keeping a per-cpu list, we avoid having to embed
 * the work_struct in fdtable itself which avoids a 64 byte (i386) increase in
 * this per-task structure.
 */
static DEFINE_PER_CPU(struct fdtable_defer, fdtable_defer_list);

/*
 * Allocate an fd array, using kmalloc or vmalloc.
 * Note: the array isn't cleared at allocation time.
 */
struct file ** alloc_fd_array(int num)
{
	struct file **new_fds;
	int size = num * sizeof(struct file *);

	if (size <= PAGE_SIZE)
		new_fds = (struct file **) kmalloc(size, GFP_KERNEL);
	else
		new_fds = (struct file **) vmalloc(size);
	return new_fds;
}

void free_fd_array(struct file **array, int num)
{
	int size = num * sizeof(struct file *);

	if (!array) {
		printk (KERN_ERR "free_fd_array: array = 0 (num = %d)\n", num);
		return;
	}

	if (num <= NR_OPEN_DEFAULT) /* Don't free the embedded fd array! */
		return;
	else if (size <= PAGE_SIZE)
		kfree(array);
	else
		vfree(array);
}

static void __free_fdtable(struct fdtable *fdt)
{
	free_fdset(fdt->open_fds, fdt->max_fdset);
	free_fdset(fdt->close_on_exec, fdt->max_fdset);
	free_fd_array(fdt->fd, fdt->max_fds);
	kfree(fdt);
}

static void fdtable_timer(unsigned long data)
{
	struct fdtable_defer *fddef = (struct fdtable_defer *)data;

	spin_lock(&fddef->lock);
	/*
	 * If someone already emptied the queue return.
	 */
	if (!fddef->next)
		goto out;
	if (!schedule_work(&fddef->wq))
		mod_timer(&fddef->timer, 5);
out:
	spin_unlock(&fddef->lock);
}

static void free_fdtable_work(struct fdtable_defer *f)
{
	struct fdtable *fdt;

	spin_lock_bh(&f->lock);
	fdt = f->next;
	f->next = NULL;
	spin_unlock_bh(&f->lock);
	while(fdt) {
		struct fdtable *next = fdt->next;
		__free_fdtable(fdt);
		fdt = next;
	}
}

static void free_fdtable_rcu(struct rcu_head *rcu)
{
	struct fdtable *fdt = container_of(rcu, struct fdtable, rcu);
	int fdset_size, fdarray_size;
	struct fdtable_defer *fddef;

	BUG_ON(!fdt);
	fdset_size = fdt->max_fdset / 8;
	fdarray_size = fdt->max_fds * sizeof(struct file *);

	if (fdt->free_files) {
		/*
		 * The this fdtable was embedded in the files structure
		 * and the files structure itself was getting destroyed.
		 * It is now safe to free the files structure.
		 */
		kmem_cache_free(files_cachep, fdt->free_files);
		return;
	}
	if (fdt->max_fdset <= __FD_SETSIZE && fdt->max_fds <= NR_OPEN_DEFAULT) {
		/*
		 * The fdtable was embedded
		 */
		return;
	}
	if (fdset_size <= PAGE_SIZE && fdarray_size <= PAGE_SIZE) {
		kfree(fdt->open_fds);
		kfree(fdt->close_on_exec);
		kfree(fdt->fd);
		kfree(fdt);
	} else {
		fddef = &get_cpu_var(fdtable_defer_list);
		spin_lock(&fddef->lock);
		fdt->next = fddef->next;
		fddef->next = fdt;
		/*
		 * vmallocs are handled from the workqueue context.
		 * If the per-cpu workqueue is running, then we
		 * defer work scheduling through a timer.
		 */
		if (!schedule_work(&fddef->wq))
			mod_timer(&fddef->timer, 5);
		spin_unlock(&fddef->lock);
		put_cpu_var(fdtable_defer_list);
	}
}

void free_fdtable(struct fdtable *fdt)
{
	if (fdt->free_files || fdt->max_fdset > __FD_SETSIZE ||
					fdt->max_fds > NR_OPEN_DEFAULT)
		call_rcu(&fdt->rcu, free_fdtable_rcu);
}

/*
 * Expand the fdset in the files_struct.  Called with the files spinlock
 * held for write.
 */
static void copy_fdtable(struct fdtable *nfdt, struct fdtable *fdt)
{
	int i;
	int count;

	BUG_ON(nfdt->max_fdset < fdt->max_fdset);
	BUG_ON(nfdt->max_fds < fdt->max_fds);
	/* Copy the existing tables and install the new pointers */

	i = fdt->max_fdset / (sizeof(unsigned long) * 8);
	count = (nfdt->max_fdset - fdt->max_fdset) / 8;

	/*
	 * Don't copy the entire array if the current fdset is
	 * not yet initialised.
	 */
	if (i) {
		memcpy (nfdt->open_fds, fdt->open_fds,
						fdt->max_fdset/8);
		memcpy (nfdt->close_on_exec, fdt->close_on_exec,
						fdt->max_fdset/8);
		memset (&nfdt->open_fds->fds_bits[i], 0, count);
		memset (&nfdt->close_on_exec->fds_bits[i], 0, count);
	}

	/* Don't copy/clear the array if we are creating a new
	   fd array for fork() */
	if (fdt->max_fds) {
		memcpy(nfdt->fd, fdt->fd,
			fdt->max_fds * sizeof(struct file *));
		/* clear the remainder of the array */
		memset(&nfdt->fd[fdt->max_fds], 0,
		       (nfdt->max_fds - fdt->max_fds) *
					sizeof(struct file *));
	}
	nfdt->next_fd = fdt->next_fd;
}

/*
 * Allocate an fdset array, using kmalloc or vmalloc.
 * Note: the array isn't cleared at allocation time.
 */
fd_set * alloc_fdset(int num)
{
	fd_set *new_fdset;
	int size = num / 8;

	if (size <= PAGE_SIZE)
		new_fdset = (fd_set *) kmalloc(size, GFP_KERNEL);
	else
		new_fdset = (fd_set *) vmalloc(size);
	return new_fdset;
}

void free_fdset(fd_set *array, int num)
{
	int size = num / 8;

	if (num <= __FD_SETSIZE) /* Don't free an embedded fdset */
		return;
	else if (size <= PAGE_SIZE)
		kfree(array);
	else
		vfree(array);
}

static struct fdtable *alloc_fdtable(int nr)
{
	struct fdtable *fdt = NULL;
	int nfds = 0;
  	fd_set *new_openset = NULL, *new_execset = NULL;
	struct file **new_fds;

	fdt = kmalloc(sizeof(*fdt), GFP_KERNEL);
	if (!fdt)
  		goto out;
	memset(fdt, 0, sizeof(*fdt));

	nfds = __FD_SETSIZE;
  	/* Expand to the max in easy steps */
  	do {
		if (nfds < (PAGE_SIZE * 8))
			nfds = PAGE_SIZE * 8;
		else {
			nfds = nfds * 2;
			if (nfds > NR_OPEN)
				nfds = NR_OPEN;
		}
	} while (nfds <= nr);

  	new_openset = alloc_fdset(nfds);
  	new_execset = alloc_fdset(nfds);
  	if (!new_openset || !new_execset)
  		goto out;
	fdt->open_fds = new_openset;
	fdt->close_on_exec = new_execset;
	fdt->max_fdset = nfds;

	nfds = NR_OPEN_DEFAULT;
	/*
	 * Expand to the max in easy steps, and keep expanding it until
	 * we have enough for the requested fd array size.
	 */
	do {
#if NR_OPEN_DEFAULT < 256
		if (nfds < 256)
			nfds = 256;
		else
#endif
		if (nfds < (PAGE_SIZE / sizeof(struct file *)))
			nfds = PAGE_SIZE / sizeof(struct file *);
		else {
			nfds = nfds * 2;
			if (nfds > NR_OPEN)
				nfds = NR_OPEN;
  		}
	} while (nfds <= nr);
	new_fds = alloc_fd_array(nfds);
	if (!new_fds)
		goto out;
	fdt->fd = new_fds;
	fdt->max_fds = nfds;
	fdt->free_files = NULL;
	return fdt;
out:
  	if (new_openset)
  		free_fdset(new_openset, nfds);
  	if (new_execset)
  		free_fdset(new_execset, nfds);
	kfree(fdt);
	return NULL;
}

/*
 * Expands the file descriptor table - it will allocate a new fdtable and
 * both fd array and fdset. It is expected to be called with the
 * files_lock held.
 */
static int expand_fdtable(struct files_struct *files, int nr)
	__releases(files->file_lock)
	__acquires(files->file_lock)
{
	int error = 0;
	struct fdtable *fdt;
	struct fdtable *nfdt = NULL;

	spin_unlock(&files->file_lock);
	nfdt = alloc_fdtable(nr);
	if (!nfdt) {
		error = -ENOMEM;
		spin_lock(&files->file_lock);
		goto out;
	}

	spin_lock(&files->file_lock);
	fdt = files_fdtable(files);
	/*
	 * Check again since another task may have expanded the
	 * fd table while we dropped the lock
	 */
	if (nr >= fdt->max_fds || nr >= fdt->max_fdset) {
		copy_fdtable(nfdt, fdt);
	} else {
		/* Somebody expanded while we dropped file_lock */
		spin_unlock(&files->file_lock);
		__free_fdtable(nfdt);
		spin_lock(&files->file_lock);
		goto out;
	}
	rcu_assign_pointer(files->fdt, nfdt);
	free_fdtable(fdt);
out:
	return error;
}

/*
 * Expand files.
 * Return <0 on error; 0 nothing done; 1 files expanded, we may have blocked.
 * Should be called with the files->file_lock spinlock held for write.
 */
int expand_files(struct files_struct *files, int nr)
{
	int err, expand = 0;
	struct fdtable *fdt;

	fdt = files_fdtable(files);
	if (nr >= fdt->max_fdset || nr >= fdt->max_fds) {
		if (fdt->max_fdset >= NR_OPEN ||
			fdt->max_fds >= NR_OPEN || nr >= NR_OPEN) {
			err = -EMFILE;
			goto out;
		}
		expand = 1;
		if ((err = expand_fdtable(files, nr)))
			goto out;
	}
	err = expand;
out:
	return err;
}

static void __devinit fdtable_defer_list_init(int cpu)
{
	struct fdtable_defer *fddef = &per_cpu(fdtable_defer_list, cpu);
	spin_lock_init(&fddef->lock);
	OSA_REGISTER_SPINLOCK(&fddef->lock, "fdtable_defer->lock", 19);
	INIT_WORK(&fddef->wq, (void (*)(void *))free_fdtable_work, fddef);
	init_timer(&fddef->timer);
	fddef->timer.data = (unsigned long)fddef;
	fddef->timer.function = fdtable_timer;
	fddef->next = NULL;
}

void __init files_defer_init(void)
{
	int i;
	for_each_cpu(i)
		fdtable_defer_list_init(i);
}


text:
<?php
namespace Craft;

class StructuresService extends BaseApplicationComponent
{
	// Properties
	// =========================================================================

	/**
	 * @var
	 */
	private $_rootElementRecordsByStructureId;

	// Public Methods
	// =========================================================================

	// Structure CRUD
	// -------------------------------------------------------------------------

	/**
	 * Returns a structure by its ID.
	 *
	 * @param int $structureId
	 *
	 * @return StructureModel|null
	 */
	public function getStructureById($structureId)
	{
		$structureRecord = StructureRecord::model()->findById($structureId);

		if ($structureRecord)
		{
			return StructureModel::populateModel($structureRecord);
		}
	}

	/**
	 * Saves a structure
	 *
	 * @param StructureModel $structure
	 *
	 * @throws Exception
	 * @return bool
	 */
	public function saveStructure(StructureModel $structure)
	{
		if ($structure->id)
		{
			$structureRecord = StructureRecord::model()->findById($structure->id);

			if (!$structureRecord)
			{
				throw new Exception(Craft::t('No structure exists with the ID "{id}".', array('id' => $structure->id)));
			}
		}
		else
		{
			$structureRecord = new StructureRecord();
		}

		$structureRecord->maxLevels = $structure->maxLevels;

		$success = $structureRecord->save();

		if ($success)
		{
			$structure->id = $structureRecord->id;
		}
		else
		{
			$structure->addErrors($structureRecord->getErrors());
		}

		return $success;
	}

	/**
	 * Deletes a structure by its ID.
	 *
	 * @param int $structureId
	 *
	 * @return bool
	 */
	public function deleteStructureById($structureId)
	{
		if (!$structureId)
		{
			return false;
		}

		$affectedRows = craft()->db->createCommand()->delete('structures', array(
			'id' => $structureId
		));

		return (bool) $affectedRows;
	}

	/**
	 * Returns the descendant level delta for a given element.
	 *
	 * @param int              $structureId
	 * @param BaseElementModel $element
	 *
	 * @return int
	 */
	public function getElementLevelDelta($structureId, BaseElementModel $element)
	{
		$elementRecord = $this->_getElementRecord($structureId, $element);
		$descendants = $elementRecord->descendants();
		$criteria = $descendants->getDbCriteria();
		$criteria->order = 'level desc';
		$deepestDescendant = $descendants->find();

		if ($deepestDescendant)
		{
			return $deepestDescendant->level - $elementRecord->level;
		}
		else
		{
			return 0;
		}
	}

	// Moving elements around
	// -------------------------------------------------------------------------

	/**
	 * Prepends an element to another within a given structure.
	 *
	 * @param int              $structureId
	 * @param BaseElementModel $element
	 * @param BaseElementModel $parentElement
	 * @param string           $mode          Whether this is an "insert", "update", or "auto".
	 *
	 * @return bool
	 */
	public function prepend($structureId, BaseElementModel $element, BaseElementModel $parentElement, $mode = 'auto')
	{
		$parentElementRecord = $this->_getElementRecord($structureId, $parentElement);

		return $this->_doIt($structureId, $element, $parentElementRecord, 'prependTo', 'moveAsFirst', $mode);
	}

	/**
	 * Appends an element to another within a given structure.
	 *
	 * @param int              $structureId
	 * @param BaseElementModel $element
	 * @param BaseElementModel $parentElement
	 * @param string           $mode          Whether this is an "insert", "update", or "auto".
	 *
	 * @return bool
	 */
	public function append($structureId, BaseElementModel $element, BaseElementModel $parentElement, $mode = 'auto')
	{
		$parentElementRecord = $this->_getElementRecord($structureId, $parentElement);

		return $this->_doIt($structureId, $element, $parentElementRecord, 'appendTo', 'moveAsLast', $mode);
	}

	/**
	 * Prepends an element to the root of a given structure.
	 *
	 * @param int              $structureId
	 * @param BaseElementModel $element
	 * @param string           $mode        Whether this is an "insert", "update", or "auto".
	 *
	 * @return bool
	 */
	public function prependToRoot($structureId, BaseElementModel $element, $mode = 'auto')
	{
		$parentElementRecord = $this->_getRootElementRecord($structureId);

		return $this->_doIt($structureId, $element, $parentElementRecord, 'prependTo', 'moveAsFirst', $mode);
	}

	/**
	 * Appends an element to the root of a given structure.
	 *
	 * @param int              $structureId
	 * @param BaseElementModel $element
	 * @param string           $mode        Whether this is an "insert", "update", or "auto".
	 *
	 * @return bool
	 */
	public function appendToRoot($structureId, BaseElementModel $element, $mode = 'auto')
	{
		$parentElementRecord = $this->_getRootElementRecord($structureId);

		return $this->_doIt($structureId, $element, $parentElementRecord, 'appendTo', 'moveAsLast', $mode);
	}

	/**
	 * Moves an element before another within a given structure.
	 *
	 * @param int              $structureId
	 * @param BaseElementModel $element
	 * @param BaseElementModel $nextElement
	 * @param string           $mode        Whether this is an "insert", "update", or "auto".
	 *
	 * @return bool
	 */
	public function moveBefore($structureId, BaseElementModel $element, BaseElementModel $nextElement, $mode = 'auto')
	{
		$nextElementRecord = $this->_getElementRecord($structureId, $nextElement);

		return $this->_doIt($structureId, $element, $nextElementRecord, 'insertBefore', 'moveBefore', $mode);
	}

	/**
	 * Moves an element after another within a given structure.
	 *
	 * @param int              $structureId
	 * @param BaseElementModel $element
	 * @param BaseElementModel $prevElement
	 * @param string           $mode        Whether this is an "insert", "update", or "auto".
	 *
	 * @return bool
	 */
	public function moveAfter($structureId, BaseElementModel $element, BaseElementModel $prevElement, $mode = 'auto')
	{
		$prevElementRecord = $this->_getElementRecord($structureId, $prevElement);

		return $this->_doIt($structureId, $element, $prevElementRecord, 'insertAfter', 'moveAfter', $mode);
	}

	/**
	 * Fires an 'onBeforeMoveElement' event.
	 *
	 * @param Event $event
	 *
	 * @return null
	 */
	public function onBeforeMoveElement(Event $event)
	{
		$this->raiseEvent('onBeforeMoveElement', $event);
	}

	/**
	 * Fires an 'onMoveElement' event.
	 *
	 * @param Event $event
	 *
	 * @return null
	 */
	public function onMoveElement(Event $event)
	{
		$this->raiseEvent('onMoveElement', $event);
	}

	// Private Methods
	// =========================================================================

	/**
	 * Returns a structure element record from given structure and element IDs.
	 *
	 * @param int              $structureId
	 * @param BaseElementModel $element
	 *
	 * @return StructureElementRecord|null
	 */
	private function _getElementRecord($structureId, BaseElementModel $element)
	{
		$elementId = $element->id;

		if ($elementId)
		{
			return StructureElementRecord::model()->findByAttributes(array(
				'structureId' => $structureId,
				'elementId'   => $elementId
			));
		}
	}

	/**
	 * Returns the root node for a given structure ID, or creates one if it doesn't exist.
	 *
	 * @param int $structureId
	 *
	 * @return StructureElementRecord
	 */
	private function _getRootElementRecord($structureId)
	{
		if (!isset($this->_rootElementRecordsByStructureId[$structureId]))
		{
			$elementRecord = StructureElementRecord::model()->roots()->findByAttributes(array(
				'structureId' => $structureId
			));

			if (!$elementRecord)
			{
				// Create it
				$elementRecord = new StructureElementRecord();
				$elementRecord->structureId = $structureId;
				$elementRecord->saveNode();
			}

			$this->_rootElementRecordsByStructureId[$structureId] = $elementRecord;
		}

		return $this->_rootElementRecordsByStructureId[$structureId];
	}

	/**
	 * Updates a BaseElementModel with the new structure attributes from a StructureElementRecord.
	 *
	 * @param  int                    $structureId
	 * @param  BaseElementModel       $element
	 * @param  StructureElementRecord $targetElementRecord
	 * @param  string                 $insertAction
	 * @param  string                 $updateAction
	 * @param  string                 $mode
	 *
	 * @throws \Exception
	 * @return bool
	 */
	private function _doIt($structureId, BaseElementModel $element, StructureElementRecord $targetElementRecord, $insertAction, $updateAction, $mode)
	{
		// Figure out what we're doing
		if ($mode != 'insert')
		{
			// See if there's an existing structure element record
			$elementRecord = $this->_getElementRecord($structureId, $element);

			if ($elementRecord)
			{
				$mode = 'update';
				$action = $updateAction;
			}
		}

		if (empty($elementRecord))
		{
			$elementRecord = new StructureElementRecord();
			$elementRecord->structureId = $structureId;
			$elementRecord->elementId   = $element->id;

			$mode = 'insert';
			$action = $insertAction;
		}

		$transaction = craft()->db->getCurrentTransaction() === null ? craft()->db->beginTransaction() : null;
		try
		{
			if ($mode == 'update')
			{
				// Fire an 'onBeforeMoveElement' event
				$event = new Event($this, array(
					'structureId'  => $structureId,
					'element'      => $element,
				));

				$this->onBeforeMoveElement($event);
			}

			// Was there was no onBeforeMoveElement event, or is the event giving us the go-ahead?
			if (!isset($event) || $event->performAction)
			{
				// Really do it
				$success = $elementRecord->$action($targetElementRecord);

				// If it didn't work, rollback the transaction in case something changed in onBeforeMoveElement
				if (!$success)
				{
					if ($transaction !== null)
					{
						$transaction->rollback();
					}

					return false;
				}

				$element->root  = $elementRecord->root;
				$element->lft   = $elementRecord->lft;
				$element->rgt   = $elementRecord->rgt;
				$element->level = $elementRecord->level;

				// Tell the element type about it
				$elementType = craft()->elements->getElementType($element->getElementType());
				$elementType->onAfterMoveElementInStructure($element, $structureId);
			}
			else
			{
				$success = false;
			}

			// Commit the transaction regardless of whether we moved the element, in case something changed
			// in onBeforeMoveElement
			if ($transaction !== null)
			{
				$transaction->commit();
			}
		}
		catch (\Exception $e)
		{
			if ($transaction !== null)
			{
				$transaction->rollback();
			}

			throw $e;
		}

		if ($success && $mode == 'update')
		{
			// Fire an 'onMoveElement' event
			$this->onMoveElement(new Event($this, array(
				'structureId'  => $structureId,
				'element'      => $element,
			)));
		}

		return $success;
	}
}


text:
package net.openaudiomc.jclient.utils.config;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

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

@Getter @Setter @ToString
public class ConfigStorageSpeakerMedia {

    private String name;
    private String source;

    public List<String> serialize() {
        List<String> list = new ArrayList<>();
        list.add("    " + name + ":");
        list.add("      src: '" + source + "'");
        return list;
    }
}


text:
<?php
    /**
     * Business layer class for snapshot service.
     *
     * @author   Team Rah
     * @package  CORE
     * @category Services
     * @version  0.0.2.1
     */
    class cBusiness
    {
        /**
         * @var array   Data array
         */
        protected $aData = array();

        /**
         * @var string  HTTP Response code.
         */
        protected $sResponseCode = '';

        /**
         * @var string  Body of response
         */
        protected $sResponseBody = '';

        /**
         * @var array   Extra headers to pass thru the service response.
         */
        protected $aExtraHeaders = array();

        /**
         * @var array   Ignored files.
         */
        protected $aIgnoredFiles = array(
            'desktop.ini',
            'sftp-config.json',
            '.ds_store',
            '._.ds_store'
        );

        /**
         * @var array   Ignored folders.
         */
        protected $aIgnoredFolders = array(
            'logs',
            '_macosx',
            '.svn'
        );

        /**
         * @var string predetermined core hash
         */
        protected $sBaseHash = null;

        /**
         * constructor for snapshot business.
         */
        public function __construct ()
        {
            $sHashFile = sSERVICE_INC_PATH . DIRECTORY_SEPARATOR . 'snapshot' . DIRECTORY_SEPARATOR . 'core.hash';
            if ( file_exists( $sHashFile ) )
            {
                $this->sBaseHash = trim( file_get_contents( $sHashFile ) );
            }
        }

        /**
         * Checks request method. Only allow GET.
         *
         * @return  boolean
         */
        public function ValidateRequest ()
        {
            // check the request method.
            $bValidRequest = false;

            if ( $_SERVER[ 'REQUEST_METHOD' ] === 'GET' )
            {
                $bValidRequest = true;
            }

            return $bValidRequest;
        }

        /**
         * check for any immediate problems with the CORE Environment.
         *  - /libs folder is missing
         *  - /libs/PHPCore folder is missing
         *  - /logs folder is not writable.
         *  - /libs/PHPCore is not accessible ( can not execute list command )
         *  - Expected core folder is missing or not accessible:
         *      - classes
         *      - cli
         *      - docs
         *      - includes
         *      - js
         *      - templates
         *      - tests
         *
         * @return  boolean
         */
        public function CheckEnvironment ()
        {
            // initialize
            $bReturn = true;

            // check core exists
            $bReturn = $bReturn && @file_exists( sBASE_INC_PATH . DIRECTORY_SEPARATOR . 'libs' ) === TRUE;
            $bReturn = $bReturn && @file_exists( sBASE_INC_PATH . DIRECTORY_SEPARATOR . 'configs' ) === TRUE;
            $bReturn = $bReturn && @file_exists( sCORE_INC_PATH ) === TRUE;

            // check logs are writable.
            $bReturn = $bReturn && @is_writable( sBASE_INC_PATH . DIRECTORY_SEPARATOR . 'logs' ) === TRUE;

            // check core directory is executable (can list files/subfolders)
            $bReturn = $bReturn && @file_exists( sCORE_INC_PATH . DIRECTORY_SEPARATOR . '.' ) === TRUE;

            // check core directory has expected folder structure.
            $bReturn = $bReturn && @file_exists( sCORE_INC_PATH . DIRECTORY_SEPARATOR . 'classes' )   === TRUE;
            $bReturn = $bReturn && @file_exists( sCORE_INC_PATH . DIRECTORY_SEPARATOR . 'cli' )       === TRUE;
            $bReturn = $bReturn && @file_exists( sCORE_INC_PATH . DIRECTORY_SEPARATOR . 'docs' )      === TRUE;
            $bReturn = $bReturn && @file_exists( sCORE_INC_PATH . DIRECTORY_SEPARATOR . 'includes' )  === TRUE;
            $bReturn = $bReturn && @file_exists( sCORE_INC_PATH . DIRECTORY_SEPARATOR . 'js' )        === TRUE;
            $bReturn = $bReturn && @file_exists( sCORE_INC_PATH . DIRECTORY_SEPARATOR . 'templates' ) === TRUE;
            $bReturn = $bReturn && @file_exists( sCORE_INC_PATH . DIRECTORY_SEPARATOR . 'tests' )     === TRUE;

            return $bReturn;
        }

        /**
         * Gets all files and folders recursively.
         *
         * @param   string      $sDirPath   Path to directory.
         *
         * @return  array                   contains files/folders information.
         */
        public function GetDirectoryFiles ( $sDirPath )
        {
            // initialize
            $aFiles = array();

            if ( $rhFolder = opendir( $sDirPath ) )
            {
                // loop all files and subfolders recursively.
                while ( false !== ( $sPath = readdir( $rhFolder ) ) )
                {
                    $sFullPath = $sDirPath . DIRECTORY_SEPARATOR . $sPath;
                    if ( $sPath == "." || $sPath == ".." )
                    {
                        continue;
                    }

                    // get metadata.
                    $sPerms = substr( sprintf( '%o', fileperms( $sFullPath ) ), -4 );

                    $bIsDir = is_dir( $sFullPath );

                    // setup information array
                    $aFile = array();
                    $aFile[ 'path' ]    = $sFullPath;
                    $aFile[ 'perms' ]   = $sPerms;
                    $aFile[ 'name' ]    = basename( $sFullPath );
                    $aFile[ 'is_dir' ]  = $bIsDir;

                    // save for return.
                    $aFiles[] = $aFile;

                    if ( $bIsDir )
                    {
                        // get files in subfolder.
                        $aSubfiles = $this->GetDirectoryFiles( $sFullPath ) ;
                        $aFiles    = array_merge( $aFiles, $aSubfiles );
                    }
                }
                closedir($rhFolder);
            }

            return $aFiles;
        }

        /**
         * Gets all files from the core library.
         *
         * @return  array
         */
        public function GetCoreFiles ()
        {
            // get core files.
            $aCoreFiles = array();
            $aCoreFiles = $this->GetDirectoryFiles( sCORE_INC_PATH );

            return $aCoreFiles;
        }

        /**
         * Creates an MD5 hash of pertinent file information. For files,
         * it uses name and file content. For directories, it uses the name.
         *
         * @param   array       $aFile  file array
         *
         * @return  string
         */
        public function CreateFileHash ( array $aFile )
        {
            // initialize hash cipher as file / folder name.
            $sFileContent = $aFile[ 'name' ];

            if ( !$aFile[ 'is_dir' ] )
            {
                // get file contents
                $sContent = file_get_contents( $aFile[ 'path' ] );
                if ( $sContent === false )
                {
                    throw new Exception( 'Failed to read file contents to create hash: ' . print_r( $aFile, 1 ) );
                }

                // combine file name and contents.
                $sFileContent = $sFileContent . $sContent;
            }

            // create hash.
            return md5( $sFileContent );
        }

        /**
         * Creates a hash of filename and permission.
         *
         * @param   array       $aFile  File info.
         *
         * @return  string
         */
        public function CreatePermHash ( array $aFile )
        {
            // create hash.
            return md5( $aFile[ 'name' ] . $aFile[ 'perms' ] );
        }

        /**
         * Concatenate all file hashes into a single string and perform
         * an md5 on that string to give us our master hash for core.
         *
         * @param   array       $aFileHashes    array of md5 hashes
         *
         * @return  string
         */
        public function CreateMasterHash ( array $aFileHashes )
        {
            return md5( implode( '', $aFileHashes ) );
        }

        /**
         * Performs the snapshot logic. Validates Request, Checks the environment,
         * Creates hashes of all core files and combines them into a master hashsum.
         *
         * This hashsum is then returned to the consumer that called the service.
         *
         * @return  array
         */
        public function TakeSnapshot ()
        {
            // initialize
            $aReturn = array();

            // validate the request and check the environment first.
            $bValidRequest = $this->ValidateRequest( );
            $bCheckEnv     = $this->CheckEnvironment( );

            if ( $bValidRequest && $bCheckEnv )
            {
                // loop through /libs/PHPCore files
                $aFileHashes = array();
                $aFiles      = $this->GetCoreFiles();

                $iFileCount  = count( $aFiles );
                for ( $iIndex = 0; $iIndex < $iFileCount; $iIndex++ )
                {
                    // get file information and create hash.
                    $aFile     = $aFiles[ $iIndex ];
                    $sFileHash = $this->CreateFileHash( $aFile );
                    $sFilename = basename( $aFile[ 'path' ] );

                    // skip ignored files and folders.
                    if (   in_array( strtolower( $sFilename ), $this->aIgnoredFiles )
                        || in_array( strtolower( $sFilename ), $this->aIgnoredFolders )
                        )
                    {
                        unset( $aFiles[ $iIndex ] );
                        continue;
                    }

                    // save file hash.
                    $aFileHashes[ $sFilename ] = $sFileHash;
                }

                // reset keys
                $aFiles = array_values( $aFiles );

                // create master hash.
                $sMasterHash = $this->CreateMasterHash( $aFileHashes );

                // check for known hash.
                if (   !empty( $this->sBaseHash )
                    && $this->sBaseHash !== $sMasterHash
                    )
                {
                    // send alert
                    $this->sResponseCode = 'HTTP/1.1 207 Multi-Status';
                    $this->sResponseBody = array( $this->sBaseHash, $sMasterHash, 'Mismatch between expected core hash and latest snapshot.' );
                }
                else
                {
                    // set response.
                    $this->sResponseCode = 'HTTP/1.1 200 OK';
                    $this->sResponseBody = $sMasterHash;
                }
            }
            else if ( !$bValidRequest )
            {
                // send notification.
                $this->sResponseCode   = 'HTTP/1.1 405 Method Not Allowed';
                $this->aExtraHeaders[] = 'Allow: GET';
            }
            else if ( !$bCheckEnv )
            {
                // send notification.
                $this->sResponseCode = 'HTTP/1.1 417 Expectation Failed';
                $this->sResponseBody = 'Core does not exist, logs are not writable, core directory is not executable, or core directory is missing folders.';
            }

            // send the data back to the controller.
            $aReturn[ 'data' ]         = $this->aData;
            $aReturn[ 'code' ]         = $this->sResponseCode;
            $aReturn[ 'response' ]     = $this->sResponseBody;
            $aReturn[ 'extraheaders' ] = $this->aExtraHeaders;

            return $aReturn;
        }

        /**
         * Performs a check of all permissions on files and folder in the core directory.
         * Validates Request, Checks the environment.
         *
         * @return  array
         */
        public function CheckPermissions ()
        {

            // initialize
            $aReturn = array();

            // validate the request and check the environment first.
            $bValidRequest = $this->ValidateRequest( );
            $bCheckEnv     = $this->CheckEnvironment( );
            if ( $bValidRequest && $bCheckEnv )
            {
                // loop through /libs/PHPCore files
                $aFileHashes = array();
                $aFiles      = $this->GetCoreFiles();
                $iFileCount  = count( $aFiles );
                for ( $iIndex = 0; $iIndex < $iFileCount; $iIndex++ )
                {
                    // get file information and create hash.
                    $aFile     = $aFiles[ $iIndex ];
                    $sFileHash = $this->CreatePermHash( $aFile );
                    $sFilename = basename( $aFile[ 'path' ] );

                    // skip ignored files and folders.
                    if (   in_array( strtolower( $sFilename ), $this->aIgnoredFiles )
                        || in_array( strtolower( $sFilename ), $this->aIgnoredFolders )
                        )
                    {
                        unset( $aFiles[ $iIndex ] );
                        continue;
                    }

                    // save file hash.
                    $aFileHashes[ $sFilename ] = $sFileHash;
                }

                // reset keys
                $aFiles = array_values( $aFiles );

                // create master hash.
                $sMasterHash = $this->CreateMasterHash( $aFileHashes );

                // set response.
                $this->sResponseCode = 'HTTP/1.1 200 OK';
                $this->sResponseBody = $sMasterHash;
            }
            else if ( !$bValidRequest )
            {
                // send notification.
                $this->sResponseCode   = 'HTTP/1.1 405 Method Not Allowed';
                $this->aExtraHeaders[] = 'Allow: GET';
            }
            else if ( $bCheckEnv )
            {
                // send notification.
                $this->sResponseCode = 'HTTP/1.1 417 Expectation Failed';
                $this->sResponseBody = 'Core does not exist, logs are not writable, core directory is not executable, or core directory is missing folders.';
            }

            // send the data back to the controller.
            $aReturn[ 'data' ]         = $this->aData;
            $aReturn[ 'code' ]         = $this->sResponseCode;
            $aReturn[ 'response' ]     = $this->sResponseBody;
            $aReturn[ 'extraheaders' ] = $this->aExtraHeaders;

            return $aReturn;
        }
    }
?>


text:
namespace app { namespace Fuse { struct Node; } }

namespace app {
namespace Fuse {
namespace Input {

struct Pointer_PELHolder;

struct Pointer_PELHolder__uType : ::uClassType
{
};

Pointer_PELHolder__uType* Pointer_PELHolder__typeof();

void Pointer_PELHolder___ObjInit(Pointer_PELHolder* __this);
Pointer_PELHolder* Pointer_PELHolder__New_1(::uStatic* __this);

struct Pointer_PELHolder : ::uObject
{
    ::uStrong< ::app::Fuse::Node*> Node;
    int Status;

    void _ObjInit() { Pointer_PELHolder___ObjInit(this); }
};

}}}

#endif


text:
<<<<<<< HEAD
<?php
/**
This Example shows how to Add the contact details to the given signup form
**/
require_once 'inc/BMEAPI.class.php';
require_once 'inc/config.php'; //contains username & password

$api = new BMEAPI($username, $password, $apiURL);
if ($api->errorCode){
  // an error occurred while logging in
  echo "code:".$api->errorCode."\n";
  echo "msg :".$api->errorMessage."\n";
  die();
}

$signupForms = $api->listGetSignupForms(1, 10, "");
$signupFormID = $signupForms[0]["id"];

$details["email"] = "tom@____.com";
$details["firstname"] = "Tom";
$details["lastname"] = "Jones";

$retval = $api->listAddContactsForm($signupFormID, $details);

if (!$retval){
  echo "Error!";
  echo "\n\tCode=".$api->errorCode;
  echo "\n\tMsg=".$api->errorMessage."\n";
} else {
  echo "Total Contacts:". $retval ."\n";
}

?>
=======
<?php
/**
This Example shows how to Add the contact details to the given signup form
**/
require_once 'inc/BMEAPI.class.php';
require_once 'inc/config.php'; //contains username & password

$api = new BMEAPI($username, $password, $apiURL);
if ($api->errorCode){
  // an error occurred while logging in
  echo "code:".$api->errorCode."\n";
  echo "msg :".$api->errorMessage."\n";
  die();
}

$signupForms = $api->listGetSignupForms(1, 10, "");
$signupFormID = $signupForms[0]["id"];

$details["email"] = "tom@____.com";
$details["firstname"] = "Tom";
$details["lastname"] = "Jones";

$retval = $api->listAddContactsForm($signupFormID, $details);

if (!$retval){
  echo "Error!";
  echo "\n\tCode=".$api->errorCode;
  echo "\n\tMsg=".$api->errorMessage."\n";
} else {
  echo "Total Contacts:". $retval ."\n";
}

?>
>>>>>>> 250a993699aa8885e23578fdfcdb6d486f7dbfae


text:
package com.fagnerbrack.servlet.convention.tag;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import com.fagnerbrack.servlet.convention.ConventionURI;
import com.fagnerbrack.servlet.convention.RequestAttr;

public class IncludeHeadTag extends TagSupport {
private static final long serialVersionUID = 1;

	@Override
	public int doStartTag() throws JspException {
		HttpServletRequest request = ( HttpServletRequest )pageContext.getRequest();
		String currentURI = ( String )request.getAttribute( RequestAttr.CURRENT_URI.value() );
		ConventionURI uri = new ConventionURI( currentURI, request.getContextPath() );
		try {
			String head = uri.getJSPHeadLocation();
			if ( pageContext.getServletContext().getResource( head ) != null ) {
				pageContext.include( head );
			}
		} catch ( ServletException | IOException e ) {
			e.printStackTrace();
		}
		return SKIP_BODY;
	}
}


text:
#pragma once
#include <aws/s3/S3_EXPORTS.h>
#include <aws/s3/model/DeleteMarkerReplicationStatus.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Xml
{
  class XmlNode;
} // namespace Xml
} // namespace Utils
namespace S3
{
namespace Model
{

  /**
   *
Specifies whether Amazon S3 replicates delete markers. If you specify a
   * Filter in your replication configuration, you must also include a
   * DeleteMarkerReplication element. If your Filter
   * includes a Tag element, the DeleteMarkerReplication
   * Status must be set to Disabled, because Amazon S3 does not support
   * replicating delete markers for tag-based rules. For an example configuration,
   * see Basic
   * Rule Configuration.

For more information about delete marker
   * replication, see Basic
   * Rule Configuration.

If you are using an earlier version of
   * the replication configuration, Amazon S3 handles replication of delete markers
   * differently. For more information, see Backward
   * Compatibility.

See Also:
   AWS
   * API Reference

   */
  class AWS_S3_API DeleteMarkerReplication
  {
  public:
    DeleteMarkerReplication();
    DeleteMarkerReplication(const Aws::Utils::Xml::XmlNode& xmlNode);
    DeleteMarkerReplication& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);

    void AddToNode(Aws::Utils::Xml::XmlNode& parentNode) const;

    /**
     *
Indicates whether to replicate delete markers.

Indicates
     * whether to replicate delete markers.

     */
    inline const DeleteMarkerReplicationStatus& GetStatus() const{ return m_status; }

    /**
     *
Indicates whether to replicate delete markers.

Indicates
     * whether to replicate delete markers.

     */
    inline bool StatusHasBeenSet() const { return m_statusHasBeenSet; }

    /**
     *
Indicates whether to replicate delete markers.

Indicates
     * whether to replicate delete markers.

     */
    inline void SetStatus(const DeleteMarkerReplicationStatus& value) { m_statusHasBeenSet = true; m_status = value; }

    /**
     *
Indicates whether to replicate delete markers.

Indicates
     * whether to replicate delete markers.

     */
    inline void SetStatus(DeleteMarkerReplicationStatus&& value) { m_statusHasBeenSet = true; m_status = std::move(value); }

    /**
     *
Indicates whether to replicate delete markers.

Indicates
     * whether to replicate delete markers.

     */
    inline DeleteMarkerReplication& WithStatus(const DeleteMarkerReplicationStatus& value) { SetStatus(value); return *this;}

    /**
     *
Indicates whether to replicate delete markers.

Indicates
     * whether to replicate delete markers.

     */
    inline DeleteMarkerReplication& WithStatus(DeleteMarkerReplicationStatus&& value) { SetStatus(std::move(value)); return *this;}

  private:

    DeleteMarkerReplicationStatus m_status;
    bool m_statusHasBeenSet = false;
  };

} // namespace Model
} // namespace S3
} // namespace Aws


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using Sofire.Dynamic.Factories;

namespace Sofire.Serialization.BinarySuite
{
    internal static class SerializationHelper
    {
        #region Serializable Members - 可序列化成员

        private readonly static Dictionary<int, SerializableFieldInfo[]> FieldsCache = new Dictionary<int, SerializableFieldInfo[]>();

        public static SerializableFieldInfo[] GetSerializableMembers(Type type)
        {
            var sourceType = type;
            var sourceTypeID = type.MetadataToken;
            lock(sourceType)
            {
                SerializableFieldInfo[] sfields;
                if(!FieldsCache.TryGetValue(sourceTypeID, out sfields))
                {
                    List<SerializableFieldInfo> list = new List<SerializableFieldInfo>();
                    int depth = 0;
                    while((type != Types.Object))
                    {
                        var fields = type.GetFields(Sofire.Dynamic.MemberFlags.InstanceFlags);
                        foreach(FieldInfo field in fields)
                        {
                            if(field == null
#if !SILVERLIGHT
 || field.IsNotSerialized
#endif
 || field.IsDefined(IgnoreAttribute.Type, false)) continue;

                            list.Add(new SerializableFieldInfo(field, depth));
                        }
                        type = type.BaseType;
                        depth++;
                    }
                    sfields = list.ToArray();
                    FieldsCache.Add(sourceTypeID, sfields);
                }
                return sfields;
            }
        }

        #endregion

        #region Simplify Qualified Name - 简化限定名称

        private readonly static Dictionary<int, string> SimplifyQualifiedNameCache = new Dictionary<int, string>();

        public static string SimplifyQualifiedName(Type type)
        {
            string s;
            var typeID = type.MetadataToken;
            lock(type)
            {
                if(!SimplifyQualifiedNameCache.TryGetValue(typeID, out s))
                {
                    StringBuilder builder = new StringBuilder();
                    SimplifyQualifiedName(type, ref builder);
                    s = builder.ToString();
                    SimplifyQualifiedNameCache.Add(typeID, s);
                }
            }
            return s;
        }

        private static void AddNamespace(string ns, ref StringBuilder builder)
        {
            switch(ns)
            {
                case "System":
                    builder.Append('s');
                    break;
                case "System.Text":
                    builder.Append("st");
                    break;
                case "System.Data":
                    builder.Append("sd");
                    break;
                case "System.Collections":
                    builder.Append("sc");
                    break;
                case "System.Collections.Generic":
                    builder.Append("scg");
                    break;
                case "System.IO":
                    builder.Append("si");
                    break;
                default:
                    builder.Append(ns);
                    break;
            }
        }

        private static void AddTypeName(Type type, ref StringBuilder builder)
        {
            var ns = type.Namespace;
            if(!string.IsNullOrEmpty(ns))
            {
                AddNamespace(ns, ref builder);
                builder.Append('.');
                if(type.ReflectedType != null)
                {
                    builder.Append(type.ReflectedType.Name);
                    builder.Append('+');
                }
            }
            builder.Append(type.Name);
        }

        private static void SimplifyQualifiedName(Type type, ref StringBuilder builder)
        {
            int index = builder.Length;

            AddTypeName(type, ref builder);
            if(type.IsGenericType)
            {
                var genericTypes = type.GetGenericArguments();
                builder.Append('[');
                foreach(var gType in genericTypes)
                {
                    builder.Append('[');
                    SimplifyQualifiedName(gType, ref builder);
                    builder.Append(']');
                    builder.Append(',');
                }
                builder.Remove(builder.Length - 1, 1);
                builder.Append(']');
            }
            if(type.Assembly != AssemblyInfoCollection.mscorlib.Assembly)
            {
                builder.Append(',');
                builder.Append(new AssemblyName(type.Assembly.FullName).Name);
            }
            // return builder.ToString();
        }

        #endregion

        #region Recovery Qualified Name - 还原限定名称

        private readonly static Dictionary<string, Type> RecoverySimplifyQualifiedCache = new Dictionary<string, Type>();

        private static void AppendQualifiedName(this StringBuilder builder, string typeName, string fullname)
        {
            builder.Append(typeName);
            builder.Append(", ");
            builder.Append(fullname);
        }

        private static string GetNamespace(string ns)
        {
            switch(ns)
            {
                case "s":
                    return "System";

                case "st":
                    return "System.Text";

                case "sd":
                    return "System.Data";

                case "sc":
                    return "System.Collections";

                case "scg":
                    return "System.Collections.Generic";

                case "si":
                    return "System.IO";

                default:
                    return ns;
            }
        }

        public static Type RecoveryQualifiedName(string simplifyQualifiedName)
        {
            Type type;
            lock(simplifyQualifiedName)
            {
                if(!RecoverySimplifyQualifiedCache.TryGetValue(simplifyQualifiedName, out type))
                {
                    StringBuilder builder = new StringBuilder();
                    RecoveryQualifiedName(simplifyQualifiedName, ref builder);
                    type = AssemblyInfoCollection.GetTypeFromQualifiedName(builder.ToString());
                    if(type == null) throw new ArgumentException("无法找到简化限定符的类型 " + simplifyQualifiedName);
                    RecoverySimplifyQualifiedCache.Add(simplifyQualifiedName, type);
                }
            }
            return type;
        }

        private static void RecoveryQualifiedName(string simplifyQualifiedName, ref StringBuilder builder)
        {
            int builderIndex = builder.Length;

            int depth = 0;
            int index = 0;
            int firstIndex = -1;
            string assemblyName = string.Empty;
            for(int i = 0 ; i < simplifyQualifiedName.Length ; )
            {
                var c = simplifyQualifiedName[i];
                switch(c)
                {
                    case '[':
                        if(firstIndex == -1) firstIndex = i;
                        if(depth == 0)
                        {
                            builder.Append('[');
                            index = i + 1;
                        }
                        depth++;
                        break;
                    case ']':
                        depth--;
                        if(depth == 1)
                        {
                            string str = simplifyQualifiedName.Substring(index + 1, i - index - 1);

                            builder.Append('[');
                            //builder.Append();
                            RecoveryQualifiedName(str, ref builder);
                            index = i + 2;
                        }
                        if(depth < 2)
                        {
                            builder.Append(']');
                        }
                        break;
                    case ',':
                        if(firstIndex == -1) firstIndex = i;
                        if(depth == 0)
                        {
                            assemblyName = simplifyQualifiedName.Substring(i + 1);
                            i = simplifyQualifiedName.Length;
                        }
                        else if(depth < 2)
                        {
                            builder.Append(',');
                        }
                        break;
                    default:
                        if(depth == 0)
                        {
                            builder.Append(c);
                        }
                        break;
                }
                i++;
            }
            if(string.IsNullOrEmpty(assemblyName))
            {
                assemblyName = "mscorlib";
            }

            string typeName = firstIndex == -1 ? simplifyQualifiedName : simplifyQualifiedName.Substring(0, firstIndex);
            var nsIndex = typeName.LastIndexOf('.');
            if(nsIndex > -1)
            {
                var ns = typeName.Substring(0, nsIndex);
                builder.Remove(builderIndex, nsIndex);
                builder.Insert(builderIndex, GetNamespace(ns));
            }
            builder.Append(", ");
            builder.Append(AssemblyInfoCollection.Find(assemblyName).Fullname);

            //  return builder.ToString();
        }

        #endregion
    }

}