text:
// ==========================================================================
//  Squidex Headless CMS
// ==========================================================================
//  Copyright (c) Squidex UG (haftungsbeschraenkt)
//  All rights reserved. Licensed under the MIT license.
// ==========================================================================

using Microsoft.AspNetCore.Mvc;
using Microsoft.Net.Http.Headers;
using Squidex.Areas.Api.Controllers.Apps.Models;
using Squidex.Domain.Apps.Entities;
using Squidex.Domain.Apps.Entities.Apps;
using Squidex.Domain.Apps.Entities.Apps.Commands;
using Squidex.Infrastructure.Commands;
using Squidex.Infrastructure.Security;
using Squidex.Infrastructure.Translations;
using Squidex.Infrastructure.Validation;
using Squidex.Shared;
using Squidex.Web;

namespace Squidex.Areas.Api.Controllers.Apps;

/// <summary>
/// Update and query apps.
/// </summary>
[ApiExplorerSettings(GroupName = nameof(Apps))]
public sealed class AppsController : ApiController
{
    private readonly IAppProvider appProvider;

    public AppsController(ICommandBus commandBus, IAppProvider appProvider)
        : base(commandBus)
    {
        this.appProvider = appProvider;
    }

    /// <summary>
    /// Get your apps.
    /// </summary>
    /// <response code="200">Apps returned.</response>.
    /// <remarks>
    /// You can only retrieve the list of apps when you are authenticated as a user (OpenID implicit flow).
    /// You will retrieve all apps, where you are assigned as a contributor.
    /// </remarks>
    [HttpGet]
    [Route("apps/")]
    [ProducesResponseType(typeof(AppDto[]), StatusCodes.Status200OK)]
    [ApiPermission]
    [ApiCosts(0)]
    public async Task<IActionResult> GetApps()
    {
        var userOrClientId = UserOrClientId!;
        var userPermissions = Resources.Context.UserPermissions;

        var apps = await appProvider.GetUserAppsAsync(userOrClientId, userPermissions, HttpContext.RequestAborted);

        var response = Deferred.Response(() =>
        {
            return apps.OrderBy(x => x.Name).Select(a => AppDto.FromDomain(a, userOrClientId, IsFrontend, Resources)).ToArray();
        });

        Response.Headers[HeaderNames.ETag] = apps.ToEtag();

        return Ok(response);
    }

    /// <summary>
    /// Get team apps.
    /// </summary>
    /// <param name="team">The ID of the team.</param>
    /// <response code="200">Apps returned.</response>.
    /// <remarks>
    /// You can only retrieve the list of apps when you are authenticated as a user (OpenID implicit flow).
    /// You will retrieve all apps, where you are assigned as a contributor.
    /// </remarks>
    [HttpGet]
    [Route("teams/{team}/apps")]
    [ProducesResponseType(typeof(AppDto[]), StatusCodes.Status200OK)]
    [ApiPermission]
    [ApiCosts(0)]
    public async Task<IActionResult> GetTeamApps(string team)
    {
        var apps = await appProvider.GetTeamAppsAsync(Team.Id, HttpContext.RequestAborted);

        var response = Deferred.Response(() =>
        {
            return apps.OrderBy(x => x.Name).Select(a => AppDto.FromDomain(a, UserOrClientId, IsFrontend, Resources)).ToArray();
        });

        Response.Headers[HeaderNames.ETag] = apps.ToEtag();

        return Ok(response);
    }

    /// <summary>
    /// Get an app by name.
    /// </summary>
    /// <param name="app">The name of the app.</param>
    /// <response code="200">Apps returned.</response>.
    /// <response code="404">App not found.</response>.
    [HttpGet]
    [Route("apps/{app}")]
    [ProducesResponseType(typeof(AppDto), StatusCodes.Status200OK)]
    [ApiPermission]
    [ApiCosts(0)]
    public IActionResult GetApp(string app)
    {
        var response = Deferred.Response(() =>
        {
            var isFrontend = HttpContext.User.IsInClient(DefaultClients.Frontend);

            return AppDto.FromDomain(App, UserOrClientId, IsFrontend, Resources);
        });

        Response.Headers[HeaderNames.ETag] = App.ToEtag();

        return Ok(response);
    }

    /// <summary>
    /// Create a new app.
    /// </summary>
    /// <param name="request">The app object that needs to be added to Squidex.</param>
    /// <response code="201">App created.</response>.
    /// <response code="400">App request not valid.</response>.
    /// <response code="409">App name is already in use.</response>.
    /// <remarks>
    /// You can only create an app when you are authenticated as a user (OpenID implicit flow).
    /// You will be assigned as owner of the new app automatically.
    /// </remarks>
    [HttpPost]
    [Route("apps/")]
    [ProducesResponseType(typeof(AppDto), 201)]
    [ApiPermission]
    [ApiCosts(0)]
    public async Task<IActionResult> PostApp([FromBody] CreateAppDto request)
    {
        var response = await InvokeCommandAsync(request.ToCommand());

        return CreatedAtAction(nameof(GetApps), response);
    }

    /// <summary>
    /// Update the app.
    /// </summary>
    /// <param name="app">The name of the app to update.</param>
    /// <param name="request">The values to update.</param>
    /// <response code="200">App updated.</response>.
    /// <response code="400">App request not valid.</response>.
    /// <response code="404">App not found.</response>.
    [HttpPut]
    [Route("apps/{app}/")]
    [ProducesResponseType(typeof(AppDto), StatusCodes.Status200OK)]
    [ApiPermissionOrAnonymous(PermissionIds.AppUpdate)]
    [ApiCosts(0)]
    public async Task<IActionResult> PutApp(string app, [FromBody] UpdateAppDto request)
    {
        var response = await InvokeCommandAsync(request.ToCommand());

        return Ok(response);
    }

    /// <summary>
    /// Transfer the app.
    /// </summary>
    /// <param name="app">The name of the app to update.</param>
    /// <param name="request">The team information.</param>
    /// <response code="200">App transferred.</response>.
    /// <response code="400">App request not valid.</response>.
    /// <response code="404">App not found.</response>.
    [HttpPut]
    [Route("apps/{app}/team")]
    [ProducesResponseType(typeof(AppDto), StatusCodes.Status200OK)]
    [ApiPermissionOrAnonymous(PermissionIds.AppTransfer)]
    [ApiCosts(0)]
    public async Task<IActionResult> PutAppTeam(string app, [FromBody] TransferToTeamDto request)
    {
        var response = await InvokeCommandAsync(request.ToCommand());

        return Ok(response);
    }

    /// <summary>
    /// Upload the app image.
    /// </summary>
    /// <param name="app">The name of the app to update.</param>
    /// <param name="file">The file to upload.</param>
    /// <response code="200">App image uploaded.</response>.
    /// <response code="400">App request not valid.</response>.
    /// <response code="404">App not found.</response>.
    [HttpPost]
    [Route("apps/{app}/image")]
    [ProducesResponseType(typeof(AppDto), StatusCodes.Status200OK)]
    [ApiPermissionOrAnonymous(PermissionIds.AppImageUpload)]
    [ApiCosts(0)]
    public async Task<IActionResult> UploadImage(string app, IFormFile file)
    {
        var response = await InvokeCommandAsync(CreateCommand(file));

        return Ok(response);
    }

    /// <summary>
    /// Remove the app image.
    /// </summary>
    /// <param name="app">The name of the app to update.</param>
    /// <response code="200">App image removed.</response>.
    /// <response code="404">App not found.</response>.
    [HttpDelete]
    [Route("apps/{app}/image")]
    [ProducesResponseType(typeof(AppDto), StatusCodes.Status200OK)]
    [ApiPermissionOrAnonymous(PermissionIds.AppImageDelete)]
    [ApiCosts(0)]
    public async Task<IActionResult> DeleteImage(string app)
    {
        var response = await InvokeCommandAsync(new RemoveAppImage());

        return Ok(response);
    }

    /// <summary>
    /// Delete the app.
    /// </summary>
    /// <param name="app">The name of the app to delete.</param>
    /// <response code="204">App deleted.</response>.
    /// <response code="404">App not found.</response>.
    [HttpDelete]
    [Route("apps/{app}/")]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    [ApiPermission(PermissionIds.AppDelete)]
    [ApiCosts(0)]
    public async Task<IActionResult> DeleteApp(string app)
    {
        var command = new DeleteApp();

        await CommandBus.PublishAsync(command, HttpContext.RequestAborted);

        return NoContent();
    }

    private Task<AppDto> InvokeCommandAsync(ICommand command)
    {
        return InvokeCommandAsync(command, x =>
        {
            return AppDto.FromDomain(x, UserOrClientId, IsFrontend, Resources);
        });
    }

    private async Task<T> InvokeCommandAsync<T>(ICommand command, Func<IAppEntity, T> converter)
    {
        var context = await CommandBus.PublishAsync(command, HttpContext.RequestAborted);

        var result = context.Result<IAppEntity>();
        var response = converter(result);

        return response;
    }

    private UploadAppImage CreateCommand(IFormFile? file)
    {
        if (file == null || Request.Form.Files.Count != 1)
        {
            var error = T.Get("validation.onlyOneFile");

            throw new ValidationException(error);
        }

        return new UploadAppImage { File = file.ToAssetFile() };
    }
}


text:
if (FastClick){
  window.addEventListener('load', function() {
    FastClick.attach(document.body);
  }, false);
}
__ = _.noConflict();

redpajama_set_name: RedPajamaGithub


text:
using JetBrains.Annotations;
using SIM.Products;
using System;

namespace SIM.Instances
{
  public class ContainerizedInstance : Instance
  {
    private string _name;

    public ContainerizedInstance()
    {
    }

    public ContainerizedInstance(string name)
      : base(Int32.MaxValue) // Containerized instances are not run on local IIS, we cannot resolve proper site ID, thus 'Int32.MaxValue' is set.
    {
      this._name = name;
    }

    public override string Name => _name;

    public override string DisplayName
    {
      get { return Name; }
    }

    public override string BindingsNames => string.Empty;

    [NotNull]
    public override Product Product
    {
      get { return Product.Undefined; }
    }

    public override string WebRootPath
    {
      get { return this.SitecoreEnvironment.UnInstallDataPath; }
    }
  }
}


text:
module GemMonitor
  class Reader

    attr_accessor :file_path

    def initialize args = {}
      self.file_path = args.fetch(:file_path, nil)
    end

    def read
      begin
        File.read file_path
      rescue => e
        raise GemMonitor::Error.new("Could not find file #{file_path}.")
      end
    end
  end
end


text:
{-# OPTIONS_GHC -fplugin GHC.NT.Plugin #-}

module LiftNested where

import GHC.NT
import Newtype hiding (main)

data Bal a = End a | Node (Bal (a,a)) deriving Show

balNT :: NT a b -> NT (Bal a) (Bal b)
balNT = deriveThisNT

main = do
    let n = Node (Node (End ((1,2),(3,4))))
    let a = coerce (sym (balNT ageNT)) n
    print n
    print a


text:
require("babel-core/register");
require("json5/lib/require");

require("./lib/server.js");
require("./lib/spot.js");


text:
<?php

namespace Nopolabs\Yabot\Message;

use Nopolabs\Yabot\Helpers\SlackTrait;
use Nopolabs\Yabot\Slack\Client;
use Slack\Channel;
use Slack\User;

class Message
{
    use SlackTrait;

    /** @var array */
    private $data;

    /** @var User */
    private $user;

    /** @var Channel */
    private $channel;

    /** @var bool */
    private $handled;

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

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

    public function __construct(
        Client $slackClient,
        array $data,
        string $formattedText,
        User $user = null,
        Channel $channel)
    {
        $this->setSlack($slackClient);
        $this->data = $data;
        $this->user = $user;
        $this->channel = $channel;
        $this->handled = false;
        $this->formattedText = $formattedText;
    }

    public function getData() : array
    {
        return $this->data;
    }

    public function getText() : string
    {
        return $this->data['text'];
    }

    public function getFormattedText() : string
    {
        return $this->formattedText;
    }

    public function setPluginText(string $text)
    {
        $this->pluginText = $text;
    }

    public function getPluginText()
    {
        return $this->pluginText;
    }

    public function getChannel() : Channel
    {
        return $this->channel;
    }

    public function getUser()
    {
        return $this->user;
    }

    public function getThreadTs()
    {
        return $this->data['thread_ts'] ?? $this->data['ts'];
    }

    public function isSelf() : bool
    {
        return $this->user === $this->getAuthedUser();
    }

    public function isBot() : bool
    {
        if (isset($this->data['bot_id'])) {
            return true;
        }

        if (isset($this->user->data['is_bot'])) {
            return (bool) $this->user->data['is_bot'];
        }

        return false;
    }

    public function hasAttachments()
    {
        return isset($this->data['attachments']) && count($this->data['attachments']) > 0;
    }

    public function getAttachments()
    {
        return $this->hasAttachments() ? $this->data['attachments'] : [];
    }

    public function reply(string $text, array $additionalParameters = [])
    {
        $this->say($text, $this->getChannel(), $additionalParameters);
    }

    public function thread(string $text, array $additionalParameters = [])
    {
        $additionalParameters['thread_ts'] = $this->getThreadTs();
        $this->reply($text, $additionalParameters);
    }

    public function isHandled() : bool
    {
        return $this->handled;
    }

    public function setHandled(bool $handled)
    {
        $this->handled = $handled;
    }

    public function getUsername()
    {
        $user = $this->getUser();

        return $user ? $user->getUsername() : ($this->isBot() ? 'unknown-bot' : 'unknown-user');
    }

    public function getChannelName()
    {
        return $this->getChannel()->getName();
    }
}


text:
package org.usermanagement.exception;

public class RequestValidationException extends CustomException {
    private static final long serialVersionUID = -896015072208863L;

    public RequestValidationException() {}

    public RequestValidationException(String message) {
        super(message);
    }

    public RequestValidationException(String message, Throwable cause) {
        super(message, cause);
    }

    public RequestValidationException(int code) {
        super(code);
    }

    public RequestValidationException(int code, String message) {
        super(code, message);
    }

    public RequestValidationException(int code, Throwable cause) {
        super(code, cause);
    }

    public RequestValidationException(int code, String message, Throwable cause) {
        super(code, message, cause);
    }

    public RequestValidationException(int code, String message, Throwable cause, boolean enableSuppression,
            boolean writableStackTrace) {
        super(code, message, cause, enableSuppression, writableStackTrace);
    }
}


text:
using System.Runtime.Serialization;

#if !CORECLR
using System.Security.Permissions;
#else
// Use stub for SerializableAttribute.
using Microsoft.PowerShell.CoreClr.Stubs;
#endif

namespace System.Management.Automation
{
    /// <summary>
    /// This is a wrapper for exception class
    /// <see cref="System.ArgumentException"/>
    /// which provides additional information via
    /// <see cref="System.Management.Automation.IContainsErrorRecord"/>.
    /// </summary>
    /// <remarks>
    /// Instances of this exception class are usually generated by the
    /// Monad Engine.  It is unusual for code outside the Monad Engine
    /// to create an instance of this class.
    /// </remarks>
    [Serializable]
    public class PSArgumentException
            : ArgumentException, IContainsErrorRecord
    {
        #region ctor
        /// <summary>
        /// Initializes a new instance of the PSArgumentException class.
        /// </summary>
        /// <returns> constructed object </returns>
        public PSArgumentException()
            : base()
        {
        }

        /// <summary>
        /// Initializes a new instance of the PSArgumentException class.
        /// </summary>
        /// <param name="message">  </param>
        /// <returns> constructed object </returns>
        /// <remarks>
        /// Per MSDN, the parameter is message.
        /// I confirm this experimentally as well.
        /// </remarks>
        public PSArgumentException(string message)
            : base(message)
        {
        }

        /// <summary>
        /// Initializes a new instance of the PSArgumentException class.
        /// </summary>
        /// <param name="paramName">  </param>
        /// <param name="message">  </param>
        /// <returns> constructed object </returns>
        /// <remarks>
        /// Note the unusual order of the construction parameters.
        /// ArgumentException has this ctor form and we imitate it here.
        /// </remarks>
        public PSArgumentException(string message, string paramName)
                : base(message, paramName)
        {
            _message = message;
        }

        #region Serialization
#if !CORECLR // ArgumentException Has No Serialization In CoreCLR
        /// <summary>
        /// Initializes a new instance of the PSArgumentException class
        /// using data serialized via
        /// <see cref="System.Runtime.Serialization.ISerializable"/>
        /// </summary>
        /// <param name="info"> serialization information </param>
        /// <param name="context"> streaming context </param>
        /// <returns> constructed object </returns>
        protected PSArgumentException(SerializationInfo info,
                           StreamingContext context)
                : base(info, context)
        {
            _errorId = info.GetString("ErrorId");
            _message = info.GetString("PSArgumentException_MessageOverride");
        }

        /// <summary>
        /// Serializer for <see cref="System.Runtime.Serialization.ISerializable"/>
        /// </summary>
        /// <param name="info"> serialization information </param>
        /// <param name="context"> streaming context </param>
        [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
        public override void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            if (info == null)
            {
                throw new PSArgumentNullException("info");
            }

            base.GetObjectData(info, context);
            info.AddValue("ErrorId", _errorId);
            info.AddValue("PSArgumentException_MessageOverride", _message);
        }
#endif
        #endregion Serialization

        /// <summary>
        /// Initializes a new instance of the PSArgumentException class.
        /// </summary>
        /// <param name="message">  </param>
        /// <param name="innerException">  </param>
        /// <returns> constructed object </returns>
        public PSArgumentException(string message,
                                    Exception innerException)
                : base(message, innerException)
        {
            _message = message;
        }
        #endregion ctor

        /// <summary>
        /// Additional information about the error
        /// </summary>
        /// <value></value>
        /// <remarks>
        /// Note that ErrorRecord.Exception is
        /// <see cref="System.Management.Automation.ParentContainsErrorRecordException"/>.
        /// </remarks>
        public ErrorRecord ErrorRecord
        {
            get
            {
                if (null == _errorRecord)
                {
                    _errorRecord = new ErrorRecord(
                        new ParentContainsErrorRecordException(this),
                        _errorId,
                        ErrorCategory.InvalidArgument,
                        null);
                }
                return _errorRecord;
            }
        }
        private ErrorRecord _errorRecord;
        private string _errorId = "Argument";

        /// <summary>
        /// see <see cref="System.Exception.Message"/>
        /// </summary>
        /// <remarks>
        /// Exception.Message is get-only, but you can effectively
        /// set it in a subclass by overriding this virtual property.
        /// </remarks>
        /// <value></value>
        public override string Message
        {
            get { return String.IsNullOrEmpty(_message) ? base.Message : _message; }
        }
        private string _message;
    } // PSArgumentException
} // System.Management.Automation


text:
{-# LANGUAGE FlexibleContexts #-}

module Control.Concurrent.Timer.Lifted
( Timer
, TimerIO

, oneShotTimer
, oneShotStart
, oneShotRestart

, repeatedTimer
, repeatedStart
, repeatedRestart

, newTimer
, stopTimer
) where

------------------------------------------------------------------------------
import           Control.Applicative
import           Control.Concurrent.Lifted         (ThreadId, fork, killThread)
import           Control.Concurrent.MVar.Lifted    (newMVar, tryTakeMVar, putMVar, modifyMVar_)
import           Control.Concurrent.Suspend.Lifted (Delay, suspend)
import           Control.Monad
import           Control.Monad.Base                (MonadBase)
import           Control.Monad.Trans.Control       (MonadBaseControl)
------------------------------------------------------------------------------
import           Control.Concurrent.Timer.Types (Timer(..), TimerImmutable(..))
------------------------------------------------------------------------------

-- | Attempts to start a timer.
-- The started timer will have the given delay and action associated and will be one-shot timer.
--
-- If the timer was already initialized, it the previous timer will be stoped (the thread killed) and the timer will be started anew.
--
-- Returns True if the strat was successful,
-- otherwise (e.g. other thread is attempting to manipulate the timer) returns False.
oneShotStart :: MonadBaseControl IO m
               => Timer m
               -> m ()  -- ^ The action the timer will start with.
               -> Delay -- ^ The dealy the timer will start with.
               -> m Bool
oneShotStart (Timer mvmtim) a d = do
    mtim <- tryTakeMVar mvmtim
    case mtim of
         Just (Just (TimerImmutable _ _ tid)) -> do
             killThread tid
             oneShotTimerImmutable a d >>= putMVar mvmtim . Just
             return True
         Just (Nothing) -> do
             oneShotTimerImmutable a d >>= putMVar mvmtim . Just
             return True
         Nothing -> return False
{-# INLINEABLE oneShotStart #-}

-- | Attempts to start a timer.
-- The started timer will have the given delay and action associated and will be repeated timer.
--
-- If the timer was already initialized, it the previous timer will be stoped (the thread killed) and the timer will be started anew.
--
-- Returns True if the strat was successful,
-- otherwise (e.g. other thread is attempting to manipulate the timer) returns False.
repeatedStart :: MonadBaseControl IO m
                => Timer m
                -> m ()   -- ^ The action the timer will start with.
                -> Delay  -- ^ The dealy the timer will start with.
                -> m Bool
repeatedStart (Timer mvmtim) a d = do
    mtim <- tryTakeMVar mvmtim
    case mtim of
         Just (Just (TimerImmutable _ _ tid)) -> do
             killThread tid
             repeatedTimerImmutable a d >>= putMVar mvmtim . Just
             return True
         Just (Nothing) -> do
             repeatedTimerImmutable a d >>= putMVar mvmtim . Just
             return True
         Nothing -> return False
{-# INLINEABLE repeatedStart #-}

-- | Attempts to restart already initialized timer.
-- The restarted timer will have the same delay and action associated and will be one-shot timer.
--
-- Returns True if the restrat was successful,
-- otherwise (e.g. other thread is attempting to manipulate the timer or the timer was not initialized) returns False.
oneShotRestart :: MonadBaseControl IO m
               => Timer m
               -> m Bool
oneShotRestart (Timer mvmtim) = do
    mtim <- tryTakeMVar mvmtim
    case mtim of
         Just (Just (TimerImmutable a d tid)) -> do
             killThread tid
             oneShotTimerImmutable a d >>= putMVar mvmtim . Just
             return True
         _ -> return False
{-# INLINEABLE oneShotRestart #-}

-- | Attempts to restart already initialized timer.
-- The restarted timer will have the same delay and action associated and will be one-shot timer.
--
-- Returns True if the restrat was successful,
-- otherwise (e.g. other thread is attempting to manipulate the timer or the timer was not initialized) returns False.
repeatedRestart :: MonadBaseControl IO m
                => Timer m
                -> m Bool
repeatedRestart (Timer mvmtim) = do
    mtim <- tryTakeMVar mvmtim
    case mtim of
         Just (Just (TimerImmutable a d tid)) -> do
             killThread tid
             repeatedTimerImmutable a d >>= putMVar mvmtim . Just
             return True
         _ -> return False
{-# INLINEABLE repeatedRestart #-}

-- | Executes the the given action once after the given delay elapsed, no sooner, maybe later.
oneShotTimer :: MonadBaseControl IO m
             => m ()        -- ^ The action to be executed.
             -> Delay      -- ^ The (minimal) time until the execution in microseconds.
             -> m (Timer m)
oneShotTimer a d = Timer <$> (oneShotTimerImmutable a d >>= newMVar . Just)
{-# INLINE oneShotTimer #-}

-- | Executes the the given action repeatedly with at least the given delay between executions.
repeatedTimer :: MonadBaseControl IO m
              => m ()    -- ^ The action to be executed.
              -> Delay   -- ^ The (minimal) delay between executions.
              -> m (Timer m)
repeatedTimer a d = Timer <$> (repeatedTimerImmutable a d >>= newMVar . Just)
{-# INLINE repeatedTimer #-}

-- | This function is blocking. It waits until it can stop the timer
-- (until there is a value in the MVar), then it kills the timer's thread.
--
-- After this action completes, the Timer is not innitialized anymore (the MVar contains Nothing).
stopTimer :: MonadBaseControl IO m
          => Timer m
          -> m ()
stopTimer (Timer mvmtim) = modifyMVar_ mvmtim $
    maybe (return Nothing)
          (\(TimerImmutable _ _ tid) -> killThread tid >> return Nothing)
{-# INLINE stopTimer #-}

-- | Creates a new timer. This does not start the timer.
newTimer :: MonadBase IO m
         => m (Timer m)
newTimer = Timer <$> newMVar Nothing
{-# INLINE newTimer #-}

------------------------------------------------------------------------------
-- | Utility

type TimerIO = Timer IO

-- | Forks a new thread that runs the supplied action
-- (at least) after the given delay and stores the action,
-- delay and thread id in the immutable TimerImmutable value.
oneShotTimerImmutable :: MonadBaseControl IO m
                      => m ()        -- ^ The action to be executed.
                      -> Delay       -- ^ The (minimal) time until the execution in microseconds.
                      -> m (TimerImmutable m)
oneShotTimerImmutable a d = TimerImmutable a d <$> oneShotAction a d
{-# INLINE oneShotTimerImmutable #-}

-- | Forks a new thread that repeats the supplied action
-- with (at least) the given delay between each execution and stores the action,
-- delay and thread id in the immutable TimerImmutable value.
repeatedTimerImmutable :: MonadBaseControl IO m
                       => m ()        -- ^ The action to be executed.
                       -> Delay       -- ^ The (minimal) time until the execution in microseconds.
                       -> m (TimerImmutable m)
repeatedTimerImmutable a d = TimerImmutable a d <$> repeatedAction a d
{-# INLINE repeatedTimerImmutable #-}

-- | Forks a new thread that runs the supplied action
-- (at least) after the given delay.
oneShotAction :: MonadBaseControl IO m
              => m ()
              -> Delay
              -> m ThreadId
oneShotAction action delay = fork (suspend delay >> action)
{-# INLINE oneShotAction #-}

-- | Forks a new thread that repeats the supplied action
-- with (at least) the given delay between each execution.
repeatedAction :: MonadBaseControl IO m
               => m ()
               -> Delay
               -> m ThreadId
repeatedAction action delay = fork (forever $ suspend delay >> action)
{-# INLINE repeatedAction #-}


text:
..
..
.. Licensed under the Apache License, Version 2.0 (the "License");
.. you may not use this file except in compliance with the License.
.. You may obtain a copy of the License at
..
..     http://www.apache.org/licenses/LICENSE-2.0
..
.. Unless required by applicable law or agreed to in writing, software
.. distributed under the License is distributed on an "AS IS" BASIS,
.. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
.. See the License for the specific language governing permissions and
.. limitations under the License.
..

.. _to-api-current-stats:

*****************
``current_stats``
*****************
An API endpoint that returns current statistics for each CDN and an aggregate across them all.

``GET``
=======
Retrieves current stats for each CDN. Also includes aggregate stats across them.

:Auth. Required: Yes
:Roles Required: None
:Response Type:  Array

Request Structure
-----------------
No parameters available.

.. code-block:: http
	:caption: Request Example

	GET /api/4.0/current_stats HTTP/1.1
	Host: trafficops.infra.ciab.test
	User-Agent: curl/7.47.0
	Accept: */*
	Cookie: mojolicious=...

Response Structure
------------------
:cdn:         The name of the CDN
:connections: Current number of TCP connections maintained
:capacity:    85 percent capacity of the CDN in Gps
:bandwidth:   The total amount of bandwidth in Gbs

.. note:: If ``cdn`` name is total and capacity is omitted it represents the aggregate stats across CDNs

.. code-block:: http
	:caption: Response Example

	HTTP/1.1 200 OK
	Access-Control-Allow-Credentials: true
	Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Set-Cookie, Cookie
	Access-Control-Allow-Methods: POST,GET,OPTIONS,PUT,DELETE
	Access-Control-Allow-Origin: *
	Content-Encoding: gzip
	Content-Type: application/json
	Set-Cookie: mojolicious=; Path=/; HttpOnly
	Whole-Content-Sha512: Rs3wgd7v5dP0bOQs4I3J1q6mnWIMSM2AKSAWirK1kymvDYOoFISArF7Kkypgy10I34yn7FtFdMh6U7ABaS1Tjw==
	X-Server-Name: traffic_ops_golang/
	Date: Thu, 14 Nov 2019 15:35:31 GMT
	Content-Length: 138

	{"response": {
		"currentStats": [
			{
				"bandwidth": null,
				"capacity": null,
				"cdn": "ALL",
				"connections": null
			},
			{
				"bandwidth": 0.000104,
				"capacity": 17,
				"cdn": "CDN-in-a-Box",
				"connections": 4
			},
			{
				"bandwidth": 0.000104,
				"cdn": "total",
				"connections": 4
			}
		]
	}}


text: A tool to flash firmware to walkera receivers.


text:
'''
Author: John D. Anderson
Email: jander43@vols.utk.edu
Problem Statement:
    Write code to partition a linked list around a value x, such that all nodes
less than x come before all nodes greater than or equal to x. If x is
contained within the list, the values of x only need to be after the elements
less than x (see below). The partition element x can appear anywhere in the
right partition; it does not need to appear between the left and right
partition.
EXAMPLE
Input: 3 -> 5 -> 8 -> 5 -> 10 -> 2 -> 1 [partition = 5]
Output: 3 -> 1 -> 2 -> 10 -> 5 -> 5 -> 8
Complexity: TODO
Usage: TODO
'''


text:
module.exports = function (grunt) { return function() {

    var jsdiff = require('diff'),
        files = grunt.file.expandMapping(
            grunt.config.get('compare.src'),
            grunt.config.get('compare.dest'),
            {flatten: true});

    var ret = files.every(function(file) {
        var src = file.src[0],
            dst = file.dest;
        if (!grunt.file.exists(dst)) {
            grunt.log.error((dst + " not found.").red);
            return false;
        }

        var left  = grunt.file.read(src),
            right = grunt.file.read(dst);
        if (left === right) {
            grunt.log.ok((src + " - ok").green);
            return true;
        }

        grunt.log.writeln();
        var diff = jsdiff.diffLines(left, right),
            line = 0;
        diff.every(function(part, i) {
            line += part.count;
            if (part.added || part.removed) {
                grunt.log.error((src + " error at L" + line + ":").red);
                grunt.log.write(part.value.green);
                part = diff[i + 1];
                grunt.log.write(part.value.red);
                return false;
            }
            return true;
        });

        return false;
    });

    grunt.log.writeln();
    return ret;

};};


text:
var ben = require("ben"),
	testString = "doo, *#foo > elem.bar[class$=bAz i]:not([ id *= \"2\" ]):nth-child(2n)",
	helper = require("./helper.js"),
	CSSselect = helper.CSSselect,
	compile = CSSselect.compile,
	dom = helper.getDefaultDom();

//console.log("Parsing took:", ben(1e5, function(){compile(testString);}));
var compiled = compile(testString);
console.log("Executing took:", ben(1e6, function(){CSSselect(compiled, dom);})*1e3);


text:
Below you can find common questions and answers.

### Q: Boxen Keychain Helper: Encountered error code: -25308

If you run `boxen` in a session without GUI (e.g. via SSH), you will most likely need to unlock the keychain manually.

```bash
security create-keychain -p $your_password $keychain_name
security default-keychain -d user -s $keychain_name
# if necessary..
security unlock-keychain -p $your_password # unlocks the default keychain, which boxen will use to store the token
```

### Q: How do you uninstall an application and get it to reinstall in the application folder with boxen?

When removing applications make sure to remove the corresponding `/var/db/.puppet_appdmg_installed_application` so that boxen will reinstall it.

### Q: How do you remove Boxen?

Run `script/nuke` from inside the `/opt/boxen/repo` directory.

### Q: How do you upgrade your boxen from the public our-boxen?

Answer distilled from http://grahamgilbert.com/blog/2014/04/04/updating-boxen/
As Boxen is made by GitHub, updating it is much like updating any other project on there that you've made a fork of. First we're going to add it as a remote repository:

```bash
cd ~/src/our-boxen
git remote add upstream https://github.com/boxen/our-boxen.git
```
Then we're going to fetch the stuff from the upstream repository:

```bash
git fetch upstream
```

Now we're going to merge the updated repository with our own:

```bash
git checkout master
git merge upstream/master
```

Now deal with conflicts in (Puppetfile, manifests/site.pp), ignore any diffs in Puppetfile.lock and Gemfile.lock.

```bash
git mergetool
```

The next step is to update your Puppet modules and RubyGems. First delete Puppetfile.lock and Gemfile.lock. Now go back to your trusty Terminal and:

```bash
rm Puppetfile.lock Gemfile.lock
bundle install --no-deployment --without development --path .bundle
bundle exec librarian-puppet install --path=shared --clean
```

### Q: What's a good approach to merging our-boxen back into my private fork?

One approach is to delete the Gemfile.lock and Puppetfile.lock and run:

    # Regenerates Gemfile.lock and installs new Gems
    bundle install --without development --path .bundle

    # Regenerates Puppetfile.lock and caches tarballs
    bundle exec librarian-puppet install --path=shared --clean

These will generate the respective lock files suitable for committing. Hope that helps.

### Q: Should you keep the cache of the module and gem in the repository?

We recommend you to keep the files inside `vendor/cache` and `vendor/puppet/cache` inside
the repository.

It ends up adding a negligible amount of disk space in return for much faster runtimes
for other folks on your team (since they don't have to fetch the tarballs one-by-one
through the GitHub API any time a module version changes).


text:
/**
 * System module
 * @module System
 * @namespace RGPP.System
 */
(function(global) {
	/* global RGPP */
	"use strict";
		var objName = "Mouse";
	var mMouseButton = [];
	var mMouseButtonPrevious = [];
	var MOUSE_BUTTON_LEFT = 0;
	var MOUSE_BUTTON_CENTER = 1;
	var MOUSE_BUTTON_RIGHT = 2;
	var MOUSE_BUTTON_COUNT = 3;

	function initialize() {
		for (var i = 0; i < MOUSE_BUTTON_COUNT; ++i) {
			mMouseButton[i] = false;
			mMouseButtonPrevious[i] = false;
		}
	}

	function isDragged() {
		if (mMouseButton[MOUSE_BUTTON_LEFT]) {
			return true;
		}
		else {
			return false;
		}
	}

	function checkMouseButton(e) {
		if (!e) {
			e = window.event;
		}

		if (e.buttons !== undefined) {
			var data = e.buttons;

			mMouseButton[MOUSE_BUTTON_LEFT] = ((data & 0x0001) ? true : false);
			mMouseButton[MOUSE_BUTTON_RIGHT] = ((data & 0x0002) ? true : false);
			mMouseButton[MOUSE_BUTTON_CENTER] = ((data & 0x0004) ? true : false);
		}
	}

	// replace global function
	global.onmousedown = function(e) {
		checkMouseButton(e);
	};

	global.onmouseup = function(e) {
		checkMouseButton(e);
	};

	global.onmousemove = function(e) {
		checkMouseButton(e);
		// prevent default action
		if (e.preventDefault) {
			e.preventDefault();
		}
		else {
			return false;
		}
	};

	/**
	 * Mouse Operator
	 * @class Template
	 * @author arcsin
	 * @constructor
	 * @param spec {Object}
	 * @param spec.element {Element}
	 * @param spec.moveFunc {Function}
	 * @param spec.downFunc {Function}
	 * @param spec.upFunc {Function}
	 * @param spec.outFunc {Function}
	 * @param spec.overFunc {Function}
	 * @param spec.doubleClickFunc {Function}
	 */
	var constructor = function(spec) {
		// element
		// moveFunc
		// downFunc
		// upFunc
		// outFunc
		// overFunc
		// doubleClickFunc

		var mMouseX = 0;
		var mMouseY = 0;

		var mMouseOverFlag = false;
		var Mode = {
			INIT_MODE: false,
			DRAG_MODE: true,
		};

		var mLeftButtonMode = Mode.INIT_MODE;

		var scriptUtil = RGPP.System.ScriptUtil.getInstance();

		var that = {};

		// Interface
		that.initialize = initialize;
		that.mouseMoveFunc = mouseMoveFunc;
		that.mouseDownFunc = mouseDownFunc;
		that.mouseUpFunc = mouseUpFunc;
		that.mouseOutFunc = mouseOutFunc;
		that.mouseOverFunc = mouseOverFunc;
		that.mouseDoubleClickFunc = mouseDoubleClickFunc;
		that.getX = getX;
		that.getY = getY;

		that.isPressedLeftButton = isPressedLeftButton;
		that.isPressedRightButton = isPressedRightButton;
		that.isPressedCenterButton = isPressedCenterButton;

		that.isLeftClick = isLeftClick;
		that.isCenterClick = isCenterClick;
		that.isRightClick = isRightClick;
		that.isMouseOver = isMouseOver;
		that.isDragged = isDragged;
		that.savePreviousButton = savePreviousButton;

		spec.element.onmousemove = function(e) {
			mouseMoveFunc(e);
			if (spec.moveFunc !== undefined) {
				spec.moveFunc(e);
			}
		};

		spec.element.onmousedown = function(e) {
			global.onmousedown(e);
			mouseDownFunc(e);
			if (spec.downFunc !== undefined) {
				spec.downFunc(e);
			}
		};

		spec.element.onmouseup = function(e) {
			global.onmouseup(e);
			mouseUpFunc(e);
			if (spec.upFunc !== undefined) {
				spec.upFunc(e);
			}
		};

		spec.element.onmouseout = function(e) {
			mouseOutFunc(e);
			if (spec.outFunc !== undefined) {
				spec.outFunc(e);
			}
		};

		spec.element.onmouseover = function(e) {
			mouseOverFunc(e);
			if (spec.overFunc !== undefined) {
				spec.overFunc(e);
			}
		};

		spec.element.ondblclick = function(e) {
			mouseDoubleClickFunc(e);
			if (spec.doubleClickFunc !== undefined) {
				spec.doubleClickFunc(e);
			}
		};

		function mouseMoveFunc(e) {
			checkPosition(e);
		}

		function mouseDownFunc(e) {
			checkPosition(e);
			scriptUtil.outputMsgToConsole("mouse down!");
			if (mMouseOverFlag) {
				if (mMouseButton[MOUSE_BUTTON_LEFT]) {
					mLeftButtonMode = Mode.DRAG_MODE;
				}
			}
		}

		function mouseUpFunc(e) {
			scriptUtil.outputMsgToConsole("mouse up!");
		}

		function mouseOutFunc(e) {
			mMouseOverFlag = false;
			scriptUtil.outputMsgToConsole("out flag!");
		}

		function mouseOverFunc(e) {
			mMouseOverFlag = true;
			checkPosition(e);
			var scriptUtil = RGPP.System.ScriptUtil.getInstance();
			scriptUtil.outputMsgToConsole("over flag!");
		}

		function mouseDoubleClickFunc(e) {
			var scriptUtil = RGPP.System.ScriptUtil.getInstance();
			scriptUtil.outputMsgToConsole("double click!");
		}

		var checkPosition = function(e) {
			if (e) {
				var rect = e.target.getBoundingClientRect();
				var mouseX = e.clientX - rect.left;
				var mouseY = e.clientY - rect.top;
				mMouseX = mouseX;
				mMouseY = mouseY;
			}
			else {
				mMouseX = event.offsetX;
				mMouseY = event.offsetY;
			}
		};

		function getX() {
			return mMouseX;
		}

		function getY() {
			return mMouseY;
		}

		function isPressedLeftButton() {
			if (mMouseButton[MOUSE_BUTTON_LEFT]) {
				return mLeftButtonMode;
			}
			mLeftButtonMode = Mode.INIT_MODE;
			return false;
		}

		function isPressedRightButton() {
			return mMouseButton[MOUSE_BUTTON_RIGHT];
		}

		function isPressedCenterButton() {
			return mMouseButton[MOUSE_BUTTON_CENTER];
		}

		function isLeftClick() {
			if (!mMouseButtonPrevious[MOUSE_BUTTON_LEFT]) {
				if (isPressedLeftButton()) {
					return true;
				}
			}
			return false;
		}

		function isCenterClick() {
			if (!mMouseButtonPrevious[MOUSE_BUTTON_CENTER]) {
				if (isPressedCenterButton()) {
					return true;
				}
			}
			return false;
		}

		function isRightClick() {
			if (!mMouseButtonPrevious[MOUSE_BUTTON_RIGHT]) {
				if (isPressedRightButton()) {
					return true;
				}
			}
			return false;
		}

		function isMouseOver() {
			return mMouseOverFlag;
		}

		function savePreviousButton() {
			for (var i = 0; i < MOUSE_BUTTON_COUNT; i += 1) {
				mMouseButtonPrevious[i] = mMouseButton[i];
			}
		}

		initialize();

		return that;
	};

	RGPP.System.exports({
		name: objName,
		constructorFunc: constructor,
		module: module
	});

})((this || 0).self || global);


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package napakalakiGame;

import java.util.ArrayList;

/**
 *
 * @author alejandro
 */
public class SpecificBadConsequence extends BadConsequence{
    private ArrayList<TreasureKind> specificHiddenTreasures = new ArrayList();
    private ArrayList<TreasureKind> specificVisibleTreasures = new ArrayList();

    public SpecificBadConsequence(String texto,int levels, ArrayList<TreasureKind> v,ArrayList<TreasureKind> h){
        super(texto,levels);
        specificHiddenTreasures=h;
        specificVisibleTreasures=v;
    }

    @Override
    public boolean isEmpty() {
       return (specificVisibleTreasures.isEmpty() && specificHiddenTreasures.isEmpty());
    }

    @Override
    public void substractVisibleTreasure(Treasure t) {
        int i;
        if ((i=specificVisibleTreasures.indexOf(t.getType()))!=-1)
                specificVisibleTreasures.remove(i);
    }

    @Override
    public void substractHiddenTreasure(Treasure t) {
        int i;
        if ((i=specificHiddenTreasures.indexOf(t.getType()))!=-1)
                specificHiddenTreasures.remove(i);
    }

    private ArrayList<TreasureKind> sameSpecific(ArrayList<Treasure> treasures, ArrayList<TreasureKind> specific) {
        ArrayList<TreasureKind> salida=new ArrayList();
        ArrayList<Treasure> aux=new ArrayList(treasures);

        for (TreasureKind a : specific){
            for (Treasure b: aux) {
                if (a==b.getType()){
                    salida.add(b.getType());
                    aux.remove(b);
                    break;
                }
            }
        }

        return salida;

    }

    @Override
    public SpecificBadConsequence adjustToFitTreasureLists(ArrayList<Treasure> v,
                                                           ArrayList<Treasure> h){
        SpecificBadConsequence bc=new SpecificBadConsequence("",0,
                                            sameSpecific(v, specificVisibleTreasures),
                                            sameSpecific(h, specificHiddenTreasures));
        return bc;
    }

    @Override
    public String toString(){
        String s = super.toString();
        s += "Específicos Visibles: " + specificVisibleTreasures.toString() + "\n";
        s += "Específicos Ocultos: "  +  specificHiddenTreasures.toString() + "\n";
        return s;
    }
}


text:
## ContentFirstChildTarget
Mixin that defines the target of a component -- the element the
component is managing or somehow responsible for -- as its first child

**Kind**: global class


text:
package xyz.imxqd.day23_2;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import day_23.IMyService;

public class MainActivity extends AppCompatActivity implements ServiceConnection {

    private static final String TAG = "Client2";

    private boolean isConnected = false;
    private IMyService remoteService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onDestroy() {
        if (isConnected) {
            unbindService(this);
            isConnected = false;
        }
        super.onDestroy();
    }

    public void serviceBind(View view) {
        Log.d(TAG, "serviceBind: ");
        Intent intent = new Intent();
        intent.setAction("xyz.imxqd.day_23.MyService.action");
        intent.setPackage("xyz.imxqd.day_23");
        bindService(intent, this, BIND_AUTO_CREATE);
    }

    public void serviceUnbind(View view) {
        Log.d(TAG, "serviceUnbind: ");
        if (isConnected) {
            unbindService(this);
            isConnected = false;
        }
    }

    public void binderStart(View view) {
        Log.d(TAG, "binderStart: ");
        if (isConnected && remoteService != null) {
            try {
                remoteService.start();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    public void binderPause(View view) {
        Log.d(TAG, "binderPause: ");
        if (isConnected && remoteService != null) {
            try {
                remoteService.pause();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    public void binderCurrent(View view) {
        Log.d(TAG, "binderCurrent: ");
        if (isConnected && remoteService != null) {
            try {
                System.out.println(remoteService.getCurrent());
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        Log.d(TAG, "onServiceConnected: ");
        isConnected = true;
        remoteService = IMyService.Stub.asInterface(service);
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.d(TAG, "onServiceDisconnected: ");
        isConnected = false;
    }

    public void serviceStart(View view) {
        Log.d(TAG, "serviceStart: ");
        Intent intent = new Intent();
        intent.setAction("xyz.imxqd.day_23.MyService.action");
        intent.setPackage("xyz.imxqd.day_23");
        startService(intent);
    }

    public void serviceStop(View view) {
        Log.d(TAG, "serviceStop: ");
        Intent intent = new Intent();
        intent.setAction("xyz.imxqd.day_23.MyService.action");
        intent.setPackage("xyz.imxqd.day_23");
        stopService(intent);
    }
}


text:
@extends('dashboard')

@section('content')

Randomly Generated Tasks

          <button class="btn btn-box-tool" data-widget="collapse" data-toggle="tooltip" title="Collapse"></button>
          <button class="btn btn-box-tool" data-widget="remove" data-toggle="tooltip" title="Remove"></button>

        @foreach($tasks as $task)

          {{ $task['name'] }}
          {{$task['progress']}}%

        @endforeach

        <form action='#'>
          <input type='text' placeholder='New task' class='form-control input-sm' />
        </form>

Second Box

          <button class="btn btn-box-tool" data-widget="collapse" data-toggle="tooltip" title="Collapse"></button>
          <button class="btn btn-box-tool" data-widget="remove" data-toggle="tooltip" title="Remove"></button>

        A separate section to add any kind of widget. Feel free
        to explore all of AdminLTE widgets by visiting the demo page
        on Almsaeed Studio.

@endsection


text:
<?php

namespace Magento\PageCache\Test\Block\Cache;

use Magento\Backend\Test\Block\Widget\Grid as ParentGrid;

/**
 * Backend Cache Management grid.
 */
class Grid extends ParentGrid
{
    /**
     * Search for item and select it.
     *
     * @param array $filter
     * @return void
     * @throws \Exception
     */
    public function searchAndSelect(array $filter)
    {
        $selectItem = $this->getRow($filter, false)->find($this->selectItem);
        if ($selectItem->isVisible()) {
            $selectItem->click();
        } else {
            throw new \Exception('Searched item was not found.');
        }
    }
}


text:
<?php

namespace selvinortiz\doxter\common\parsers;

use cebe\markdown\Parser;

/**
 * The markdown parser
 *
 * Class DoxterCodeBlockParser
 *
 * @package Craft
 */
class Markdown extends BaseParser
{
    /**
     * @var Markdown
     */
    protected static $_instance;

    /**
     * @var Parser
     */
    protected static $_parser;

    public function __construct($parser = null)
    {
        self::$_parser = $parser ? $parser : new \cebe\markdown\GithubMarkdown();
    }

    /**
     * @param string $source
     * @param array  $options
     *
     * @return string
     */
    public function parse($source, array $options = [])
    {
        return static::$_parser->parse($source);
    }

    /**
     * @param string $source
     *
     * @return string
     */
    public function parseInline($source)
    {
        return static::$_parser->parseParagraph($source);
    }
}


text:
package org.hl7.fhir.dstu3.model.codesystems;

// Generated on Tue, Dec 6, 2016 09:42-0500 for FHIR v1.8.0

import org.hl7.fhir.exceptions.FHIRException;

public enum MapTransform {

        /**
         * create(type : string) - type is passed through to the application on the standard API, and must be known by it
         */
        CREATE,
        /**
         * copy(source)
         */
        COPY,
        /**
         * truncate(source, length) - source must be stringy type
         */
        TRUNCATE,
        /**
         * escape(source, fmt1, fmt2) - change source from one kind of escaping to another (plain, java, xml, json). note that this is for when the string itself is escaped
         */
        ESCAPE,
        /**
         * cast(source, type?) - case source from one type to another. target type can be left as implicit if there is one and only one target type known
         */
        CAST,
        /**
         * append(source...) - source is element or string
         */
        APPEND,
        /**
         * translate(source, uri_of_map) - use the translate operation
         */
        TRANSLATE,
        /**
         * reference(source : object) - return a string that references the provided tree properly
         */
        REFERENCE,
        /**
         * Perform a date operation. Parameters to be documented
         */
        DATEOP,
        /**
         * Generate a random UUID (in lowercase). No Parameters
         */
        UUID,
        /**
         * Return the appropriate string to put in a Reference that refers to the resource provided as a parameter
         */
        POINTER,
        /**
         * Execute the supplied fluentpath expression and use the value returned by that
         */
        EVALUATE,
        /**
         * Create a CodeableConcept. Parameters = (text) or (system. Code[, display])
         */
        CC,
        /**
         * Create a Coding. Parameters = (system. Code[, display])
         */
        C,
        /**
         * Create a quantity. Parameters = (text) or (value, unit, [system, code]) where text =s the natural represenation e.g. [comparator]value[space]unit
         */
        QTY,
        /**
         * Create an identifier. Parameters = (system, value[, type]) where type is a code from the identifier type value set
         */
        ID,
        /**
         * Create a contact details. Parameters = (value) or (system, value). If no system is provided, the system should be inferred from the content of the value
         */
        CP,
        /**
         * added to help the parsers
         */
        NULL;
        public static MapTransform fromCode(String codeString) throws FHIRException {
            if (codeString == null || "".equals(codeString))
                return null;
        if ("create".equals(codeString))
          return CREATE;
        if ("copy".equals(codeString))
          return COPY;
        if ("truncate".equals(codeString))
          return TRUNCATE;
        if ("escape".equals(codeString))
          return ESCAPE;
        if ("cast".equals(codeString))
          return CAST;
        if ("append".equals(codeString))
          return APPEND;
        if ("translate".equals(codeString))
          return TRANSLATE;
        if ("reference".equals(codeString))
          return REFERENCE;
        if ("dateOp".equals(codeString))
          return DATEOP;
        if ("uuid".equals(codeString))
          return UUID;
        if ("pointer".equals(codeString))
          return POINTER;
        if ("evaluate".equals(codeString))
          return EVALUATE;
        if ("cc".equals(codeString))
          return CC;
        if ("c".equals(codeString))
          return C;
        if ("qty".equals(codeString))
          return QTY;
        if ("id".equals(codeString))
          return ID;
        if ("cp".equals(codeString))
          return CP;
        throw new FHIRException("Unknown MapTransform code '"+codeString+"'");
        }
        public String toCode() {
          switch (this) {
            case CREATE: return "create";
            case COPY: return "copy";
            case TRUNCATE: return "truncate";
            case ESCAPE: return "escape";
            case CAST: return "cast";
            case APPEND: return "append";
            case TRANSLATE: return "translate";
            case REFERENCE: return "reference";
            case DATEOP: return "dateOp";
            case UUID: return "uuid";
            case POINTER: return "pointer";
            case EVALUATE: return "evaluate";
            case CC: return "cc";
            case C: return "c";
            case QTY: return "qty";
            case ID: return "id";
            case CP: return "cp";
            default: return "?";
          }
        }
        public String getSystem() {
          return "http://hl7.org/fhir/map-transform";
        }
        public String getDefinition() {
          switch (this) {
            case CREATE: return "create(type : string) - type is passed through to the application on the standard API, and must be known by it";
            case COPY: return "copy(source)";
            case TRUNCATE: return "truncate(source, length) - source must be stringy type";
            case ESCAPE: return "escape(source, fmt1, fmt2) - change source from one kind of escaping to another (plain, java, xml, json). note that this is for when the string itself is escaped";
            case CAST: return "cast(source, type?) - case source from one type to another. target type can be left as implicit if there is one and only one target type known";
            case APPEND: return "append(source...) - source is element or string";
            case TRANSLATE: return "translate(source, uri_of_map) - use the translate operation";
            case REFERENCE: return "reference(source : object) - return a string that references the provided tree properly";
            case DATEOP: return "Perform a date operation. Parameters to be documented";
            case UUID: return "Generate a random UUID (in lowercase). No Parameters";
            case POINTER: return "Return the appropriate string to put in a Reference that refers to the resource provided as a parameter";
            case EVALUATE: return "Execute the supplied fluentpath expression and use the value returned by that";
            case CC: return "Create a CodeableConcept. Parameters = (text) or (system. Code[, display])";
            case C: return "Create a Coding. Parameters = (system. Code[, display])";
            case QTY: return "Create a quantity. Parameters = (text) or (value, unit, [system, code]) where text =s the natural represenation e.g. [comparator]value[space]unit";
            case ID: return "Create an identifier. Parameters = (system, value[, type]) where type is a code from the identifier type value set";
            case CP: return "Create a contact details. Parameters = (value) or (system, value). If no system is provided, the system should be inferred from the content of the value";
            default: return "?";
          }
        }
        public String getDisplay() {
          switch (this) {
            case CREATE: return "create";
            case COPY: return "copy";
            case TRUNCATE: return "truncate";
            case ESCAPE: return "escape";
            case CAST: return "cast";
            case APPEND: return "append";
            case TRANSLATE: return "translate";
            case REFERENCE: return "reference";
            case DATEOP: return "dateOp";
            case UUID: return "uuid";
            case POINTER: return "pointer";
            case EVALUATE: return "evaluate";
            case CC: return "cc";
            case C: return "c";
            case QTY: return "qty";
            case ID: return "id";
            case CP: return "cp";
            default: return "?";
          }
    }

}


text:
<?php
/* @var $this AdminRolesController */
/* @var $model AdminRoles */

$this->breadcrumbs=array(
	'Admin Roles'=>array('index'),
	'Create',
);

$this->menu=array(
	array('label'=>'List AdminRoles', 'url'=>array('index')),
	array('label'=>'Manage AdminRoles', 'url'=>array('admin')),
);
?>

Create AdminRoles

<?php $this->renderPartial('_form', array('model'=>$model)); ?>


text:
@implementation ADCell

-(void)setDataArray:(NSArray *)dataArray
{
    _dataArray = dataArray;

    for (int i=0; i<dataArray.count; i++) {

        //模型对象
        ADModel *model = dataArray[i];

        CGRect frame = CGRectMake(375*i, 0, 375, 160);

        UIImageView *imageView = [MyUtil createImageViewFrame:frame imageName:nil];
        [imageView sd_setImageWithURL:[NSURL URLWithString:model.pic] placeholderImage:[UIImage imageNamed:@"placeholder"]];
        [self.myScrollView addSubview:imageView];
    }

    self.myScrollView.delegate = self;
    self.myScrollView.pagingEnabled = YES;
    self.myScrollView.bounces = NO;
    self.myScrollView.contentSize = CGSizeMake(375*dataArray.count, 160);

    //分页
    self.myPageCtrl.numberOfPages = dataArray.count;
}

#pragma mark - UIScrollView代理
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSInteger index = scrollView.contentOffset.x/scrollView.bounds.size.width;

    self.myPageCtrl.currentPage = index;

}

- (void)awakeFromNib {
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/android.iml" filepath="$PROJECT_DIR$/android.iml" />
      <module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
      <module fileurl="file://$PROJECT_DIR$/go500px/go500px.iml" filepath="$PROJECT_DIR$/go500px/go500px.iml" />
    </modules>
  </component>
</project>


text:
package com.example.wei.myapplication;

import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

import java.awt.font.NumericShaper;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by wei on 17-10-9.
 */
/*

一个异步任务的执行一般包括以下几个步骤:

1.execute(Params... params),执行一个异步任务,需要我们在代码中调用此方法,触发异步任务的执行。

2.onPreExecute(),在execute(Params... params)被调用后立即执行,一般用来在执行后台任务前对UI做一些标记。

3.doInBackground(Params... params),在onPreExecute()完成后立即执行,用于执行较为费时的操作,此方法将接收输入参数和返回计算结果。在执行过程中可以调用publishProgress(Progress... values)来更新进度信息。

4.onProgressUpdate(Progress... values),在调用publishProgress(Progress... values)时,此方法被执行,直接将进度信息更新到UI组件上。

5.onPostExecute(Result result),当后台操作结束时,此方法将会被调用,计算结果将做为参数传递到此方法中,直接将结果显示到UI组件上。

 */
//下载
public class DownloadTask extends AsyncTask<String,Integer,Integer> {

    public static final int TYPE_SUCCESS = 0;
    public static final int TYPE_FAILED = 1;
    public static final int TYPE_PASUSED = 2;
    public static final int TYPE_CANCLED = 3;
    private DownloadListener listener;
    private boolean isCancled = false;
    private boolean isPaused = false;
    private int lastProgress;

    public DownloadTask(DownloadListener listener) {
        this.listener = listener;
    }

    @Override
    protected Integer doInBackground(String... params) {
        //用于在后台执行具体的下载逻辑
        InputStream is = null;
        RandomAccessFile saveFile = null;
        File file = null;
        try {
            long downloadLength = 0;//记录下载文件的长度
            String downloadUrl = params[0];
            String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/"));
            String directory = Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOWNLOADS).getPath();
            Log.d("test",">>weiyandong>>> fileName + directory ="+directory+fileName);
            file = new File(directory+fileName);
            if(!file.exists()){
                try {
                    file.createNewFile() ;
                    //file is create
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            Log.d("test",">>weiyandong>> file.exists ="+file.exists());
            if (file.exists()) {
                downloadLength = file.length();
            }
            long contentLength = getContentLength(downloadUrl);
            Log.d("test",">>weiyandong>>> contentLength="+contentLength);
            if (contentLength == 0) {
                return TYPE_FAILED;
            } else if (contentLength == downloadLength) {
                return TYPE_SUCCESS;
            }
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .addHeader("RANGE","bytes ="+downloadLength+"-")
                    .url(downloadUrl)
                    .build();
            Response response = client.newCall(request).execute();
            Log.d("test",">>weiyandong>>> response true?="+response.isSuccessful());
            if (response != null && response.isSuccessful()) {
                is = response.body().byteStream();
                Log.d("test",">>weiyandong>> saveFile before ="+saveFile);
                saveFile = new RandomAccessFile(file,"rw");
                Log.d("test",">>weiyandong>> saveFile after ="+saveFile);
                saveFile.seek(downloadLength);// 跳过已下载的章节
                byte [] b = new byte[1024];
                int total = 0;
                int len;
                while ((len = is.read(b)) != -1) {
                    if (isCancled) {
                        return TYPE_CANCLED;
                    } else if (isPaused) {
                        return TYPE_PASUSED;
                    } else {
                        total += len;
                        saveFile.write(b,0,len);
                        //计算已下载的百分比
                        int progress = (int)((total+downloadLength)*100/contentLength);
                        if (progress > 100) {
                            progress = 100;
                        }
                        publishProgress(progress);

                    }
                }
                response.body().close();
                return TYPE_SUCCESS;
            }

        } catch (Exception e){

        }finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (saveFile != null) {
                    saveFile.close();
                }
                if (isCancled && file != null) {
                    file.delete();

                }
            } catch (IOException e){
                e.printStackTrace();
            }
        }

        return TYPE_FAILED;
    }

    @Override
    protected void onPostExecute(Integer status) {
        //用于通知最终的下载结果
        switch (status) {
            case TYPE_CANCLED:
                listener.onCancled();
                break;
            case TYPE_SUCCESS:
                listener.onSuccess();
                break;
            case TYPE_FAILED:
                listener.onFailed();
                break;
            case TYPE_PASUSED:
                listener.onPaused();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        //用于在界面上更新当前的下载进度
        int progress = values[0];
        if (progress > lastProgress) {
            listener.onProgress(progress);
            lastProgress = progress;
        }
    }

    public void pauseDownload() {
        isPaused = true;
    }

    public void cancleDownload() {
        isCancled = true;
    }

    private long getContentLength(String downloadUrl) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(downloadUrl)
                .build();
        Response response = client.newCall(request).execute();
        if (response != null && response.isSuccessful()) {
            long contentLength = response.body().contentLength();
            response.close();
            return contentLength;
        }
        return 0;
    }
}


text:
{% load image_tags %}
{% load i18n %}
{% trans "Insert embed" as ins_emb_str %}
{% include "wagtailadmin/shared/header.html" with title=ins_emb_str merged=1 %}

        <form class="embed-form" action="{% url 'wagtailembeds_chooser_upload' %}" method="POST">
            {% csrf_token %}

                {% for field in form %}
                    {% include "wagtailadmin/shared/field_as_li.html" with field=field %}
                {% endfor %}

<input type="submit" value="{% trans 'Insert' %}" />

        </form>


text:
export default function () {
    var classnames;
    document.addEventListener('turbolinks:before-visit', function (evnt) {
        classnames = document
            .querySelector('.mm-wrapper')
            .className.split(' ')
            .filter(function (name) { return /mm-/.test(name); });
    });
    document.addEventListener('turbolinks:load', function (evnt) {
        if (typeof classnames === 'undefined') {
            return;
        }
        document.querySelector('.mm-wrapper').className = classnames;
    });
}


text:
package io.crnk.home;

import com.fasterxml.jackson.databind.JsonNode;
import io.crnk.core.boot.CrnkBoot;
import io.crnk.core.engine.http.HttpHeaders;
import io.crnk.core.engine.http.HttpRequestContextBase;
import io.crnk.core.engine.http.HttpResponse;
import io.crnk.core.engine.internal.http.HttpRequestDispatcherImpl;
import io.crnk.core.engine.url.ConstantServiceUrlProvider;
import io.crnk.meta.MetaModule;
import io.crnk.meta.MetaModuleConfig;
import io.crnk.meta.provider.resource.ResourceMetaProvider;
import io.crnk.test.mock.TestModule;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;

import java.io.IOException;

public class JsonApiFormatTest {

	private CrnkBoot boot;

	private HomeModule module;

	@Before
	public void setup() {
		MetaModuleConfig config = new MetaModuleConfig();
		config.addMetaProvider(new ResourceMetaProvider());
		MetaModule metaModule = MetaModule.createServerModule(config);

		this.module = Mockito.spy(HomeModule.create(HomeFormat.JSON_API));
		boot = new CrnkBoot();
		boot.addModule(module);
		boot.addModule(metaModule);
		boot.addModule(new TestModule());
		boot.setServiceUrlProvider(new ConstantServiceUrlProvider("http://localhost"));
		boot.boot();
	}

	@Test
	public void testWithAnyRequest() throws IOException {
		testJsonApiReturned(true);
	}

	@Test
	public void testWithJsonApiRequest() throws IOException {
		testJsonApiReturned(false);
	}

	private void testJsonApiReturned(boolean anyRequest) throws IOException {
		ArgumentCaptor<HttpResponse> responseCaptor = ArgumentCaptor.forClass(HttpResponse.class);

		HttpRequestContextBase requestContextBase = Mockito.mock(HttpRequestContextBase.class);

		Mockito.when(requestContextBase.getMethod()).thenReturn("GET");
		Mockito.when(requestContextBase.getPath()).thenReturn("/");
		Mockito.when(requestContextBase.getRequestHeader("Accept"))
				.thenReturn(anyRequest ? "*" : HttpHeaders.JSONAPI_CONTENT_TYPE);

		HttpRequestDispatcherImpl requestDispatcher = boot.getRequestDispatcher();
		requestDispatcher.process(requestContextBase);

		Mockito.verify(requestContextBase, Mockito.times(1)).setResponse(responseCaptor.capture());
		String expectedContentType = anyRequest ? HomeModule.JSON_CONTENT_TYPE : HttpHeaders.JSONAPI_CONTENT_TYPE;
		Assert.assertEquals(expectedContentType, responseCaptor.getValue().getHeader(("Content-Type")));
		Assert.assertEquals(200, responseCaptor.getValue().getStatusCode());

		String json = new String(responseCaptor.getValue().getBody());
		JsonNode response = boot.getObjectMapper().reader().readTree(json);

		JsonNode resourcesNode = response.get("links");
		JsonNode tasksNode = resourcesNode.get("tasks");
		Assert.assertEquals("http://localhost/tasks", tasksNode.asText());

		Assert.assertEquals("http://localhost/meta/", resourcesNode.get("meta").asText());
		Assert.assertNull(resourcesNode.get("meta/resource"));
		Assert.assertNull(resourcesNode.get("meta/attribute"));
	}

	@Test
	public void testRequestSubDirectory() throws IOException {
		ArgumentCaptor<HttpResponse> responseCaptor = ArgumentCaptor.forClass(HttpResponse.class);

		HttpRequestContextBase requestContextBase = Mockito.mock(HttpRequestContextBase.class);

		Mockito.when(requestContextBase.getMethod()).thenReturn("GET");
		Mockito.when(requestContextBase.getPath()).thenReturn("/meta/");

		HttpRequestDispatcherImpl requestDispatcher = boot.getRequestDispatcher();
		requestDispatcher.process(requestContextBase);

		Mockito.verify(requestContextBase, Mockito.times(1)).setResponse(responseCaptor.capture());
		String expectedContentType = HomeModule.JSON_CONTENT_TYPE;
		Assert.assertEquals(expectedContentType, responseCaptor.getValue().getHeader("Content-Type"));
		Assert.assertEquals(200, responseCaptor.getValue().getStatusCode());
		String json = new String(responseCaptor.getValue().getBody());
		JsonNode response = boot.getObjectMapper().reader().readTree(json);

		JsonNode linksNode = response.get("links");
		JsonNode resourceNode = linksNode.get("resource");
		Assert.assertEquals("http://localhost/meta/resource", resourceNode.asText());

		Assert.assertNull(linksNode.get("meta"));
		Assert.assertNotNull(linksNode.get("element"));
		Assert.assertNotNull(linksNode.get("attribute"));
	}
}


text:
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.android_webview;

/**
 * Simple class that provides access to the array of uncompressed pak locales. See
 * //android_webview/BUILD.gn for more details.
 */
public final class AwLocaleConfig {
    private AwLocaleConfig() {}

    public static String[] getWebViewSupportedPakLocales() {
        return ProductConfig.LOCALES;
    }
}


text:
package eagle.jfaster.org.benchmark.pojo;

import java.io.Serializable;

/**
 * Created by fangyanpeng on 2017/9/8.
 */
public class User implements Serializable {

    private int id;

    private String name;

    private int age;

    private Sex sex;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Sex getSex() {
        return sex;
    }

    public void setSex(Sex sex) {
        this.sex = sex;
    }
}


text:
class IndexBuffer;
class ShapeData;

class Renderable {
	public:
		Renderable();
		~Renderable();

		void Bind();
		void Unbind();
		void Feed(ShapeData* sd);

		VertexArray& VAO();
		IndexBuffer* IBO() const;
		ShapeData* SD() const;

	private:
		ShapeData* m_shape_data;
		VertexArray m_vao;
		IndexBuffer* m_ibo;
		bool m_fed;
};


text:
title: "Overview of the Broker log tab"
excerpt: ""
---
[block:callout]
{
  "type": "danger",
  "title": "The Broker log tab is only available for administrators!"
}
[/block]
The Broker log tab records the activity of all the VMs.
[block:image]
{
  "images": [
    {
      "image": [
        "https://files.readme.io/33ce360-brokerlog_overview_210.png",
        "brokerlog_overview_210.png",
        1262,
        676,
        "#eff7f7"
      ]
    }
  ]
}
[/block]
This broker log history gives several information:

  * User of the VM
  * State of the VM
  * Driver used
  * Machine ID
  * Machine size
  * Pool size
  * Creation date of the VM


text:
require File.expand_path('../../fixtures/classes', __FILE__)
require File.expand_path('../../fixtures/encoded_strings', __FILE__)

describe :array_join_with_default_separator, :shared => true do
  before do
    @separator = $,
  end

  after do
    $, = @separator
  end

  it "returns an empty string if the Array is empty" do
    [].send(@method).should == ''
  end

  ruby_version_is "1.9" do
    it "returns a US-ASCII string for an empty Array" do
      [].send(@method).encoding.should == Encoding::US_ASCII
    end
  end

  it "returns a string formed by concatenating each String element separated by $," do
    $, = " | "
    ["1", "2", "3"].send(@method).should == "1 | 2 | 3"
  end

  ruby_version_is ""..."1.9" do
    it "coerces non-String elements via #to_s" do
      obj = mock('foo')
      obj.should_receive(:to_s).and_return("foo")
      [obj].send(@method).should == "foo"
    end

    it "raises a NoMethodError if an element does not respond to #to_s" do
      obj = mock('o')
      class << obj; undef :to_s; end
      lambda { [obj].send(@method) }.should raise_error(NoMethodError)
    end
  end

  ruby_version_is "1.9" do
    it "attempts coercion via #to_str first" do
      obj = mock('foo')
      obj.should_receive(:to_str).any_number_of_times.and_return("foo")
      [obj].send(@method).should == "foo"
    end

    it "attempts coercion via #to_ary second" do
      obj = mock('foo')
      obj.should_receive(:to_str).any_number_of_times.and_return(nil)
      obj.should_receive(:to_ary).any_number_of_times.and_return(["foo"])
      [obj].send(@method).should == "foo"
    end

    it "attempts coercion via #to_s third" do
      obj = mock('foo')
      obj.should_receive(:to_str).any_number_of_times.and_return(nil)
      obj.should_receive(:to_ary).any_number_of_times.and_return(nil)
      obj.should_receive(:to_s).any_number_of_times.and_return("foo")
      [obj].send(@method).should == "foo"
    end

    it "raises a NoMethodError if an element does not respond to #to_str, #to_ary, or #to_s" do
      obj = mock('o')
      class << obj; undef :to_s; end
      lambda { [1, obj].send(@method) }.should raise_error(NoMethodError)
    end
  end

  ruby_version_is "".."1.9" do
    ruby_bug "[ruby-dev:37019]", "1.8.6.319" do
      it "represents a recursive element with '[...]'" do
        ArraySpecs.recursive_array.send(@method).should == "1two3.0[...][...][...][...][...]"
        ArraySpecs.head_recursive_array.send(@method).should == "[...][...][...][...][...]1two3.0"
        ArraySpecs.empty_recursive_array.send(@method).should == "[...]"
      end
    end
  end

  ruby_version_is "1.9" do
    it "raises an ArgumentError when the Array is recursive" do
      lambda { ArraySpecs.recursive_array.send(@method) }.should raise_error(ArgumentError)
      lambda { ArraySpecs.head_recursive_array.send(@method) }.should raise_error(ArgumentError)
      lambda { ArraySpecs.empty_recursive_array.send(@method) }.should raise_error(ArgumentError)
    end
  end

  it "taints the result if the Array is tainted and non-empty" do
    [1, 2].taint.send(@method).tainted?.should be_true
  end

  it "does not taint the result if the Array is tainted but empty" do
    [].taint.send(@method).tainted?.should be_false
  end

  it "taints the result if an element is tainted" do
    ["str".taint].send(@method).tainted?.should be_true
  end

  ruby_version_is "1.9" do
    it "untrusts the result if the Array is untrusted and non-empty" do
      [1, 2].untrust.send(@method).untrusted?.should be_true
    end

    it "does not untrust the result if the Array is untrusted but empty" do
      [].untrust.send(@method).untrusted?.should be_false
    end

    it "untrusts the result if an element is untrusted" do
      ["str".untrust].send(@method).untrusted?.should be_true
    end
  end

  ruby_version_is "1.9" do
    it "uses the first encoding when other strings are compatible" do
      ary1 = ArraySpecs.array_with_7bit_utf8_and_usascii_strings
      ary2 = ArraySpecs.array_with_usascii_and_7bit_utf8_strings
      ary3 = ArraySpecs.array_with_utf8_and_7bit_ascii8bit_strings
      ary4 = ArraySpecs.array_with_usascii_and_7bit_ascii8bit_strings

      ary1.send(@method).encoding.should == Encoding::UTF_8
      ary2.send(@method).encoding.should == Encoding::US_ASCII
      ary3.send(@method).encoding.should == Encoding::UTF_8
      ary4.send(@method).encoding.should == Encoding::US_ASCII
    end

    it "uses the widest common encoding when other strings are incompatible" do
      ary1 = ArraySpecs.array_with_utf8_and_usascii_strings
      ary2 = ArraySpecs.array_with_usascii_and_utf8_strings

      ary1.send(@method).encoding.should == Encoding::UTF_8
      ary2.send(@method).encoding.should == Encoding::UTF_8
    end

    it "fails for arrays with incompatibly-encoded strings" do
      ary_utf8_bad_ascii8bit = ArraySpecs.array_with_utf8_and_ascii8bit_strings

      lambda { ary_utf8_bad_ascii8bit.send(@method) }.should raise_error(EncodingError)
    end
  end
end

describe :array_join_with_string_separator, :shared => true do
  ruby_version_is ""..."1.9" do
    it "returns a string formed by concatenating each element.to_s separated by separator" do
      obj = mock('foo')
      obj.should_receive(:to_s).and_return("foo")
      [1, 2, 3, 4, obj].send(@method, ' | ').should == '1 | 2 | 3 | 4 | foo'
    end
  end

  ruby_version_is "1.9" do
    it "returns a string formed by concatenating each element.to_str separated by separator" do
      obj = mock('foo')
      obj.should_receive(:to_str).and_return("foo")
      [1, 2, 3, 4, obj].send(@method, ' | ').should == '1 | 2 | 3 | 4 | foo'
    end
  end

  it "uses the same separator with nested arrays" do
    [1, [2, [3, 4], 5], 6].send(@method, ":").should == "1:2:3:4:5:6"
    [1, [2, ArraySpecs::MyArray[3, 4], 5], 6].send(@method, ":").should == "1:2:3:4:5:6"
  end

  it "taints the result if the separator is tainted and the array is non-empty" do
    [1, 2].send(@method, ":".taint).tainted?.should be_true
  end

  it "does not taint the result if the separator is tainted but the array is empty" do
    [].send(@method, ":".taint).tainted?.should be_false
  end

  ruby_version_is '1.9' do
    it "untrusts the result if the separator is untrusted and the array is non-empty" do
      [1, 2].send(@method, ":".untrust).untrusted?.should be_true
    end

    it "does not untrust the result if the separator is untrusted but the array is empty" do
      [].send(@method, ":".untrust).untrusted?.should be_false
    end
  end
end


text:
@interface PodsDummy_React_Core : NSObject
@end
@implementation PodsDummy_React_Core
@end


text:
<?php

namespace Norm\Schema;

class File extends Object
{
    public function prepare($value)
    {
        $app = \App::getInstance();

        if ($app->request->isPost() && !empty($_FILES)) {
            $fileMeta = $_FILES[$this['name']];

            $bucket = trim($this['bucket'], '/');
            $bucketPath = getcwd().'/'.$bucket;

            @mkdir($bucketPath, 0755, true);

            $fileMeta['bucket'] = $bucket;

            switch ($fileMeta['error']) {
                case UPLOAD_ERR_INI_SIZE:
                case UPLOAD_ERR_FORM_SIZE:
                    throw new \Exception('The uploaded file exceeds allowed file size.');
                case UPLOAD_ERR_PARTIAL:
                    throw new \Exception('The uploaded file was only partially uploaded.');
                case UPLOAD_ERR_NO_FILE:
                    $this->filter[] = 'ignoreNull';
                    return null;
                case UPLOAD_ERR_NO_TMP_DIR:
                    throw new \Exception('Missing a temporary folder.');
                case UPLOAD_ERR_CANT_WRITE:
                    throw new \Exception('Failed to write file to disk.');
                case UPLOAD_ERR_EXTENSION:
                    throw new \Exception('Unknown upload error.');
            }

            unset($fileMeta['error']);

            $filename = $this['filename'];
            if (is_callable($filename)) {
                $filename = call_user_func($filename, $fileMeta);
            } else {
                throw new \Exception('Unimplemented yet!');
            }

            $fileMeta['original_name'] = $fileMeta['name'];
            $fileMeta['name'] = $filename;

            $filepath = $bucketPath.'/'.$filename;
            $tmpName = $fileMeta['tmp_name'];

            unset($fileMeta['tmp_name']);

            move_uploaded_file($tmpName, $filepath);

            $value = $fileMeta;
        }

        return parent::prepare($value);
    }

    public function formatReadonly($value, $entry = null)
    {
        return ''.($value['name'] ?: '-').'';
    }

    public function formatInput($value, $entry = null)
    {
        return '
            <input type="hidden" name="'.$this['name'].'">
            <input type="file" name="'.$this['name'].'">
        '.@$value['name'];
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using ExtMessage;

public partial class Modules_DanhMuc_DM_TT_LAMVIEC : SoftCore.Security.WebBase
{

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!X.IsAjaxRequest)
        {
            hdfMaDonVi.Text = Session["MaDonVi"].ToString();
            // button
            btnAddNew.Visible = SetVisible(btnAddNew.Text);
            btnEdit.Visible = SetVisible(btnEdit.Text);
            btnDelete.Visible = SetVisible(btnDelete.Text);
            // context menu
            mnuAddNew.Visible = SetVisible(btnAddNew.Text);
            mnuEdit.Visible = SetVisible(btnEdit.Text);
            mnuDelete.Visible = SetVisible(btnDelete.Text);
        }

        if (btnAddNew.Visible)
        {

        }
        if (btnEdit.Visible)
        {
            checkboxSelection.Listeners.RowSelect.Handler += "btnEdit.enable();";
            GridPanel1.DirectEvents.DblClick.Event += new ComponentDirectEvent.DirectEventHandler(btnEdit_Click);
        }
        if (btnDelete.Visible)
        {
            checkboxSelection.Listeners.RowSelect.Handler += "btnDelete.enable();";
        }
    }
    protected void btnCapNhat_Click(object sender, DirectEventArgs e)
    {
        DAL.DM_TT_LAMVIEC obj = new DAL.DM_TT_LAMVIEC();
        KyHieuChamCongController ctr = new KyHieuChamCongController();
        obj.KYHIEU_TT_LAMVIEC = txtKYHIEU_TT_LAMVIEC.Text;
        obj.TEN_TT_LAMVIEC = txtTEN_TT_LAMVIEC.Text;
        obj.DIEN_GIAI = txtDIEN_GIAI.Text;
        if (!string.IsNullOrEmpty(txtSTT.Text))
            obj.STT = decimal.Parse(txtSTT.Text);
        else
            obj.STT = 0;
        obj.CREATED_USER = CurrentUser.DisplayName;
        obj.DATE_CREATE = DateTime.Now;
        obj.IS_IN_USED = chkIsIS_IN_USED.Checked;
        obj.QUI_UOC_CHAM_CONG = txtQUI_UOC_CHAM_CONG.SelectedItem.Value;
        obj.MA_DONVI = Session["MaDonVi"].ToString();
        try
        {
            if (e.ExtraParams["Command"] == "Edit")
            {
                obj.PR_KEY = int.Parse(hdfRecordID.Text);
                ctr.Update(obj);
                Dialog.ShowNotification(CommonMessage.INSERT_SUCCESSFULLY);
                wdAddWindow.Hide();
                //RM.RegisterClientScriptBlock("fd", string.Format("addUpdatedRecord('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}')", txtKYHIEU_TT_LAMVIEC.Text, txtTEN_TT_LAMVIEC.Text, txtDIEN_GIAI.Text, txtSTT.Text, CurrentUser.DisplayName, DateTime.Now, chkIsIS_IN_USED.Checked, txtQUI_UOC_CHAM_CONG.SelectedItem.Value));
            }
            else
            {
                if (ctr.CheckDuplicateSignal(obj.KYHIEU_TT_LAMVIEC, Session["MaDonVi"].ToString()))
                {
                    X.MessageBox.Alert("Có lỗi xảy ra", "Kí hiệu chấm công bị trùng, bạn vui lòng chọn kí hiệu khác").Show();
                    return;
                }
                int prkey = ctr.Insert(obj);
                Dialog.ShowNotification(CommonMessage.INSERT_SUCCESSFULLY);
                if (e.ExtraParams["Close"] == "True")
                {
                    wdAddWindow.Hide();
                }
                else
                {
                    RM.RegisterClientScriptBlock("rs", "resetWindowHide();");
                }
                //RM.RegisterClientScriptBlock("fd", string.Format("addRecord('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}','{8}')", txtKYHIEU_TT_LAMVIEC.Text, txtTEN_TT_LAMVIEC.Text, txtDIEN_GIAI.Text, txtSTT.Text, CurrentUser.DisplayName, DateTime.Now, chkIsIS_IN_USED.Checked, txtQUI_UOC_CHAM_CONG.SelectedItem.Value, prkey));
            }
            GridPanel1.Reload();
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            if (ex.Number == 2627)
            {
                X.MessageBox.Alert("Có lỗi xảy ra", "Qui ước chấm công bị trùng, bạn hãy chọn quy ước chấm công khác").Show();
            }
        }
        catch (Exception ex)
        {
            X.MessageBox.Alert("Có lỗi xảy ra", ex.Message).Show();
        }
    }

    [DirectMethod]
    public void DeleteRecord(int pr_key)
    {
        new KyHieuChamCongController().DeleteByPrkey(pr_key);
        hdfRecordID.Text = "";
    }

    [DirectMethod]
    public void ResetWindowTitle()
    {
        wdAddWindow.Icon = Icon.Add;
        wdAddWindow.Title = "Thêm mới kí hiệu chấm công";
        hdfCommand.SetValue("");
    }

    protected void btnEdit_Click(object sender, DirectEventArgs e)
    {
        DAL.DM_TT_LAMVIEC record = new KyHieuChamCongController().GetbyPrKey(int.Parse(hdfRecordID.Text));
        txtKYHIEU_TT_LAMVIEC.Text = record.KYHIEU_TT_LAMVIEC;
        txtTEN_TT_LAMVIEC.Text = record.TEN_TT_LAMVIEC;
        txtDIEN_GIAI.Text = record.DIEN_GIAI;
        txtSTT.Text = record.STT.Value.ToString();
        chkIsIS_IN_USED.Checked = record.IS_IN_USED;
        txtQUI_UOC_CHAM_CONG.SetValue(record.QUI_UOC_CHAM_CONG);

        hdfCommand.Text = "Update";
        wdAddWindow.Icon = Icon.Pencil;
        wdAddWindow.Title = "Sửa kí hiệu chấm công";
        wdAddWindow.Show();
    }
}


text:
package org.apache.geode.distributed.internal.membership.gms.messenger;

import static org.apache.geode.distributed.ConfigurationProperties.LOCATORS;
import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.util.Properties;
import java.util.concurrent.RejectedExecutionException;

import org.jgroups.Event;
import org.jgroups.Message;
import org.jgroups.protocols.UNICAST3.Header;
import org.jgroups.protocols.pbcast.NakAckHeader2;
import org.jgroups.stack.Protocol;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import org.apache.geode.distributed.internal.membership.api.MembershipConfig;
import org.apache.geode.distributed.internal.membership.api.MembershipStatistics;
import org.apache.geode.distributed.internal.membership.gms.Services;
import org.apache.geode.distributed.internal.membership.gms.interfaces.Manager;
import org.apache.geode.test.junit.categories.MembershipTest;

/**
 * This class tests the GMS StatRecorder class, which records JGroups messaging statistics
 */
@Category({MembershipTest.class})
public class StatRecorderJUnitTest {

  private Protocol mockDownProtocol;
  private Protocol mockUpProtocol;
  private StatRecorder recorder;
  private MembershipStatistics stats;
  private Services services;

  @Before
  public void setUp() throws Exception {
    stats = mock(MembershipStatistics.class);

    // create a StatRecorder that has mock up/down protocols and stats
    mockDownProtocol = mock(Protocol.class);
    mockUpProtocol = mock(Protocol.class);

    services = mock(Services.class);
    when(services.getStatistics()).thenReturn(stats);

    recorder = new StatRecorder();
    recorder.setServices(services);
    recorder.setUpProtocol(mockUpProtocol);
    recorder.setDownProtocol(mockDownProtocol);
  }

  /**
   * Ensure that unicast events are recorded in DMStats
   */
  @Test
  public void testUnicastStats() throws Exception {
    Message msg = mock(Message.class);
    when(msg.getHeader(any(Short.class))).thenReturn(Header.createDataHeader(1L, (short) 1, true));
    when(msg.size()).thenReturn(150L);

    Event evt = new Event(Event.MSG, msg);
    recorder.up(evt);
    verify(stats).incUcastReadBytes(150);

    recorder.down(evt);
    verify(stats).incUcastWriteBytes(150);

    msg = mock(Message.class);
    when(msg.getHeader(any(Short.class))).thenReturn(Header.createXmitReqHeader());
    when(msg.size()).thenReturn(150L);
    evt = new Event(Event.MSG, msg);
    recorder.down(evt);
    verify(stats).incUcastRetransmits();
  }

  @Test
  public void recorderHandlesRejectedExecution() throws Exception {
    Message msg = mock(Message.class);
    when(msg.getHeader(any(Short.class))).thenReturn(Header.createDataHeader(1L, (short) 1, true));
    when(msg.size()).thenReturn(150L);

    // GEODE-1178, the TP protocol may throw a RejectedExecutionException & StatRecorder should
    // retry
    when(mockDownProtocol.down(any(Event.class))).thenThrow(new RejectedExecutionException());

    // after the first down() throws an exception we want StatRecorder to retry, so
    // we set the Manager to say no shutdown is in progress the first time and then say
    // one IS in progress so we can break out of the StatRecorder exception handling loop
    when(services.getCancelCriterion()).thenReturn(new Services().getCancelCriterion());
    Manager manager = mock(Manager.class);
    when(services.getManager()).thenReturn(manager);
    when(manager.shutdownInProgress()).thenReturn(Boolean.FALSE, Boolean.TRUE);

    verify(mockDownProtocol, never()).down(isA(Event.class));

    Event evt = new Event(Event.MSG, msg);
    recorder.down(evt);

    verify(mockDownProtocol, times(2)).down(isA(Event.class));
  }

  /**
   * ensure that multicast events are recorded in DMStats
   */
  @Test
  public void testMulticastStats() throws Exception {
    Message msg = mock(Message.class);
    when(msg.getHeader(any(Short.class))).thenReturn(NakAckHeader2.createMessageHeader(1L));
    when(msg.size()).thenReturn(150L);

    Event evt = new Event(Event.MSG, msg);
    recorder.up(evt);
    verify(stats).incMcastReadBytes(150);

    recorder.down(evt);
    verify(stats).incMcastWriteBytes(150);

    msg = mock(Message.class);
    when(msg.size()).thenReturn(150L);
    when(msg.getHeader(any(Short.class))).thenReturn(NakAckHeader2.createXmitRequestHeader(null));
    evt = new Event(Event.MSG, msg);
    recorder.down(evt);
    verify(stats).incMcastRetransmitRequests();

    msg = mock(Message.class);
    when(msg.size()).thenReturn(150L);
    when(msg.getHeader(any(Short.class))).thenReturn(NakAckHeader2.createXmitResponseHeader());
    evt = new Event(Event.MSG, msg);
    recorder.down(evt);
    verify(stats).incMcastRetransmits();
  }

  /**
   * Ensure that the messenger JGroups configuration XML strings contain the statistics recorder
   * protocol
   */
  @Test
  public void messengerStackHoldsStatRecorder() throws Exception {
    Services mockServices = mock(Services.class);

    // first test to see if the non-multicast stack has the recorder installed
    Properties nonDefault = new Properties();
    nonDefault.put(MCAST_PORT, "0");
    nonDefault.put(LOCATORS, "localhost[12345]");
    MembershipConfig mockConfig = mock(MembershipConfig.class);
    when(mockConfig.getMembershipPortRange()).thenReturn(new int[] {0, 10});
    when(mockConfig.getSecurityUDPDHAlgo()).thenReturn("");
    when(mockServices.getConfig()).thenReturn(mockConfig);

    JGroupsMessenger messenger = new JGroupsMessenger();
    messenger.init(mockServices);
    String jgroupsConfig = messenger.jgStackConfig;
    System.out.println(jgroupsConfig);
    assertTrue(jgroupsConfig.contains("gms.messenger.StatRecorder"));

    // now test to see if the multicast stack has the recorder installed
    when(mockConfig.getMcastPort()).thenReturn(12345);
    when(mockServices.getConfig()).thenReturn(mockConfig);

    messenger = new JGroupsMessenger();
    messenger.init(mockServices);
    assertTrue(jgroupsConfig.contains("gms.messenger.StatRecorder"));
  }
}