text:
@implementation ANXImagePickerAssetInput

#pragma mark Constructor

-(id)initWithAsset:(ALAsset *)asset
{
    self = [super init];

    if (self)
    {
        _asset = asset;
    }

    return self;
}

#pragma mark properties

@synthesize asset = _asset;

#pragma mark methods

-(long long) getSize
{
    ALAssetRepresentation *representation = [self.asset defaultRepresentation];

    return representation.size;
}

-(void) readBytes: (FREObject) bytes fromOffset: (long long) offset desiredLength: (NSUInteger) length
{
    ALAssetRepresentation *representation = [self.asset defaultRepresentation];

    uint8_t *buffer = malloc(length);

    NSError *error;

    NSUInteger actualLength = [representation getBytes:buffer fromOffset:offset length:length error:&error];

    if (error != nil)
    {
        [[ANXImagePicker sharedInstance] dispatch:@"ImagePicker.AssetInput.ReadBytes.Failed" withLevel: error.localizedDescription];

        free(buffer);

        return;
    }

    FREResult result;

    FREObject size;
    result = FRENewObjectFromUint32((uint32_t) actualLength, &size);

    if (result != FRE_OK)
    {
        [[ANXImagePicker sharedInstance] dispatchError:@"ImagePicker.AssetInput.ReadBytes.Failed"];

        free(buffer);

        return;
    }

    result = FRESetObjectProperty(bytes, (const uint8_t *) "length", size, NULL);

    if (result != FRE_OK)
    {
        [[ANXImagePicker sharedInstance] dispatchError:@"ImagePicker.AssetInput.ReadBytes.Failed"];

        free(buffer);

        return;
    }

    FREByteArray container;
    result = FREAcquireByteArray(bytes, &container);

    if (result != FRE_OK)
    {
        [[ANXImagePicker sharedInstance] dispatchError:@"ImagePicker.AssetInput.ReadBytes.Failed"];

        FREReleaseByteArray(bytes);

        free(buffer);

        return;
    }

    memcpy(container.bytes, buffer, actualLength);

    free(buffer);

    FREReleaseByteArray(bytes);

}

@end


text:
sudo mkdir -p /mounts/var/cassandra/data/data
sudo mkdir -p /mounts/var/cassandra/data/commitlog

sudo mount -o rw /dev/xvdf /mounts/var/cassandra/data/data
sudo mount -o rw /dev/xvdg /mounts/var/cassandra/data/commitlog

sudo umount /dev/xvdf
sudo umount /dev/xvdg

redpajama_set_name: RedPajamaGithub


text:
<?php

if( class_exists( 'KWS_GF_Change_Lead_Creator' ) ) {
    return;
}

/**
 * @since 3.6.2
 */
class KWS_GF_Change_Lead_Creator {

    function __construct() {

        add_action('plugins_loaded', array($this, 'load'));
    }

    /**
     * @since  3.6.3
     * @return void
     */
    function load() {

        // Does GF exist? Can the user edit entries?
        if( !class_exists('GFCommon') ) {
            return;
        }

        if( !GFCommon::current_user_can_any("gravityforms_edit_entries") ) {
            return;
        }

        // If screen mode isn't set, then we're in the wrong place.
        if( empty( $_REQUEST['screen_mode'] ) ) {
            return;
        }

        // Now, no validation is required in the methods; let's hook in.
        add_action('admin_init', array( &$this, 'set_screen_mode' ) );

        add_action("gform_entry_info", array( &$this, 'add_select' ), 10, 2);

        add_action("gform_after_update_entry", array( &$this, 'update_entry_creator' ), 10, 2);

    }

    /**
     * Allows for edit links to work with a link instead of a form (GET instead of POST)
     * @return [type] [description]
     */
    function set_screen_mode() {

        if( !empty( $_REQUEST["screen_mode"] ) ) {
            $_POST["screen_mode"] = esc_attr( $_REQUEST["screen_mode"] );
        }

    }

    /**
     * When the entry creator is changed, add a note to the entry
     * @param  array $form   GF entry array
     * @param  int $leadid Lead ID
     * @return void
     */
    function update_entry_creator($form, $leadid) {
            global $current_user;

        // Update the entry
        $created_by = intval( rgpost('created_by') );

        RGFormsModel::update_lead_property($leadid, 'created_by', $created_by);

        // If the creator has changed, let's add a note about who it used to be.
        $originally_created_by = rgpost('originally_created_by');

        if($originally_created_by !== $created_by) {

            $user_data = get_userdata($current_user->ID);

            $user_format = __('%s (ID #%d)', 'gravity-view');

            $original_name = $created_by_name = esc_attr__( 'No User', 'gravity-view');

            if( !empty( $originally_created_by ) ) {
                $originally_created_by_user_data = get_userdata($originally_created_by);
                $original_name = sprintf( $user_format, $originally_created_by_user_data->display_name, $originally_created_by_user_data->ID );
            }

            if( !empty( $created_by ) ) {
                $created_by_user_data =  get_userdata($created_by);
                $created_by_name = sprintf( $user_format, $created_by_user_data->display_name, $created_by_user_data->ID );
            }

            RGFormsModel::add_note($leadid, $current_user->ID, $user_data->display_name, sprintf(__('Changed lead creator from %s to %s', 'gravity-forms-addons'), $original_name, $created_by_name ) );
        }

    }

    /**
     * Output the select to change the entry creator
     * @param int $form_id GF Form ID
     * @param array $lead    GF lead array
     * @return void
     */
    function add_select($form_id, $lead) {

        if( rgpost('screen_mode') !== 'edit' ) {
            return;
        }

        /**
         * There are issues with too many users where it breaks the select. We try to keep it at a reasonable number.
         * @link   texthttp://codex.wordpress.org/Function_Reference/get_users
         * @var  array Settings array
         */
        $get_users_settings = apply_filters( 'gravityview_change_entry_creator_user_parameters', array( 'number' => 300 ) );

        $users = get_users( $get_users_settings );

        $output = '<label for="change_created_by">';
        $output .= esc_html__('Change Entry Creator:', 'gravity-forms-addons');
        $output .= '</label>
        <select name="created_by" id="change_created_by" class="widefat">';
        $output .= '<option value=""> — '.esc_attr__( 'No User', 'gravity-view').' — </option>';
        foreach($users as $user) {
            $output .= '<option value="'. $user->ID .'"'. selected( $lead['created_by'], $user->ID, false ).'>'.esc_attr( $user->display_name.' ('.$user->user_nicename.')' ).'</option>';
        }
        $output .= '</select>';
        $output .= '<input name="originally_created_by" value="'.$lead['created_by'].'" type="hidden" />';
        echo $output;

    }

}

new KWS_GF_Change_Lead_Creator;


text:
using UnityEngine;

namespace Leap.Unity {
  /// <summary>
  /// Time-step independent exponential smoothing.
  /// </summary>
  /// <remarks>
  /// When moving at a constant speed: speed * delay = Value - SmoothedFloat.value.
  /// </remarks>
  [System.Serializable]
  public class SmoothedFloat {
    public float value = 0f; // Filtered value
    public float delay = 0f; // Mean delay
    public bool reset = true; // Reset on Next Update

    public void SetBlend(float blend, float deltaTime = 1f) {
      delay = deltaTime * blend / (1f - blend);
    }

    public float Update(float input, float deltaTime = 1f) {
      if (deltaTime > 0f && !reset) {
        float alpha = delay / deltaTime;
        float blend = alpha / (1f + alpha);
        // NOTE: If delay -> 0 then blend -> 0,
        // reducing the filter to this.value = value.
        // NOTE: If deltaTime -> 0 blend -> 1,
        // so the change in the filtered value will be suppressed
        value = Mathf.Lerp(value, input, 1f - blend);
      } else {
        value = input;
        reset = false;
      }
      return value;
    }
  }
}


text:
require 'active_support/core_ext/hash/keys'
require 'liquid'
require 'liquid/tags/paginate'
require 'liquid/tags/contact_form'
require 'liquid/tags/captcha'
require 'liquid/tags/lr_include'
require 'liquid/filters'
require 'hashie'
require 'json'

module Limitedrun
  module Themekit
    class Renderer < Struct.new(:theme_path, :request_path)
      def render(template, template_assigns = nil)
        assigns = global_assigns

        if template_assigns
          template_assigns.each_key do |k|
            unless template_assigns[k].is_a?(Hashie::Mash)
              template_assigns[k] = Hashie::Mash.new(instance_eval &template_assigns[k])
            end
          end

          assigns.merge!(template_assigns.stringify_keys)
        end

        layout = parse_template File.join(Limitedrun::Themekit::Config.layouts_dir, 'default.html')
        template = parse_template File.join(Limitedrun::Themekit::Config.templates_dir, template)

        layout.render(assigns.merge('content' => template.render(assigns)))
      end

      def render_string(string)
        Liquid::Template.parse(string).render('config' => theme_config)
      end

      protected

      # Assignments for all liquid templates
      def global_assigns
        { 'config' => theme_config, 'store' => store }
      end

      # Theme configuration extracted from config/defaults.js and store.config overrides
      def theme_config
        return @theme_config if @theme_config

        settings = JSON.parse(
          File.read(
            File.join(
              Limitedrun::Themekit::Config.theme_path,
              Limitedrun::Themekit::Config.configs_dir,
              'default.json'
            )
          )
        )['settings']

        config = {}

        settings.each do |k, v|
          config[k] = v['default'] if v['default']
        end

        if store && store.config
          store.config.each { |k, v| config[k] = v }
        end

        @config = config
      end

      # Store mock data model loaded from store.json
      def store
        @store ||= Hashie::Mash.new(JSON.parse(File.read(File.join(Limitedrun::Themekit::Config.theme_path, 'store.json'))))
      end

      def parse_template(template)
        Liquid::Template.parse(
          File.read(
            File.join(
              Limitedrun::Themekit::Config.theme_path,
              template
            )
          )
        )
      end
    end
  end
end


text:
layout: post
title: Why, yes, 15 minutes is plenty of time to brush up on the JavaScript and jQuery!
date:
type: post
published: false
status: draft
categories: []
tags: []
meta:
  google_plus_activity_id: z12jgbdxzm2bjpc2i234i3fogkmne1adz
author:
  login: admin
  email: cczona@gmail.com
  display_name: admin
  first_name: Carina C.
  last_name: Zon
---

Why, yes, 15 minutes is plenty of time to brush up on the JavaScript and jQuery!


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

import static com.amazonaws.util.StringUtils.UTF8;
import static com.amazonaws.util.StringUtils.COMMA_SEPARATOR;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.regex.Pattern;

import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.codepipeline.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.IdempotentUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.json.*;

/**
 * DeleteCustomActionTypeRequest Marshaller
 */
public class DeleteCustomActionTypeRequestMarshaller
        implements
        Marshaller<Request<DeleteCustomActionTypeRequest>, DeleteCustomActionTypeRequest> {

    public Request<DeleteCustomActionTypeRequest> marshall(
            DeleteCustomActionTypeRequest deleteCustomActionTypeRequest) {

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

        Request<DeleteCustomActionTypeRequest> request = new DefaultRequest<DeleteCustomActionTypeRequest>(
                deleteCustomActionTypeRequest, "AWSCodePipeline");
        request.addHeader("X-Amz-Target",
                "CodePipeline_20150709.DeleteCustomActionType");

        request.setHttpMethod(HttpMethodName.POST);

        request.setResourcePath("");

        try {
            final SdkJsonGenerator jsonGenerator = new SdkJsonGenerator();

            jsonGenerator.writeStartObject();

            if (deleteCustomActionTypeRequest.getCategory() != null) {
                jsonGenerator.writeFieldName("category").writeValue(
                        deleteCustomActionTypeRequest.getCategory());
            }
            if (deleteCustomActionTypeRequest.getProvider() != null) {
                jsonGenerator.writeFieldName("provider").writeValue(
                        deleteCustomActionTypeRequest.getProvider());
            }
            if (deleteCustomActionTypeRequest.getVersion() != null) {
                jsonGenerator.writeFieldName("version").writeValue(
                        deleteCustomActionTypeRequest.getVersion());
            }

            jsonGenerator.writeEndObject();

            byte[] content = jsonGenerator.getBytes();
            request.setContent(new ByteArrayInputStream(content));
            request.addHeader("Content-Length",
                    Integer.toString(content.length));
            request.addHeader("Content-Type", "application/x-amz-json-1.1");
        } catch (Throwable t) {
            throw new AmazonClientException(
                    "Unable to marshall request to JSON: " + t.getMessage(), t);
        }

        return request;
    }

}


text:
require File.join(File.dirname(__FILE__), 'provider_database_postgresql')

class Chef
  class Provider
    class Database
      class PostgresqlSchema < Chef::Provider::Database::Postgresql
        include Chef::Mixin::ShellOut

        def load_current_resource
          Gem.clear_paths
          begin
            require 'pg'
          rescue LoadError
            Chef::Log.fatal('Could not load the required pg gem. Make sure to include the database::postgresql or postgresql::ruby recipes in your runlist')
            raise
          end
          @current_resource = Chef::Resource::PostgresqlDatabaseSchema.new(@new_resource.name)
          @current_resource.schema_name(@new_resource.schema_name)
          @current_resource
        end

        def action_create
          unless exists?
            begin
              if new_resource.owner
                db(@new_resource.database_name).query("CREATE SCHEMA \"#{@new_resource.schema_name}\" AUTHORIZATION \"#{@new_resource.owner}\"")
              else
                db(@new_resource.database_name).query("CREATE SCHEMA \"#{@new_resource.schema_name}\"")
              end
              @new_resource.updated_by_last_action(true)
            ensure
              close
            end
          end
        end

        def action_drop
          if exists?
            begin
              db(@new_resource.database_name).query("DROP SCHEMA \"#{@new_resource.schema_name}\"")
              @new_resource.updated_by_last_action(true)
            ensure
              close
            end
          end
        end

        private

        def exists?
          begin
            exists = db(@new_resource.database_name).query("SELECT schema_name FROM information_schema.schemata WHERE schema_name='#{@new_resource.schema_name}'").num_tuples != 0
          ensure
            close
          end
          exists
        end
      end
    end
  end
end


text:
using Microsoft.Win32.SafeHandles;
using System.ComponentModel;
using System.Diagnostics;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;

namespace System.Net
{
    internal static class SslStreamPal
    {
        private const string SecurityPackage = "Microsoft Unified Security Protocol Provider";

        private const Interop.SspiCli.ContextFlags RequiredFlags =
            Interop.SspiCli.ContextFlags.ReplayDetect |
            Interop.SspiCli.ContextFlags.SequenceDetect |
            Interop.SspiCli.ContextFlags.Confidentiality |
            Interop.SspiCli.ContextFlags.AllocateMemory;

        private const Interop.SspiCli.ContextFlags ServerRequiredFlags =
            RequiredFlags | Interop.SspiCli.ContextFlags.AcceptStream;

        public static Exception GetException(SecurityStatusPal status)
        {
            int win32Code = (int)SecurityStatusAdapterPal.GetInteropFromSecurityStatusPal(status);
            return new Win32Exception(win32Code);
        }

        internal const bool StartMutualAuthAsAnonymous = true;

        public static void VerifyPackageInfo()
        {
            SSPIWrapper.GetVerifyPackageInfo(GlobalSSPI.SSPISecureChannel, SecurityPackage, true);
        }

        public static SecurityStatusPal AcceptSecurityContext(ref SafeFreeCredentials credentialsHandle, ref SafeDeleteContext context, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer, bool remoteCertRequired)
        {
            Interop.SspiCli.ContextFlags unusedAttributes = default(Interop.SspiCli.ContextFlags);

            int errorCode = SSPIWrapper.AcceptSecurityContext(
                GlobalSSPI.SSPISecureChannel,
                ref credentialsHandle,
                ref context,
                ServerRequiredFlags | (remoteCertRequired ? Interop.SspiCli.ContextFlags.MutualAuth : Interop.SspiCli.ContextFlags.Zero),
                Interop.SspiCli.Endianness.Native,
                inputBuffer,
                outputBuffer,
                ref unusedAttributes);

            return SecurityStatusAdapterPal.GetSecurityStatusPalFromNativeInt(errorCode);
        }

        public static SecurityStatusPal InitializeSecurityContext(ref SafeFreeCredentials credentialsHandle, ref SafeDeleteContext context, string targetName, SecurityBuffer inputBuffer, SecurityBuffer outputBuffer)
        {
            Interop.SspiCli.ContextFlags unusedAttributes = default(Interop.SspiCli.ContextFlags);

            int errorCode = SSPIWrapper.InitializeSecurityContext(
                GlobalSSPI.SSPISecureChannel,
                ref credentialsHandle,
                ref context,
                targetName,
                RequiredFlags | Interop.SspiCli.ContextFlags.InitManualCredValidation,
                Interop.SspiCli.Endianness.Native,
                inputBuffer,
                outputBuffer,
                ref unusedAttributes);

            return SecurityStatusAdapterPal.GetSecurityStatusPalFromNativeInt(errorCode);
        }

        public static SecurityStatusPal InitializeSecurityContext(SafeFreeCredentials credentialsHandle, ref SafeDeleteContext context, string targetName, SecurityBuffer[] inputBuffers, SecurityBuffer outputBuffer)
        {
            Interop.SspiCli.ContextFlags unusedAttributes = default(Interop.SspiCli.ContextFlags);

            int errorCode = SSPIWrapper.InitializeSecurityContext(
                            GlobalSSPI.SSPISecureChannel,
                            credentialsHandle,
                            ref context,
                            targetName,
                            RequiredFlags | Interop.SspiCli.ContextFlags.InitManualCredValidation,
                            Interop.SspiCli.Endianness.Native,
                            inputBuffers,
                            outputBuffer,
                            ref unusedAttributes);

            return SecurityStatusAdapterPal.GetSecurityStatusPalFromNativeInt(errorCode);
        }

        public static SafeFreeCredentials AcquireCredentialsHandle(X509Certificate certificate, SslProtocols protocols, EncryptionPolicy policy, bool isServer)
        {
            int protocolFlags = GetProtocolFlagsFromSslProtocols(protocols, isServer);
            Interop.SspiCli.SecureCredential.Flags flags;
            Interop.SspiCli.CredentialUse direction;

            if (!isServer)
            {
                direction = Interop.SspiCli.CredentialUse.Outbound;
                flags = Interop.SspiCli.SecureCredential.Flags.ValidateManual | Interop.SspiCli.SecureCredential.Flags.NoDefaultCred;

                // CoreFX: always opt-in SCH_USE_STRONG_CRYPTO except for SSL3.
                if (((protocolFlags & (Interop.SChannel.SP_PROT_TLS1_0 | Interop.SChannel.SP_PROT_TLS1_1 | Interop.SChannel.SP_PROT_TLS1_2)) != 0)
                     && (policy != EncryptionPolicy.AllowNoEncryption) && (policy != EncryptionPolicy.NoEncryption))
                {
                    flags |= Interop.SspiCli.SecureCredential.Flags.UseStrongCrypto;
                }
            }
            else
            {
                direction = Interop.SspiCli.CredentialUse.Inbound;
                flags = Interop.SspiCli.SecureCredential.Flags.Zero;
            }

            Interop.SspiCli.SecureCredential secureCredential = CreateSecureCredential(
                Interop.SspiCli.SecureCredential.CurrentVersion,
                certificate,
                flags,
                protocolFlags,
                policy);

            return AcquireCredentialsHandle(direction, secureCredential);
        }

        public static SecurityStatusPal EncryptMessage(SafeDeleteContext securityContext, byte[] input, int offset, int size, int headerSize, int trailerSize, ref byte[] output, out int resultSize)
        {
            // Ensure that there is sufficient space for the message output.
            try
            {
                int bufferSizeNeeded = checked(size + headerSize + trailerSize);

                if (output == null || output.Length < bufferSizeNeeded)
                {
                    output = new byte[bufferSizeNeeded];
                }
            }
            catch (Exception e)
            {
                if (!ExceptionCheck.IsFatal(e))
                {
                    if (GlobalLog.IsEnabled)
                    {
                        GlobalLog.Assert("SslStreamPal.Windows: SecureChannel#" + LoggingHash.HashString(securityContext) + "::Encrypt", "Arguments out of range.");
                    }

                    Debug.Fail("SslStreamPal.Windows: SecureChannel#" + LoggingHash.HashString(securityContext) + "::Encrypt", "Arguments out of range.");
                }

                throw;
            }

            byte[] writeBuffer = output;

            // Copy the input into the output buffer to prepare for SCHANNEL's expectations
            Buffer.BlockCopy(input, offset, writeBuffer, headerSize, size);

            // Encryption using SCHANNEL requires 4 buffers: header, payload, trailer, empty.
            SecurityBuffer[] securityBuffer = new SecurityBuffer[4];

            securityBuffer[0] = new SecurityBuffer(writeBuffer, 0, headerSize, SecurityBufferType.Header);
            securityBuffer[1] = new SecurityBuffer(writeBuffer, headerSize, size, SecurityBufferType.Data);
            securityBuffer[2] = new SecurityBuffer(writeBuffer, headerSize + size, trailerSize, SecurityBufferType.Trailer);
            securityBuffer[3] = new SecurityBuffer(null, SecurityBufferType.Empty);

            int errorCode = SSPIWrapper.EncryptMessage(GlobalSSPI.SSPISecureChannel, securityContext, securityBuffer, 0);

            if (errorCode != 0)
            {
                if (GlobalLog.IsEnabled)
                {
                    GlobalLog.Print("SslStreamPal.Windows: SecureChannel#" + LoggingHash.HashString(securityContext) + "::Encrypt ERROR" + errorCode.ToString("x"));
                }
                resultSize = 0;
            }
            else
            {
                // The full buffer may not be used.
                resultSize = securityBuffer[0].size + securityBuffer[1].size + securityBuffer[2].size;
            }

            return SecurityStatusAdapterPal.GetSecurityStatusPalFromNativeInt(errorCode);
        }

        public static SecurityStatusPal DecryptMessage(SafeDeleteContext securityContext, byte[] buffer, ref int offset, ref int count)
        {
            // Decryption using SCHANNEL requires four buffers.
            SecurityBuffer[] decspc = new SecurityBuffer[4];
            decspc[0] = new SecurityBuffer(buffer, offset, count, SecurityBufferType.Data);
            decspc[1] = new SecurityBuffer(null, SecurityBufferType.Empty);
            decspc[2] = new SecurityBuffer(null, SecurityBufferType.Empty);
            decspc[3] = new SecurityBuffer(null, SecurityBufferType.Empty);

            Interop.SecurityStatus errorCode = (Interop.SecurityStatus)SSPIWrapper.DecryptMessage(
                GlobalSSPI.SSPISecureChannel,
                securityContext,
                decspc,
                0);

            count = 0;
            for (int i = 0; i < decspc.Length; i++)
            {
                // Successfully decoded data and placed it at the following position in the buffer,
                if ((errorCode == Interop.SecurityStatus.OK && decspc[i].type == SecurityBufferType.Data)
                    // or we failed to decode the data, here is the encoded data.
                    || (errorCode != Interop.SecurityStatus.OK && decspc[i].type == SecurityBufferType.Extra))
                {
                    offset = decspc[i].offset;
                    count = decspc[i].size;
                    break;
                }
            }

            return SecurityStatusAdapterPal.GetSecurityStatusPalFromInterop(errorCode);
        }

        public unsafe static SafeFreeContextBufferChannelBinding QueryContextChannelBinding(SafeDeleteContext securityContext, ChannelBindingKind attribute)
        {
            return SSPIWrapper.QueryContextChannelBinding(GlobalSSPI.SSPISecureChannel, securityContext, (Interop.SspiCli.ContextAttribute)attribute);
        }

        public static void QueryContextStreamSizes(SafeDeleteContext securityContext, out StreamSizes streamSizes)
        {
            streamSizes = SSPIWrapper.QueryContextAttributes(
                GlobalSSPI.SSPISecureChannel,
                securityContext,
                Interop.SspiCli.ContextAttribute.StreamSizes) as StreamSizes;
        }

        public static void QueryContextConnectionInfo(SafeDeleteContext securityContext, out SslConnectionInfo connectionInfo)
        {
            connectionInfo = SSPIWrapper.QueryContextAttributes(
                GlobalSSPI.SSPISecureChannel,
                securityContext,
                Interop.SspiCli.ContextAttribute.ConnectionInfo) as SslConnectionInfo;
        }

        private static int GetProtocolFlagsFromSslProtocols(SslProtocols protocols, bool isServer)
        {
            int protocolFlags = (int)protocols;

            if (isServer)
            {
                protocolFlags &= Interop.SChannel.ServerProtocolMask;
            }
            else
            {
                protocolFlags &= Interop.SChannel.ClientProtocolMask;
            }

            return protocolFlags;
        }

        private static Interop.SspiCli.SecureCredential CreateSecureCredential(
            int version,
            X509Certificate certificate,
            Interop.SspiCli.SecureCredential.Flags flags,
            int protocols, EncryptionPolicy policy)
        {
            var credential = new Interop.SspiCli.SecureCredential()
            {
                rootStore = IntPtr.Zero,
                phMappers = IntPtr.Zero,
                palgSupportedAlgs = IntPtr.Zero,
                certContextArray = IntPtr.Zero,
                cCreds = 0,
                cMappers = 0,
                cSupportedAlgs = 0,
                dwSessionLifespan = 0,
                reserved = 0
            };

            if (policy == EncryptionPolicy.RequireEncryption)
            {
                // Prohibit null encryption cipher.
                credential.dwMinimumCipherStrength = 0;
                credential.dwMaximumCipherStrength = 0;
            }
            else if (policy == EncryptionPolicy.AllowNoEncryption)
            {
                // Allow null encryption cipher in addition to other ciphers.
                credential.dwMinimumCipherStrength = -1;
                credential.dwMaximumCipherStrength = 0;
            }
            else if (policy == EncryptionPolicy.NoEncryption)
            {
                // Suppress all encryption and require null encryption cipher only
                credential.dwMinimumCipherStrength = -1;
                credential.dwMaximumCipherStrength = -1;
            }
            else
            {
                throw new ArgumentException(SR.Format(SR.net_invalid_enum, "EncryptionPolicy"), nameof(policy));
            }

            credential.version = version;
            credential.dwFlags = flags;
            credential.grbitEnabledProtocols = protocols;
            if (certificate != null)
            {
                credential.certContextArray = certificate.Handle;
                credential.cCreds = 1;
            }

            return credential;
        }

        //
        // Security: we temporarily reset thread token to open the handle under process account.
        //
        private static SafeFreeCredentials AcquireCredentialsHandle(Interop.SspiCli.CredentialUse credUsage, Interop.SspiCli.SecureCredential secureCredential)
        {
            // First try without impersonation, if it fails, then try the process account.
            // I.E. We don't know which account the certificate context was created under.
            try
            {
                //
                // For app-compat we want to ensure the credential are accessed under >>process<< account.
                //
                return WindowsIdentity.RunImpersonated<SafeFreeCredentials>(SafeAccessTokenHandle.InvalidHandle, () =>
                {
                    return SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPISecureChannel, SecurityPackage, credUsage, secureCredential);
                });
            }
            catch
            {
                return SSPIWrapper.AcquireCredentialsHandle(GlobalSSPI.SSPISecureChannel, SecurityPackage, credUsage, secureCredential);
            }
        }
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using Azure.Core;

namespace Azure.Containers.ContainerRegistry.Specialized
{
    [CodeGenModel("OCIManifest")]
    public partial class OciManifest
    {
    }
}


text:
if (!window.console) {
  window.console = {};
  [
    "log","info","warn","error","assert","dir","clear","profile","profileEnd"
  ].forEach(function (method) {
      window.console[method] = function() {};
  });
}

// From: http://stackoverflow.com/a/5539378
if (Function.prototype.bind && window.console && typeof console.log == "object"){
    [
      "log","info","warn","error","assert","dir","clear","profile","profileEnd"
    ].forEach(function (method) {
      console[method] = this.bind(console[method], console);
    }, Function.prototype.call);
}


text:
package com.yolodata.tbana.hadoop.mapred.splunk;

import com.yolodata.tbana.hadoop.mapred.splunk.recordreader.ExportRecordReader;
import com.yolodata.tbana.hadoop.mapred.splunk.recordreader.JobRecordReader;
import com.yolodata.tbana.hadoop.mapred.splunk.recordreader.SplunkRecordReader;
import com.yolodata.tbana.hadoop.mapred.splunk.split.SplitProvider;
import com.yolodata.tbana.hadoop.mapred.util.ArrayListTextWritable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.*;

import java.io.IOException;
import java.util.List;

public class SplunkInputFormat implements InputFormat<LongWritable, ArrayListTextWritable> {

    public static final String INPUTFORMAT_SPLITS = "splunk.inputformat.splits";
    public static final String INPUTFORMAT_MODE = "splunk.inputformat.mode";

    public static enum Mode { Job, Export, Indexer, TwoLayerIndexer};
    private static final Mode DEFAULT_MODE = Mode.Job;

    @Override
    public RecordReader<LongWritable,ArrayListTextWritable> getRecordReader(InputSplit inputSplit, JobConf configuration, Reporter reporter) throws IOException {
        SplunkConf splunkConf = new SplunkConf(configuration);
        SplunkRecordReader splunkRecordReader = getRecordReaderFromConf(splunkConf);
        splunkRecordReader.initialize(inputSplit);

        return splunkRecordReader;
    }

    @Override
    public InputSplit[] getSplits(JobConf conf, int i) throws IOException {

        Mode mode = getMethodFromConf(conf);
        SplitProvider sp = SplitProvider.getProvider(mode);

        return sp.getSplits(conf,i);
    }

    private static Mode getMethodFromConf(Configuration conf) {
        String mode = conf.get(INPUTFORMAT_MODE,"Job");

        for(Mode m : Mode.values())
            if(m.toString().equalsIgnoreCase(mode))
                return m;

        return DEFAULT_MODE;
    }

    public static SplunkRecordReader getRecordReaderFromConf(SplunkConf conf) throws IOException {
        Mode mode = getMethodFromConf(conf);
        switch(mode) {
            case Job:
                return new JobRecordReader(conf);
            case Export:
                return new ExportRecordReader(conf);
            case Indexer:
                return new JobRecordReader(conf);
            default:
                throw new RuntimeException("Cannot get SplunkRecordReader in SplunkInputFormat using mode "+ mode.toString());
        }

    }
}


text:
extern "C" _Unwind_Reason_Code
trace_function(struct _Unwind_Context*, void* ntraced) {
  (*reinterpret_cast<size_t*>(ntraced))++;
  // We should never have a call stack this deep...
  assert(*reinterpret_cast<size_t*>(ntraced) < 20);
  return _URC_NO_REASON;
}

__attribute__ ((__noinline__))
void call3_throw(size_t* ntraced) {
  try {
    _Unwind_Backtrace(trace_function, ntraced);
  } catch (...) {
    assert(false);
  }
}

__attribute__ ((__noinline__, __disable_tail_calls__))
void call3_nothrow(size_t* ntraced) {
  _Unwind_Backtrace(trace_function, ntraced);
}

__attribute__ ((__noinline__, __disable_tail_calls__))
void call2(size_t* ntraced, bool do_throw) {
  if (do_throw) {
    call3_throw(ntraced);
  } else {
    call3_nothrow(ntraced);
  }
}

__attribute__ ((__noinline__, __disable_tail_calls__))
void call1(size_t* ntraced, bool do_throw) {
  call2(ntraced, do_throw);
}

int main() {
  size_t throw_ntraced = 0;
  size_t nothrow_ntraced = 0;

  call1(&nothrow_ntraced, false);

  try {
    call1(&throw_ntraced, true);
  } catch (...) {
    assert(false);
  }

  // Different platforms (and different runtimes) will unwind a different number
  // of times, so we can't make any better assumptions than this.
  assert(nothrow_ntraced > 1);
  assert(throw_ntraced == nothrow_ntraced); // Make sure we unwind through catch
  return 0;
}


text:
import * as Sequelize from 'sequelize';

import { MenuInstance } from '../instance/menu.instance';
import { MenuAttribute } from '../attribute/menu.attribute';

export interface MenuModel extends Sequelize.Model<MenuInstance, MenuAttribute> {

}


text:
using System;
using System.Collections.Concurrent;
using System.Data.Linq;
using System.Globalization;
using System.Linq.Expressions;
using System.Xml;

namespace LinqToDB.Common
{
	using Expressions;

	using Extensions;

	using Mapping;

	public static class Converter
	{
		static readonly ConcurrentDictionary<object,LambdaExpression> _expressions = new ConcurrentDictionary<object,LambdaExpression>();

#if !SILVERLIGHT && !NETFX_CORE
		static XmlDocument CreateXmlDocument(string str)
		{
			var xml = new XmlDocument();
			xml.LoadXml(str);
			return xml;
		}
#endif

		static Converter()
		{
			SetConverter<string,         char>       (v => v.Length == 0 ? '\0' : v[0]);
			SetConverter<string,         Binary>     (v => new Binary(Convert.FromBase64String(v)));
			SetConverter<Binary,         string>     (v => Convert.ToBase64String(v.ToArray()));
			SetConverter<Binary,         byte[]>     (v => v.ToArray());
			SetConverter<bool,           decimal>    (v => v ? 1m : 0m);
			SetConverter<DateTimeOffset, DateTime>   (v => v.LocalDateTime);
#if !SILVERLIGHT && !NETFX_CORE
			SetConverter<string,         XmlDocument>(v => CreateXmlDocument(v));
#endif
			SetConverter<string,         byte[]>     (v => Convert.FromBase64String(v));
			SetConverter<byte[],         string>     (v => Convert.ToBase64String(v));
			SetConverter<TimeSpan,       DateTime>   (v => DateTime.MinValue + v);
			SetConverter<DateTime,       TimeSpan>   (v => v - DateTime.MinValue);
			SetConverter<string,         DateTime>   (v => DateTime.Parse(v, null, DateTimeStyles.NoCurrentDateDefault));
			SetConverter<char,           bool>       (v => ToBoolean(v));
			SetConverter<string,         bool>       (v => v.Length == 1 ? ToBoolean(v[0]) : bool.Parse(v));
		}

		static bool ToBoolean(char ch)
		{
			switch (ch)
			{
				case '\x0' : // Allow int <=> Char <=> Boolean
				case   '0' :
				case   'n' :
				case   'N' :
				case   'f' :
				case   'F' : return false;

				case '\x1' : // Allow int <=> Char <=> Boolean
				case   '1' :
				case   'y' :
				case   'Y' :
				case   't' :
				case   'T' : return true;
			}

			throw new InvalidCastException("Invalid cast from System.String to System.Bool");
		}

		public static void SetConverter<TFrom,TTo>(Expression<Func<TFrom,TTo>> expr)
		{
			_expressions[new { from = typeof(TFrom), to = typeof(TTo) }] = expr;
		}

		internal static LambdaExpression GetConverter(Type from, Type to)
		{
			LambdaExpression l;
			_expressions.TryGetValue(new { from, to }, out l);
			return l;
		}

		static readonly ConcurrentDictionary<object,Func<object,object>> _converters = new ConcurrentDictionary<object,Func<object,object>>();

		public static object ChangeType(object value, Type conversionType, MappingSchema mappingSchema = null)
		{
			if (value == null || value is DBNull)
				return mappingSchema == null ?
					DefaultValue.GetValue(conversionType) :
					mappingSchema.GetDefaultValue(conversionType);

			if (value.GetType() == conversionType)
				return value;

			var from = value.GetType();
			var to   = conversionType;
			var key  = new { from, to };

			var converters = mappingSchema == null ? _converters : mappingSchema.Converters;

			Func<object,object> l;

			if (!converters.TryGetValue(key, out l))
			{
				var li =
					ConvertInfo.Default.Get   (               value.GetType(), to) ??
					ConvertInfo.Default.Create(mappingSchema, value.GetType(), to);

				var b  = li.CheckNullLambda.Body;
				var ps = li.CheckNullLambda.Parameters;

				var p  = Expression.Parameter(typeof(object), "p");
				var ex = Expression.Lambda<Func<object,object>>(
					Expression.Convert(
						b.Transform(e =>
							e == ps[0] ?
								Expression.Convert(p, e.Type) :
							IsDefaultValuePlaceHolder(e) ?
								new DefaultValueExpression(mappingSchema, e.Type) :
								e),
						typeof(object)),
					p);

				l = ex.Compile();

				converters[key] = l;
			}

			return l(value);
		}

		static class ExprHolder<T>
		{
			public static readonly ConcurrentDictionary<Type,Func<object,T>> Converters = new ConcurrentDictionary<Type,Func<object,T>>();
		}

		public static T ChangeTypeTo<T>(object value, MappingSchema mappingSchema = null)
		{
			if (value == null || value is DBNull)
				return mappingSchema == null ?
					DefaultValue<T>.Value :
					(T)mappingSchema.GetDefaultValue(typeof(T));

			if (value.GetType() == typeof(T))
				return (T)value;

			var from = value.GetType();
			var to   = typeof(T);

			Func<object,T> l;

			if (!ExprHolder<T>.Converters.TryGetValue(from, out l))
			{
				var li = ConvertInfo.Default.Get(from, to) ?? ConvertInfo.Default.Create(mappingSchema, from, to);
				var b  = li.CheckNullLambda.Body;
				var ps = li.CheckNullLambda.Parameters;

				var p  = Expression.Parameter(typeof(object), "p");
				var ex = Expression.Lambda<Func<object,T>>(
					b.Transform(e =>
						e == ps[0] ?
							Expression.Convert (p, e.Type) :
							IsDefaultValuePlaceHolder(e) ?
								new DefaultValueExpression(mappingSchema, e.Type) :
								e),
					p);

				l = ex.Compile();

				ExprHolder<T>.Converters[from] = l;
			}

			return l(value);
		}

		internal static bool IsDefaultValuePlaceHolder(Expression expr)
		{
			var me = expr as MemberExpression;

			if (me != null)
			{
				if (me.Member.Name == "Value" && me.Member.DeclaringType.IsGenericTypeEx())
					return me.Member.DeclaringType.GetGenericTypeDefinition() == typeof(DefaultValue<>);
			}

			return expr is DefaultValueExpression;
		}

		public static Type GetDefaultMappingFromEnumType(MappingSchema mappingSchema, Type enumType)
		{
			return ConvertBuilder.GetDefaultMappingFromEnumType(mappingSchema, enumType);
		}
	}
}


text:
.class Lcom/android/internal/policy/impl/KeyguardUpdateMonitor$4;
.super Landroid/database/ContentObserver;
.source "KeyguardUpdateMonitor.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/android/internal/policy/impl/KeyguardUpdateMonitor;-><init>(Landroid/content/Context;Lcom/android/internal/widget/LockPatternUtils;)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/internal/policy/impl/KeyguardUpdateMonitor;

# direct methods
.method constructor <init>(Lcom/android/internal/policy/impl/KeyguardUpdateMonitor;Landroid/os/Handler;)V
    .locals 0
    .parameter
    .parameter "x0"

    .prologue
    .line 406
    iput-object p1, p0, Lcom/android/internal/policy/impl/KeyguardUpdateMonitor$4;->this$0:Lcom/android/internal/policy/impl/KeyguardUpdateMonitor;

    invoke-direct {p0, p2}, Landroid/database/ContentObserver;-><init>(Landroid/os/Handler;)V

    return-void
.end method

# virtual methods
.method public onChange(Z)V
    .locals 4
    .parameter "selfChange"

    .prologue
    const/4 v0, 0x0

    .line 409
    invoke-super {p0, p1}, Landroid/database/ContentObserver;->onChange(Z)V

    .line 410
    iget-object v1, p0, Lcom/android/internal/policy/impl/KeyguardUpdateMonitor$4;->this$0:Lcom/android/internal/policy/impl/KeyguardUpdateMonitor;

    iget-object v2, p0, Lcom/android/internal/policy/impl/KeyguardUpdateMonitor$4;->this$0:Lcom/android/internal/policy/impl/KeyguardUpdateMonitor;

    #getter for: Lcom/android/internal/policy/impl/KeyguardUpdateMonitor;->mContext:Landroid/content/Context;
    invoke-static {v2}, Lcom/android/internal/policy/impl/KeyguardUpdateMonitor;->access$1600(Lcom/android/internal/policy/impl/KeyguardUpdateMonitor;)Landroid/content/Context;

    move-result-object v2

    invoke-virtual {v2}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;

    move-result-object v2

    const-string v3, "device_provisioned"

    invoke-static {v2, v3, v0}, Landroid/provider/Settings$Secure;->getInt(Landroid/content/ContentResolver;Ljava/lang/String;I)I

    move-result v2

    if-eqz v2, :cond_0

    const/4 v0, 0x1

    :cond_0
    #setter for: Lcom/android/internal/policy/impl/KeyguardUpdateMonitor;->mDeviceProvisioned:Z
    invoke-static {v1, v0}, Lcom/android/internal/policy/impl/KeyguardUpdateMonitor;->access$1502(Lcom/android/internal/policy/impl/KeyguardUpdateMonitor;Z)Z

    .line 412
    const-string v0, "KeyguardUpdateMonitor"

    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    const-string v2, "DEVICE_PROVISIONED Changed, new mDeviceProvisioned state = "

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    iget-object v2, p0, Lcom/android/internal/policy/impl/KeyguardUpdateMonitor$4;->this$0:Lcom/android/internal/policy/impl/KeyguardUpdateMonitor;

    #getter for: Lcom/android/internal/policy/impl/KeyguardUpdateMonitor;->mDeviceProvisioned:Z
    invoke-static {v2}, Lcom/android/internal/policy/impl/KeyguardUpdateMonitor;->access$1500(Lcom/android/internal/policy/impl/KeyguardUpdateMonitor;)Z

    move-result v2

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Z)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    invoke-static {v0, v1}, Lcom/mediatek/xlog/Xlog;->d(Ljava/lang/String;Ljava/lang/String;)I

    .line 413
    iget-object v0, p0, Lcom/android/internal/policy/impl/KeyguardUpdateMonitor$4;->this$0:Lcom/android/internal/policy/impl/KeyguardUpdateMonitor;

    #getter for: Lcom/android/internal/policy/impl/KeyguardUpdateMonitor;->mDeviceProvisioned:Z
    invoke-static {v0}, Lcom/android/internal/policy/impl/KeyguardUpdateMonitor;->access$1500(Lcom/android/internal/policy/impl/KeyguardUpdateMonitor;)Z

    move-result v0

    if-eqz v0, :cond_1

    .line 414
    iget-object v0, p0, Lcom/android/internal/policy/impl/KeyguardUpdateMonitor$4;->this$0:Lcom/android/internal/policy/impl/KeyguardUpdateMonitor;

    #getter for: Lcom/android/internal/policy/impl/KeyguardUpdateMonitor;->mHandler:Landroid/os/Handler;
    invoke-static {v0}, Lcom/android/internal/policy/impl/KeyguardUpdateMonitor;->access$1700(Lcom/android/internal/policy/impl/KeyguardUpdateMonitor;)Landroid/os/Handler;

    move-result-object v0

    iget-object v1, p0, Lcom/android/internal/policy/impl/KeyguardUpdateMonitor$4;->this$0:Lcom/android/internal/policy/impl/KeyguardUpdateMonitor;

    #getter for: Lcom/android/internal/policy/impl/KeyguardUpdateMonitor;->mHandler:Landroid/os/Handler;
    invoke-static {v1}, Lcom/android/internal/policy/impl/KeyguardUpdateMonitor;->access$1700(Lcom/android/internal/policy/impl/KeyguardUpdateMonitor;)Landroid/os/Handler;

    move-result-object v1

    const/16 v2, 0x134

    invoke-virtual {v1, v2}, Landroid/os/Handler;->obtainMessage(I)Landroid/os/Message;

    move-result-object v1

    invoke-virtual {v0, v1}, Landroid/os/Handler;->sendMessage(Landroid/os/Message;)Z

    .line 416
    :cond_1
    return-void
.end method


text:
if [ "$JAVA_HOME" = "" ]
then
  echo "JAVA_HOME must be set and valid to run $0" ; exit 1
fi

VERSION=1.6.3-SNAPSHOT

$JAVA_HOME/bin/java -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=45999 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Djava.rmi.server.hostname=localhost -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=1045 -javaagent:"$(dirname $0)/../../../../../agent/jvm/target/jolokia-jvm-${VERSION}-agent.jar=port=8779" -classpath "$(dirname $0)/../../../target/jolokia-jmx-adapter-${VERSION}-standalone.jar:$JAVA_HOME/lib/jconsole.jar:$JAVA_HOME/classes" -Dapplication.home=$JAVA_HOME -Xms8m -Djconsole.showOutputViewer sun.tools.jconsole.JConsole


text:
import assert from "assert";
import xor from "../";
import xorInplace from "../inplace";
import * as fixtures from "./fixtures";
describe('xor', function () {
    fixtures.forEach(function (f) {
        it('returns ' + f.expected + ' for ' + f.a + '/' + f.b, function () {
            var a = new Buffer(f.a, 'hex');
            var b = new Buffer(f.b, 'hex');
            var actual = xor(a, b);
            assert.equal(actual.toString('hex'), f.expected);
            // a/b unchanged
            assert.equal(a.toString('hex'), f.a);
            assert.equal(b.toString('hex'), f.b);
        });
    });
});
describe('xor/inplace', function () {
    fixtures.forEach(function (f) {
        it('returns ' + f.expected + ' for ' + f.a + '/' + f.b, function () {
            var a = new Buffer(f.a, 'hex');
            var b = new Buffer(f.b, 'hex');
            var actual = xorInplace(a, b);
            assert.equal(actual.toString('hex'), f.expected);
            // a mutated, b unchanged
            assert.equal(a.toString('hex'), f.mutated || f.expected);
            assert.equal(b.toString('hex'), f.b);
        });
    });
});


text:
package io.taig.android.util.syntax

trait all extends bitmap with bundle with `class` with file with string

object all extends all


text:
package validator

import (
	"github.com/open-policy-agent/opa/internal/gqlparser/ast"

	//nolint:revive // Validator rules each use dot imports for convenience.
	. "github.com/open-policy-agent/opa/internal/gqlparser/validator"
)

func init() {
	AddRule("KnownTypeNames", func(observers *Events, addError AddErrFunc) {
		observers.OnVariable(func(walker *Walker, variable *ast.VariableDefinition) {
			typeName := variable.Type.Name()
			typdef := walker.Schema.Types[typeName]
			if typdef != nil {
				return
			}

			addError(
				Message(`Unknown type "%s".`, typeName),
				At(variable.Position),
			)
		})

		observers.OnInlineFragment(func(walker *Walker, inlineFragment *ast.InlineFragment) {
			typedName := inlineFragment.TypeCondition
			if typedName == "" {
				return
			}

			def := walker.Schema.Types[typedName]
			if def != nil {
				return
			}

			addError(
				Message(`Unknown type "%s".`, typedName),
				At(inlineFragment.Position),
			)
		})

		observers.OnFragment(func(walker *Walker, fragment *ast.FragmentDefinition) {
			typeName := fragment.TypeCondition
			def := walker.Schema.Types[typeName]
			if def != nil {
				return
			}

			var possibleTypes []string
			for _, t := range walker.Schema.Types {
				possibleTypes = append(possibleTypes, t.Name)
			}

			addError(
				Message(`Unknown type "%s".`, typeName),
				SuggestListQuoted("Did you mean", typeName, possibleTypes),
				At(fragment.Position),
			)
		})
	})
}


text:
package com.intellij.codeInspection;

import com.intellij.codeInsight.AnnotationTargetUtil;
import com.intellij.openapi.project.Project;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.util.PsiUtil;
import com.intellij.refactoring.introduceVariable.IntroduceVariableBase;
import com.siyeh.InspectionGadgetsBundle;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;

public class RedundantExplicitVariableTypeInspection extends AbstractBaseJavaLocalInspectionTool {
  @NotNull
  @Override
  public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly) {
    if (!PsiUtil.getLanguageLevel(holder.getFile()).isAtLeast(LanguageLevel.JDK_10)) {
      return PsiElementVisitor.EMPTY_VISITOR;
    }
    return new JavaElementVisitor() {
      @Override
      public void visitLocalVariable(PsiLocalVariable variable) {
        PsiTypeElement typeElement = variable.getTypeElement();
        if (!typeElement.isInferredType()) {
          PsiElement parent = variable.getParent();
          if (parent instanceof PsiDeclarationStatement && ((PsiDeclarationStatement)parent).getDeclaredElements().length > 1) {
            return;
          }
          doCheck(variable, (PsiLocalVariable)variable.copy(), typeElement);
        }
      }

      @Override
      public void visitForeachStatement(PsiForeachStatement statement) {
        super.visitForeachStatement(statement);
        PsiParameter parameter = statement.getIterationParameter();
        PsiTypeElement typeElement = parameter.getTypeElement();
        if (typeElement != null && !typeElement.isInferredType()) {
          PsiForeachStatement copy = (PsiForeachStatement)statement.copy();
          doCheck(parameter, copy.getIterationParameter(), typeElement);
        }
      }

      private void doCheck(PsiVariable variable,
                           PsiVariable copyVariable,
                           PsiTypeElement element2Highlight) {
        ArrayList<PsiAnnotation> typeUseAnnotations = new ArrayList<>();
        AnnotationTargetUtil.collectStrictlyTypeUseAnnotations(copyVariable.getModifierList(), typeUseAnnotations);
        if (!typeUseAnnotations.isEmpty()) return;

        PsiTypeElement typeElementCopy = copyVariable.getTypeElement();
        if (typeElementCopy != null) {
          IntroduceVariableBase.expandDiamondsAndReplaceExplicitTypeWithVar(typeElementCopy, variable);
          if (variable.getType().equals(getNormalizedType(copyVariable))) {
            holder.registerProblem(element2Highlight,
                                   InspectionGadgetsBundle.message("inspection.redundant.explicit.variable.type.description"),
                                   ProblemHighlightType.LIKE_UNUSED_SYMBOL,
                                   new ReplaceWithVarFix());
          }
        }
       }

      private PsiType getNormalizedType(PsiVariable copyVariable) {
        PsiType type = copyVariable.getType();
        PsiClass refClass = PsiUtil.resolveClassInType(type);
        if (refClass instanceof PsiAnonymousClass) {
          type = ((PsiAnonymousClass)refClass).getBaseClassType();
        }
        return type;
      }
    };
  }

  private static class ReplaceWithVarFix implements LocalQuickFix {
    @Nls
    @NotNull
    @Override
    public String getFamilyName() {
      return InspectionGadgetsBundle.message("replace.with.var.fix.family.name");
    }

    @Override
    public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
      PsiElement element = descriptor.getPsiElement();
      if (element instanceof PsiTypeElement) {
        CodeStyleManager.getInstance(project)
          .reformat(IntroduceVariableBase.expandDiamondsAndReplaceExplicitTypeWithVar((PsiTypeElement)element, element));
      }
    }
  }
}


text:
package playground.java.nio.tcp;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;

import static playground.java.nio.tcp.Util.reportSocketConfig;
import static playground.java.nio.tcp.Util.set;
import static playground.java.nio.tcp.Util.reportSocketConfiguration;

/**
 * @author Ovidiu Feodorov <ovidiu@swim.ai>
 * @since 7/24/18
 */
public class ClientMain {

    public static void main(String[] args) throws Exception {

        Configuration config = new Configuration(args);

        final CommandLine c = new CommandLine();
        c.start();

        //
        // Use a selector to receive data asynchronously
        //

        final Selector selector = Selector.open();

        //
        // Create the SocketChannel
        //

        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress(config.getAddress(), config.getPort()));
        socketChannel.configureBlocking(false);

        c.info("socket connected, " + reportSocketConfig(socketChannel));

        //
        // Register the ServerSocketChannel with the selector
        //

        socketChannel.register(selector, SelectionKey.OP_READ);

        //
        // Create a selector thread that will be notified on asynchronous data arrival
        //

        new Thread(() -> {

            while(true) {

                try {

                    selector.select();

                    Set<SelectionKey> selectedKeys = selector.selectedKeys();

                    for(Iterator<SelectionKey> i = selectedKeys.iterator(); i.hasNext(); ) {

                        SelectionKey k = i.next();

                        if ((k.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {

                            //
                            // New data available, read it
                            //

                            //
                            // Remove the key from the set
                            //

                            i.remove();

                            SocketChannel sc = (SocketChannel)k.channel();
                            ByteBuffer buffer = ByteBuffer.allocate(1024);
                            int bytesRead = sc.read(buffer);

                            if (bytesRead == -1) {

                                //
                                // TCP connection was closed
                                //

                                c.info(ServerMain.TIMESTAMP_FORMAT.format(new Date()) + ": TCP connection closed");

                                //
                                // Unregister the channel, by canceling the key. If we don't do this, data availability
                                // events for zero-length data will keep popping up.
                                //

                                k.cancel();

                            }
                            else {

                                //
                                // Read data
                                //

                                buffer.flip();
                                byte[] content = new byte[bytesRead];
                                buffer.get(content, 0, bytesRead);

                                c.info(ServerMain.TIMESTAMP_FORMAT.format(new Date()) + ": " + new String(content));
                            }
                        }
                        else {

                            c.info("unexpected selection key " + k);
                        }
                    }
                }
                catch(IOException e) {

                    e.printStackTrace();
                }
            }
        }, "Selector Thread").start();

        //
        // Enter the command line loop, this is where we write data on the socket
        //

        while(true) {

            String line = c.readLine();

            if (line.startsWith("exit")) {

                break;
            }
            else if (line.startsWith("config")) {

                reportSocketConfiguration(line, c, socketChannel);

            }
            else if (line.startsWith("set-")) {

                set(line, c, socketChannel);

            }
            else //noinspection Duplicates
            {

                //
                // Send the content as data on the connection
                //

                ByteBuffer buffer = ByteBuffer.allocate(1024);
                buffer.clear();
                buffer.put(line.getBytes());
                buffer.flip();

                while (buffer.hasRemaining()) {

                    socketChannel.write(buffer);
                }
            }
        }

        socketChannel.close();

        c.info("socket channel closed");

        System.exit(0);
    }

}


text:
/*
	Internal use only, never use it for displaying a chart.
	Scale.js is designed to be extended by other file like axis.js and other charts.

	Note:
		Anywhere elses in the app, should not defined any scale fn or init the scale fn, all others should be extended from this file to keep it dry

		options.info is an absolutely required parameter. If it is not present, it will throw an error. To set this option, follow this pattern. E.G.
			d3.chart("FinalChart", {
				initialize: function(containerInfo) {  <= defined containerInfo option obj here.
					var area = this.mixin("Area", this.base.append('g').classed('area', true), {
						info: containerInfo  <= defined containerInfo option obj in the instance level. Required
					});
				}
			});
			var canvas = container.canvas().chart("FinalChart", container.info() ); <= passing obj as 2nd arg when init the canvas

	Arguments:
		private atrribute:
			x & y:  scale representation for the x axis and y axis. take x or y as a key, value should be a string representation of scale value, default value is linear, everything will override the default

			Internally, it transformed from x & y to _x & _y as internal variables

			Note: x, y could only be set by the initialization fn, option objects.

		public attributes:
			width, height,  (# canvas width and height values.)
			info  (# graph info about the details of this graph, canvas related info, svg info)
			xScale, yScale (# scale fn on the x & y axis. it should always be used when dealing with xScale and yScale. cause it only init the scale on x and y once, it won't be changed. The behavoir could be overrided by each individual fn)

		Note: by default, you do not need to specified width, height value in the third args, it will use the info options for the value, if you want to override the default, you could definied the width and height to override the info value

		info arg is absolutely required the param. it is used to figure out the width and height stuffs.

	APIs:  ( defined in the constructor level )
		private api:
			_x, _y (# contain the string representation of scale value. used in base.js _updateScale() )
			_switchXScale(xScaleString, widthValue), _switchYScale(yScaleString, heightValue) (#update the range array when window resize or any time scale updates)
			_scale(scaleString)   (# simply just return a new instance of d3.scale # initialize the scale for this graph, always use it internally, do not override )

	Options
		x & y for scale on x axis and y axis, available scale attribute is
		linear, ordinal, log, pow, sqrt, identity, quantile, quantize, threshold

	Example:
		var container = d3ma.container('#vis');
		container.resize().box(1400, 600);

		// Important, to pass the container.info() as a 2nd param
		var canvas = container.canvas().chart("FinalChart", container.info() ); // <= this is the ABSOLUTELY required setup
		canvas.draw(data);

		d3.chart("FinalChart", {
			//important, to pass the option of containerInfo as an obj options
			initialize: function(containerInfo) {  // <= this is the ABSOLUTELY required setup
				var axis =  this.mixin("MyAxis",  this.base.append("g").classed('axisgroup', true), {
					info: containerInfo,   // <= this is the ABSOLUTELY required setup
					x: 'ordinal',
					guide: true
				});
				var bars = this.mixin("MyBars", this.base.append('g').classed('bars', true), {
					info: containerInfo,  // <= this is the ABSOLUTELY required setup
					x: 'ordinal'
				});
			}
		});

 */
d3.chart('Scale', {

	initialize: function(options) {

		options = options || {};

		if(!options.info){
			throw new Error('Container Info {info: containerInfo} is absolultely required when an instance is created');
		}

		var x = options.x || 'linear';
		var y = options.y || 'linear';

		this._x = x;
		this._y = y;

		this.width = options.width || options.info.canvasW || this.base.attr('width') || 1;
		this.width = +this.width;
		this.height = options.height || options.info.canvasH || this.base.attr('height') || 1;
		this.height = +this.height;

		this.info = options.info;

		// init the scale
		this.xScale = this._scale(x);
		this.yScale = this._scale(y);

		this._switchXScale(x, this.width);
		this._switchYScale(y, this.height, false);

		if(options.y1) {
			var y1 = options.y1 || 'linear';
			this.y1Scale = this._scale(y1);
			// using the same _switchYScale fn, most likely using the same axis
			// if 3rd arg is true, it will switch from this.yScale to this.y1Scale
			this._switchYScale(y1, this.height, true);
		}
	},

	_switchXScale: function(x, _width) {
		switch(x) {
			case 'linear' :
				this.xScale.range([0, _width]);
			break;

			case 'ordinal' :
				this.xScale.rangeRoundBands([0, _width], 0.1);
			break;
		}
	},

	_switchYScale: function(y, _height, y1flag) {
		var yscale = (y1flag) ? this.y1Scale : this.yScale;
		switch(y) {
			case 'linear' :
				yscale.range([_height, 15]);
			break;

			case 'ordinal' :
				yscale.rangeRoundBands([_height, 15], 0.1);
			break;
		}
	},

	_scale: function(scale) {
		switch(scale) {
			case 'linear':
				return d3.scale.linear();
			break;

			case 'ordinal':
				return d3.scale.ordinal();
			break;

			case 'log':
				return d3.scale.log();
			break;

			case 'pow':
				return d3.scale.pow();
			break;

			case 'sqrt':
				return d3.scale.sqrt();
			break;

			case 'identity':
				return d3.scale.identity();
			break;

			case 'quantile':
				return d3.scale.quantile();
			break;

			case 'quantize':
				return d3.scale.quantize();
			break;

			case 'threshold':
				return d3.scale.threshold();
			break;

			case 'time':
				return d3.time.scale();
			break;

			default:
				return d3.scale.linear();
			break;
		}
	}
});


text:
<?php
$localfilename = "datafile.txt";
$remoteurls = [
  'http://info.vroute.net/vatsim-data.txt',
  'http://data.vattastic.com/vatsim-data.txt',
  'http://vatsim.aircharts.org/vatsim-data.txt',
  'http://vatsim-data.hardern.net/vatsim-data.txt',
  'http://wazzup.flightoperationssystem.com/vatsim/vatsim-data.txt',
];
$randomurl = $remoteurls[array_rand($remoteurls)];
////////////Cache the datafile/////////////////////
//if (file_exists($localfilename) && (filemtime($localfilename) > (time() - 60 * 3))) {
   // Cache file is less than five minutes old.
   // Don't bother refreshing, just use the file as-is.
   //$file = file_get_contents($localfilename);
//} else {
   // Our cache is out-of-date, so load the data from our remote server,
   // and also save it over our cache for next time.
   $file = file_get_contents($randomurl);
   file_put_contents($localfilename, $file, LOCK_EX);
//}
////////////////GET IRISH POSITIONS ONLINE//////////////////////
preg_match_all("/(EI(?:\w{2})_(?:[\w\d]{1,2})?(?:CTR|APP|TWR|GND|DEL)):(\d+):.*?:ATC:(?!199\.998)(?=.*:([1-9])::([\d+]):)(?=.*:(\d+)::::)/",$file , $result);
require_once('db.php');
//////////////////////PREPARE THE QUERY//////////////////////
$insert = $conn->prepare("INSERT INTO sessions (cid, rating, start, finish, position, facility)
VALUES (:cid, :rating, :start, TIMESTAMP(NOW()), :position, :facility)
  ON DUPLICATE KEY UPDATE
    finish = VALUES(finish);
");
//////////////////////TIME TO LOOP THROUGH THE POSITIONS ONLINE//////////////////////
foreach($result[1] as $i => $atc) {
    $time = $result[5][$i];
    $dt = new DateTime($time, new DateTimezone('GMT'));
    $IST = new DateTimeZone('Europe/Dublin');
    $dt->setTimezone($IST);
    $start = $dt->format("Y-m-d H:i:s");
    /////////////////////////////////////////////////////////////////////////////
    $insert->bindParam(":cid", $result[2][$i]);
    $insert->bindParam(":rating", $result[3][$i]);
    $insert->bindParam(":start", $start);
    $insert->bindParam(":position", $atc);
    $insert->bindParam(":facility", $result[4][$i]);
    $insert->execute();
}


text:
<!--[metadata]>
+++
title = "provision"
description = "Re-run provisioning on a created machine."
keywords = ["machine, provision, subcommand"]
[menu.main]
parent="smn_machine_subcmds"
+++
<![end-metadata]-->

# provision

Re-run provisioning on a created machine.

Sometimes it may be helpful to re-run Machine's provisioning process on a
created machine.  Reasons for doing so may include a failure during the original
provisioning process, or a drift from the desired system state (including the
originally specified Swarm or Engine configuration).

Usage is `docker-machine provision [name]`.  Multiple names may be specified.

    $ docker-machine provision foo bar
    Copying certs to the local machine directory...
    Copying certs to the remote machine...
    Setting Docker configuration on the remote daemon...

The Machine provisioning process will:

1.  Set the hostname on the instance to the name Machine addresses it by (e.g.
    `default`).
2.  Install Docker if it is not present already.
3.  Generate a set of certificates (usually with the default, self-signed CA) and
    configure the daemon to accept connections over TLS.
4.  Copy the generated certificates to the server and local config directory.
5.  Configure the Docker Engine according to the options specified at create
    time.
6.  Configure and activate Swarm if applicable.


text:
var gridOptions = {
    columnDefs: [
        { field: "country", rowGroup: true },
        { field: "year", pivot: true }, // pivot on 'year'
        { field: "total", aggFunc: 'sum' },
    ],
    defaultColDef: {
        flex: 4,
        minWidth: 100,
        resizable: true
    },
    autoGroupColumnDef: {
        flex: 5,
        minWidth: 200,
    },

    // use the server-side row model
    rowModelType: 'serverSide',
    serverSideStoreType: 'partial',

    // enable pivoting
    pivotMode: true,

    animateRows: true,
    // debug: true
};

// setup the grid after the page has finished loading
document.addEventListener('DOMContentLoaded', function() {
    var gridDiv = document.querySelector('#myGrid');
    new agGrid.Grid(gridDiv, gridOptions);

    agGrid.simpleHttpRequest({ url: 'https://www.ag-grid.com/example-assets/olympic-winners.json' }).then(function(data) {
        // setup the fake server with entire dataset
        var fakeServer = new FakeServer(data);

        // create datasource with a reference to the fake server
        var datasource = new ServerSideDatasource(fakeServer);

        // register the datasource with the grid
        gridOptions.api.setServerSideDatasource(datasource);
    });
});

function ServerSideDatasource(server) {
    return {
        getRows: function(params) {
            console.log('[Datasource] - rows requested by grid: ', params.request);

            // get data for request from our fake server
            var response = server.getData(params.request);

            // add pivot colDefs in the grid based on the resulting data
            addPivotColDefs(response, params.columnApi);

            // simulating real server call with a 500ms delay
            setTimeout(function() {
                if (response.success) {
                    // supply data to grid
                    params.success({ rowData: response.rows, rowCount: response.lastRow });
                } else {
                    params.fail();
                }
            }, 500);
        }
    };
}

function addPivotColDefs(response, columnApi) {
    // check if pivot colDefs already exist
    var existingPivotColDefs = columnApi.getSecondaryColumns();
    if (existingPivotColDefs && existingPivotColDefs.length > 0) {
        return;
    }

    // create colDefs
    var pivotColDefs = response.pivotFields.map(function(field) {
        var headerName = field.split('_')[0];
        return { headerName: headerName, field: field };
    });

    // supply secondary columns to the grid
    columnApi.setSecondaryColumns(pivotColDefs);
}


text:
namespace System.Workflow.ComponentModel.Design
{
    using System;
    using System.Text;
    using System.Drawing;
    using System.Windows.Forms;
    using System.Drawing.Drawing2D;
    using System.Collections.Generic;
    using System.ComponentModel.Design;

    #region Class DynamicActionMessageFilter
    //Behavior needs coordinates in client coordinate system
    internal sealed class DynamicActionMessageFilter : WorkflowDesignerMessageFilter
    {
        #region Members, Construction and Destruction
        private List<DynamicAction> actions = new List<DynamicAction>();

        private int draggedButtonIndex = -1;
        private int draggedActionIndex = -1;

        private bool infoTipSet = false;

        internal DynamicActionMessageFilter()
        {
        }
        #endregion

        #region Properties and Methods
        internal void AddAction(DynamicAction action)
        {
            if (action == null)
                throw new ArgumentNullException("action");

            if (!this.actions.Contains(action))
            {
                if (IsButtonDragged)
                    SetDraggedButton(-1, -1);

                this.actions.Add(action);
                RefreshAction(action);
            }
        }

        internal bool ActionExists(DynamicAction action)
        {
            if (action == null)
                throw new ArgumentNullException("action");

            return this.actions.Contains(action);
        }

        internal void RemoveAction(DynamicAction action)
        {
            if (action == null)
                throw new ArgumentNullException("action");

            if (this.actions.Contains(action))
            {
                if (IsButtonDragged)
                    SetDraggedButton(-1, -1);

                RefreshAction(action);
                this.actions.Remove(action);
            }
        }

        internal void RefreshAction(DynamicAction action)
        {
            if (action == null)
                throw new ArgumentNullException("action");

            int actionIndex = this.actions.IndexOf(action);
            if (actionIndex >= 0)
                ParentView.InvalidateClientRectangle(GetActionBounds(actionIndex));
        }
        #endregion

        #region Behavior Overrides
        protected override void Initialize(WorkflowView parentView)
        {
            base.Initialize(parentView);

            IServiceContainer serviceContainer = GetService(typeof(IServiceContainer)) as IServiceContainer;
            if (serviceContainer != null)
            {
                serviceContainer.RemoveService(typeof(DynamicActionMessageFilter));
                serviceContainer.AddService(typeof(DynamicActionMessageFilter), this);
            }
        }

        protected override void Dispose(bool disposing)
        {
            try
            {
                IServiceContainer serviceContainer = GetService(typeof(IServiceContainer)) as IServiceContainer;
                if (serviceContainer != null)
                    serviceContainer.RemoveService(typeof(DynamicActionMessageFilter));
            }
            finally
            {
                base.Dispose(disposing);
            }
        }

        protected override bool OnMouseEnter(MouseEventArgs eventArgs)
        {
            UpdateTransparency(new Point(eventArgs.X, eventArgs.Y));
            Refresh();
            return false;
        }

        protected override bool OnMouseDown(MouseEventArgs eventArgs)
        {
            Point clientPoint = new Point(eventArgs.X, eventArgs.Y);

            Refresh();
            UpdateTransparency(clientPoint);

            bool retval = false;
            if ((eventArgs.Button & MouseButtons.Left) > 0)
            {
                for (int i = this.actions.Count - 1; i >= 0; i--)
                {
                    DynamicAction action = this.actions[i];
                    Rectangle actionBounds = GetActionBounds(i);
                    if (actionBounds.Contains(clientPoint))
                    {
                        //If we clicked on disabled button then no further action is needed
                        for (int j = 0; j < action.Buttons.Count; j++)
                        {
                            Rectangle buttonBounds = GetButtonBounds(i, j);
                            if (buttonBounds.Contains(clientPoint) && action.Buttons[j].State == ActionButton.States.Disabled)
                                return true;
                        }

                        //Now check all the buttons and update their states
                        for (int j = 0; j < action.Buttons.Count; j++)
                        {
                            ActionButton actionButton = action.Buttons[j];
                            if (actionButton.State != ActionButton.States.Disabled)
                            {
                                Rectangle buttonBounds = GetButtonBounds(i, j);
                                if (buttonBounds.Contains(clientPoint))
                                {
                                    actionButton.State = ActionButton.States.Pressed;
                                    if (action.ActionType != DynamicAction.ActionTypes.TwoState)
                                        SetDraggedButton(i, j);
                                }
                                else if (action.ActionType == DynamicAction.ActionTypes.TwoState)
                                {
                                    actionButton.State = ActionButton.States.Normal;
                                }
                            }
                        }

                        retval = true;
                    }
                }
            }

            return retval;
        }

        protected override bool OnMouseMove(MouseEventArgs eventArgs)
        {
            Point clientPoint = new Point(eventArgs.X, eventArgs.Y);

            Refresh();
            UpdateTransparency(clientPoint);

            string infoTip = String.Empty;
            bool retval = IsButtonDragged;
            if (!IsButtonDragged)
            {
                for (int i = this.actions.Count - 1; i >= 0; i--)
                {
                    DynamicAction action = this.actions[i];
                    Rectangle actionBounds = GetActionBounds(i);

                    for (int j = 0; j < action.Buttons.Count; j++)
                    {
                        ActionButton actionButton = action.Buttons[j];

                        if (actionBounds.Contains(clientPoint))
                        {
                            Rectangle buttonBounds = GetButtonBounds(i, j);
                            bool buttonContainsPoint = buttonBounds.Contains(clientPoint);

                            if (buttonContainsPoint && infoTip.Length == 0)
                                infoTip = actionButton.Description;

                            if (actionButton.State != ActionButton.States.Disabled &&
                                actionButton.State != ActionButton.States.Pressed)
                            {
                                if (buttonContainsPoint)
                                    actionButton.State = ActionButton.States.Highlight;
                                else
                                    actionButton.State = ActionButton.States.Normal;
                            }

                            retval = true;
                        }
                        else
                        {
                            if (actionButton.State == ActionButton.States.Highlight)
                                actionButton.State = ActionButton.States.Normal;
                        }
                    }
                }
            }

            WorkflowView parentView = ParentView;
            if (infoTip.Length > 0)
            {
                this.infoTipSet = true;
                parentView.ShowInfoTip(infoTip);
            }
            else if (this.infoTipSet)
            {
                parentView.ShowInfoTip(String.Empty);
                this.infoTipSet = false;
            }

            return retval;
        }

        protected override bool OnMouseDoubleClick(MouseEventArgs eventArgs)
        {
            for (int i = this.actions.Count - 1; i >= 0; i--)
            {
                DynamicAction action = this.actions[i];
                Rectangle actionBounds = GetActionBounds(i);
                if (actionBounds.Contains(new Point(eventArgs.X, eventArgs.Y)))
                    return true;
            }

            return false;
        }

        protected override bool OnMouseUp(MouseEventArgs eventArgs)
        {
            Point clientPoint = new Point(eventArgs.X, eventArgs.Y);

            Refresh();
            UpdateTransparency(clientPoint);

            bool retval = false;
            if ((eventArgs.Button & MouseButtons.Left) > 0)
            {
                for (int i = this.actions.Count - 1; i >= 0; i--)
                {
                    DynamicAction action = this.actions[i];
                    Rectangle actionBounds = GetActionBounds(i);
                    if (actionBounds.Contains(clientPoint))
                    {
                        for (int j = 0; j < action.Buttons.Count; j++)
                        {
                            ActionButton actionButton = action.Buttons[j];

                            if (actionButton.State != ActionButton.States.Disabled)
                            {
                                Rectangle buttonBounds = GetButtonBounds(i, j);

                                if (buttonBounds.Contains(clientPoint) && action.ActionType != DynamicAction.ActionTypes.TwoState)
                                    actionButton.State = ActionButton.States.Highlight;
                                else if (actionButton.State == ActionButton.States.Highlight)
                                    actionButton.State = ActionButton.States.Normal;
                            }
                        }

                        retval = true;
                    }
                }
            }

            if (IsButtonDragged)
                SetDraggedButton(-1, -1);

            return retval;
        }

        protected override bool OnMouseLeave()
        {
            ParentView.ShowInfoTip(String.Empty);
            UpdateTransparency(Point.Empty);
            Refresh();
            return false;
        }

        protected override bool OnMouseCaptureChanged()
        {
            if (IsButtonDragged)
                SetDraggedButton(-1, -1);
            return false;
        }

        protected override bool OnPaintWorkflowAdornments(PaintEventArgs e, Rectangle viewPort, AmbientTheme ambientTheme)
        {
            for (int i = 0; i < this.actions.Count; i++)
            {
                GraphicsContainer graphicsState = e.Graphics.BeginContainer();
                Point actionLocation = GetActionBounds(i).Location;
                e.Graphics.TranslateTransform(actionLocation.X, actionLocation.Y);
                this.actions[i].Draw(e.Graphics);
                e.Graphics.EndContainer(graphicsState);
            }
            return false;
        }
        #endregion

        #region Helpers
        private void Refresh()
        {
            WorkflowView parentView = ParentView;
            for (int i = 0; i < this.actions.Count; i++)
                parentView.InvalidateClientRectangle(GetActionBounds(i));
        }

        private Rectangle GetActionBounds(int actionIndex)
        {
            Rectangle bounds = new Rectangle(Point.Empty, ParentView.ViewPortSize);
            DynamicAction action = this.actions[actionIndex];

            bounds.Inflate(-action.DockMargin.Width, -action.DockMargin.Height);
            return new Rectangle(ActivityDesignerPaint.GetRectangleFromAlignment(action.DockAlignment, bounds, action.Bounds.Size).Location, action.Bounds.Size);
        }

        private Rectangle GetButtonBounds(int actionIndex, int buttonIndex)
        {
            Rectangle bounds = GetActionBounds(actionIndex);
            Rectangle buttonBounds = this.actions[actionIndex].GetButtonBounds(buttonIndex);
            buttonBounds.Offset(bounds.Location);
            return buttonBounds;
        }

        private void UpdateTransparency(Point point)
        {
            for (int i = 0; i < this.actions.Count; i++)
            {
                float transparency = 0;
                if (!point.IsEmpty)
                {
                    Rectangle actionBounds = GetActionBounds(i);
                    if (actionBounds.Contains(point) || this.draggedActionIndex == i)
                    {
                        transparency = 1.0f;
                    }
                    else
                    {
                        Rectangle rectangle = ParentView.ViewPortRectangle;
                        double distance = DesignerGeometryHelper.DistanceFromPointToRectangle(point, actionBounds);
                        if (distance > rectangle.Width / 3 || distance > rectangle.Height / 3)
                        {
                            transparency = 0.3f;
                        }
                        else
                        {
                            //Uncomment the following code for fluctuating transparency
                            //1.0f - ((float)Convert.ToInt32(distance)) / Math.Max(ParentView.ViewPortSize.Width, ParentView.ViewPortSize.Height);
                            transparency = 1.0f;
                        }
                    }
                }

                this.actions[i].Transparency = transparency;
            }
        }

        private bool IsButtonDragged
        {
            get
            {
                return (this.draggedActionIndex >= 0 && this.draggedButtonIndex >= 0);
            }
        }

        private void SetDraggedButton(int actionIndex, int buttonIndex)
        {
            if (this.draggedActionIndex == actionIndex && this.draggedButtonIndex == buttonIndex)
                return;

            WorkflowView parentView = ParentView;
            if (this.draggedActionIndex >= 0 && this.draggedButtonIndex >= 0)
            {
                if (this.draggedActionIndex < this.actions.Count)
                    this.actions[this.draggedActionIndex].Buttons[this.draggedButtonIndex].State = ActionButton.States.Highlight;

                this.draggedActionIndex = -1;
                this.draggedButtonIndex = -1;
                parentView.Capture = false;
                UpdateTransparency(parentView.PointToClient(Control.MousePosition));
            }

            this.draggedActionIndex = actionIndex;
            this.draggedButtonIndex = buttonIndex;

            if (this.draggedActionIndex >= 0 && this.draggedButtonIndex >= 0)
                parentView.Capture = true;
        }
        #endregion
    }
    #endregion

    #region Class DynamicAction
    internal class DynamicAction : IDisposable
    {
        #region Members and constructor
        private static float DefaultTransparency = 0.0f;
        private static Size[] Sizes = new Size[] { new Size(20, 20), new Size(24, 24), new Size(28, 28), new Size(32, 32), new Size(36, 36) };
        private static Size[] Margins = new Size[] { new Size(1, 1), new Size(1, 1), new Size(2, 2), new Size(2, 2), new Size(3, 3) };
        internal enum ButtonSizes { Small = 0, SmallMedium = 1, Medium = 2, MediumLarge = 3, Large = 4 };
        internal enum ActionTypes { Standard = 1, TwoState = 2 };

        private ItemList<ActionButton> buttons = null;
        private ButtonSizes buttonSizeType = ButtonSizes.Medium;
        private DesignerContentAlignment dockAlignment = DesignerContentAlignment.TopLeft;
        private float minimumTransparency = DynamicAction.DefaultTransparency;
        private float transparency = DynamicAction.DefaultTransparency;
        private ActionTypes actionType = ActionTypes.Standard;

        private Size borderSize = new Size(2, 2);
        private Size dockMargin = DynamicAction.Sizes[(int)ButtonSizes.Medium];
        private Size buttonSize = DynamicAction.Sizes[(int)ButtonSizes.Medium];
        private Size margin = DynamicAction.Margins[(int)ButtonSizes.Medium];

        internal DynamicAction()
        {
            this.buttons = new ItemList<ActionButton>(this);
        }

        ~DynamicAction()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            foreach (ActionButton button in this.buttons)
                ((IDisposable)button).Dispose();
            this.buttons.Clear();
        }
        #endregion

        #region Properties and Methods
        internal IList<ActionButton> Buttons
        {
            get
            {
                return this.buttons;
            }
        }

        internal Size DockMargin
        {
            get
            {
                return this.dockMargin;
            }

            set
            {
                this.dockMargin = value;
            }
        }

        internal ActionTypes ActionType
        {
            get
            {
                return this.actionType;
            }
        }

        internal ButtonSizes ButtonSize
        {
            get
            {
                return this.buttonSizeType;
            }

            set
            {
                if (this.buttonSizeType == value)
                    return;

                this.buttonSizeType = value;
                this.buttonSize = DynamicAction.Sizes[(int)this.buttonSizeType];
                this.margin = DynamicAction.Margins[(int)this.buttonSizeType];
            }
        }

        internal DesignerContentAlignment DockAlignment
        {
            get
            {
                return this.dockAlignment;
            }

            set
            {
                if (this.dockAlignment == value)
                    return;

                this.dockAlignment = value;
            }
        }

        internal float Transparency
        {
            get
            {
                return this.transparency;
            }

            set
            {
                if (this.transparency == value)
                    return;

                this.transparency = Math.Max(DynamicAction.DefaultTransparency, value);
            }
        }

        internal void Draw(Graphics graphics)
        {
            if (this.transparency == 0 || this.buttons.Count == 0)
                return;

            ActivityDesignerPaint.Draw3DButton(graphics, null, Bounds, this.transparency - 0.1f, ButtonState.Normal);

            for (int i = 0; i < this.buttons.Count; i++)
            {
                Rectangle buttonBounds = GetButtonBounds(i);
                ActionButton button = this.buttons[i];
                if (button.StateImages.Length == 1)
                {
                    Image buttonImage = button.StateImages[0];
                    if (button.State == ActionButton.States.Normal || button.State == ActionButton.States.Disabled)
                    {
                        buttonBounds.Inflate(-2, -2);
                        ActivityDesignerPaint.DrawImage(graphics, buttonImage, buttonBounds, new Rectangle(Point.Empty, buttonImage.Size), DesignerContentAlignment.Fill, transparency, (button.State == ActionButton.States.Disabled));
                    }
                    else
                    {
                        ButtonState state = (button.State == ActionButton.States.Highlight) ? ButtonState.Normal : ButtonState.Pushed;
                        ActivityDesignerPaint.Draw3DButton(graphics, buttonImage, buttonBounds, this.transparency, state);
                    }
                }
                else
                {
                    Image buttonImage = this.buttons[i].StateImages[(int)this.buttons[i].State];
                    buttonBounds.Inflate(-2, -2);
                    ActivityDesignerPaint.DrawImage(graphics, buttonImage, buttonBounds, new Rectangle(Point.Empty, buttonImage.Size), DesignerContentAlignment.Fill, this.transparency, false);
                }
            }
        }

        internal Rectangle Bounds
        {
            get
            {
                Size size = Size.Empty;
                int buttonCount = Math.Max(1, this.buttons.Count);
                size.Width = (2 * borderSize.Width) + (buttonCount * this.buttonSize.Width) + ((buttonCount + 1) * this.margin.Width);
                size.Height = (2 * borderSize.Height) + this.buttonSize.Height + (2 * this.margin.Height);
                return new Rectangle(Point.Empty, size);
            }
        }

        internal Rectangle GetButtonBounds(int buttonIndex)
        {
            if (buttonIndex < 0 || buttonIndex >= this.buttons.Count)
                throw new ArgumentOutOfRangeException("buttonIndex");

            Rectangle rectangle = Rectangle.Empty;
            rectangle.X = this.borderSize.Width + (buttonIndex * this.buttonSize.Width) + ((buttonIndex + 1) * this.margin.Width);
            rectangle.Y = this.borderSize.Height + this.margin.Height;
            rectangle.Size = this.buttonSize;
            return rectangle;
        }
        #endregion
    }
    #endregion

    #region Class ActionButton
    internal sealed class ActionButton : IDisposable
    {
        #region Members, Constructor and Destruction
        internal enum States { Normal = 0, Highlight = 1, Pressed = 2, Disabled = 3 };

        internal event EventHandler StateChanged;

        private Image[] stateImages = null;
        private string description = String.Empty;
        private States buttonState = States.Normal;

        internal ActionButton(Image[] stateImages)
        {
            StateImages = stateImages;
        }

        void IDisposable.Dispose()
        {
        }
        #endregion

        #region Properties and Methods
        internal Image[] StateImages
        {
            get
            {
                return this.stateImages;
            }

            set
            {
                if (value == null)
                    throw new ArgumentNullException("value");

                if (value.Length != 1 && value.Length != 4)
                    throw new ArgumentException(SR.GetString(SR.Error_InvalidStateImages), "value");

                this.stateImages = value;
                foreach (Image image in this.stateImages)
                {
                    Bitmap bitmap = image as Bitmap;
                    if (bitmap != null)
                        bitmap.MakeTransparent(AmbientTheme.TransparentColor);
                }
            }
        }

        internal States State
        {
            get
            {
                return this.buttonState;
            }

            set
            {
                if (this.buttonState == value)
                    return;

                this.buttonState = value;

                if (StateChanged != null)
                    StateChanged(this, EventArgs.Empty);
            }
        }

        internal string Description
        {
            get
            {
                return this.description;
            }

            set
            {
                this.description = value;
            }
        }
        #endregion
    }
    #endregion
}


text:
package io.dropwizard.health;

import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.health.HealthCheckRegistry;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.dropwizard.configuration.ResourceConfigurationSourceProvider;
import io.dropwizard.configuration.YamlConfigurationFactory;
import io.dropwizard.health.response.ServletHealthResponder;
import io.dropwizard.health.response.ServletHealthResponderFactory;
import io.dropwizard.jackson.Jackson;
import io.dropwizard.jersey.setup.JerseyEnvironment;
import io.dropwizard.jersey.validation.Validators;
import io.dropwizard.jetty.setup.ServletEnvironment;
import io.dropwizard.lifecycle.ExecutorServiceManager;
import io.dropwizard.lifecycle.JettyManaged;
import io.dropwizard.lifecycle.setup.LifecycleEnvironment;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;

import javax.servlet.Servlet;
import javax.servlet.ServletRegistration;
import javax.validation.Validator;
import java.util.stream.Collectors;

import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

class DefaultHealthFactoryTest {
    private final ObjectMapper objectMapper = Jackson.newObjectMapper();
    private final Validator validator = Validators.newValidator();
    private final YamlConfigurationFactory<DefaultHealthFactory> configFactory =
        new YamlConfigurationFactory<>(DefaultHealthFactory.class, validator, objectMapper, "dw");

    @Test
    void shouldBuildHealthFactoryFromYaml() throws Exception {
        final DefaultHealthFactory healthFactory = configFactory.build(new ResourceConfigurationSourceProvider(), "/yml/health.yml");

        assertThat(healthFactory.isDelayedShutdownHandlerEnabled()).isTrue();
        assertThat(healthFactory.isEnabled()).isTrue();
        assertThat(healthFactory.isInitialOverallState()).isTrue();
        assertThat(healthFactory.getShutdownWaitPeriod().toMilliseconds()).isEqualTo(1L);
        assertThat(healthFactory.getHealthCheckUrlPaths()).isEqualTo(singletonList("/health-check"));

        assertThat(healthFactory.getHealthChecks()).isEqualTo(healthFactory.getHealthCheckConfigurations());

        assertThat(healthFactory.getHealthCheckConfigurations()
            .stream()
            .map(HealthCheckConfiguration::getName)
            .collect(Collectors.toList()))
            .contains("foundationdb", "kafka", "redis");
        assertThat(healthFactory.getHealthCheckConfigurations()
            .stream()
            .map(HealthCheckConfiguration::isCritical)
            .collect(Collectors.toList()))
            .contains(true, false, false);
        healthFactory.getHealthCheckConfigurations().forEach(healthCheckConfig -> {
            assertThat(healthCheckConfig.getSchedule().getCheckInterval().toSeconds()).isEqualTo(5L);
            assertThat(healthCheckConfig.getSchedule().getDowntimeInterval().toSeconds()).isEqualTo(30L);
            assertThat(healthCheckConfig.getSchedule().getFailureAttempts()).isEqualTo(3);
            assertThat(healthCheckConfig.getSchedule().getSuccessAttempts()).isEqualTo(2);
        });
    }

    @Test
    void configure() throws Exception {
        final DefaultHealthFactory healthFactory = configFactory.build(new ResourceConfigurationSourceProvider(), "/yml/health.yml");

        LifecycleEnvironment lifecycleEnvironment = new LifecycleEnvironment(new MetricRegistry());

        ServletRegistration.Dynamic mockServletRegistration = mock(ServletRegistration.Dynamic.class);
        ServletEnvironment servletEnvironment = mock(ServletEnvironment.class);
        ArgumentCaptor<Servlet> servletCaptor = ArgumentCaptor.forClass(Servlet.class);
        when(servletEnvironment.addServlet(eq("health-check-test-servlet"), any(Servlet.class)))
            .thenReturn(mockServletRegistration);

        HealthEnvironment healthEnvironment = new HealthEnvironment(mock(HealthCheckRegistry.class));

        healthFactory.configure(
            lifecycleEnvironment,
            servletEnvironment,
            mock(JerseyEnvironment.class),
            healthEnvironment,
            new ObjectMapper(),
            "test");

        assertThat(lifecycleEnvironment.getManagedObjects())
            .hasSize(2)
            .allSatisfy(obj -> assertThat(obj).isInstanceOf(JettyManaged.class))
            .map(managed -> ((JettyManaged)managed).getManaged())
            .satisfies(obj -> assertThat(obj).element(0).isInstanceOfSatisfying(ExecutorServiceManager.class, executorServiceManager ->
                assertThat(executorServiceManager.getPoolName()).isEqualTo("health-check-test-scheduled-executor")))
            .satisfies(obj -> assertThat(obj).element(1).isInstanceOf(HealthCheckConfigValidator.class));

        assertThat(healthFactory.getHealthResponderFactory())
            .isInstanceOf(ServletHealthResponderFactory.class);

        verify(servletEnvironment).addServlet(eq("health-check-test-servlet"), servletCaptor.capture());
        assertThat(servletCaptor.getValue()).isInstanceOf(ServletHealthResponder.class);

        verify(mockServletRegistration).addMapping("/health-check");

        assertThat(healthEnvironment.healthStateAggregator()).isNotNull();
    }
}