text:
using SteamKit2;
using SteamKit2X.Exceptions;
using System;
using System.Diagnostics;
using System.Threading;
// SteamKit2 Callbacks
using AccountInfoCallback       = SteamKit2.SteamUser.AccountInfoCallback;
using ChatActionResultCallback  = SteamKit2.SteamFriends.ChatActionResultCallback;
using ChatEnterCallback         = SteamKit2.SteamFriends.ChatEnterCallback;
using ChatInviteCallback        = SteamKit2.SteamFriends.ChatInviteCallback;
using ChatMemberInfoCallback    = SteamKit2.SteamFriends.ChatMemberInfoCallback;
using ChatMsgCallback           = SteamKit2.SteamFriends.ChatMsgCallback;
using ClanStateCallback         = SteamKit2.SteamFriends.ClanStateCallback;
using CMListCallback            = SteamKit2.SteamClient.CMListCallback;
using ConnectedCallback         = SteamKit2.SteamClient.ConnectedCallback;
using DisconnectedCallback      = SteamKit2.SteamClient.DisconnectedCallback;
using FriendAddedCallback       = SteamKit2.SteamFriends.FriendAddedCallback;
using FriendMsgCallback         = SteamKit2.SteamFriends.FriendMsgCallback;
using FriendsListCallback       = SteamKit2.SteamFriends.FriendsListCallback;
using IgnoreFriendCallback      = SteamKit2.SteamFriends.IgnoreFriendCallback;
using LoggedOffCallback         = SteamKit2.SteamUser.LoggedOffCallback;
using LoggedOnCallback          = SteamKit2.SteamUser.LoggedOnCallback;
using MarketingMessageCallback  = SteamKit2.SteamUser.MarketingMessageCallback;
using PersonaStateCallback      = SteamKit2.SteamFriends.PersonaStateCallback;
using ProfileInfoCallback       = SteamKit2.SteamFriends.ProfileInfoCallback;
using ServerListCallback        = SteamKit2.SteamClient.ServerListCallback;
using SessionTokenCallback      = SteamKit2.SteamUser.SessionTokenCallback;
using UpdateMachineAuthCallback = SteamKit2.SteamUser.UpdateMachineAuthCallback;
using WalletInfoCallback        = SteamKit2.SteamUser.WalletInfoCallback;
using WebAPIUserNonceCallback   = SteamKit2.SteamUser.WebAPIUserNonceCallback;

namespace SteamKit2X.Managing
{
    /// <summary>
    /// The base class is responsible for the connection to the Steam network. (Not thread-safe!)
    /// </summary>
    /// <remarks>This class is NOT thread-safe!</remarks>
    public abstract partial class ManagerBase
    {
        /// <summary>
        /// Indicates whether the manager thread is running or not.
        /// </summary>
        protected bool IsRunning { get; set; }

        /// <summary>
        /// The manager thread.
        /// </summary>
        private Thread managerThread;

        /// <summary>
        /// Indicates whether or not the resources have been disposed.
        /// </summary>
        protected bool Disposed { get; private set; }

        /// <summary>
        /// Creates a new manager base.
        /// </summary>
        protected ManagerBase()
        {
            IsRunning = false;
            Disposed = true; // The resources are not yet set, so they are disposed.
        }

        /// <summary>
        /// Start the manager thread.
        /// </summary>
        /// <exception cref="SteamKit2X.Exceptions.ManagerRunningException"/>
        protected void Start()
        {
            // Ensure the manager thread is not already running.
            if (managerThread != null || IsRunning)
                throw new ManagerRunningException("The manager thread is already running.");

            // When the resource have not been disposed, dispose them now.
            if (!Disposed)
                Dispose();
            Disposed = false;

            // Create and start the thread.
            managerThread = new Thread(() => Run());
            managerThread.Name = "Manager Thread";
            managerThread.Start();
        }

        /// <summary>
        /// This is the actual thread method.
        /// </summary>
        private void Run()
        {
            try
            {
                // Indicates the manager thread is running.
                IsRunning = true;

                // First initialize all the variables.
                Initialize();

                // Do the actual work.
                DoWork();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
            finally
            {
                // Release all the used resources.
                Dispose();
            }

#if DEBUG
            // Give a message so we know it has quited.
            Debug.WriteLine("Manager thread quited!");
#endif
        }

        /// <summary>
        /// Initialize for a new execution.
        /// </summary>
        private void Initialize()
        {
            // SteamKit2
            steamClient = new SteamClient();
            callbackManager = new CallbackManager(steamClient);
            steamUser = steamClient.GetHandler<SteamUser>();
            steamFriends = steamClient.GetHandler<SteamFriends>();

            // Class critical, do not allow override!
            callbackManager.Register(new Callback<DisconnectedCallback>(Disconnected));

            // Register the overridable callbacks
            {
                #region SteamClient
                callbackManager.Register(new Callback<CMListCallback>(OnCMList));
                callbackManager.Register(new Callback<ConnectedCallback>(OnConnected));
                callbackManager.Register(new Callback<DisconnectedCallback>(OnDisconnected));
                callbackManager.Register(new Callback<ServerListCallback>(OnServerList));
                #endregion // SteamClient

                #region SteamFriends
                callbackManager.Register(new Callback<ChatActionResultCallback>(OnChatActionResult));
                callbackManager.Register(new Callback<ChatEnterCallback>(OnChatEnter));
                callbackManager.Register(new Callback<ChatInviteCallback>(OnChatInvite));
                callbackManager.Register(new Callback<ChatMemberInfoCallback>(OnChatMemberInfo));
                callbackManager.Register(new Callback<ChatMsgCallback>(OnChatMsg));
                callbackManager.Register(new Callback<ClanStateCallback>(OnClanState));
                callbackManager.Register(new Callback<FriendAddedCallback>(OnFriendAdded));
                callbackManager.Register(new Callback<FriendMsgCallback>(OnFriendMsg));
                callbackManager.Register(new Callback<FriendsListCallback>(OnFriendsList));
                callbackManager.Register(new Callback<IgnoreFriendCallback>(OnIgnoreFriend));
                callbackManager.Register(new Callback<PersonaStateCallback>(OnPersonaState));
                callbackManager.Register(new Callback<ProfileInfoCallback>(OnProfileInfo));
                #endregion // SteamFriends

                #region SteamUser
                callbackManager.Register(new Callback<AccountInfoCallback>(OnAccountInfo));
                callbackManager.Register(new Callback<LoggedOffCallback>(OnLoggedOff));
                callbackManager.Register(new Callback<LoggedOnCallback>(OnLoggedOn));
                callbackManager.Register(new Callback<MarketingMessageCallback>(OnMarketingMessage));
                callbackManager.Register(new Callback<SessionTokenCallback>(OnSessionToken));
                callbackManager.Register(new Callback<UpdateMachineAuthCallback>(OnUpdateMachineAuth));
                callbackManager.Register(new Callback<WalletInfoCallback>(OnWalletInfo));
                callbackManager.Register(new Callback<WebAPIUserNonceCallback>(OnWebAPIUserNonce));
                #endregion // SteamUser
            }
        }

        /// <summary>
        /// This does the actual work on the manager thread.
        /// </summary>
        private void DoWork()
        {
            // Connect to the Steam network.
            steamClient.Connect();

            do
            {
                // Wait 1 second between receiving callbacks.
                callbackManager.RunWaitCallbacks(TimeSpan.FromSeconds(1));
            }
            while (IsRunning);
        }

        /// <summary>
        /// Dispose of the used resources.
        /// </summary>
        private void Dispose()
        {
            // Notify about the disposed resources.
            Disposed = true;

            // Log the user off.
            steamUser.LogOff();
            steamUser = null;

            // Disconnect from the Steam network.
            steamClient.Disconnect();
            steamClient = null;

            // Release the references to the remaining SteamKit2 objects.
            steamFriends = null;
            callbackManager = null;

            // Release the reference to this thread, it has stopped and change the running state aswell.
            managerThread = null;
        }

        private void Disconnected(DisconnectedCallback callback)
        {
            // When disconnected we should stop listening for callbacks.
            IsRunning = false;
        }

        #region Callbacks

        #region SteamClient

        /// <summary>
        /// Called when the cleint received the CM list from Steam.
        /// </summary>
        /// <param name="callback"></param>
        protected virtual void OnCMList(CMListCallback callback) { }

        /// <summary>
        /// Called when the client has connected to the Steam network.
        /// </summary>
        /// <param name="callback"></param>
        protected virtual void OnConnected(ConnectedCallback callback) { }

        /// <summary>
        /// Called when the client has disconnected from the Steam network.
        /// </summary>
        /// <param name="callback"></param>
        protected virtual void OnDisconnected(DisconnectedCallback callback) { }

        /// <summary>
        /// Called when the client received a list of publically available Steam servers.
        /// </summary>
        /// <remarks>
        /// This may be called multiple times for different lists of servers.
        /// </remarks>
        /// <param name="callback"></param>
        protected virtual void OnServerList(ServerListCallback callback) { }

        #endregion // SteamClient

        #region SteamFriends

        /// <summary>
        /// Called when a chat related action has completed. (kick, ban, new owner, etc.)
        /// </summary>
        /// <param name="callback"></param>
        protected virtual void OnChatActionResult(ChatActionResultCallback callback) { }

        /// <summary>
        /// Called when attempting to join a chat.
        /// </summary>
        /// <param name="callback"></param>
        protected virtual void OnChatEnter(ChatEnterCallback callback) { }

        /// <summary>
        /// Called when a chat invite has been received.
        /// </summary>
        /// <param name="callback"></param>
        protected virtual void OnChatInvite(ChatInviteCallback callback) { }

        /// <summary>
        /// Called when the user information of a chatroom member has been received.
        /// </summary>
        /// <param name="callback"></param>
        protected virtual void OnChatMemberInfo(ChatMemberInfoCallback callback) { }

        /// <summary>
        /// Called when a chatroom message has been received.
        /// </summary>
        /// <param name="callback"></param>
        protected virtual void OnChatMsg(ChatMsgCallback callback) { }

        /// <summary>
        /// Called when the state of a clan has changed.
        /// </summary>
        /// <param name="callback"></param>
        protected virtual void OnClanState(ClanStateCallback callback) { }

        /// <summary>
        /// Called when the client added a friend to the friendslist.
        /// </summary>
        /// <param name="callback"></param>
        protected virtual void OnFriendAdded(FriendAddedCallback callback) { }

        /// <summary>
        /// Called when a message has been received from a friend.
        /// </summary>
        /// <param name="callback"></param>
        protected virtual void OnFriendMsg(FriendMsgCallback callback) { }

        /// <summary>
        /// Called when the friendslist has been received.
        /// </summary>
        /// <param name="callback"></param>
        protected virtual void OnFriendsList(FriendsListCallback callback) { }

        /// <summary>
        /// Called when trying to ignore a friend.
        /// </summary>
        /// <param name="callback"></param>
        protected virtual void OnIgnoreFriend(IgnoreFriendCallback callback) { }

        /// <summary>
        /// Called when the information of a friend has changed.
        /// </summary>
        /// <param name="callback"></param>
        protected virtual void OnPersonaState(PersonaStateCallback callback) { }

        /// <summary>
        /// Called when profile info of an user has been received.
        /// </summary>
        /// <param name="callback"></param>
        protected virtual void OnProfileInfo(ProfileInfoCallback callback) { }

        #endregion // SteamFriends

        #region SteamUser

        /// <summary>
        /// Called when the account information has been received.
        /// </summary>
        /// <remarks>
        /// Regularly this happens shortly after log on.
        /// </remarks>
        /// <param name="callback"></param>
        protected virtual void OnAccountInfo(AccountInfoCallback callback) { }

        /// <summary>
        /// Called when an user attempts to log off the Steam network.
        /// </summary>
        /// <param name="callback"></param>
        protected virtual void OnLoggedOff(LoggedOffCallback callback) { }

        /// <summary>
        /// Called when an user attempts to log on to the Steam network.
        /// </summary>
        /// <param name="callback"></param>
        protected virtual void OnLoggedOn(LoggedOnCallback callback) { }

        /// <summary>
        /// Called when the client received a marketing message update.
        /// </summary>
        /// <param name="callback"></param>
        protected virtual void OnMarketingMessage(MarketingMessageCallback callback) { }

        /// <summary>
        /// Called when the client receives a session token.
        /// The token is used for content downloading that requires authentication.
        /// </summary>
        /// <param name="callback"></param>
        protected virtual void OnSessionToken(SessionTokenCallback callback) { }

        /// <summary>
        /// Called when the local machine's authentication data has to be updated.
        /// </summary>
        /// <param name="callback"></param>
        protected virtual void OnUpdateMachineAuth(UpdateMachineAuthCallback callback) { }

        /// <summary>
        /// Called when wallet information has been received.
        /// </summary>
        /// <param name="callback"></param>
        protected virtual void OnWalletInfo(WalletInfoCallback callback) { }

        /// <summary>
        /// Called when requesting a new WebAPI authentication user nonce.
        /// </summary>
        /// <param name="callback"></param>
        protected virtual void OnWebAPIUserNonce(WebAPIUserNonceCallback callback) { }

        #endregion // SteamUser

        #endregion // Callbacks
    }
}


text:
var map = require('map-obj');
var extend = require('xtend');
var isColor = require('./is-color');
var isLength = require('./is-length');
var normalize = require('./normalize-color');

var WIDTH = /^(thin|medium|thick)$/;
var STYLE = /^(none|hidden|dotted|dashed|solid|double|groove|ridge|inset|outset)$/i;
var KEYWORD = /^(inherit|initial)$/i;

var outline = function(value) {
	var values = normalize(value).split(/\s+/);

	if(values.length > 3) return;
	if (values.length === 1 && KEYWORD.test(values[0])) {
		return {
			'outline-width': values[0],
			'outline-style': values[0],
			'outline-color': values[0]
		};
	}

	var result = {};
	for(var i = 0; i < values.length; i++) {
		var v = values[i];

		if (isLength(v) || WIDTH.test(v)) {
			if(result['outline-width']) return;
			result['outline-width'] = v;
		} else if (STYLE.test(v)) {
			if(result['outline-style']) return;
			result['outline-style'] = v;
		} else if (isColor(v)) {
			if(result['outline-color']) return;
			result['outline-color'] = v;
		} else {
			return;
		}
	};

	return result;
};

module.exports = exports = outline;

redpajama_set_name: RedPajamaGithub


text:
import { Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { HttpErrorResponse, HttpResponse } from '@angular/common/http';
import { Subscription } from 'rxjs';
import { FileUploadExercise } from 'app/entities/file-upload-exercise.model';
import { FileUploadExerciseService } from './file-upload-exercise.service';
import { filter } from 'rxjs/operators';
import { AlertService } from 'app/core/util/alert.service';
import { ExerciseManagementStatisticsDto } from 'app/exercises/shared/statistics/exercise-management-statistics-dto';
import { ExerciseType } from 'app/entities/exercise.model';
import { StatisticsService } from 'app/shared/statistics-graph/statistics.service';
import dayjs from 'dayjs/esm';
import { onError } from 'app/shared/util/global.utils';
import { Course } from 'app/entities/course.model';
import { EventManager } from 'app/core/util/event-manager.service';

@Component({
    selector: 'jhi-file-upload-exercise-detail',
    templateUrl: './file-upload-exercise-detail.component.html',
})
export class FileUploadExerciseDetailComponent implements OnInit, OnDestroy {
    readonly dayjs = dayjs;
    fileUploadExercise: FileUploadExercise;
    isExamExercise: boolean;
    course: Course | undefined;
    private subscription: Subscription;
    private eventSubscriber: Subscription;

    readonly ExerciseType = ExerciseType;
    doughnutStats: ExerciseManagementStatisticsDto;

    constructor(
        private eventManager: EventManager,
        private fileUploadExerciseService: FileUploadExerciseService,
        private route: ActivatedRoute,
        private alertService: AlertService,
        private statisticsService: StatisticsService,
    ) {}

    /**
     * Initializes subscription for file upload exercise
     */
    ngOnInit() {
        // TODO: route determines whether the component is in exam mode
        this.subscription = this.route.params.subscribe((params) => {
            this.load(params['exerciseId']);
        });
        this.registerChangeInFileUploadExercises();
    }

    /**
     * Loads file upload exercise from the server
     * @param exerciseId the id of the file upload exercise
     */
    load(exerciseId: number) {
        // TODO: Use a separate find method for exam exercises containing course, exam, exerciseGroup and exercise id
        this.fileUploadExerciseService
            .find(exerciseId)
            .pipe(filter((res) => !!res.body))
            .subscribe({
                next: (fileUploadExerciseResponse: HttpResponse<FileUploadExercise>) => {
                    this.fileUploadExercise = fileUploadExerciseResponse.body!;
                    this.isExamExercise = this.fileUploadExercise.exerciseGroup !== undefined;
                    this.course = this.isExamExercise ? this.fileUploadExercise.exerciseGroup?.exam?.course : this.fileUploadExercise.course;
                },
                error: (error: HttpErrorResponse) => onError(this.alertService, error),
            });
        this.statisticsService.getExerciseStatistics(exerciseId).subscribe((statistics: ExerciseManagementStatisticsDto) => {
            this.doughnutStats = statistics;
        });
    }

    /**
     * Unsubscribes on component destruction
     */
    ngOnDestroy() {
        this.subscription.unsubscribe();
        this.eventManager.destroy(this.eventSubscriber);
    }

    /**
     * Listens to file upload exercise list modifications
     */
    registerChangeInFileUploadExercises() {
        this.eventSubscriber = this.eventManager.subscribe('fileUploadExerciseListModification', () => this.load(this.fileUploadExercise.id!));
    }
}


text: InTense MediaWiki extension


text:
module RiotApi
  module Model
    class PlayerStatSummary < Base
      attribute :aggregated_stats, Array[RiotApi::Model::Statistic]
      attribute :losses, Integer
      attribute :modify_date, Integer
      attribute :modify_date_str, String
      attribute :player_stat_summary_type, String
      attribute :wins, Integer
    end
  end
end


text:
var Patch = require('../models/patch')
var AssetController = require('./assetController')
var fsPath = require('path')
var assetHelper = require('../models/asset-helper')
var GraphAnalyser = require('../common/graphAnalyser').GraphAnalyser
var helper = require('./controllerHelpers')
var checksum = require('checksum')

function PatchController(patchService, fs) {
	var args = Array.prototype.slice.apply(arguments)
	args.unshift(Patch)
	AssetController.apply(this, args)

	this.graphAnalyser = new GraphAnalyser(fs)
}

PatchController.prototype = Object.create(AssetController.prototype)

PatchController.prototype._makePath = function(req, name) {
	return '/'
		+ req.user.username
		+ '/patches/'
		+ assetHelper.slugify(
			fsPath.basename(name, fsPath.extname(name)))
}

PatchController.prototype._makeGridFsPath = function(req, path) {
	return this._makePath(req, path) + '.json'
}

// POST /:username/patches
PatchController.prototype.save = function(req, res, next) {
	var that = this
	var path = this._makePath(req, req.body.name)
	var patchHash = checksum(req.body.graph)
	var gridFsPath = this._makeGridFsPath(req, req.body.name+'-'+patchHash)

	var tags = that._parseTags(req.body.tags)

	this._service.canWrite(req.user, path)
	.then(function(can) {
		if (!can) {
			return res.status(403)
				.json(helper.responseStatusError('Sorry, permission denied'))
		}

		return that.graphAnalyser.analyseJson(req.body.graph)
		.then(function(stat) {
			if (!stat.numNodes) {
				return res.status(400)
					.json(helper.responseStatusError('bad data'))
			}

			return that._fs.writeString(gridFsPath, req.body.graph)
			.then(function() {
				var url = that._fs.url(gridFsPath)

				var model = {
					category: req.body.category,
					name: req.body.name,
					type: stat.type || 'patch',
					path: path,
					tags: tags,
					stat: stat,
					url: url
				}

				console.log('Saved patch model', model)

				return that._service.save(model, req.user)
				.then(function(asset) {
					res.json(asset)
				})
			})
		})
	})
	.catch(next)
}

module.exports = PatchController


text:
using System.ComponentModel;

namespace System.ServiceModel.Security
{
    public enum SecurityTokenAttachmentMode
    {
        Signed,
        Endorsing,
        SignedEndorsing,
        SignedEncrypted
    }

    internal static class SecurityTokenAttachmentModeHelper
    {
        internal static bool IsDefined(SecurityTokenAttachmentMode value)
        {
            return value == SecurityTokenAttachmentMode.Endorsing
                || value == SecurityTokenAttachmentMode.Signed
                || value == SecurityTokenAttachmentMode.SignedEncrypted
                || value == SecurityTokenAttachmentMode.SignedEndorsing;
        }

        internal static void Validate(SecurityTokenAttachmentMode value)
        {
            if (!IsDefined(value))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("value", (int)value,
                    typeof(SecurityTokenAttachmentMode)));
            }
        }

        internal static void Categorize(SecurityTokenAttachmentMode value,
            out bool isBasic, out bool isSignedButNotBasic, out ReceiveSecurityHeaderBindingModes mode)
        {
            SecurityTokenAttachmentModeHelper.Validate(value);

            switch (value)
            {
                case SecurityTokenAttachmentMode.Endorsing:
                    isBasic = false;
                    isSignedButNotBasic = false;
                    mode = ReceiveSecurityHeaderBindingModes.Endorsing;
                    break;
                case SecurityTokenAttachmentMode.Signed:
                    isBasic = false;
                    isSignedButNotBasic = true;
                    mode = ReceiveSecurityHeaderBindingModes.Signed;
                    break;
                case SecurityTokenAttachmentMode.SignedEncrypted:
                    isBasic = true;
                    isSignedButNotBasic = false;
                    mode = ReceiveSecurityHeaderBindingModes.Basic;
                    break;
                case SecurityTokenAttachmentMode.SignedEndorsing:
                    isBasic = false;
                    isSignedButNotBasic = true;
                    mode = ReceiveSecurityHeaderBindingModes.SignedEndorsing;
                    break;
                default:
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value"));
            }
        }
    }
}


text:
pub mod account_model;
pub mod account_statement_model;
pub mod test_model;
pub mod money_map_model;
pub mod money_map_user_model;
pub mod transaction_model;
pub mod user_model;


text:
package com.refinedmods.refinedstorage.item.blockitem;

import com.refinedmods.refinedstorage.RS;
import com.refinedmods.refinedstorage.RSBlocks;
import com.refinedmods.refinedstorage.apiimpl.API;
import com.refinedmods.refinedstorage.apiimpl.network.grid.factory.PortableGridGridFactory;
import com.refinedmods.refinedstorage.inventory.player.PlayerSlot;
import com.refinedmods.refinedstorage.item.WirelessGridItem;
import com.refinedmods.refinedstorage.render.Styles;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.TranslatableComponent;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.InteractionResultHolder;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.item.context.UseOnContext;
import net.minecraft.world.level.Level;

import javax.annotation.Nullable;
import java.util.List;

public class PortableGridBlockItem extends EnergyBlockItem {
    private final Type type;

    public PortableGridBlockItem(Type type) {
        super(
            type == Type.CREATIVE ? RSBlocks.CREATIVE_PORTABLE_GRID.get() : RSBlocks.PORTABLE_GRID.get(),
            new Item.Properties().tab(RS.MAIN_GROUP).stacksTo(1),
            type == Type.CREATIVE,
            () -> RS.SERVER_CONFIG.getPortableGrid().getCapacity()
        );

        this.type = type;
    }

    public Type getType() {
        return type;
    }

    @Override
    public InteractionResultHolder<ItemStack> use(Level level, Player player, InteractionHand hand) {
        ItemStack stack = player.getItemInHand(hand);

        if (!level.isClientSide) {
            API.instance().getGridManager().openGrid(PortableGridGridFactory.ID, (ServerPlayer) player, stack, PlayerSlot.getSlotForHand(player, hand));
        }

        return InteractionResultHolder.success(stack);
    }

    @Override
    public void appendHoverText(ItemStack stack, @Nullable Level level, List<Component> tooltip, TooltipFlag flag) {
        super.appendHoverText(stack, level, tooltip, flag);

        tooltip.add(new TranslatableComponent("block.refinedstorage.portable_grid.tooltip").setStyle(Styles.GRAY));
    }

    @Override
    public InteractionResult useOn(UseOnContext context) {
        if (context.getPlayer() == null) {
            return InteractionResult.FAIL;
        }

        //Place
        if (context.getPlayer().isCrouching()) {
            return super.useOn(context);
        }

        ItemStack stack = context.getPlayer().getItemInHand(context.getHand());

        if (!context.getLevel().isClientSide) {
            API.instance().getGridManager().openGrid(PortableGridGridFactory.ID, (ServerPlayer) context.getPlayer(), stack, PlayerSlot.getSlotForHand(context.getPlayer(), context.getHand()));
        }

        return InteractionResult.SUCCESS;
    }

    @Override
    public int getEntityLifespan(ItemStack stack, Level level) {
        return Integer.MAX_VALUE;
    }

    @Override
    public boolean shouldCauseReequipAnimation(ItemStack oldStack, ItemStack newStack, boolean slotChanged) {
        if (oldStack.getItem() == newStack.getItem() &&
            WirelessGridItem.getSortingDirection(oldStack) == WirelessGridItem.getSortingDirection(newStack) &&
            WirelessGridItem.getSortingType(oldStack) == WirelessGridItem.getSortingType(newStack) &&
            WirelessGridItem.getSearchBoxMode(oldStack) == WirelessGridItem.getSearchBoxMode(newStack) &&
            WirelessGridItem.getTabSelected(oldStack) == WirelessGridItem.getTabSelected(newStack) &&
            WirelessGridItem.getTabPage(oldStack) == WirelessGridItem.getTabPage(newStack) &&
            WirelessGridItem.getSize(oldStack) == WirelessGridItem.getSize(newStack)) {
            return false;
        }

        return super.shouldCauseReequipAnimation(oldStack, newStack, slotChanged);
    }

    public enum Type {
        NORMAL,
        CREATIVE
    }
}


text:
module Rack
  class Bug

    class TemplatesPanel < Panel
      require "rack/bug/panels/templates_panel/actionview_extension"

      autoload :Trace,      "rack/bug/panels/templates_panel/trace"
      autoload :Rendering,  "rack/bug/panels/templates_panel/rendering"

      def self.record(template)
        return yield unless Rack::Bug.enabled?

        template_trace.start(template)
        begin
          result = yield
        ensure
          template_trace.finished(template)
        end
        return result
      end

      def self.reset
        Thread.current["rack.bug.template_trace"] = Trace.new
      end

      def self.template_trace
        Thread.current["rack.bug.template_trace"] ||= Trace.new
      end

      def name
        "templates"
      end

      def heading
        "Templates: %.2fms" % (self.class.template_trace.total_time * 1_000)
      end

      def content
        result = render_template "panels/templates", :template_trace => self.class.template_trace
        self.class.reset
        return result
      end

    end

  end
end


text:
class CategoryTag < ActiveRecord::Base
  belongs_to :category
  belongs_to :tag
end

# == Schema Information
#
# Table name: category_tags
#
#  id          :integer          not null, primary key
#  category_id :integer          not null
#  tag_id      :integer          not null
#  created_at  :datetime
#  updated_at  :datetime
#
# Indexes
#
#  idx_category_tags_ix1  (category_id,tag_id) UNIQUE
#  idx_category_tags_ix2  (tag_id,category_id) UNIQUE
#


text:
<?xml version="1.0" encoding="UTF-8"?>
<application xmlns="http://java.sun.com/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_6.xsd"
             version="6">
</application>


text:
atPrintableTestData::atPrintableTestData(atTestData* pData) : std::tr1::shared_ptr<atTestData>(pData)
{
}

const char* atPrintableTestData::GetTestName() const
{
    const atTestData* pData = get();

    if (pData)
    {
        return pData->_testName.asASCIICharArray();
    }
    else
    {
        return "Error: Invalid test data";
    }
};

::std::ostream& operator<<(::std::ostream& os, const atPrintableTestData& printableTestData)
{
    return os << printableTestData.GetTestName();
}


text:
from __future__ import unicode_literals, print_function
import json
from tempfile import NamedTemporaryFile

from nose.tools import assert_dict_equal
from nose.tools import assert_equal, assert_true, \
    assert_regexp_matches, assert_list_equal, raises
import pytest

from gcdt.kumo_core import _generate_parameters, \
    load_cloudformation_template, write_template_to_file, _get_stack_name, \
    _get_stack_policy, _get_stack_policy_during_update, _get_conf_value, \
    _generate_parameter_entry, _call_hook, generate_template
from gcdt.kumo_start_stop import _get_autoscaling_min_max
from gcdt.utils import fix_old_kumo_config
from gcdt.gcdt_config_reader import read_json_config

from gcdt_testtools.helpers import cleanup_tempfiles, temp_folder  # fixtures!
from gcdt_testtools.helpers import Bunch
from . import here

def test_load_cloudformation_template(cleanup_tempfiles):
    tf = NamedTemporaryFile(delete=False, suffix='py')
    open(tf.name, 'w').write('def plus(a, b):\n    return a+b')
    cleanup_tempfiles.append(tf.name)

    module, success = load_cloudformation_template(tf.name)
    assert_equal(success, True)
    assert_equal(module.plus(1, 2), 3)

def test_cloudformation_template_not_available():
    module, success = load_cloudformation_template()
    assert_equal(module, None)
    assert_equal(success, False)

def test_load_cloudformation_template_from_cwd(temp_folder):
    # prepare dummy template for test
    open('cloudformation.py', 'w').write('def plus(a, b):\n    return a+b\n')

    module, success = load_cloudformation_template()
    assert_true(success, True)
    assert_equal(module.plus(1, 2), 3)

def test_simple_cloudformation_stack():
    # read the template
    template_path = here(
        'resources/simple_cloudformation_stack/cloudformation.py')
    #config_path = here(
    #    'resources/simple_cloudformation_stack/settings_dev.conf')

    cloudformation, success = load_cloudformation_template(template_path)
    assert_true(success)

    config = {
        'stack': {
            'StackName': "infra-dev-kumo-sample-stack"
        },
        'parameters': {
            'InstanceType': "t2.micro"
        }
    }

    expected_templ_file_name = '%s-generated-cf-template.json' % \
                               _get_stack_name(config)
    actual = write_template_to_file(config, generate_template({}, config, cloudformation))
    assert_equal(actual, expected_templ_file_name)

def _create_simple_cf():
    # use Bunch to create group of variables:
    # cf = Bunch(datum=y, squared=y*y, coord=x)
    cf = Bunch()
    return cf

def test_simple_cloudformation_stack_default():
    cf = _create_simple_cf()
    stack_policy = _get_stack_policy(cf)
    # policy defined in _get_stack_policy is used
    assert_regexp_matches(stack_policy, '{"Statement":')

def test_simple_cloudformation_stack_custom():
    def gsp():
        return 'have indiv. policy'
    cf = _create_simple_cf()
    cf.get_stack_policy = gsp
    stack_policy = _get_stack_policy(cf)
    assert_equal(stack_policy, 'have indiv. policy')

def test_simple_cloudformation_stack_during_update_custom():
    def gsp():
        return 'have indiv. policy'
    cf = _create_simple_cf()
    cf.get_stack_policy_during_update = gsp
    stack_policy = _get_stack_policy_during_update(cf, False)
    assert_equal(stack_policy, 'have indiv. policy')

def test_simple_cloudformation_stack_during_update_override_custom():
    # test make sure override has no impact on custom policy
    def gsp():
        return 'have indiv. policy'
    cf = _create_simple_cf()
    cf.get_stack_policy_during_update = gsp
    stack_policy = _get_stack_policy_during_update(cf, True)
    assert_equal(stack_policy, 'have indiv. policy')

def test_simple_cloudformation_stack_during_update_default():
    cf = _create_simple_cf()
    stack_policy = _get_stack_policy_during_update(cf, False)
    assert_regexp_matches(stack_policy, '{"Statement":')
    assert_equal('Deny', json.loads(stack_policy)['Statement'][1]['Effect'])
    assert_list_equal(["Update:Replace", "Update:Delete"],
                      json.loads(stack_policy)['Statement'][1]['Action'])

def test_simple_cloudformation_stack_during_update_override_default():
    cf = _create_simple_cf()
    stack_policy = _get_stack_policy_during_update(cf, True)
    assert_regexp_matches(stack_policy, '{"Statement":')

def test_parameter_substitution():
    expected = [
        {
            'ParameterKey': 'ConfigOne',
            'ParameterValue': 'value1',
            'UsePreviousValue': False
        },
        {
            'ParameterKey': 'ConfigTwo',
            'ParameterValue': 'value2,value3',
            'UsePreviousValue': False
        }
    ]
    conf = {
        'parameters': {
            'ConfigOne': 'value1',
            'ConfigTwo': ['value2', 'value3']
        }
    }

    converted_conf = _generate_parameters(conf)
    assert_equal(converted_conf, expected)

def test_parameter_substitution_reserved_terms():
    conf = {
        'parameters': {
            'ConfigOne': 'value1'
        },
        'stack': {
            'StackName': 'value2',
            'TemplateBody': 'value3',
            'artifactBucket': 'value4',
        }
    }
    expected = [
        {
            'ParameterKey': 'ConfigOne',
            'ParameterValue': 'value1',
            'UsePreviousValue': False
        }
    ]
    converted_conf = _generate_parameters(conf)
    assert_equal(converted_conf, expected)

def test_get_conf_value():
    config = {
        'parameters': {
            'ConfigOne': 'value1'
        }
    }
    assert_equal(_get_conf_value(config, 'ConfigOne'), 'value1')

def test_get_conf_value_list():
    config = {
        'parameters': {
            'ConfigOne': ['a', 'b', 'c']
        }
    }
    assert_equal(_get_conf_value(config, 'ConfigOne'), 'a,b,c')

@raises(KeyError)
def test_get_conf_value_unknown():
    config = {
        'parameters': {
            'ConfigOne': ['a', 'b', 'c']
        }
    }
    _get_conf_value(config, 'Unknown')

def test_generate_parameter_entry():
    config = {
        'parameters': {
            'ConfigOne': 'value1'
        }
    }
    assert_dict_equal(_generate_parameter_entry(config, 'ConfigOne'),
                      {
                          'ParameterKey': 'ConfigOne',
                          'ParameterValue': 'value1',
                          'UsePreviousValue': False
                      })

def _create_cfn_with_hook():
    def hook():
        pass

    # use Bunch to create group of variables:
    cfn = Bunch(pre_hook=hook)
    return cfn

def test_call_hook_unknown_hook(capsys):
    _call_hook(None, None, None, None, None, 'unknown_hook')
    out, err = capsys.readouterr()
    assert out == 'Unknown hook: unknown_hook\n'

def test_call_hook_backward_compatible(capsys):
    _call_hook(None, None, None, None, _create_cfn_with_hook(), 'pre_hook')
    out, err = capsys.readouterr()
    assert out == 'Executing pre hook...\n'

def test_call_hook_not_present(capsys):
    _call_hook(None, None, None, None, _create_cfn_with_hook(),
               'pre_create_hook')
    out, err = capsys.readouterr()
    assert out == ''

def test_new_cloudformation_template_hooks():
    template_path = here(
        'resources/simple_cloudformation_stack_hooks/cloudformation.py')
    module, success = load_cloudformation_template(template_path)
    assert_equal(success, True)

    assert module.COUNTER['register'] == 1
    # currently deregister is not called (but we need that later!)
    #assert module.COUNTER['deregister'] == 1

def test_generate_template_no_arguments():
    cloudformation_simple_stack, _ = load_cloudformation_template(
        here('resources/simple_cloudformation_stack/cloudformation.py')
    )
    context = {}
    config_simple_stack = fix_old_kumo_config(read_json_config(
        here('resources/simple_cloudformation_stack/gcdt_dev.json')
    ))['kumo']
    expected_template_body = read_json_config(
        here('resources/simple_cloudformation_stack/expected_template_body.json')
    )
    template_body = json.loads(
        generate_template(context, config_simple_stack, cloudformation_simple_stack)
    )
    assert template_body == expected_template_body

def test_generate_template_with_arguments():
    cloudformation_simple_stack, _ = load_cloudformation_template(
        here('resources/simple_cloudformation_stack/cloudformation_with_arguments.py')
    )
    context = {'foo': 'bar'}
    config_simple_stack = fix_old_kumo_config(read_json_config(
        here('resources/simple_cloudformation_stack/gcdt_dev.json')
    ))['kumo']
    expected_template_body = read_json_config(
        here('resources/simple_cloudformation_stack/expected_template_body.json')
    )
    template_body = json.loads(
        generate_template(context, config_simple_stack, cloudformation_simple_stack)
    )
    assert template_body == expected_template_body

def test_generate_template_invalid_arguments():
    cloudformation_simple_stack, _ = load_cloudformation_template(
        here('resources/simple_cloudformation_stack/cloudformation_invalid_arguments.py')
    )
    context = {'foo': 'bar'}
    config_simple_stack = fix_old_kumo_config(read_json_config(
        here('resources/simple_cloudformation_stack/gcdt_dev.json')
    ))['kumo']

    with pytest.raises(Exception) as einfo:
        generate_template(context, config_simple_stack, cloudformation_simple_stack)
    assert einfo.match(r"Arguments of 'generate_template' not as expected: \['invalid_context', 'invalid_config'\]")

def test_get_autoscaling_min_max():
    with open(here('resources/cfn_template/cloudformation.template'), 'r') as tfile:
        template_json = json.load(tfile)

    parameters = [{'ParameterKey': 'ScaleMinCapacity', 'ParameterValue': '1'},
                  {'ParameterKey': 'ScaleMaxCapacity', 'ParameterValue': '2'}]

    assert _get_autoscaling_min_max(
        template_json, parameters, 'SupercarsAutoscalingGroup'
    ) == (1, 2)


text:
var ISY = require('./isy');
var ISYDevice = require('./isydevice');

function handleInitialized() {
	var deviceList = isy.getDeviceList();
    console.log("Device count: "+deviceList.length);
	if(deviceList == null) {
		console.log("No device list returned!");
	} else {
		console.log("Got device list. Device count: "+deviceList.length);
		for(var index = 0; index < deviceList.length; index++ ) {
			console.log("Device: "+deviceList[index].name+", "+deviceList[index].deviceType+", "+deviceList[index].address+", "+deviceList[index].deviceFriendlyName);
		}
	}
	var fanDevice = isy.getDevice('14 A8 BC 2');
	var fanSpeed = fanDevice.getCurrentFanState();
	console.log('Current fan speed '+fanSpeed);
	fanDevice.sendFanCommand(fanDevice.FAN_LEVEL_MEDIUM, function() {});
	setTimeout(function() {
		console.log('Fan state (should be medium): '+fanDevice.getCurrentFanState());
		fanDevice.sendFanCommand(fanDevice.FAN_LEVEL_HIGH, function() {});
		setTimeout(function() {
			console.log('Fan state (should be high): '+fanDevice.getCurrentFanState());
			fanDevice.sendFanCommand((fanDevice.FAN_OFF), function() {});
		}, 4000)
	},4000);
    //runBasicSceneTest(deviceList);
}

function handleChanged(isy, device) {
	var logMessage = 'From isy: '+isy.address+' device changed: '+device.name;
	if(device.deviceType == isy.DEVICE_TYPE_FAN) {
		logMessage += ' fan state: '+device.getCurrentFanState();
	} else if(device.deviceType == isy.DEVICE_TYPE_LIGHT) {
		logMessage += ' light state: '+device.getCurrentLightState();
	} else if(device.deviceType == isy.DEVICE_TYPE_DIMMABLE_LIGHT) {
		logMessage += ' dimmable light state: '+device.getCurrentLightState()+' dimm Level: '+device.getCurrentLightDimState();
	} else if(device.deviceType == isy.DEVICE_TYPE_LOCK || device.deviceType == isy.DEVICE_TYPE_SECURE_LOCK) {
		logMessage += ' lock state: '+device.getCurrentLockState();
	} else if(device.deviceType == isy.DEVICE_TYPE_OUTLET) {
		logMessage += ' outlet state: '+device.getCurrentOutletState();
	} else if(device.deviceType == isy.DEVICE_TYPE_ALARM_DOOR_WINDOW_SENSOR) {
		logMessage += ' door window sensor state: '+device.getCurrentDoorWindowState()+' logical: '+device.getLogicalState()+' physical: '+device.getPhysicalState();
	} else if(device.deviceType == isy.DEVICE_TYPE_DOOR_WINDOW_SENSOR) {
		logMessage += ' door window sensor state: '+device.getCurrentDoorWindowState();
	} else if(device.deviceType == isy.DEVICE_TYPE_ALARM_PANEL) {
		logMessage += ' alarm panel state: '+device.getAlarmStatusAsText();
	} else if(device.deviceType == isy.DEVICE_TYPE_MOTION_SENSOR) {
		logMessage += ' motion sensor state: '+device.getCurrentMotionSensorState();
	} else if(device.deviceType == isy.DEVICE_TYPE_SCENE) {
		logMessage += ' scene. light state: '+device.getCurrentLightState()+' dimm Level: '+device.getCurrentLightDimState();
    } else {
		logMessage += ' unknown device, cannot parse state';
	}

    console.log(logMessage);
}

//var isy = new ISY.ISY('10.0.1.19', 'admin', 'password', true, handleChanged, false, true,true);
var isy = new ISY.ISY('127.0.0.1:3000', 'admin', 'password', true, handleChanged, false, true,true);

isy.initialize(handleInitialized);
console.log('initialize completed');

function runBasicSceneTest(devices) {
    for(var index = 0; index < devices.length; index++) {
        var device = devices[index];
        if(device.deviceType == isy.DEVICE_TYPE_SCENE && device.childDevices.length > 0 && device.childDevices.length < 5) {
            console.log('Using scene: '+device.name);
            console.log('Contains devices: ');
            for(var childIndex = 0; childIndex < device.childDevices.length; childIndex++) {
                console.log('Device: name='+device.childDevices[childIndex].name+' type='+device.childDevices[childIndex].deviceType);
            }
            console.log('Light state: '+devices[index].getCurrentLightState());
            device.sendLightCommand(true, function() {
                console.log('Turned them off to start so we make sure to get an on');
                device.sendLightCommand(true, function() {
                    console.log('SHould have seen them all turn on');
                    device.sendLightCommand(false, function() {
                        console.log('Should have seen them all turn off');
                        device.sendLightDimCommand(50, function() {
                            console.log('Should have seen them all set to 50%');
                            device.sendLightCommand(false, function() {});
                        });
                    });
                });
            });
            break;
        }
    }
}


text:
Title: Meet Up Enterprise Search Paris
Date: 2015-04-08
Slug: Meet Up Enterprise Search Paris
Author: Jérôme Bernardes
Category: Solr
Tags: français,solr,opensource,meetup
Summary: Découvrez la présentation effectué par Mappy lors du dernier Meet Up Enterprise Search Paris

Voici la présentation effectuée par Mappy lors du dernier [Meet Up Enterprise Search Paris](http://www.meetup.com/Enterprise-Search-Paris/events/220773793/) impeccablement organisé par [France Labs](http://www.francelabs.com/) au NUMA.

<iframe src="//slides.com/solrmappy/deck/embed" width="576" height="420" scrolling="no" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>


text:
@implementation LXFLineBrush

- (void)drawInContext:(CGContextRef)ctx {
    CGContextMoveToPoint(ctx, self.startPoint.x, self.startPoint.y);
    CGContextAddLineToPoint(ctx, self.endPoint.x, self.endPoint.y);
}

- (BOOL)keepDrawing {
    return NO;
}

@end


text:
{{ vm.nodeConfig.name }} *

            OUTPUT

            DISABLED
            ENABLED

    <button ng-disabled="vm.originalOutput == vm.output" class="btn btn-primary btn-sm" type="button" ng-click="vm.save()">OK</button>
    <button class="btn btn-warning btn-sm" type="button" ng-click="vm.cancel()">CANCEL</button>


text:
package com.helger.xml.serialize.read;

import java.util.Locale;
import java.util.Map;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.NotThreadSafe;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.ContentHandler;
import org.xml.sax.DTDHandler;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.ext.DeclHandler;
import org.xml.sax.ext.LexicalHandler;

import com.helger.commons.ValueEnforcer;
import com.helger.commons.annotation.ReturnsMutableCopy;
import com.helger.commons.annotation.ReturnsMutableObject;
import com.helger.commons.callback.CallbackList;
import com.helger.commons.callback.exception.IExceptionCallback;
import com.helger.commons.collection.impl.CommonsEnumMap;
import com.helger.commons.collection.impl.ICommonsMap;
import com.helger.commons.lang.ICloneable;
import com.helger.commons.string.ToStringGenerator;
import com.helger.xml.EXMLParserFeature;
import com.helger.xml.EXMLParserProperty;

/**
 * SAX reader settings
 *
 * @author Philip Helger
 */
@NotThreadSafe
public class SAXReaderSettings implements ISAXReaderSettings, ICloneable <SAXReaderSettings>
{
  private static final Logger LOGGER = LoggerFactory.getLogger (SAXReaderSettings.class);

  private EntityResolver m_aEntityResolver;
  private DTDHandler m_aDTDHandler;
  private ContentHandler m_aContentHandler;
  private ErrorHandler m_aErrorHandler;
  private final ICommonsMap <EXMLParserProperty, Object> m_aProperties = new CommonsEnumMap <> (EXMLParserProperty.class);
  private final ICommonsMap <EXMLParserFeature, Boolean> m_aFeatures = new CommonsEnumMap <> (EXMLParserFeature.class);
  private final CallbackList <IExceptionCallback <Throwable>> m_aExceptionCallbacks = new CallbackList <> ();
  private boolean m_bRequiresNewXMLParserExplicitly;

  /**
   * Default constructor
   */
  public SAXReaderSettings ()
  {
    // Set default values
    setEntityResolver (SAXReaderDefaultSettings.getEntityResolver ());
    setDTDHandler (SAXReaderDefaultSettings.getDTDHandler ());
    setContentHandler (SAXReaderDefaultSettings.getContentHandler ());
    setErrorHandler (SAXReaderDefaultSettings.getErrorHandler ());
    setPropertyValues (SAXReaderDefaultSettings.getAllPropertyValues ());
    setFeatureValues (SAXReaderDefaultSettings.getAllFeatureValues ());
    exceptionCallbacks ().set (SAXReaderDefaultSettings.exceptionCallbacks ());
    setRequiresNewXMLParserExplicitly (SAXReaderDefaultSettings.isRequiresNewXMLParserExplicitly ());
  }

  /**
   * Copy constructor
   *
   * @param aOther
   *        the object to copy the settings from. May not be null.
   */
  public SAXReaderSettings (@Nonnull final ISAXReaderSettings aOther)
  {
    ValueEnforcer.notNull (aOther, "Other");

    // Set default values
    setEntityResolver (aOther.getEntityResolver ());
    setDTDHandler (aOther.getDTDHandler ());
    setContentHandler (aOther.getContentHandler ());
    setErrorHandler (aOther.getErrorHandler ());
    setPropertyValues (aOther.getAllPropertyValues ());
    setFeatureValues (aOther.getAllFeatureValues ());
    exceptionCallbacks ().set (aOther.exceptionCallbacks ());
    setRequiresNewXMLParserExplicitly (aOther.isRequiresNewXMLParserExplicitly ());
  }

  @Nullable
  public EntityResolver getEntityResolver ()
  {
    return m_aEntityResolver;
  }

  @Nonnull
  public final SAXReaderSettings setEntityResolver (@Nullable final EntityResolver aEntityResolver)
  {
    m_aEntityResolver = aEntityResolver;
    return this;
  }

  @Nullable
  public DTDHandler getDTDHandler ()
  {
    return m_aDTDHandler;
  }

  @Nonnull
  public final SAXReaderSettings setDTDHandler (@Nullable final DTDHandler aDTDHandler)
  {
    m_aDTDHandler = aDTDHandler;
    return this;
  }

  @Nullable
  public ContentHandler getContentHandler ()
  {
    return m_aContentHandler;
  }

  @Nonnull
  public final SAXReaderSettings setContentHandler (@Nullable final ContentHandler aContentHandler)
  {
    m_aContentHandler = aContentHandler;
    return this;
  }

  @Nullable
  public ErrorHandler getErrorHandler ()
  {
    return m_aErrorHandler;
  }

  @Nonnull
  public final SAXReaderSettings setErrorHandler (@Nullable final ErrorHandler aErrorHandler)
  {
    m_aErrorHandler = aErrorHandler;
    return this;
  }

  @Nullable
  public LexicalHandler getLexicalHandler ()
  {
    return (LexicalHandler) getPropertyValue (EXMLParserProperty.SAX_LEXICAL_HANDLER);
  }

  @Nonnull
  public final SAXReaderSettings setLexicalHandler (@Nullable final LexicalHandler aLexicalHandler)
  {
    return setPropertyValue (EXMLParserProperty.SAX_LEXICAL_HANDLER, aLexicalHandler);
  }

  @Nullable
  public DeclHandler getDeclarationHandler ()
  {
    return (DeclHandler) getPropertyValue (EXMLParserProperty.SAX_DECLARATION_HANDLER);
  }

  @Nonnull
  public final SAXReaderSettings setDeclarationHandler (@Nullable final DeclHandler aDeclHandler)
  {
    return setPropertyValue (EXMLParserProperty.SAX_DECLARATION_HANDLER, aDeclHandler);
  }

  public boolean hasAnyProperties ()
  {
    return !m_aProperties.isEmpty ();
  }

  @Nullable
  public Object getPropertyValue (@Nullable final EXMLParserProperty eProperty)
  {
    return eProperty == null ? null : m_aProperties.get (eProperty);
  }

  @Nonnull
  @ReturnsMutableCopy
  public ICommonsMap <EXMLParserProperty, Object> getAllPropertyValues ()
  {
    return m_aProperties.getClone ();
  }

  @Nonnull
  public final SAXReaderSettings setPropertyValue (@Nonnull final EXMLParserProperty eProperty,
                                                   @Nullable final Object aPropertyValue)
  {
    ValueEnforcer.notNull (eProperty, "Property");

    if (aPropertyValue != null &&
        eProperty.getValueClass () != null &&
        !eProperty.getValueClass ().isAssignableFrom (aPropertyValue.getClass ()))
      if (LOGGER.isWarnEnabled ())
        LOGGER.warn ("Setting the XML parser property '" +
                     eProperty +
                     "' to a value of " +
                     aPropertyValue.getClass () +
                     " will most likely not be interpreted!");

    if (aPropertyValue != null)
      m_aProperties.put (eProperty, aPropertyValue);
    else
      m_aProperties.remove (eProperty);
    return this;
  }

  @Nonnull
  public final SAXReaderSettings setPropertyValues (@Nullable final Map <EXMLParserProperty, ?> aProperties)
  {
    if (aProperties != null)
      m_aProperties.putAll (aProperties);
    return this;
  }

  @Nonnull
  public final SAXReaderSettings removePropertyValue (@Nullable final EXMLParserProperty eProperty)
  {
    if (eProperty != null)
      m_aProperties.removeObject (eProperty);
    return this;
  }

  @Nonnull
  public final SAXReaderSettings removeAllPropertyValues ()
  {
    m_aProperties.removeAll ();
    return this;
  }

  @Nullable
  public Locale getLocale ()
  {
    return (Locale) getPropertyValue (EXMLParserProperty.GENERAL_LOCALE);
  }

  @Nonnull
  public SAXReaderSettings setLocale (@Nullable final Locale aLocale)
  {
    return setPropertyValue (EXMLParserProperty.GENERAL_LOCALE, aLocale);
  }

  public boolean hasAnyFeature ()
  {
    return !m_aFeatures.isEmpty ();
  }

  @Nullable
  public Boolean getFeatureValue (@Nullable final EXMLParserFeature eFeature)
  {
    return eFeature == null ? null : m_aFeatures.get (eFeature);
  }

  @Nonnull
  @ReturnsMutableCopy
  public ICommonsMap <EXMLParserFeature, Boolean> getAllFeatureValues ()
  {
    return m_aFeatures.getClone ();
  }

  @Nonnull
  public final SAXReaderSettings setFeatureValue (@Nonnull final EXMLParserFeature eFeature, final boolean bValue)
  {
    ValueEnforcer.notNull (eFeature, "Feature");

    m_aFeatures.put (eFeature, Boolean.valueOf (bValue));
    return this;
  }

  @Nonnull
  public final SAXReaderSettings setFeatureValue (@Nonnull final EXMLParserFeature eFeature,
                                                  @Nullable final Boolean aValue)
  {
    ValueEnforcer.notNull (eFeature, "Feature");

    if (aValue == null)
      m_aFeatures.remove (eFeature);
    else
      m_aFeatures.put (eFeature, aValue);
    return this;
  }

  /**
   * Add multiple XML parser features at once.
   *
   * @param aValues
   *        The values to be added. May be null.
   * @return this for chaining
   */
  @Nonnull
  public final SAXReaderSettings setFeatureValues (@Nullable final Map <EXMLParserFeature, Boolean> aValues)
  {
    if (aValues != null)
      m_aFeatures.putAll (aValues);
    return this;
  }

  @Nonnull
  public final SAXReaderSettings removeFeature (@Nullable final EXMLParserFeature eFeature)
  {
    if (eFeature != null)
      m_aFeatures.removeObject (eFeature);
    return this;
  }

  @Nonnull
  public final SAXReaderSettings removeFeatures (@Nullable final EXMLParserFeature... aFeatures)
  {
    if (aFeatures != null)
      for (final EXMLParserFeature eFeature : aFeatures)
        m_aFeatures.removeObject (eFeature);
    return this;
  }

  @Nonnull
  public final SAXReaderSettings removeAllFeatures ()
  {
    m_aFeatures.removeAll ();
    return this;
  }

  public boolean requiresNewXMLParser ()
  {
    // Force a new XML parser?
    if (m_bRequiresNewXMLParserExplicitly)
      return true;

    if (!m_aProperties.isEmpty () || !m_aFeatures.isEmpty ())
      return true;

    // Special case for JDK > 1.7.0_45 because of maximum entity expansion
    // See http://docs.oracle.com/javase/tutorial/jaxp/limits/limits.html
    return m_aEntityResolver != null;
  }

  @Nonnull
  @ReturnsMutableObject
  public CallbackList <IExceptionCallback <Throwable>> exceptionCallbacks ()
  {
    return m_aExceptionCallbacks;
  }

  public boolean isRequiresNewXMLParserExplicitly ()
  {
    return m_bRequiresNewXMLParserExplicitly;
  }

  @Nonnull
  public final SAXReaderSettings setRequiresNewXMLParserExplicitly (final boolean bRequiresNewXMLParserExplicitly)
  {
    m_bRequiresNewXMLParserExplicitly = bRequiresNewXMLParserExplicitly;
    return this;
  }

  @Nonnull
  public SAXReaderSettings getClone ()
  {
    return new SAXReaderSettings (this);
  }

  public void applyToSAXReader (@Nonnull final org.xml.sax.XMLReader aParser)
  {
    ValueEnforcer.notNull (aParser, "Parser");

    aParser.setContentHandler (getContentHandler ());
    aParser.setDTDHandler (getDTDHandler ());
    aParser.setEntityResolver (getEntityResolver ());
    aParser.setErrorHandler (getErrorHandler ());

    // Apply properties
    if (hasAnyProperties ())
      for (final Map.Entry <EXMLParserProperty, Object> aEntry : getAllPropertyValues ().entrySet ())
        aEntry.getKey ().applyTo (aParser, aEntry.getValue ());

    // Apply features
    if (hasAnyFeature ())
      for (final Map.Entry <EXMLParserFeature, Boolean> aEntry : getAllFeatureValues ().entrySet ())
        aEntry.getKey ().applyTo (aParser, aEntry.getValue ().booleanValue ());
  }

  @Override
  public String toString ()
  {
    return new ToStringGenerator (this).append ("entityResolver", m_aEntityResolver)
                                       .append ("dtdHandler", m_aDTDHandler)
                                       .append ("contentHandler", m_aContentHandler)
                                       .append ("errorHandler", m_aErrorHandler)
                                       .append ("properties", m_aProperties)
                                       .append ("features", m_aFeatures)
                                       .append ("exceptionHandler", m_aExceptionCallbacks)
                                       .append ("requiresNewXMLParserExplicitly", m_bRequiresNewXMLParserExplicitly)
                                       .getToString ();
  }

  /**
   * Create a clone of the passed settings, depending on the parameter. If the
   * parameter is null a new empty {@link SAXReaderSettings} object
   * is created, otherwise a copy of the parameter is created.
   *
   * @param aOther
   *        The parameter to be used. May be null.
   * @return Never null.
   */
  @Nonnull
  public static SAXReaderSettings createCloneOnDemand (@Nullable final ISAXReaderSettings aOther)
  {
    if (aOther == null)
    {
      // Create plain object
      return new SAXReaderSettings ();
    }

    // Create a clone
    return new SAXReaderSettings (aOther);
  }
}


text:
import React from 'react';
import { Route, NotFoundRoute } from 'react-router';
import Index from './index/Index.jsx';
import Signin from './index/Signin.jsx';
import Register from './index/Register.jsx';
import Hello from './index/Hello.jsx';
import Profile from './user/Profile.jsx';
import NotFound from './NotFound.jsx';

export default function () {
  return [
    <Route name="root" handler={Index}>
      <Route name="signin" path="/signin" handler={Signin}/>
      <Route name="register" path="/register" handler={Register}/>
      <Route name="profile" path="/profile" handler={Profile}/>
      <Route name="index" path="/" handler={Hello} />
    </Route>,
    <NotFoundRoute name="not-found" handler={NotFound} />
  ];
}


text:
package hudson.plugins.git.extensions.impl;

import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.Test;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

public class LocalBranchTest {

    @Test
    public void equalsContract() {
        EqualsVerifier.forClass(LocalBranch.class)
                .usingGetClass()
                .verify();
    }

    @Test
    public void checkToString() {
        LocalBranch setting = new LocalBranch("branch-name");
        assertThat(setting.toString(), is("LocalBranch{localBranch='branch-name'}"));
    }

    @Test
    public void checkToStringNull() {
        LocalBranch setting = new LocalBranch(null);
        assertThat(setting.toString(), is("LocalBranch{same-as-remote}"));
    }

    @Test
    public void checkToStringWildcards() {
        LocalBranch setting = new LocalBranch("**");
        assertThat(setting.toString(), is("LocalBranch{same-as-remote}"));
    }
}


text:
interface TranslateOption {
    from?: string;
    to?: string;
    raw?: boolean;
}
interface TranslateResult {
    text: string;
    from: {
        language: {
            didYouMean: boolean;
            iso: string;
        }
        text: {
            autoCorrected: boolean;
            value: string;
            didYouMean: boolean;
        }
    };
    raw: string;
}
declare function translate(text: string, options?: TranslateOption): Promise<TranslateResult>;
export = translate;


text:
module Projects
  class ParticipantsService < BaseService
    def initialize(project, user)
      @project  = project
      @user     = user
    end

    def execute(note_type, note_id)
      participating =
        if note_type && note_id
          participants_in(note_type, note_id)
        else
          []
        end
      team_members = sorted(@project.team.members)
      participants = all_members + groups + team_members + participating
      participants.uniq
    end

    def participants_in(type, id)
      users = case type
              when "Issue"
                issue = @project.issues.find_by_iid(id)
                issue ? issue.participants : []
              when "MergeRequest"
                merge_request = @project.merge_requests.find_by_iid(id)
                merge_request ? merge_request.participants : []
              when "Commit"
                author_ids = Note.for_commit_id(id).pluck(:author_id).uniq
                User.where(id: author_ids)
              else
                []
              end
      sorted(users)
    end

    def sorted(users)
      users.uniq.to_a.compact.sort_by(&:username).map { |user| { username: user.username, name: user.name } }
    end

    def groups
      @user.authorized_groups.sort_by(&:path).map { |group| { username: group.path, name: group.name } }
    end

    def all_members
      [{ username: "all", name: "Project and Group Members" }]
    end
  end
end