text:
var request = require('request');
var BotConnectorStorage = (function () {
    function BotConnectorStorage(options) {
        this.options = options;
    }
    BotConnectorStorage.prototype.get = function (address, callback) {
        var ops = 2;
        var settings = this.options;
        var data = {};
        function read(path, field) {
            if (path) {
                var options = {
                    url: settings.endpoint + '/bot/v1.0/bots' + path
                };
                if (settings.appId && settings.appSecret) {
                    options.auth = {
                        username: settings.appId,
                        password: settings.appSecret
                    };
                    options.headers = {
                        'Ocp-Apim-Subscription-Key': settings.appSecret
                    };
                }
                request.get(options, function (err, response, body) {
                    if (!err) {
                        try {
                            data[field + 'Hash'] = body;
                            data[field] = typeof body === 'string' ? JSON.parse(body) : null;
                        }
                        catch (e) {
                            err = e instanceof Error ? e : new Error(e.toString());
                        }
                    }
                    if (callback && (err || --ops == 0)) {
                        callback(err, data);
                        callback = null;
                    }
                });
            }
            else if (callback && --ops == 0) {
                callback(null, data);
            }
        }
        var userPath = address.userId ? '/users/' + address.userId : null;
        var convoPath = address.conversationId ? '/conversations/' + address.conversationId + userPath : null;
        read(userPath, 'userData');
        read(convoPath, 'conversationData');
    };
    BotConnectorStorage.prototype.save = function (address, data, callback) {
        var ops = 2;
        var settings = this.options;
        function write(path, field) {
            if (path) {
                var err;
                var body;
                var hashField = field + 'Hash';
                try {
                    body = JSON.stringify(data[field]);
                }
                catch (e) {
                    err = e instanceof Error ? e : new Error(e.toString());
                }
                if (!err && (!data[hashField] || body !== data[hashField])) {
                    data[hashField] = body;
                    var options = {
                        url: settings.endpoint + '/bot/v1.0/bots' + path,
                        body: body
                    };
                    if (settings.appId && settings.appSecret) {
                        options.auth = {
                            username: settings.appId,
                            password: settings.appSecret
                        };
                        options.headers = {
                            'Ocp-Apim-Subscription-Key': settings.appSecret
                        };
                    }
                    request.post(options, function (err) {
                        if (callback && (err || --ops == 0)) {
                            callback(err);
                            callback = null;
                        }
                    });
                }
                else if (callback && (err || --ops == 0)) {
                    callback(err);
                    callback = null;
                }
            }
            else if (callback && --ops == 0) {
                callback(null);
            }
        }
        var userPath = address.userId ? '/users/' + address.userId : null;
        var convoPath = address.conversationId ? '/conversations/' + address.conversationId + userPath : null;
        write(userPath, 'userData');
        write(convoPath, 'conversationData');
    };
    return BotConnectorStorage;
})();
exports.BotConnectorStorage = BotConnectorStorage;


text:
var GameModel = function(name){
	var _this = this;
	_this.Name = ko.observable(name || "");
	_this.Id = ko.pureComputed(function(){
		//return _this.Name().replace(/\s+/g, '-').toLowerCase();
		return "WORKSPACE-" + _this.Name().toLowerCase();
	});

	_this.Name.subscribe(function(oldValue) {
		localStorage.removeItem(_this.Id());
	}, _this, "beforeChange");

	_this.Name.subscribe(function(newValue) {
		WORKSPACE.CurrentGame = _this;
		WORKSPACE.ViewModels.GameViewModel.Save();
		WORKSPACE.Save();
	}, _this);
};

var GameViewModel = function() {
	var _this = this;
	_this.Selector = null;
	_this.Position = ko.observable({Right: 0, Top: 0}).extend({ trackChange: true });
	_this.IsMinimized = ko.observable(false).extend({ trackChange: true });
	_this.GameList = ko.observableArray([new GameModel("tmp")]);
	_this.SelectedGame = ko.observable();
	_this.IsLoaded = ko.observable(false);

	_this.Load = function(data) {
		_this.Position({
			Left: data.Position.Left || 0,
			Top: data.Position.Top || 0
		});
		_this.IsMinimized(data.IsMinimized);
		_this.LoadGameList(WORKSPACE.GameList);
		_this.LoadSelectedGame(WORKSPACE.CurrentGame);
	};

	_this.Save = function(){
		if (WORKSPACE.SupportsStorage()) {
			if(WORKSPACE.DEBUG) console.log("Game Model Saving");
			localStorage.setItem("WORKSPACE", JSON.stringify({
				"CurrentGame": ko.toJS( _this.SelectedGame() ),
				"GameList": ko.toJS( _this.GameList() ),
				"MapSlides": ko.toJS( WORKSPACE.ViewModels.CombatViewModel.MapSlides() )
			}));
		}
	};

	_this.LoadGameList = function(list){
		var tmpList = [];
		$.each(list, function(i,v) {
			var game = new GameModel(v.Name);
			tmpList.push(game);
		});
		_this.GameList(tmpList);
	};

	_this.LoadSelectedGame = function(game){
		if (game !== undefined) {
			$.each(_this.GameList(), function(i, v){
				if (v.Name() == game.Name()) {
					_this.SelectedGame(v);
				}
			});
		}
	};

	/*_this.Position.subscribe(function(newValue){
		//WORKSPACE.Save();
	});

	_this.IsMinimized.subscribe(function(newValue){
		//WORKSPACE.Save();
	});

	_this.GameList.subscribe(function(newValue){
		//WORKSPACE.Save();
	});*/

	_this.SelectedGame.subscribe(function(oldValue){
		if(oldValue !== undefined) {
			_this.IsLoaded(true);
		}
	}, null, "beforeChange");

	_this.SelectedGame.subscribe(function(newValue){
		if (_this.IsLoaded()) {
			//WORKSPACE.SaveViewModel.Run();
			_this.Save();

			/**
			 *	Reload location for new WORKSPACE
			 *	I'd like it to just hotswap the viewmodels, but this was a quick temp fix
			 *	I know it's dirty, oh well
			 *
			 *	@author		#thuglife
			 */
			location.reload();

			//WORKSPACE.CurrentGame = new GameModel(_this.SelectedGame());
			//WORKSPACE.Init();
		}
	});

	_this.AddGame = function(){
		var newgame = new GameModel( "Game" + ( _this.GameList().length + 1 ) );
		_this.GameList.push(newgame);
		_this.SelectedGame(newgame);
	};

	_this.RemoveGame = function(){
		var game = _this.SelectedGame();
		if (WORKSPACE.SupportsStorage() && localStorage.getItem(game.Id()) !== null) {
			localStorage.removeItem(game.Id());
			_this.GameList.remove(game);
		}
	};
};

redpajama_set_name: RedPajamaGithub


text: A boilerplate for developing React-Redux application with webpack


text:
<readable><title>3612485611_12dd7742f7</title><content>
Two men dressed in street clothes horse around in front of a building .
Two men jump around together outside of a building .
Two men jumping outside on the grass .
Two young men goofing around on the grass in front the of union building .
Two young men in sportswear are running and jumping on the grass by a brick building .
</content></readable>


text:
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//

/*=============================================================
**
** Source: test1.c
**
** Purpose: Sets up a new unhandled exception filter, and makes sure it
**          returns the previous filter.  Raises an unhandled exception and
**          makes sure this reaches the filter.
**
**
**============================================================*/

#include <palsuite.h>

/* This isn't defined in the pal, so copied from win32 */
#define EXCEPTION_EXECUTE_HANDLER       1
#define EXCEPTION_CONTINUE_EXECUTION    -1

int InFilter = FALSE;

LONG PALAPI FirstFilter(LPEXCEPTION_POINTERS p)
{
    return EXCEPTION_EXECUTE_HANDLER;
}

LONG PALAPI ContinueFilter(LPEXCEPTION_POINTERS p)
{
    InFilter = TRUE;

    Trace("This test has succeeded as far at the automated checks can "
          "tell.  Manual verification is now required to be completely sure.\n");
    Trace("Now the PAL's handling of application errors will be tested "
          "with an exception code of %u.\n",
          p->ExceptionRecord->ExceptionCode);
    Trace("Please verify that the actions that the PAL now takes are "
          "as specified for it.\n");

    return EXCEPTION_CONTINUE_SEARCH;
}

int __cdecl main(int argc, char *argv[])
{
    LPTOP_LEVEL_EXCEPTION_FILTER OldFilter;

    if(0 != (PAL_Initialize(argc, argv)))
    {
        return FAIL;
    }

    SetUnhandledExceptionFilter(FirstFilter);

    OldFilter = SetUnhandledExceptionFilter(ContinueFilter);
    if (OldFilter != FirstFilter)
    {
        Fail("SetUnhandledExceptionFilter did not return a pointer to the "
            "previous filter!\n");
    }

    /*
     * Raise an unhandled exception.  This should cause our filter to be
     * excecuted and the program to exit with a code the same as the
     * exception code.
     */
    RaiseException(3,0,0,0);

    /*
     * This code should not be executed because the toplevelhandler is
     * expected to "just" set the exit code and abend the program
     */
    Fail("An unhandled exception did not cause the program to abend with"
         "the exit code == the ExceptionCode!\n");

    PAL_Terminate();
    return FAIL;
}


text:
package definiti.core.end2end.controls

import definiti.common.ast.Root
import definiti.common.tests.{ConfigurationMock, LocationPath}
import definiti.core.ProgramResultMatchers._
import definiti.core.end2end.EndToEndSpec
import definiti.core.validation.controls.EnumerationUniquenessControl

class EnumerationUniquenessControlSpec extends EndToEndSpec {
  import EnumerationUniquenessControlSpec._

  "Project.generatePublicAST" should "validate an enum having all its cases once" in {
    val output = processFile("controls.enumerationUniqueness.nominal", configuration)
    output shouldBe ok[Root]
  }

  it should "invalidate an enum with a case appearing twice" in {
    val output = processFile("controls.enumerationUniqueness.duplication", configuration)
    output should beKo(
      EnumerationUniquenessControl.errorDuplication("Monday", "Days", duplicationLocation(9, 3, 9))
    )
  }
}

object EnumerationUniquenessControlSpec {
  val configuration = ConfigurationMock().withOnlyControls(EnumerationUniquenessControl)

  val duplicationLocation = LocationPath.control(EnumerationUniquenessControl, "duplication")
}


text:
from import_export import resources

from mixins.models import ModifiedDate
from photosync.models import PhotoSet, Photo, CopySettings

class PhotoSetResource(resources.ModelResource):

    class Meta:
        model = PhotoSet

class PhotoResource(resources.ModelResource):

    class Meta:
        model = Photo

class CopySettingsResource(resources.ModelResource):

    class Meta:
        model = CopySettings


text:
module Mish.ConnectorGenerator(connectRooms) where

import qualified Data.Set                as S
import qualified Data.Map           as M
import           Mish.Config
import           Mish.Util
import           Mish.HexagonalGrid
import           System.Random
type Region = S.Set AxialCoordinate

-- Having already made random rooms and filled the array with mazes, connect rooms through use of said mazes.
connectRooms :: InternalMap -> StdGen -> Config -> (InternalMap, StdGen)
connectRooms m seed config =
  case regions of
    []    -> (m, seed)
    (h:t) -> connectRegions m seed config h (S.fromList t) (S.fromList connectorIndices) False
  where ascs = M.assocs m
        connectorIndices = connectorCandidates m ascs
        floorTiles = S.fromList $ map fst $ filter ((Floor==) . snd) ascs
        regions = createRegions floorTiles

-- all candidates for connectors, that is any wall tile which has 2 or more neighbouring floor tiles
connectorCandidates :: InternalMap -> [(AxialCoordinate, Tile)] -> [AxialCoordinate]
connectorCandidates m ascs = map fst candidates
  where candidates = filter connectorCandidate ascs

        connectorCandidate :: (AxialCoordinate, Tile) -> Bool
        connectorCandidate (p, t) =
          (t == Wall) &&
          any (\(n1, n2) -> S.member n1 floorNeighbours &&
                             S.member n2 floorNeighbours
              ) (neighbourpairs p)
          where floorNeighbours = S.fromList $ filter (\n -> maybe False (==Floor) $ M.lookup n m) $ neighbours p

        -- the acceptable pairs of neighbours for a connectorCandidate
        neighbourpairs :: AxialCoordinate -> [(AxialCoordinate, AxialCoordinate)]
        neighbourpairs c = map (\(n1, n2) -> (n1 |+| c, n2 |+| c)) matrix
          where matrix = [ ((-1, 0), (0,  1)) -- TL, B
                         , ((-1, 0), (1,  0)) -- TL, BR
                         , ((-1, 0), (1, -1)) -- TL, TR
                         , ((-1, 1), (1,  0)) -- BL, BR
                         , ((-1, 1), (1, -1)) -- BL, TR
                         , ((-1, 1), (0, -1)) -- BL, T
                         , (( 0, 1), (1, -1)) -- B , TR
                         , (( 0, 1), (0, -1)) -- B , T
                         , (( 1, 0), (0, -1)) -- BR, T
                         ]

-- take an element from the set, add all of its neighbours into a Region.
createRegions :: S.Set AxialCoordinate -> [Region]
createRegions s
  | S.null s  = []
  | otherwise = region:createRegions s'
  where any_pos  = head $ S.toList s
        any_ns = S.fromList $ any_pos:neighbours any_pos
        region   = createRegion any_ns S.empty

        -- delete every element from region found from the set of floor tiles
        s'       = s S.\\ region

        createRegion :: S.Set AxialCoordinate -> Region -> Region
        createRegion frontier visited
          | S.null frontier = visited
          | otherwise       = createRegion frontier' visited'
          where in_region = S.filter (\n -> S.notMember n visited &&
                                            S.member n s) frontier
                visited'  = S.union visited in_region
                frontier' = S.fromList $ concatMap (\p -> p:neighbours p) $ S.toList in_region

-- connect regions until only 1 remains
connectRegions :: InternalMap -> StdGen -> Config -> Region -> S.Set Region -> S.Set AxialCoordinate -> Bool -> (InternalMap, StdGen)
connectRegions m seed config region regions connectors doubled
  | S.null regions ||
    S.size regions == 1 ||
    S.null region_connectors = (m, seed)
  | S.null connectors        = error "Something has went terribly wrong, impossible to connect regions."
  | otherwise                = connectRegions m' seed''' config region' regions' connectors' doubleConnect

  where region_connectors  = S.filter (bordersRegion region) connectors
        (connector, seed') = choice (S.toList region_connectors) seed

        dcChance           = doubleConnectorChance config
        (dc, seed'')       = randomR (0.0, 1.0) seed'
        doubleConnect      = not doubled &&
                             S.size region_connectors > 1 &&
                             dc < dcChance

        regions_connected  = S.filter (`bordersRegion` connector) regions
        (chosen, seed''')  = if S.null regions_connected
                             then (region, seed'')
                             else choice (S.toList regions_connected) seed''

        region'            = S.union region chosen

        regions'           = if doubleConnect
                             then regions
                             else S.delete chosen regions

        connectors'        = if S.null regions_connected
                             then S.delete connector connectors
                             else S.filter (\c -> not (bordersRegion region c &&
                                                       bordersRegion chosen c)) connectors

        m' = if not $ S.null regions_connected
             then M.insert connector Floor m
             else m

        bordersRegion :: Region -> AxialCoordinate -> Bool
        bordersRegion r c = any (`S.member` r) $ neighbours c


text:
package dev.yn.cassandra

import java.nio.ByteBuffer
import java.util.UUID

import com.datastax.driver.core.{ResultSet, Session}
import com.datastax.driver.core.querybuilder.QueryBuilder._
import com.datastax.driver.core.querybuilder.Select.Where
import dev.yn.size.ImageSize.ImageSizeDefinition
import com.datastax.driver.core.querybuilder.QueryBuilder.{eq => fieldEq}
import play.api.Logger

import scala.concurrent.Future
import play.api.libs.concurrent.Execution.Implicits._

trait AsciiGifReadCQL extends BaseAsciiGifCQL {
  import AsciiGifReadCQL._

  /**
    * Get the id of an image by the url
    *
    * @param url
    * @param session
    * @return UrlKeyModel for the given url
    */
  def readKey(url: String)(implicit session: Session): Future[Option[UrlKeyModel]] = {
    executeStatement(session, readKeyStatement(url))
      .map(handleSingleValueResult(toUriKeyModel))
  }

  /**
    * read a specific size of an image
    *
    * @param id
    * @param size
    * @param session
    * @return gzip compressed byte buffer for the specified gif and size
    */
  def readImage(id: UUID, size: ImageSizeDefinition)(implicit session: Session): Future[Option[ByteBuffer]] = {
    executeStatement(session, readImageStatement(id, size))
      .map(handleSingleValueResult(toByteBufferForSize(size)))
  }
}

object AsciiGifReadCQL {
  import BaseAsciiGifCQL._
  private val Log = Logger(classOf[AsciiGifReadCQL])

  private def readKeyStatement(url: String): Where = {
    select(Seq(UriField, IdField): _*).from(AsciiImageKeyspace, KeyTable)
      .where(fieldEq(UriField, url))
  }

  private def readImageStatement(id: UUID, size: ImageSizeDefinition): Where = {
    select(Seq(IdField, size.fieldName): _*).from(AsciiImageKeyspace, CompositeTable)
      .where(fieldEq(IdField, id))
  }

  private val toUriKeyModel: ResultSet => UrlKeyModel = {
    resultSet =>
      val row = resultSet.one()
      UrlKeyModel(row.getString(UriField), row.getUUID(IdField))
  }

  private val toByteBufferForSize: ImageSizeDefinition => ResultSet => ByteBuffer =
    size => resultSet => resultSet.one().getBytes(size.fieldName)

  private def handleSingleValueResult[T](extractResult: ResultSet => T): ResultSet => Option[T] = {
    resultSet =>
      resultSet.getAvailableWithoutFetching match {
        case 0 => None
        case 1 => Some(extractResult(resultSet))
        case _ =>
          Log.error(s"too many results on query. Expected: 1, Actual: ${resultSet.getAvailableWithoutFetching}")
          Some(extractResult(resultSet))
      }
  }
}


text:
using BEPUutilities2;
using BEPUutilities2.Collections;
using BEPUutilities2.Memory;
using SolverPrototype.Constraints;
using System;
using System.Diagnostics;
using System.Linq;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Threading;

namespace SolverPrototype
{
    public class ConstraintLayoutOptimizer
    {
        Bodies bodies;
        Solver solver;
        struct Optimization
        {
            /// <summary>
            /// Index of the target constraint bundle to optimize.
            /// </summary>
            public int BundleIndex;
            /// <summary>
            /// Index of the last optimized type batch.
            /// </summary>
            public int TypeBatchIndex;
            /// <summary>
            /// Index of the last optimized batch.
            /// </summary>
            public int BatchIndex;

        }

        Optimization nextTarget;

        /// <summary>
        /// If true, regions are offset by a half region width. Toggled each frame. Offsets allow the sorted regions to intermix, eventually converging to a full sort.
        /// </summary>
        bool shouldOffset;

        float optimizationFraction;
        public float OptimizationFraction
        {
            get { return optimizationFraction; }
            set
            {
                if (value < 0 || value > 1)
                    throw new ArgumentException("Optimization fraction must be from 0 to 1.");
                optimizationFraction = value;
            }
        }

        Action<int> generateSortKeysDelegate;
        Action<int> regatherDelegate;
        Action<int> copyToCacheAndSortDelegate;

        public ConstraintLayoutOptimizer(Bodies bodies, Solver solver, float optimizationFraction = 0.044f)
        {
            this.bodies = bodies;
            this.solver = solver;
            OptimizationFraction = optimizationFraction;

            generateSortKeysDelegate = GenerateSortKeys;
            regatherDelegate = Regather;
            copyToCacheAndSortDelegate = CopyToCacheAndSort;
        }

        bool WrapBatch(ref Optimization o)
        {
            Debug.Assert(solver.Batches.Count >= 0);
            if (o.BatchIndex >= solver.Batches.Count)
            {
                //Wrap around.
                o = new Optimization();
                return true;
            }
            return false;
        }
        bool WrapTypeBatch(ref Optimization o)
        {
            Debug.Assert(o.BatchIndex <= solver.Batches.Count, "Should only attempt to wrap type batch indices if the batch index is known to be valid.");
            bool wrapped = false;
            //Note that it's possible for a batch to contain zero type batches. This is a byproduct of only the last constraint batch ever being removed.
            //Empty constraint batches before the last index stick around until batch compression finds them and shifts everything into a lower batch.
            //So, here, we have to be ready to walk forward multiple batches.
            while (o.TypeBatchIndex >= solver.Batches[o.BatchIndex].TypeBatches.Count)
            {
                ++o.BatchIndex;
                if (!WrapBatch(ref o))
                {
                    o.TypeBatchIndex = 0;
                    o.BundleIndex = 0;
                }
                wrapped = true;
            }
            return wrapped;
        }

        bool WrapBundle(ref Optimization o)
        {
            Debug.Assert(o.BatchIndex <= solver.Batches.Count && o.TypeBatchIndex <= solver.Batches[o.BatchIndex].TypeBatches.Count,
                "Should only attempt to wrap constraint index if the type batch and batch indices are known to be valid.");
            if (o.BundleIndex >= solver.Batches[o.BatchIndex].TypeBatches[o.TypeBatchIndex].BundleCount)
            {
                ++o.TypeBatchIndex;
                if (!WrapTypeBatch(ref o))
                {
                    o.BundleIndex = 0;
                }
                return true;
            }
            return false;
        }
        void BoundsCheckOldTarget(ref Optimization o)
        {
            if (!WrapBatch(ref o))
            {
                if (!WrapTypeBatch(ref o))
                {
                    WrapBundle(ref o);
                }
            }
        }
        Optimization FindOffsetFrameStart(Optimization o, int maximumRegionSizeInBundles)
        {
            BoundsCheckOldTarget(ref o);

            var spaceRemaining = solver.Batches[o.BatchIndex].TypeBatches[o.TypeBatchIndex].BundleCount - o.BundleIndex;
            if (spaceRemaining <= maximumRegionSizeInBundles)
            {
                ++o.TypeBatchIndex;
                WrapTypeBatch(ref o);
            }
            //Note that the bundle count is not cached; the above type batch may differ.
            o.BundleIndex = Math.Max(0,
                Math.Min(
                    o.BundleIndex + maximumRegionSizeInBundles / 2,
                    solver.Batches[o.BatchIndex].TypeBatches[o.TypeBatchIndex].BundleCount - maximumRegionSizeInBundles));

            return o;
        }

        public void Update(BufferPool bufferPool, IThreadDispatcher threadDispatcher = null)
        {
            //TODO: It's possible that the cost associated with setting up multithreading exceeds the cost of the actual optimization for smaller simulations.
            //You might want to fall back to single threaded based on some empirical testing.

            //No point in optimizing if there are no constraints- this is a necessary test since we assume that 0 is a valid batch index later.
            if (solver.Batches.Count == 0)
                return;
            var regionSizeInBundles = (int)Math.Max(2, Math.Round(solver.BundleCount * optimizationFraction));
            //The region size in bundles should be divisible by two so that it can be offset by half.
            if ((regionSizeInBundles & 1) == 1)
                ++regionSizeInBundles;
            //Note that we require that all regions are bundle aligned. This is important for the typebatch sorting process, which tends to use bulk copies from bundle arrays to cache.
            //If not bundle aligned, those bulk copies would become complex due to the constraint AOSOA layout.

            Optimization target;
            if (shouldOffset)
            {
                //Use the previous frame's start to create the new target.
                target = FindOffsetFrameStart(nextTarget, regionSizeInBundles);
                Debug.Assert(solver.Batches[target.BatchIndex].TypeBatches[target.TypeBatchIndex].BundleCount <= regionSizeInBundles || target.BundleIndex != 0,
                    "On offset frames, the only time a target bundle can be 0 is if the batch is too small for it to be anything else.");
                //Console.WriteLine($"Offset frame targeting {target.BatchIndex}.{target.TypeBatchIndex}:{target.BundleIndex}");
            }
            else
            {
                //Since the constraint set could have changed arbitrarily since the previous execution, validate from batch down.
                target = nextTarget;
                BoundsCheckOldTarget(ref target);
                nextTarget = target;
                nextTarget.BundleIndex += regionSizeInBundles;
                //Console.WriteLine($"Normal frame targeting {target.BatchIndex}.{target.TypeBatchIndex}:{target.BundleIndex}");
            }
            //Note that we have two separate parallel optimizations over multiple frames. Alternating between them on a per frame basis is a fairly simple way to guarantee
            //eventual convergence in the sort. We only ever push forward the non-offset version; the offset position is based on the nonoffset version's last start position.
            shouldOffset = !shouldOffset;

            var maximumRegionSizeInConstraints = regionSizeInBundles * Vector<int>.Count;

            var typeBatch = solver.Batches[target.BatchIndex].TypeBatches[target.TypeBatchIndex];
            SortByBodyLocation(typeBatch, target.BundleIndex, Math.Min(typeBatch.ConstraintCount - target.BundleIndex * Vector<int>.Count, maximumRegionSizeInConstraints),
                solver.HandleToConstraint, bodies.Count, bufferPool, threadDispatcher);

        }

        TypeBatch typeBatch;
        IThreadDispatcher threadDispatcher;
        Buffer<ConstraintLocation> handlesToConstraints;
        struct MultithreadingContext
        {
            public Buffer<int> SortKeys;
            public Buffer<int> SourceIndices;
            public RawBuffer BodyReferencesCache;
            public int SourceStartBundleIndex;
            public int BundlesPerWorker;
            public int BundlesPerWorkerRemainder;
            public int TypeBatchConstraintCount;

            public Buffer<int> SortedKeys; //This is only really stored for debug use.
            public Buffer<int> SortedSourceIndices;
            public Buffer<int> ScratchKeys;
            public Buffer<int> ScratchValues;
            public Buffer<int> IndexToHandleCache;
            public RawBuffer PrestepDataCache;
            public RawBuffer AccumulatesImpulsesCache;
            public int KeyUpperBound;
            public int ConstraintsInSortRegionCount;
            //Note that these differ from phase 1- one of the threads in the sort is dedicated to a sort. These regard the remaining threads.
            public int CopyBundlesPerWorker;
            public int CopyBundlesPerWorkerRemainder;
        }
        MultithreadingContext context;

        void GenerateSortKeys(int workerIndex)
        {
            var localWorkerBundleStart = context.BundlesPerWorker * workerIndex + Math.Min(workerIndex, context.BundlesPerWorkerRemainder);
            var workerBundleStart = context.SourceStartBundleIndex + localWorkerBundleStart;
            var workerBundleCount = workerIndex < context.BundlesPerWorkerRemainder ? context.BundlesPerWorker + 1 : context.BundlesPerWorker;
            var workerConstraintStart = workerBundleStart << BundleIndexing.VectorShift;
            //Note that the number of constraints we can iterate over is clamped by the type batch's constraint count. The last bundle may not be full.
            var workerConstraintCount = Math.Min(context.TypeBatchConstraintCount - workerConstraintStart, workerBundleCount << BundleIndexing.VectorShift);
            if (workerConstraintCount <= 0)
                return; //No work remains.
            var localWorkerConstraintStart = localWorkerBundleStart << BundleIndexing.VectorShift;

            typeBatch.GenerateSortKeysAndCopyReferences(
                workerBundleStart, localWorkerBundleStart, workerBundleCount,
                workerConstraintStart, localWorkerConstraintStart, workerConstraintCount,
                ref context.SortKeys[localWorkerConstraintStart], ref context.SourceIndices[localWorkerConstraintStart], ref context.BodyReferencesCache);
        }

        void CopyToCacheAndSort(int workerIndex)
        {
            //Sorting only requires that the sort keys and indices be ready. Caching doesn't need to be done yet.
            //Given that the sort is already very fast and trying to independently multithread it is a bad idea, we'll just bundle it alongside
            //the remaining cache copies. This phase is extremely memory bound and the sort likely won't match the copy duration, but there is no
            //room for complicated schemes at these timescales (<150us). We just try to get as much benefit as we can with a few simple tricks.
            //Most likely we won't get more than about 2.5x speedup on a computer with bandwidth/compute ratios similar to a 3770K with 1600mhz memory.
            if (workerIndex == threadDispatcher.ThreadCount - 1)
            {
                //TODO: If this ends up being the only place where you actually make use of the thread memory pools, you might as well get rid of it
                //in favor of just preallocating workerCount buffers of 1024 ints each. Its original use of creating the typebatch-specific memory no longer exists.
                LSBRadixSort.Sort<int, Buffer<int>, Buffer<int>>(
                    ref context.SortKeys, ref context.SourceIndices,
                    ref context.ScratchKeys, ref context.ScratchValues, 0, context.ConstraintsInSortRegionCount,
                    context.KeyUpperBound, threadDispatcher.GetThreadMemoryPool(workerIndex),
                    out context.SortedKeys, out context.SortedSourceIndices);
            }
            //Note that worker 0 still copies if there's only one thread in the pool. Mainly for debugging purposes.
            if (threadDispatcher.ThreadCount == 1 || workerIndex < threadDispatcher.ThreadCount - 1)
            {
                var localWorkerBundleStart = context.CopyBundlesPerWorker * workerIndex + Math.Min(workerIndex, context.CopyBundlesPerWorkerRemainder);
                var workerBundleStart = context.SourceStartBundleIndex + localWorkerBundleStart;
                var workerBundleCount = workerIndex < context.CopyBundlesPerWorkerRemainder ? context.CopyBundlesPerWorker + 1 : context.CopyBundlesPerWorker;
                var workerConstraintStart = workerBundleStart << BundleIndexing.VectorShift;
                //Note that the number of constraints we can iterate over is clamped by the type batch's constraint count. The last bundle may not be full.
                var workerConstraintCount = Math.Min(context.TypeBatchConstraintCount - workerConstraintStart, workerBundleCount << BundleIndexing.VectorShift);
                if (workerConstraintCount <= 0)
                    return; //No work remains.
                var localWorkerConstraintStart = localWorkerBundleStart << BundleIndexing.VectorShift;

                typeBatch.CopyToCache(
                    workerBundleStart, localWorkerBundleStart, workerBundleCount,
                    workerConstraintStart, localWorkerConstraintStart, workerConstraintCount,
                    ref context.IndexToHandleCache, ref context.PrestepDataCache, ref context.AccumulatesImpulsesCache);
            }
        }

        void CopyToCacheAndSort(BufferPool pool)
        {
            LSBRadixSort.Sort<int, Buffer<int>, Buffer<int>>(
                ref context.SortKeys, ref context.SourceIndices,
                ref context.ScratchKeys, ref context.ScratchValues, 0, context.ConstraintsInSortRegionCount,
                context.KeyUpperBound, pool,
                out context.SortedKeys, out context.SortedSourceIndices);

            var workerBundleStart = context.SourceStartBundleIndex;
            var workerBundleCount = 0 < context.CopyBundlesPerWorkerRemainder ? context.CopyBundlesPerWorker + 1 : context.CopyBundlesPerWorker;
            var workerConstraintStart = workerBundleStart << BundleIndexing.VectorShift;
            //Note that the number of constraints we can iterate over is clamped by the type batch's constraint count. The last bundle may not be full.
            var workerConstraintCount = Math.Min(context.TypeBatchConstraintCount - workerConstraintStart, workerBundleCount << BundleIndexing.VectorShift);
            if (workerConstraintCount <= 0)
                return; //No work remains.

            typeBatch.CopyToCache(
                workerBundleStart, 0, workerBundleCount,
                workerConstraintStart, 0, workerConstraintCount,
                ref context.IndexToHandleCache, ref context.PrestepDataCache, ref context.AccumulatesImpulsesCache);
        }

        void Regather(int workerIndex)
        {
            var localWorkerBundleStart = context.BundlesPerWorker * workerIndex + Math.Min(workerIndex, context.BundlesPerWorkerRemainder);
            var workerBundleStart = context.SourceStartBundleIndex + localWorkerBundleStart;
            var workerBundleCount = workerIndex < context.BundlesPerWorkerRemainder ? context.BundlesPerWorker + 1 : context.BundlesPerWorker;
            var workerConstraintStart = workerBundleStart << BundleIndexing.VectorShift;
            //Note that the number of constraints we can iterate over is clamped by the type batch's constraint count. The last bundle may not be full.
            var workerConstraintCount = Math.Min(context.TypeBatchConstraintCount - workerConstraintStart, workerBundleCount << BundleIndexing.VectorShift);
            if (workerConstraintCount <= 0)
                return; //No work remains.
            var localWorkerConstraintStart = localWorkerBundleStart << BundleIndexing.VectorShift;
            ref var firstSourceIndex = ref context.SortedSourceIndices[localWorkerConstraintStart];

            typeBatch.Regather(workerConstraintStart, workerConstraintCount, ref firstSourceIndex,
                ref context.IndexToHandleCache, ref context.BodyReferencesCache, ref context.PrestepDataCache, ref context.AccumulatesImpulsesCache, ref handlesToConstraints);

        }

        void SortByBodyLocation(TypeBatch typeBatch, int bundleStartIndex, int constraintCount, Buffer<ConstraintLocation> handlesToConstraints, int bodyCount,
            BufferPool rawPool, IThreadDispatcher threadDispatcher)
        {
            int bundleCount = (constraintCount >> BundleIndexing.VectorShift);
            if ((constraintCount & BundleIndexing.VectorMask) != 0)
                ++bundleCount;
            var threadCount = threadDispatcher == null ? 1 : threadDispatcher.ThreadCount;

            var intPool = rawPool.SpecializeFor<int>();
            intPool.Take(constraintCount, out context.SourceIndices);
            intPool.Take(constraintCount, out context.SortKeys);
            intPool.Take(constraintCount, out context.ScratchKeys);
            intPool.Take(constraintCount, out context.ScratchValues);
            intPool.Take(constraintCount, out context.IndexToHandleCache);

            typeBatch.GetBundleTypeSizes(out var bodyReferencesBundleSize, out var prestepBundleSize, out var accumulatedImpulseBundleSize);

            //The typebatch invoked by the worker will cast the body references to the appropriate type.
            //Using typeless buffers makes it easy to cache the buffers here in the constraint optimizer rather than in the individual type batches.
            rawPool.Take(bundleCount * bodyReferencesBundleSize, out context.BodyReferencesCache);
            rawPool.Take(bundleCount * prestepBundleSize, out context.PrestepDataCache);
            rawPool.Take(bundleCount * accumulatedImpulseBundleSize, out context.AccumulatesImpulsesCache);

            context.BundlesPerWorker = bundleCount / threadCount;
            context.BundlesPerWorkerRemainder = bundleCount - context.BundlesPerWorker * threadCount;
            context.TypeBatchConstraintCount = typeBatch.ConstraintCount;
            context.SourceStartBundleIndex = bundleStartIndex;

            //The second phase uses one worker to sort.
            if (threadCount > 1)
            {
                context.CopyBundlesPerWorker = bundleCount / (threadCount - 1);
                context.CopyBundlesPerWorkerRemainder = bundleCount - context.CopyBundlesPerWorker * (threadCount - 1);
            }
            else
            {
                //If there's only one worker (as is the case when this is running single-threaded), the worker will have to do the sort AND the copy.
                context.CopyBundlesPerWorker = bundleCount;
                context.CopyBundlesPerWorkerRemainder = 0;
            }
            context.ConstraintsInSortRegionCount = constraintCount;
            context.KeyUpperBound = bodyCount - 1;

            this.typeBatch = typeBatch;
            this.threadDispatcher = threadDispatcher;
            this.handlesToConstraints = handlesToConstraints;

            if (threadDispatcher == null)
            {
                GenerateSortKeys(0);
                CopyToCacheAndSort(rawPool);
                Regather(0);
            }
            else
            {
                threadDispatcher.DispatchWorkers(generateSortKeysDelegate);
                threadDispatcher.DispatchWorkers(copyToCacheAndSortDelegate);
                threadDispatcher.DispatchWorkers(regatherDelegate);
            }

            this.typeBatch = null;
            this.threadDispatcher = null;
            this.handlesToConstraints = new Buffer<ConstraintLocation>();

            //This is a pure debug function.
            typeBatch.VerifySortRegion(bundleStartIndex, constraintCount, ref context.SortedKeys, ref context.SortedSourceIndices);

            intPool.Return(ref context.SourceIndices);
            intPool.Return(ref context.SortKeys);
            intPool.Return(ref context.ScratchKeys);
            intPool.Return(ref context.ScratchValues);
            intPool.Return(ref context.IndexToHandleCache);
            rawPool.Return(ref context.BodyReferencesCache);
            rawPool.Return(ref context.PrestepDataCache);
            rawPool.Return(ref context.AccumulatesImpulsesCache);
        }
    }
}


text:
import os
import shlex
import subprocess
from subprocess import PIPE, Popen

import SGE
from Launcher import ErrorMessage, Launcher, LauncherError

global job_name

pid = os.getpid()

class SgeLauncher(Launcher):
    """
    Implementation of Launcher to launch jobs in the user's local workstation.
    """

    # Misc common SgeLauncher settings.
    max_odirs = 5

    def __init__(self, deploy):
        '''Initialize common class members.'''

        super().__init__(deploy)

        # Popen object when launching the job.
        self.process = None

    def _do_launch(self):
        global job_name
        # Update the shell's env vars with self.exports. Values in exports must
        # replace the values in the shell's env vars if the keys match.
        exports = os.environ.copy()
        if self.deploy.exports:
            exports.update(self.deploy.exports)

        # Clear the magic MAKEFLAGS variable from exports if necessary. This
        # variable is used by recursive Make calls to pass variables from one
        # level to the next. Here, self.cmd is a call to Make but it's
        # logically a top-level invocation: we don't want to pollute the flow's
        # Makefile with Make variables from any wrapper that called dvsim.
        if 'MAKEFLAGS' in exports:
            del exports['MAKEFLAGS']

        self._dump_env_vars(exports)

        try:
            f = open(self.deploy.get_log_path(),
                     "w",
                     encoding="UTF-8",
                     errors="surrogateescape")
            f.write("[Executing]:\n{}\n\n".format(self.deploy.cmd))
            f.flush()
            # ---------- prepare SGE job struct -----
            sgeJob = SGE.qsubOptions()
            sgeJob.args.N = 'VCS_RUN_' + str(pid)  # Name of Grid Engine job
            if "build.log" in self.deploy.get_log_path():
                sgeJob.args.N = 'VCS_BUILD_' + str(
                    pid)  # Name of Grid Engine job

            job_name = sgeJob.args.N
            sgeJob.args.t = '0'  # Define an array job with 20 subjobs
            sgeJob.args.slot = '1'  # Define num of slot
            sgeJob.args.sync = 'y'  # wait for job to complete before exiting
            sgeJob.args.q = 'vcs_q'  # Define the sge queue name
            sgeJob.args.p = '0'  # Set priority to 0
            sgeJob.args.ll = 'mf=20G'  # memory req,request the given resources
            # pecifies a range of priorities from -1023 to 1024.
            # The higher the number, the higher the priority.
            # The default priority for jobs is zero
            sgeJob.args.command = '"' + self.deploy.cmd + '"'
            sgeJob.args.b = 'y'  # This is a binary file
            sgeJob.args.o = self.deploy.get_log_path() + '.sge'
            cmd = str(sgeJob.execute(mode='echo'))
            # ---------------
            self.process = subprocess.Popen(shlex.split(cmd),
                                            bufsize=4096,
                                            universal_newlines=True,
                                            stdout=f,
                                            stderr=f,
                                            env=exports)
            f.close()
        except subprocess.SubprocessError as e:
            raise LauncherError('IO Error: {}\nSee {}'.format(
                e, self.deploy.get_log_path()))
        finally:
            self._close_process()

        self._link_odir("D")
        f.close()

    def poll(self):
        '''Check status of the running process

        This returns 'D', 'P' or 'F'. If 'D', the job is still running. If 'P',
        the job finished successfully. If 'F', the job finished with an error.

        This function must only be called after running self.dispatch_cmd() and
        must not be called again once it has returned 'P' or 'F'.
        '''

        assert self.process is not None
        if self.process.poll() is None:
            return 'D'
        # -------------------------------------
        # copy SGE jobb results to log file
        if os.path.exists(self.deploy.get_log_path() + '.sge'):

            file1 = open(self.deploy.get_log_path() + '.sge', 'r')
            Lines = file1.readlines()
            file1.close()
            f = open(self.deploy.get_log_path(),
                     "a",
                     encoding="UTF-8",
                     errors="surrogateescape")
            for line in Lines:
                f.write(line)
            f.flush()
            os.remove(self.deploy.get_log_path() + '.sge')
            f.close()
        # -------------------------------------

        self.exit_code = self.process.returncode
        status, err_msg = self._check_status()
        self._post_finish(status, err_msg)
        return status

    def kill(self):
        global job_name
        '''Kill the running process.

        This must be called between dispatching and reaping the process (the
        same window as poll()).

        '''
        assert self.process is not None

        # Try to kill the running process. Send SIGTERM first, wait a bit,
        # and then send SIGKILL if it didn't work.
        self.process.terminate()
        try:
            self.process.wait(timeout=2)
        except subprocess.TimeoutExpired:
            self.process.kill()
            # ----------------------------
            # qdel -f kill sge job_name
            cmd = 'qstatus -a | grep ' + job_name
            with Popen(cmd, stdout=PIPE, stderr=None, shell=True) as process:
                output = process.communicate()[0].decode("utf-8")
                output = output.rstrip("\n")
                if output != '':
                    output_l = output.split()
                    cmd = 'qdel ' + output_l[0]
                    with Popen(cmd, stdout=PIPE, stderr=None,
                               shell=True) as process:
                        output = process.communicate()[0].decode("utf-8")
                        output = output.rstrip("\n")
                        print('Killed job "' + str(output) + '"')
            # ----------------------------
        self._post_finish(
            'K',
            ErrorMessage(line_number=None, message='Job killed!', context=[]))

    def _post_finish(self, status, err_msg):
        super()._post_finish(status, err_msg)
        self._close_process()
        self.process = None

    def _close_process(self):
        '''Close the file descriptors associated with the process.'''

        assert self.process
        if self.process.stdout:
            self.process.stdout.close()


text:
package com.yscardII.framework.hibernate.service;

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

import com.yscardII.framework.hibernate.bo.IntegType;

public interface IntegTypeService {

	void saveIntegType(Map<String, Object> map);
	void updateIntegType(Map<String, Object> map);
	Map<String, Object> showIntegType(Map<String, Object> map);
	List<IntegType> queryIntegType(String queryString, Integer first, Integer max);
	void deleteIntegType(Map<String, Object> map);

}


text:
@interface Task ()

// Private interface goes here.

@end

@implementation Task

@end


text:
namespace Google.Cloud.Dialogflow.V2.Snippets
{
    // [START dialogflow_v2_generated_ConversationDatasets_ListConversationDatasets_async_flattened_resourceNames]
    using Google.Api.Gax;
    using Google.Api.Gax.ResourceNames;
    using Google.Cloud.Dialogflow.V2;
    using System;
    using System.Linq;
    using System.Threading.Tasks;

    public sealed partial class GeneratedConversationDatasetsClientSnippets
    {
        /// <summary>Snippet for ListConversationDatasetsAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task ListConversationDatasetsResourceNamesAsync()
        {
            // Create client
            ConversationDatasetsClient conversationDatasetsClient = await ConversationDatasetsClient.CreateAsync();
            // Initialize request argument(s)
            LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
            // Make the request
            PagedAsyncEnumerable<ListConversationDatasetsResponse, ConversationDataset> response = conversationDatasetsClient.ListConversationDatasetsAsync(parent);

            // Iterate over all response items, lazily performing RPCs as required
            await response.ForEachAsync((ConversationDataset item) =>
            {
                // Do something with each item
                Console.WriteLine(item);
            });

            // Or iterate over pages (of server-defined size), performing one RPC per page
            await response.AsRawResponses().ForEachAsync((ListConversationDatasetsResponse page) =>
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (ConversationDataset item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            });

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page<ConversationDataset> singlePage = await response.ReadPageAsync(pageSize);
            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (ConversationDataset item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
        }
    }
    // [END dialogflow_v2_generated_ConversationDatasets_ListConversationDatasets_async_flattened_resourceNames]
}


text:
package com.amazonaws.services.servermigration.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.servermigration.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * DeleteServerCatalogRequestMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DeleteServerCatalogRequestMarshaller {

    private static final DeleteServerCatalogRequestMarshaller instance = new DeleteServerCatalogRequestMarshaller();

    public static DeleteServerCatalogRequestMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(DeleteServerCatalogRequest deleteServerCatalogRequest, ProtocolMarshaller protocolMarshaller) {

        if (deleteServerCatalogRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
<?php

namespace Etu\Module\TrombiBundle\Controller;

use Doctrine\ORM\EntityManager;
use Doctrine\ORM\QueryBuilder;
use Etu\Core\CoreBundle\Framework\Definition\Controller;
use Etu\Core\UserBundle\Entity\User;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\HttpFoundation\Request;

class MainController extends Controller
{
    /**
     * @Route("/trombi/{page}", defaults={"page" = 1}, requirements={"page" = "\d+"}, name="trombi_index")
     * @Template()
     *
     * @param mixed $page
     */
    public function indexAction($page, Request $request)
    {
        $this->denyAccessUnlessGranted('ROLE_TROMBI');

        $user = new User();
        $search = false;
        $users = [];

        $form = $this->createFormBuilder($user)
            ->setMethod('get')
            ->add('fullName', null, ['required' => false])
            ->add('studentId', null, ['required' => false])
            ->add('phoneNumber', null, ['required' => false])
            ->add('uvs', null, ['required' => false])
            ->add('branch', ChoiceType::class, ['choices' => User::$branches, 'required' => false])
            ->add('niveau', ChoiceType::class, ['choices' => User::$levels, 'required' => false])
            ->add('personnalMail', null, ['required' => false])
            ->getForm();

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $search = true;

            /** @var $em EntityManager */
            $em = $this->getDoctrine()->getManager();

            /** @var $users QueryBuilder */
            $users = $em->createQueryBuilder()
                ->select('u')
                ->from('EtuUserBundle:User', 'u')
                ->where('u.isStudent = 1')
                ->orderBy('u.lastName');

            if (!$user->getFullName() && !$user->getStudentId() && !$user->getPhoneNumber() && !$user->getUvs() &&
                !$user->getBranch() && !$user->getNiveau() && !$user->getPersonnalMail()) {
                return $this->redirect($this->generateUrl('trombi_index'));
            }

            if ($user->getFullName()) {
                $where = 'u.login = :login ';
                $users->setParameter('login', $user->getFullName());

                $where .= 'OR u.surnom LIKE :surnom OR (';
                $users->setParameter('surnom', '%'.$user->getFullName().'%');

                $terms = explode(' ', $user->getFullName());

                foreach ($terms as $key => $term) {
                    $where .= 'u.fullName LIKE :name_'.$key.' AND ';
                    $users->setParameter('name_'.$key, '%'.$term.'%');
                }

                $where = mb_substr($where, 0, -5).')';

                $users->andWhere($where);
            }

            if ($user->getStudentId()) {
                $users->andWhere('u.studentId = :id')
                    ->setParameter('id', $user->getStudentId());
            }

            if ($user->getPhoneNumber()) {
                $phone = $user->getPhoneNumber();
                $parts = [];

                if (mb_strpos($phone, '.') !== false) {
                    $parts = explode('.', $phone);
                } elseif (mb_strpos($phone, '-') !== false) {
                    $parts = explode('-', $phone);
                } elseif (mb_strpos($phone, ' ') !== false) {
                    $parts = explode(' ', $phone);
                } else {
                    $parts = str_split($phone, 2);
                }

                $users->andWhere('u.phoneNumber LIKE :phone')
                    ->setParameter('phone', implode('%', $parts));
            }

            if ($user->getUvs()) {
                $uvs = array_map('trim', explode(',', $user->getUvs()));

                foreach ($uvs as $key => $uv) {
                    $users->andWhere('u.uvs LIKE :uv'.$key)
                        ->setParameter('uv'.$key, '%'.$uv.'%');
                }
            }

            if ($user->getBranch()) {
                $users->andWhere('u.branch = :branch')
                    ->setParameter('branch', $user->getBranch());
            }

            if ($user->getNiveau()) {
                $users->andWhere('u.niveau = :niveau')
                    ->setParameter('niveau', $user->getNiveau());
            }

            if ($user->getPersonnalMail()) {
                $users->andWhere('u.personnalMail = :personnalMail')
                    ->setParameter('personnalMail', $user->getPersonnalMail());
            }

            $query = $users->getQuery();
            $query->useResultCache(true, 3600 * 24);

            $users = $this->get('knp_paginator')->paginate($query, $page, 10);
        }

        return [
            'form' => $form->createView(),
            'search' => $search,
            'pagination' => $users,
        ];
    }
}


text:
package org.apache.polygene.api.association;

import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
import org.apache.polygene.api.entity.EntityReference;

/**
 * If you want to catch calls to ManyAssociations, then create a GenericConcern
 * that wraps the Polygene-supplied ManyAssociation instance with ManyAssociationWrappers. Override
 * methods to perform your custom code.
 */
public class ManyAssociationWrapper
    implements ManyAssociation<Object>
{
    protected ManyAssociation<Object> next;

    public ManyAssociationWrapper( ManyAssociation<Object> next )
    {
        this.next = next;
    }

    public ManyAssociation<Object> next()
    {
        return next;
    }

    @Override
    public int count()
    {
        return next.count();
    }

    @Override
    public boolean contains( Object entity )
    {
        return next.contains( entity );
    }

    @Override
    public boolean add( int i, Object entity )
    {
        return next.add( i, entity );
    }

    @Override
    public boolean add( Object entity )
    {
        return next.add( entity );
    }

    @Override
    public boolean remove( Object entity )
    {
        return next.remove( entity );
    }

    @Override
    public boolean clear()
    {
        return next.clear();
    }

    @Override
    public Object get( int i )
    {
        return next.get( i );
    }

    @Override
    public List<Object> toList()
    {
        return next.toList();
    }

    @Override
    public Set<Object> toSet()
    {
        return next.toSet();
    }

    @Override
    public Stream<EntityReference> references()
    {
        return next.references();
    }

    @Override
    public Iterator<Object> iterator()
    {
        return next.iterator();
    }

    @Override
    public int hashCode()
    {
        return next.hashCode();
    }

    @Override
    @SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
    public boolean equals( Object obj )
    {
        return next.equals( obj );
    }

    @Override
    public String toString()
    {
        return next.toString();
    }
}


text:
package config

type (
	// HTTP configures the HTTP server.
	HTTP struct {
		TLS       bool     `json:"tls"`
		Bind      string   `json:"bind"`
		Hostnames []string `json:"hostnames"`
		CertPath  string   `json:"cert"`
		KeyPath   string   `json:"key"`
		Login     string   `json:"login"`
		Password  string   `json:"password"`
	}
)

var (
	scheme = map[bool]string{
		false: "http",
		true:  "https",
	}
)


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <name>Asakusa YAESS Core</name>
  <artifactId>asakusa-yaess-core</artifactId>
  <parent>
    <artifactId>asakusa-yaess-project</artifactId>
    <groupId>com.asakusafw</groupId>
    <version>0.9.1-SNAPSHOT</version>
  </parent>

  <packaging>jar</packaging>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-assembly-plugin</artifactId>
        <executions>
          <execution>
            <id>create-distribution</id>
            <phase>package</phase>
            <goals>
              <goal>single</goal>
            </goals>
            <configuration>
              <descriptors>
                <descriptor>src/main/assembly/dist.xml</descriptor>
              </descriptors>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <dependency>
      <groupId>com.asakusafw</groupId>
      <artifactId>asakusa-runtime</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-simple</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>jul-to-slf4j</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>commons-lang</groupId>
      <artifactId>commons-lang</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.hamcrest</groupId>
      <artifactId>hamcrest-library</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>


text:
#region Copyright (c) 2002-2003, James W. Newkirk, Michael C. Two, Alexei A. Vorontsov, Charlie Poole, Philip A. Craig

#endregion

using System;
using System.IO;
using System.Xml;

namespace NUnit.Util
{
	/// <summary>
	/// This class allows loading information about
	/// configurations and assemblies in a Visual
	/// Studio project file and inspecting them.
	/// Only the most common project types are
	/// supported and an exception is thrown if
	/// an attempt is made to load an invalid
	/// file or one of an unknown type.
	/// </summary>
	public class VSProject
	{
		#region Static and Instance Variables

		/// <summary>
		/// VS Project extentions
		/// </summary>
		private static readonly string[] validExtensions = { ".csproj", ".vbproj", ".vjsproj", ".vcproj" };

		/// <summary>
		/// VS Solution extension
		/// </summary>
		private static readonly string solutionExtension = ".sln";

		/// <summary>
		/// Path to the file storing this project
		/// </summary>
		private string projectPath;

		/// <summary>
		/// Collection of configs for the project
		/// </summary>
		private VSProjectConfigCollection configs;

		#endregion

		#region Constructor

		public VSProject( string projectPath )
		{
			this.projectPath = Path.GetFullPath( projectPath );
			configs = new VSProjectConfigCollection();

			Load();
		}

		#endregion

		#region Properties

		/// <summary>
		/// The name of the project.
		/// </summary>
		public string Name
		{
			get { return Path.GetFileNameWithoutExtension( projectPath ); }
		}

		/// <summary>
		/// The path to the project
		/// </summary>
		public string ProjectPath
		{
			get { return projectPath; }
		}

		/// <summary>
		/// Our collection of configurations
		/// </summary>
		public VSProjectConfigCollection Configs
		{
			get { return configs; }
		}

		#endregion

		#region Static Methods

		public static bool IsProjectFile( string path )
		{
			string extension = Path.GetExtension( path );

			foreach( string validExtension in validExtensions )
				if ( extension == validExtension )
					return true;

			return false;
		}

		public static bool IsSolutionFile( string path )
		{
			return Path.GetExtension( path ) == solutionExtension;
		}

		#endregion

		#region Instance Methods

		public void Load()
		{
			if ( !IsProjectFile( projectPath ) )
				ThrowInvalidFileType( projectPath );

			string projectDirectory = Path.GetFullPath( Path.GetDirectoryName( projectPath ) );

			try
			{
				XmlDocument doc = new XmlDocument();
				doc.Load( projectPath );

				string extension = Path.GetExtension( projectPath );
				string assemblyName;

				switch ( extension )
				{
					case ".vcproj":
						foreach ( XmlNode configNode in doc.SelectNodes( "/VisualStudioProject/Configurations/Configuration" ) )
						{
							string name = configNode.Attributes["Name"].Value;
							string outputPath = configNode.Attributes["OutputDirectory"].Value;
							string outputDirectory = Path.Combine( projectDirectory, outputPath );
							XmlNode toolNode = configNode.SelectSingleNode( "Tool[@Name='VCLinkerTool']" );
							assemblyName = Path.GetFileName( toolNode.Attributes["OutputFile"].Value );
							string assemblyPath = Path.Combine( outputDirectory, assemblyName );

							VSProjectConfig config = new VSProjectConfig ( name );
							config.Assemblies.Add( assemblyPath );

							this.configs.Add( config );
						}

						break;

					case ".csproj":
					case ".vbproj":
					case ".vjsproj":
						XmlNode settingsNode = doc.SelectSingleNode( "/VisualStudioProject/*/Build/Settings" );

						assemblyName = settingsNode.Attributes["AssemblyName"].Value;
						string outputType = settingsNode.Attributes["OutputType"].Value;

						if ( outputType == "Exe" || outputType == "WinExe" )
							assemblyName = assemblyName + ".exe";
						else
							assemblyName = assemblyName + ".dll";

						XmlNodeList nodes = settingsNode.SelectNodes("Config");
						if ( nodes != null )
							foreach ( XmlNode configNode in nodes )
							{
								string name = configNode.Attributes["Name"].Value;
								string outputPath = configNode.Attributes["OutputPath"].Value;
								string outputDirectory = Path.Combine( projectDirectory, outputPath );
								string assemblyPath = Path.Combine( outputDirectory, assemblyName );

								VSProjectConfig config = new VSProjectConfig ( name );
								config.Assemblies.Add( assemblyPath );

								configs.Add( config );
							}

						break;

					default:
						break;
				}
			}
			catch( FileNotFoundException )
			{
				throw;
			}
			catch( Exception e )
			{
				ThrowInvalidFormat( projectPath, e );
			}
		}

		private void ThrowInvalidFileType( string projectPath )
		{
			throw new ArgumentException(
				string.Format( "Invalid project file type: {0}",
								Path.GetFileName( projectPath ) ) );
		}

		private void ThrowInvalidFormat( string projectPath, Exception e )
		{
			throw new ArgumentException(
				string.Format( "Invalid project file format: {0}",
								Path.GetFileName( projectPath ) ), e );
		}

		#endregion
	}
}


text:
import { EntityMetadata } from "../metadata/EntityMetadata";
import { FindManyOptions } from "../find-options/FindManyOptions";
import { ObjectLiteral } from "../common/ObjectLiteral";
import { FindOneOptions } from "../find-options/FindOneOptions";
import { DeepPartial } from "../common/DeepPartial";
import { SaveOptions } from "./SaveOptions";
import { RemoveOptions } from "./RemoveOptions";
import { EntityManager } from "../entity-manager/EntityManager";
import { QueryRunner } from "../query-runner/QueryRunner";
import { SelectQueryBuilder } from "../query-builder/SelectQueryBuilder";
/**
 * Repository is supposed to work with your entity objects. Find entities, insert, update, delete, etc.
 */
export declare class Repository<Entity extends ObjectLiteral> {
    /**
     * Entity Manager used by this repository.
     */
    readonly manager: EntityManager;
    /**
     * Entity metadata of the entity current repository manages.
     */
    readonly metadata: EntityMetadata;
    /**
     * Query runner provider used for this repository.
     */
    readonly queryRunner?: QueryRunner;
    /**
     * Creates a new query builder that can be used to build a sql query.
     */
    createQueryBuilder(alias?: string, queryRunner?: QueryRunner): SelectQueryBuilder<Entity>;
    /**
     * Returns object that is managed by this repository.
     * If this repository manages entity from schema,
     * then it returns a name of that schema instead.
     */
    readonly target: Function | string;
    /**
     * Checks if entity has an id.
     * If entity composite compose ids, it will check them all.
     */
    hasId(entity: Entity): boolean;
    /**
     * Gets entity mixed id.
     */
    getId(entity: Entity): any;
    /**
     * Creates a new entity instance.
     */
    create(): Entity;
    /**
     * Creates a new entities and copies all entity properties from given objects into their new entities.
     * Note that it copies only properties that present in entity schema.
     */
    create(entityLikeArray: DeepPartial<Entity>[]): Entity[];
    /**
     * Creates a new entity instance and copies all entity properties from this object into a new entity.
     * Note that it copies only properties that present in entity schema.
     */
    create(entityLike: DeepPartial<Entity>): Entity;
    /**
     * Merges multiple entities (or entity-like objects) into a given entity.
     */
    merge(mergeIntoEntity: Entity, ...entityLikes: DeepPartial<Entity>[]): Entity;
    /**
     * Creates a new entity from the given plan javascript object. If entity already exist in the database, then
     * it loads it (and everything related to it), replaces all values with the new ones from the given object
     * and returns this new entity. This new entity is actually a loaded from the db entity with all properties
     * replaced from the new object.
     *
     * Note that given entity-like object must have an entity id / primary key to find entity by.
     * Returns undefined if entity with given id was not found.
     */
    preload(entityLike: DeepPartial<Entity>): Promise<Entity | undefined>;
    /**
     * Saves all given entities in the database.
     * If entities do not exist in the database then inserts, otherwise updates.
     */
    save<T extends DeepPartial<Entity>>(entities: T[], options?: SaveOptions): Promise<T[]>;
    /**
     * Saves a given entity in the database.
     * If entity does not exist in the database then inserts, otherwise updates.
     */
    save<T extends DeepPartial<Entity>>(entity: T, options?: SaveOptions): Promise<T>;
    /**
     * Inserts a given entity into the database.
     * Unlike save method executes a primitive operation without cascades, relations and other operations included.
     * Does not modify source entity and does not execute listeners and subscribers.
     * Executes fast and efficient INSERT query.
     * Does not check if entity exist in the database, so query will fail if duplicate entity is being inserted.
     */
    insert(entity: Partial<Entity> | Partial<Entity>[], options?: SaveOptions): Promise<void>;
    /**
     * Updates entity partially. Entity can be found by a given conditions.
     */
    update(conditions: Partial<Entity>, partialEntity: DeepPartial<Entity>, options?: SaveOptions): Promise<void>;
    /**
     * Updates entity partially. Entity will be found by a given id.
     */
    updateById(id: any, partialEntity: DeepPartial<Entity>, options?: SaveOptions): Promise<void>;
    /**
     * Removes a given entities from the database.
     */
    remove(entities: Entity[], options?: RemoveOptions): Promise<Entity[]>;
    /**
     * Removes a given entity from the database.
     */
    remove(entity: Entity, options?: RemoveOptions): Promise<Entity>;
    /**
     * Deletes entities by a given conditions.
     * Unlike save method executes a primitive operation without cascades, relations and other operations included.
     * Does not modify source entity and does not execute listeners and subscribers.
     * Executes fast and efficient DELETE query.
     * Does not check if entity exist in the database.
     */
    delete(conditions: Partial<Entity>, options?: RemoveOptions): Promise<void>;
    /**
     * Deletes entities by a given conditions.
     * Unlike save method executes a primitive operation without cascades, relations and other operations included.
     * Does not modify source entity and does not execute listeners and subscribers.
     * Executes fast and efficient DELETE query.
     * Does not check if entity exist in the database.
     */
    deleteById(id: any, options?: RemoveOptions): Promise<void>;
    /**
     * Removes entity by a given entity id.
     *
     * @deprecated use deleteById method instead.
     */
    removeById(id: any, options?: RemoveOptions): Promise<void>;
    /**
     * Removes entity by a given entity id.
     *
     * @deprecated use deleteById method instead.
     */
    removeByIds(ids: any[], options?: RemoveOptions): Promise<void>;
    /**
     * Counts entities that match given options.
     */
    count(options?: FindManyOptions<Entity>): Promise<number>;
    /**
     * Counts entities that match given conditions.
     */
    count(conditions?: DeepPartial<Entity>): Promise<number>;
    /**
     * Finds entities that match given options.
     */
    find(options?: FindManyOptions<Entity>): Promise<Entity[]>;
    /**
     * Finds entities that match given conditions.
     */
    find(conditions?: DeepPartial<Entity>): Promise<Entity[]>;
    /**
     * Finds entities that match given find options.
     * Also counts all entities that match given conditions,
     * but ignores pagination settings (from and take options).
     */
    findAndCount(options?: FindManyOptions<Entity>): Promise<[Entity[], number]>;
    /**
     * Finds entities that match given conditions.
     * Also counts all entities that match given conditions,
     * but ignores pagination settings (from and take options).
     */
    findAndCount(conditions?: DeepPartial<Entity>): Promise<[Entity[], number]>;
    /**
     * Finds entities by ids.
     * Optionally find options can be applied.
     */
    findByIds(ids: any[], options?: FindManyOptions<Entity>): Promise<Entity[]>;
    /**
     * Finds entities by ids.
     * Optionally conditions can be applied.
     */
    findByIds(ids: any[], conditions?: DeepPartial<Entity>): Promise<Entity[]>;
    /**
     * Finds first entity that matches given options.
     */
    findOne(options?: FindOneOptions<Entity>): Promise<Entity | undefined>;
    /**
     * Finds first entity that matches given conditions.
     */
    findOne(conditions?: DeepPartial<Entity>): Promise<Entity | undefined>;
    /**
     * Finds entity by given id.
     * Optionally find options can be applied.
     */
    findOneById(id: any, options?: FindOneOptions<Entity>): Promise<Entity | undefined>;
    /**
     * Finds entity by given id.
     * Optionally conditions can be applied.
     */
    findOneById(id: any, conditions?: DeepPartial<Entity>): Promise<Entity | undefined>;
    /**
     * Executes a raw SQL query and returns a raw database results.
     * Raw query execution is supported only by relational databases (MongoDB is not supported).
     */
    query(query: string, parameters?: any[]): Promise<any>;
    /**
     * Clears all the data from the given table/collection (truncates/drops it).
     *
     * Note: this method uses TRUNCATE and may not work as you expect in transactions on some platforms.
     * @see https://stackoverflow.com/a/5972738/925151
     */
    clear(): Promise<void>;
}


text:
/* $Id$ */

package org.apache.fop.fo.flow.table;

import java.util.List;

/**
 * A class dedicated to the resolution of borders in tables. It receives a series of
 * events as the table is parsed and performs border resolution accordingly.
 */
interface BorderResolver {

    /**
     * Receives notification of the end of a row.
     *
     * @param row the row that has just been finished
     * @param container the FO element holding the given row
     */
    void endRow(List<GridUnit> row, TableCellContainer container);

    /**
     * Receives notification of the start of a table-header/footer/body.
     *
     * @param part the part that has started
     */
    void startPart(TablePart part);

    /**
     * Receives notification of the end of a table-header/footer/body.
     */
    void endPart();

    /**
     * Receives notification of the end of the table.
     */
    void endTable();
}


text:
/**
 *
 * Project Name:myweb-service
 * File Name:MenuServiceImpl.java
 * Package Name:com.fancy.menu.service.impl
 * Date:2015-7-24
 *
 */

package cn.telling.menu.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.telling.menu.dao.IMenuDao;
import cn.telling.menu.service.IMenuService;
import cn.telling.menu.vo.Menu;
import cn.telling.role.dao.IRoleDao;
import cn.telling.role.vo.Role;

/**
 * ClassName:MenuServiceImpl <br/>
 *
 * @author caosheng
 */
@Service
public class MenuServiceImpl implements IMenuService {

	@Autowired
	private IMenuDao menuDao;

	@Autowired
	private IRoleDao roleDao;

	public List<Menu> findMenuByUserId(String userid) {

		return menuDao.findMenuByUserId(userid);
	}

	public List<Menu> findAllMenuByUserId(String userId) throws Exception {
		if (userId == null) {
			return null;
		}

		List<Role> roles = roleDao.queryRoleByUserId(userId);
		if (CollectionUtils.isEmpty(roles)) {
			return null;
		}
		List<Menu> list = new ArrayList<Menu>();
		for (Role role : roles) {
			List<Menu> menus = menuDao.queryMenuByRoleId(role.getId());
			if (CollectionUtils.isEmpty(menus)) {
				continue;
			}
			list.addAll(menus);
		}

		return list;

	}

	/*
	 * (non-Javadoc)
	 *
	 * @see cn.telling.menu.service.IMenuService#getById(java.lang.BigDecimal)
	 */
	@Override
	public Menu getById(BigDecimal menupId) {
		return menuDao.getById(menupId);
	}

    /* (non-Javadoc)
     * @see cn.telling.menu.service.IMenuService#findMenus(java.lang.String)
     */
    @Override
    public List<Menu> findMenus(String mname) {
        return menuDao.findMenus(mname);
    }

    public Menu getPmById(BigDecimal id)
    {
        return menuDao.getPmById(id);

    }

	/* (non-Javadoc)
	 * @see cn.telling.menu.service.IMenuService#findMenuByRoleId(java.lang.Integer)
	 */
	@Override
	public List<Menu> findMenuByRoleId(Integer id) {
		//  Auto-generated method stub
		if (id == null) {
			return new ArrayList<Menu>();
		}
		return menuDao.findMenuByRoleId(id);
	}

	/* (non-Javadoc)
	 * @see cn.telling.menu.service.IMenuService#getPusMenuList()
	 */
	@Override
	public List<Menu> getPusMenuList() {
		//  Auto-generated method stub
		return menuDao.getPusMenuList();
	}

	/* (non-Javadoc)
	 * @see cn.telling.menu.service.IMenuService#batchDelete(java.lang.Integer)
	 */
	@Override
	public void batchDelete(Integer roleid) {
		menuDao.batchDelete(roleid);

	}
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.IO;
using System.Net.Test.Common;
using System.Security.Authentication;
using System.Threading.Tasks;

using Xunit;

namespace System.Net.Security.Tests
{
    public class SslStreamAllowedProtocolsTest
    {
        [Theory]
        [ClassData(typeof(SslProtocolSupport.UnsupportedSslProtocolsTestData))]
        public async Task SslStream_AuthenticateAsClient_NotSupported_Fails(SslProtocols protocol)
        {
            SslStream stream = new SslStream(new FakeStream());
            await Assert.ThrowsAsync<NotSupportedException>(
                () => stream.AuthenticateAsClientAsync("host", null, protocol, false));
        }

        [Theory]
        [ClassData(typeof(SslProtocolSupport.SupportedSslProtocolsTestData))]
        public async Task SslStream_AuthenticateAsClient_Supported_Success(SslProtocols protocol)
        {
            SslStream stream = new SslStream(new FakeStream());
            await stream.AuthenticateAsClientAsync("host", null, protocol, false);
        }

        [Fact]
        public async Task SslStream_AuthenticateAsClient_Invalid_Fails()
        {
            SslStream stream = new SslStream(new FakeStream());
            await Assert.ThrowsAsync<NotSupportedException>(
                () => stream.AuthenticateAsClientAsync("host", null, (SslProtocols)4096, false));
        }

        [Fact]
        public async Task SslStream_AuthenticateAsClient_AllUnsuported_Fails()
        {
            SslStream stream = new SslStream(new FakeStream());
            await Assert.ThrowsAsync<NotSupportedException>(
                () => stream.AuthenticateAsClientAsync(
                    "host",
                    null,
                    SslProtocolSupport.UnsupportedSslProtocols,
                    false));
        }

        [Fact]
        public async Task SslStream_AuthenticateAsClient_AllSupported_Success()
        {
            SslStream stream = new SslStream(new FakeStream());
            await stream.AuthenticateAsClientAsync(
                "host",
                null,
                SslProtocolSupport.SupportedSslProtocols,
                false);
        }

        [Fact]
        public async Task SslStream_AuthenticateAsClient_None_Success()
        {
            SslStream stream = new SslStream(new FakeStream());
            await stream.AuthenticateAsClientAsync("host", null, SslProtocols.None, false);
        }

        [Fact]
        public async Task SslStream_AuthenticateAsClient_Default_Success()
        {
            SslStream stream = new SslStream(new FakeStream());
            await stream.AuthenticateAsClientAsync("host", null, SslProtocolSupport.DefaultSslProtocols, false);
        }

        private class FakeStream : Stream
        {
            public override bool CanRead
            {
                get
                {
                    throw new NotImplementedException();
                }
            }

            public override bool CanSeek
            {
                get
                {
                    throw new NotImplementedException();
                }
            }

            public override bool CanWrite
            {
                get
                {
                    throw new NotImplementedException();
                }
            }

            public override long Length
            {
                get
                {
                    throw new NotImplementedException();
                }
            }

            public override long Position
            {
                get
                {
                    throw new NotImplementedException();
                }

                set
                {
                    throw new NotImplementedException();
                }
            }

            public override void Flush()
            {
                throw new NotImplementedException();
            }

            public override int Read(byte[] buffer, int offset, int count)
            {
                throw new NotImplementedException();
            }

            public override long Seek(long offset, SeekOrigin origin)
            {
                throw new NotImplementedException();
            }

            public override void SetLength(long value)
            {
                throw new NotImplementedException();
            }

            public override void Write(byte[] buffer, int offset, int count)
            {
                throw new NotImplementedException();
            }
        }
    }

}


text:
package specs

import "os"

// CurrentVersion is the current version of the Spec.
const CurrentVersion = "0.5.0"

// Spec is the base configuration for CDI
type Spec struct {
	Version string `json:"cdiVersion"`
	Kind    string `json:"kind"`

	Devices        []Device       `json:"devices"`
	ContainerEdits ContainerEdits `json:"containerEdits,omitempty"`
}

// Device is a "Device" a container runtime can add to a container
type Device struct {
	Name           string         `json:"name"`
	ContainerEdits ContainerEdits `json:"containerEdits"`
}

// ContainerEdits are edits a container runtime must make to the OCI spec to expose the device.
type ContainerEdits struct {
	Env         []string      `json:"env,omitempty"`
	DeviceNodes []*DeviceNode `json:"deviceNodes,omitempty"`
	Hooks       []*Hook       `json:"hooks,omitempty"`
	Mounts      []*Mount      `json:"mounts,omitempty"`
}

// DeviceNode represents a device node that needs to be added to the OCI spec.
type DeviceNode struct {
	Path        string       `json:"path"`
	HostPath    string       `json:"hostPath,omitempty"`
	Type        string       `json:"type,omitempty"`
	Major       int64        `json:"major,omitempty"`
	Minor       int64        `json:"minor,omitempty"`
	FileMode    *os.FileMode `json:"fileMode,omitempty"`
	Permissions string       `json:"permissions,omitempty"`
	UID         *uint32      `json:"uid,omitempty"`
	GID         *uint32      `json:"gid,omitempty"`
}

// Mount represents a mount that needs to be added to the OCI spec.
type Mount struct {
	HostPath      string   `json:"hostPath"`
	ContainerPath string   `json:"containerPath"`
	Options       []string `json:"options,omitempty"`
	Type          string   `json:"type,omitempty"`
}

// Hook represents a hook that needs to be added to the OCI spec.
type Hook struct {
	HookName string   `json:"hookName"`
	Path     string   `json:"path"`
	Args     []string `json:"args,omitempty"`
	Env      []string `json:"env,omitempty"`
	Timeout  *int     `json:"timeout,omitempty"`
}


text:
This app is designed for the adventurer in all of us. Whether you want to get out and have a locals provided tour, or take in an exciting interactive experience you're just a few clicks away from taking part in an exciting adventure.

## Summary ##

The user is navigated to 'crumbs' along a trail of their choosing. At each crumb the user is presented with various media left by the creator of the trail, or 'crumblayer'. Crumb media can be anything from text, images, or even augmented reality! This allows the crumblayer to craft unique trails, using videos, sounds, or virtual drawing to provide the client with an interactive experience.
This benefits multiple business avenues like the tourism industry, local musicians, theatre troupes, or even a user who wants to provide a romantic memory for their significant other.

## Problem ##
This product solves an issue which is coming about with the commercialization of tourism. Many facets are sterilized and lacking flavor, this allows for an exciting and interactive experience. With user planned routes the locals become the tour guides.

## Solution ##
Providing an easy to use interface which can provide the user with content that has a special flavor that cannot be found with simply visiting a location.

## How to Get Started ##
To get started just download the app, pick an experience, and you're off!

## Customer Quote ##
> This app was so much fun, we got to visit local landmarks and hear history lessons, see secrets left by other users, and took part in a story which had me totally engrossed, I couldn't wait to get to the next part of the story.

## Closing  ##
We are providing an interactive experience between content providers and clients. Giving the provider an assortment of options to guide the user through an interaction which can be educational, fun or general tourism. This will require a complex database of locational and content related storage, a well planned out interface and virtual augmentation to provide the user with a fully immersive experience.


text:
(function foo() {
    alert("Hello World");
})();


text:
/*--------------------------------------------------------*\
|                                                          |
|                          hprose                          |
|                                                          |
| Official WebSite: https://hprose.com                     |
|                                                          |
|  WeightedLoadBalance.cs                                  |
|                                                          |
|  Weighted LoadBalance plugin for C#.                     |
|                                                          |
|  LastModified: Apr 26, 2019                              |
|  Author: Ma Bingyao <andot@hprose.com>                   |
|                                                          |
\*________________________________________________________*/

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;

namespace Hprose.RPC.Plugins.LoadBalance {
    public abstract class WeightedLoadBalance {
        protected readonly Uri[] uris;
        protected readonly int[] weights;
        public WeightedLoadBalance(IDictionary<string, int> uriList) {
            if (uriList == null) {
                throw new ArgumentNullException(nameof(uriList));
            }
            var n = uriList.Count;
            uris = new Uri[n];
            weights = new int[n];
            var i = 0;
            foreach (var pair in uriList) {
                uris[i] = new Uri(pair.Key);
                weights[i] = pair.Value;
                if (weights[i] <= 0) {
                    throw new ArgumentOutOfRangeException(nameof(uriList), "weight must be great than 0");
                }
                i++;
            }
            if (uris.Length == 0) {
                throw new ArgumentException("cannot be empty", nameof(uriList));
            }
        }
        public abstract Task<Stream> Handler(Stream request, Context context, NextIOHandler next);
    }
}


text:
import ext from 'jquery-extend';
import { devices, actions } from '../../constants';
import {
  completelyFilledOut, formValidator, isFormValid
} from './create/validations';

const {
  UPDATE_FORM,
  INLINE_VALIDATE_ALL_FIELDS,
  VALIDATE_FIELD,
  UPDATING_URL,
  ERROR_UPDATE_URL,
  SUCCESS_UPDATE_URL,
  CLEAR_VALIDATIONS,
  UPDATE_ACTIVE_DEVICE,
  SHOW_DETAILS_EDIT_FORM,
  CLOSE_DETAILS_EDIT_FORM,
  COPIED_URL,
  CLEAR_COPIED_URL,
} = actions;

export const initialFormState = {

  url: null,
  selected_device: devices.DESKTOP,

  creating_url: false,
  success_create_url: false,
  error_create_url: false,
  form_active: false,

  valid: false,
  filled_out: false,
  complete: false,

};

export function shortener_details_form(state=initialFormState, action) {

  if (action.type.match('SUCCESS_UPDATE_URL')) {
    return  ext({}, state, {
      form_active: false
    });
  }
  switch(action.type) {
    case SHOW_DETAILS_EDIT_FORM:
      return  ext({}, state, { url: action.data.url, form_active: true });
    case CLOSE_DETAILS_EDIT_FORM:
      return  ext({}, state, { url: null, form_active: false });
    case UPDATE_ACTIVE_DEVICE:
      return ext({}, state, action.data);
    case UPDATING_URL:
      return ext({}, state, { creating_account: true, });
    case SUCCESS_UPDATE_URL:
      state.url.devices
      return ext({}, state, action.data, {

      });
    case UPDATE_FORM:
      const newState = ext({}, state, action.data);
      newState.valid = isFormValid(newState);
      return newState;
    default:
      return state;
  }
}

export function copied_url(state={
  active: false,
}, action) {
  switch(action.type) {
    case COPIED_URL:
      return { active: true };
    case CLEAR_COPIED_URL:
      return { active: false };
    default:
      return state;
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for DieuKienChamCongDacBietController
/// </summary>
public class DieuKienChamCongDacBietController:LinqProvider
{
	public DieuKienChamCongDacBietController()
	{
		//
		// TODO: Add constructor logic here
		//
	}
    public DAL.DanhSachNhanVienChamCongDacBiet GetByID(int id)
    {
        return dataContext.DanhSachNhanVienChamCongDacBiets.Where(p => p.ID == id).SingleOrDefault();
    }
    public void Update(DAL.DanhSachNhanVienChamCongDacBiet  chamcongdacbiet)
    {
        var item = dataContext.DanhSachNhanVienChamCongDacBiets.Where(p => p.ID == chamcongdacbiet.ID).SingleOrDefault();
        item.SoLanChitTay = chamcongdacbiet.SoLanChitTay;
        Save();
    }
    public void Insert(DAL.DanhSachNhanVienChamCongDacBiet chamcongdacbiet)
    {
        dataContext.DanhSachNhanVienChamCongDacBiets.InsertOnSubmit(chamcongdacbiet);
        Save();
    }

    public List<DAL.DanhSachNhanVienChamCongDacBiet> GetByAll()
    {
        var rs = from t in dataContext.DanhSachNhanVienChamCongDacBiets
                 select t;
        return rs.ToList();
    }
}


text:
<!DOCTYPE html>

<input type="time" id="input" value="01:01:01">


text:
node-red-node-ledborg
=====================

A Node-RED node to control a PiBorg LedBorg baord for a Raspberry Pi.

Install
-------

Run the following command in the root directory of your Node-RED install

    npm install node-red-node-ledborg

Usage
-----

A PiBorg LedBorg LED output node that expects a msg.payload with a three digit rgb triple, from 000 to 222. I.E. there are only 27 possible colours.

See the PiBorg site for more information.

You can also now use a msg.payload in the standard hex format "#rrggbb". The clip levels are :

>
0x00 - 0x57 = off
0x58 - 0xA7 = 50%
0xA8 - 0xFF = fully on

You can also use the @cheerlight colour names - red, amber, green, blue, cyan, magenta, yellow, orange, pink, purple, white, warmwhite, black


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dependencyinjection.Features.Default;
import dependencyinjection.MVC.IDelegate;
import dependencyinjection.MVC.IView;
import java.io.*;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
 *
 * @author david
 */
public class View implements IView {

    public IDelegate delegate = null;

   @Override
   public String getName() {
        return name;
    }

    @Override
    public void display() {
        //System.out.println("view View is displayed");
        InputStreamReader in = new InputStreamReader(System.in);
        BufferedReader reader = new BufferedReader(in);
        try {
            System.out.print("Please enter your name.\nName: ");
            String line = reader.readLine();
            this.delegate.getNameFromConsole(line);
        } catch (IOException ex) {
            Logger.getLogger(View.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    @Override
    public void viewWillAppear() {
        System.out.println("view viewWillAppear");
    }

    @Override
    public void viewDidAppear() {
        System.out.println("view viewDidAppear");
    }

}


text:
ALTER TABLE `scitm`.`courses`
ADD COLUMN `course_no` INT NOT NULL AFTER `Description`;
UPDATE `scitm`.`courses` SET `course_no`='100' WHERE `course_id`='1';
UPDATE `scitm`.`courses` SET `course_no`='101' WHERE `course_id`='2';
UPDATE `scitm`.`courses` SET `course_no`='102' WHERE `course_id`='3';
UPDATE `scitm`.`courses` SET `course_no`='200' WHERE `course_id`='4';
UPDATE `scitm`.`courses` SET `course_no`='201' WHERE `course_id`='5';
UPDATE `scitm`.`courses` SET `course_no`='202' WHERE `course_id`='6';
UPDATE `scitm`.`courses` SET `course_no`='203' WHERE `course_id`='7';
UPDATE `scitm`.`courses` SET `course_no`='204' WHERE `course_id`='8';
UPDATE `scitm`.`courses` SET `course_no`='205' WHERE `course_id`='9';
UPDATE `scitm`.`courses` SET `course_no`='300' WHERE `course_id`='10';
UPDATE `scitm`.`courses` SET `course_no`='206' WHERE `course_id`='11';
ALTER TABLE `scitm`.`student_course`
ADD COLUMN `applicant_id` INT NOT NULL AFTER `reg_date`;
ALTER TABLE `scitm`.`student_course`
CHANGE COLUMN `student_id` `student_id` VARCHAR(255) NOT NULL ,
CHANGE COLUMN `course_id` `course_id` VARCHAR(255) NOT NULL ;
ALTER TABLE `scitm`.`student_course`
CHANGE COLUMN `applicant_id` `applicant_id` INT(11) NOT NULL ,
ADD UNIQUE INDEX `applicant_id_UNIQUE` (`applicant_id` ASC);
ALTER TABLE `scitm`.`student_course`
ADD UNIQUE INDEX `student_id_UNIQUE` (`student_id` ASC);
ALTER TABLE `application_approvals` CHANGE `status` `status` BOOLEAN NULL DEFAULT FALSE;