text:
require 'spec_helper'

class MyTracker
  include HistoryTracker::Mongoid::Tracker
end

describe MyTracker, type: :mongoid do
  it { should have_index_for('association_chain.id' => 1, 'association_chain.name' => 1).with_options(background: true) }
  it { should have_index_for(modifier_id: 1).with_options(background: true) }
  it { should have_index_for(trackable_klass_name: 1).with_options(background: true) }

  it { should have_field(:association_chain).of_type(Array) }
  it { should have_field(:original).of_type(Hash).with_default_value_of({}) }
  it { should have_field(:modified).of_type(Hash).with_default_value_of({}) }
  it { should have_field(:changeset).of_type(Hash).with_default_value_of({}).with_alias(:changes) }
  it { should have_field(:action).of_type(String) }
  it { should have_field(:modifier_id).of_type(Integer) }

  it { should validate_presence_of(:association_chain) }
  it { should validate_presence_of(:action) }
  it { should validate_presence_of(:modifier_id) }
  it { should validate_presence_of(:trackable_klass_name) }
  it { should validate_inclusion_of(:action).to_allow('create', 'update', 'destroy') }
end

describe MyTracker, 'methods' do
  let(:tracker) { MyTracker.new(action: 'update', original: {name: 'Listing 1'}, modified: {name: 'Listing 2'}) }

  it '#original should be stringify_keys' do
    expect(tracker.original).to eq({'name' => 'Listing 1'})
  end

  it '#modified should be stringify_keys' do
    expect(tracker.modified).to eq({'name' => 'Listing 2'})
  end

  context '#validations' do
    it 'fails when old and new value are the same' do
      tracker = MyTracker.new(action: 'update', changeset: {name: ['Listing 1', 'Listing 1']}, original: {name: 'Listing 1'}, modified: {name: 'Listing 1'})

      tracker.valid?
      expect(tracker.errors.full_messages.to_s).to match(/the same/)
    end
  end

  context '#trackable' do
    let!(:listing)      { Listing.create!(name: 'Listing 1') }
    let(:history_track) { listing.history_tracks.first }

    it 'returns trackable' do
      expect(history_track.trackable).to eq(listing)
    end

    it 'returns trackable_class' do
      expect(history_track.trackable_class).to eq(Listing)
    end
  end
end

redpajama_set_name: RedPajamaGithub


text: LeadPipe.Net.CommonObjects is unfinished.


text:
package org.michaelbel.bottomsheet;

/**
 * Date: 17 FEB 2018
 * Time: 22:52 MSK
 *
 * @author Michael Bel
 */

public interface BottomSheetCallback {

    void onShown();

    void onDismissed();
}


text:
import logging
from collections import namedtuple

RuleConfig = namedtuple('RuleConfig', ['host', 'port', 'title'])

import socket

def port_is_open(host, port):
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(1)
        s.connect((host, int(port)))
        s.close()
        return True
    except:
        return False

class Rule(object):
    'Rule插件类,必须使用Rule作为类名'

    def __init__(self, options):
        '插件初始化方法,options是插件配置数据'
        self.options = options
        self._load_rules()

    def _load_rules(self):
        self.rules = []
        for k, v in self.options.items():
            if not k.startswith('rule'):
                continue
            rule = RuleConfig._make(v.split())
            logging.info('load rule config:%s', rule)
            self.rules.append(rule)

    def process(self, data, historys):
        '''插件方法,必须实现
        data是最新的计数数据,caches是最近的数据'''
        logging.debug('rule process:%s', data)
        for rule in self.rules:
            if not port_is_open(rule.host, rule.port):
                return self._get_send_data(rule)

        return None

    def _get_send_data(self, rule):
        result = {}
        result['title'] = rule.title
        result['content'] = '无法连接%s:%s' % (rule.host, rule.port)
        result['host'] = self.options['host'] if 'host' in self.options else 'default'
        return result


text:
use warnings;
use strict;
use 5.10.0;

my @a = ( 1, 2, 3 );
my %h = ( a => 1, b => 2, c => 3 );

# take a reference to the array

my $aref = \@a;

# take a reference to the hash

my $href = \%h;

# access the entire array through its reference

my $elem_count = scalar @{ $aref };

# access the entire hash through its reference

my $keys_count = keys %{ $href };

# get a single element through the array reference

my $element = $a->[0];

# get a single value through the hash reference

my $value = $h->{ a };

# assign to a single array element through its reference

$a->[0] = 1;

# assign a value to a single hash key through its ref

$h->{ a } = 1;


text:
import argparse
import logging
import os
from enum import Enum

from waiter import plugins, terminal
from waiter.display import get_user_selection, tabulate_service_instances, tabulate_token_services
from waiter.querying import get_service_id_from_instance_id, get_target_cluster_from_token, print_no_data, \
    print_no_services, query_service, query_token, get_services_on_cluster, print_no_instances
from waiter.util import guard_no_cluster, print_info

BASH_PATH = '/bin/bash'

class Destination(Enum):
    TOKEN = 'token'
    SERVICE_ID = 'service_id'
    INSTANCE_ID = 'instance_id'

def map_instances_with_status(instances, status):
    return [{'_status': status, **inst} for inst in instances]

def get_instances_from_service_id(clusters, service_id, include_active_instances, include_failed_instances,
                                  include_killed_instances):
    query_result = query_service(clusters, service_id)
    num_services = query_result['count']
    if num_services == 0:
        return False
    services = map(lambda service_data: service_data['service'], query_result['clusters'].values())
    instances = []
    for service in services:
        if include_active_instances:
            instances += map_instances_with_status(service['instances']['active-instances'], 'active')
        if include_failed_instances:
            instances += map_instances_with_status(service['instances']['failed-instances'], 'failed')
        if include_killed_instances:
            instances += map_instances_with_status(service['instances']['killed-instances'], 'killed')
    return instances

def kubectl_exec_to_instance(kubectl_cmd, namespace, pod_name, container_name, log_directory,
                             command_to_run=None, api_server=None, context=None):
    if context is not None:
        args = ['--context', context]
    elif api_server is not None:
        args = ['--server', api_server]
    args = [*args,
            '--namespace', namespace,
            'exec',
            '-it', pod_name,
            '-c', container_name,
            '--',
            '/bin/bash', '-c', f"cd {log_directory}; {' '.join(command_to_run) or 'exec /bin/bash'}"]
    os.execlp(kubectl_cmd, 'kubectl', *args)

def ssh_instance(instance, container_name, command_to_run=None):
    print_info(f'Attempting to ssh into instance {terminal.bold(instance["id"])}...')
    log_directory = instance['log-directory']
    k8s_pod_name = instance.get('k8s/pod-name', False)
    if k8s_pod_name:
        context = instance.get('k8s/context')
        k8s_api_server = instance['k8s/api-server-url']
        kubectl_cmd = os.getenv('WAITER_KUBECTL', plugins.get_fn('get-kubectl-cmd', lambda: 'kubectl')())
        k8s_namespace = instance['k8s/namespace']
        print_info(f'Executing ssh to k8s pod {terminal.bold(k8s_pod_name)}')
        logging.debug(f'Executing ssh to k8s pod {terminal.bold(k8s_pod_name)} '
                      f'using namespace={k8s_namespace} api_server={k8s_api_server}')
        kubectl_exec_to_instance(kubectl_cmd, k8s_namespace, k8s_pod_name, container_name,
                                 log_directory, command_to_run, api_server=k8s_api_server, context=context)
    else:
        hostname = instance['host']
        command_to_run = command_to_run or [BASH_PATH]
        ssh_cmd = os.getenv('WAITER_SSH', 'ssh')
        args = [ssh_cmd, '-t', hostname, 'cd', log_directory, ';'] + command_to_run
        print_info(f'Executing ssh to {terminal.bold(hostname)}')
        os.execlp(ssh_cmd, *args)

def ssh_instance_id(clusters, instance_id, command, container_name):
    service_id = get_service_id_from_instance_id(instance_id)
    instances = get_instances_from_service_id(clusters, service_id, True, True, True)
    if instances is False:
        print_no_data(clusters)
        return 1
    found_instance = next((instance
                           for instance in instances
                           if instance['id'] == instance_id),
                          False)
    if not found_instance:
        print_no_data(clusters)
        return 1
    return ssh_instance(found_instance, container_name, command)

def ssh_service_id(clusters, service_id, command, container_name, skip_prompts, include_active_instances,
                   include_failed_instances, include_killed_instances):
    instances = get_instances_from_service_id(clusters, service_id, include_active_instances, include_failed_instances,
                                              include_killed_instances)
    if instances is False:
        print_no_data(clusters)
        return 1
    if len(instances) == 0:
        print_no_instances(service_id)
        return 1
    if skip_prompts:
        selected_instance = instances[0]
    else:
        column_names = ['Instance Id', 'Host', 'Status']
        tabular_output = tabulate_service_instances(instances, show_index=True, column_names=column_names)
        selected_instance = get_user_selection(instances, tabular_output)
    return ssh_instance(selected_instance, container_name, command)

def ssh_token(clusters, enforce_cluster, token, command, container_name, skip_prompts, include_active_instances,
              include_failed_instances, include_killed_instances):
    if skip_prompts:
        cluster = get_target_cluster_from_token(clusters, token, enforce_cluster)
        query_result = get_services_on_cluster(cluster, token)
        services = [s
                    for s in query_result.get('services', [])
                    if s['instance-counts']['healthy-instances'] + s['instance-counts']['unhealthy-instances'] > 0]
        if len(services) == 0:
            print_no_services(clusters, token)
            return 1
        max_last_request = max(s.get('last-request-time', '') for s in services)
        selected_service_id = next(s['service-id'] for s in services if s['last-request-time'] == max_last_request)
    else:
        query_result = query_token(clusters, token, include_services=True)
        if query_result['count'] == 0:
            print_no_data(clusters)
            return 1
        clusters_by_name = {c['name']: c for c in clusters}
        cluster_data = query_result['clusters']
        services = [{'cluster': cluster, 'etag': data['etag'], **service}
                    for cluster, data in cluster_data.items()
                    for service in data['services']]
        if len(services) == 0:
            print_no_services(clusters, token)
            return 1
        column_names = ['Service Id', 'Cluster', 'Instances', 'In-flight req.', 'Status', 'Last request', 'Current?']
        tabular_output, sorted_services = tabulate_token_services(services, token, show_index=True, summary_table=False,
                                                                  column_names=column_names)
        selected_service = get_user_selection(sorted_services, tabular_output)
        selected_service_id = selected_service['service-id']
        clusters = [clusters_by_name[selected_service['cluster']]]
    return ssh_service_id(clusters, selected_service_id, command, container_name, skip_prompts,
                          include_active_instances, include_failed_instances, include_killed_instances)

def ssh(clusters, args, _, enforce_cluster):
    guard_no_cluster(clusters)
    token_or_service_id_or_instance_id = args.pop('token-or-service-id-or-instance-id')
    command = args.pop('command')
    ssh_destination = args.pop('ssh_destination')
    include_active_instances = args.pop('include_active_instances')
    include_failed_instances = args.pop('include_failed_instances')
    include_killed_instances = args.pop('include_killed_instances')
    container_name = args.pop('container_name', 'waiter-app')
    skip_prompts = args.pop('quick')
    if ssh_destination == Destination.TOKEN:
        return ssh_token(clusters, enforce_cluster, token_or_service_id_or_instance_id, command, container_name,
                         skip_prompts, include_active_instances, include_failed_instances, include_killed_instances)
    elif ssh_destination == Destination.SERVICE_ID:
        return ssh_service_id(clusters, token_or_service_id_or_instance_id, command, container_name, skip_prompts,
                              include_active_instances, include_failed_instances, include_killed_instances)
    elif ssh_destination == Destination.INSTANCE_ID:
        return ssh_instance_id(clusters, token_or_service_id_or_instance_id, command, container_name)

def register(add_parser):
    """Adds this sub-command's parser and returns the action function"""
    parser = add_parser('ssh',
                        help='ssh to a Waiter instance',
                        description='ssh to an instance given the token, service id, or instance id. Working directory '
                                    'will be the log directory.')
    parser.add_argument('token-or-service-id-or-instance-id')
    parser.add_argument('--container-name', '-c',
                        help='specify the container name you want to ssh into. Defaults to "waiter-app". Has no '
                                'effect if instance is not k8s pod.')
    id_group = parser.add_mutually_exclusive_group(required=False)
    id_group.add_argument('--token', '-t', dest='ssh_destination', action='store_const', const=Destination.TOKEN,
                          default=Destination.TOKEN, help='Default; ssh with token')
    id_group.add_argument('--service-id', '-s', dest='ssh_destination', action='store_const',
                          const=Destination.SERVICE_ID, help='ssh using a service id')
    id_group.add_argument('--instance-id', '-i', dest='ssh_destination', action='store_const',
                          const=Destination.INSTANCE_ID, help='ssh directly to instance id')
    parser.add_argument('--quick', '-q', dest='quick', action='store_true',
                        help='skips services prompt by selecting the service with latest request, and instances prompt '
                             'by selecting a random one.')
    active_group = parser.add_mutually_exclusive_group(required=False)
    failed_group = parser.add_mutually_exclusive_group(required=False)
    killed_group = parser.add_mutually_exclusive_group(required=False)
    active_group.add_argument('--active', '-a', dest='include_active_instances', action='store_true', default=True,
                              help='included by default; includes active instances when prompting')
    failed_group.add_argument('--failed', '-f', dest='include_failed_instances', action='store_true',
                              help='includes failed instances when prompting')
    killed_group.add_argument('--killed', '-k', dest='include_killed_instances', action='store_true',
                              help='includes killed instances when prompting')
    active_group.add_argument('--no-active', dest='include_active_instances', action='store_false',
                              help="don't show active instances in prompt")
    failed_group.add_argument('--no-failed', dest='include_failed_instances', action='store_false',
                              help="don't show failed instances in prompt")
    killed_group.add_argument('--no-killed', dest='include_killed_instances', action='store_false',
                              help="don't show killed instances in prompt")
    parser.add_argument('command', nargs=argparse.REMAINDER, help='command to be run on instance')
    return ssh


text:
	-- Love Frames - A GUI library for LOVE --
	-- Copyright (c) 2012-2014 Kenny Shields --
--]]------------------------------------------------

-- panel object
local newobject = loveframes.NewObject("panel", "loveframes_object_panel", true)

--[[---------------------------------------------------------
	- func: initialize()
	- desc: initializes the object
--]]---------------------------------------------------------
function newobject:initialize()

	self.type = "panel"
	self.width = 200
	self.height = 50
	self.internal = false
	self.children = {}

end

--[[---------------------------------------------------------
	- func: update(deltatime)
	- desc: updates the element
--]]---------------------------------------------------------
function newobject:update(dt)

	local state = loveframes.state
	local selfstate = self.state

	if state ~= selfstate then
		return
	end

	local visible = self.visible
	local alwaysupdate = self.alwaysupdate

	if not visible then
		if not alwaysupdate then
			return
		end
	end

	local children = self.children
	local parent = self.parent
	local base = loveframes.base
	local update = self.Update

	-- move to parent if there is a parent
	if parent ~= base and parent.type ~= "list" then
		self.x = self.parent.x + self.staticx
		self.y = self.parent.y + self.staticy
	end

	self:CheckHover()

	for k, v in ipairs(children) do
		v:update(dt)
	end

	if update then
		update(self, dt)
	end

end

--[[---------------------------------------------------------
	- func: draw()
	- desc: draws the object
--]]---------------------------------------------------------
function newobject:draw()

	local state = loveframes.state
	local selfstate = self.state

	if state ~= selfstate then
		return
	end

	local visible = self.visible

	if not visible then
		return
	end

	local children = self.children
	local skins = loveframes.skins.available
	local skinindex = loveframes.config["ACTIVESKIN"]
	local defaultskin = loveframes.config["DEFAULTSKIN"]
	local selfskin = self.skin
	local skin = skins[selfskin] or skins[skinindex]
	local drawfunc = skin.DrawPanel or skins[defaultskin].DrawPanel
	local draw = self.Draw
	local drawcount = loveframes.drawcount

	-- set the object's draw order
	self:SetDrawOrder()

	if draw then
		draw(self)
	else
		drawfunc(self)
	end

	-- loop through the object's children and draw them
	for k, v in ipairs(children) do
		v:draw()
	end

end

--[[---------------------------------------------------------
	- func: mousepressed(x, y, button)
	- desc: called when the player presses a mouse button
--]]---------------------------------------------------------
function newobject:mousepressed(x, y, button)

	local state = loveframes.state
	local selfstate = self.state

	if state ~= selfstate then
		return
	end

	local visible = self.visible

	if not visible then
		return
	end

	local children = self.children
	local hover = self.hover

	if hover and button == "l" then
		local baseparent = self:GetBaseParent()
		if baseparent and baseparent.type == "frame" then
			baseparent:MakeTop()
		end
	end

	for k, v in ipairs(children) do
		v:mousepressed(x, y, button)
	end

end

--[[---------------------------------------------------------
	- func: mousereleased(x, y, button)
	- desc: called when the player releases a mouse button
--]]---------------------------------------------------------
function newobject:mousereleased(x, y, button)

	local state = loveframes.state
	local selfstate = self.state

	if state ~= selfstate then
		return
	end

	local visible  = self.visible
	local children = self.children

	if not visible then
		return
	end

	for k, v in ipairs(children) do
		v:mousereleased(x, y, button)
	end

end


text:
YUI.add('overlay', function (Y, NAME) {

/**
 * Provides a basic Overlay widget, with Standard Module content support. The Overlay widget
 * provides Page XY positioning support, alignment and centering support along with basic
 * stackable support (z-index and shimming).
 *
 * @module overlay
 */

/**
 * A basic Overlay Widget, which can be positioned based on Page XY co-ordinates and is stackable (z-index support).
 * It also provides alignment and centering support and uses a standard module format for it's content, with header,
 * body and footer section support.
 *
 * @class Overlay
 * @constructor
 * @extends Widget
 * @uses WidgetStdMod
 * @uses WidgetPosition
 * @uses WidgetStack
 * @uses WidgetPositionAlign
 * @uses WidgetPositionConstrain
 * @param {Object} object The user configuration for the instance.
 */
Y.Overlay = Y.Base.create("overlay", Y.Widget, [Y.WidgetStdMod, Y.WidgetPosition, Y.WidgetStack, Y.WidgetPositionAlign, Y.WidgetPositionConstrain]);

}, '3.9.1', {
    "requires": [
        "widget",
        "widget-stdmod",
        "widget-position",
        "widget-position-align",
        "widget-stack",
        "widget-position-constrain"
    ],
    "skinnable": true
});


text:
layout: contributor-profile
credit-name: R.L. Thull
first-name: R.L.
last-name: Thull
file-as: t
role: Author
role-2:
role-3:
title: R.L. Thull — Work in Fireside
description:
twitter-handle:
profile-pic: r-l-thull.jpg
website-url:
short-name: r-l-thull
permalink: r-l-thull
---
R. L. Thull is a graphic designer with a small robot collection. Her fiction has received an honorable mention in the L. Ron Hubbard Writers of the Future contest. She resides in Minneapolis, Minnesota with her husband and two misbehaving cats.


text:
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE CPP #-}

-- | HTTP over TLS support for Warp via the TLS package.
--
--   If HTTP\/2 is negotiated by ALPN, HTTP\/2 over TLS is used.
--   Otherwise HTTP\/1.1 over TLS is used.
--
--   Support for SSL is now obsoleted.

module Network.Wai.Handler.WarpTLS (
    -- * Settings
      TLSSettings
    , defaultTlsSettings
    -- * Smart constructors
    , tlsSettings
    , tlsSettingsMemory
    , tlsSettingsChain
    , tlsSettingsChainMemory
    -- * Accessors
    , certFile
    , keyFile
    , tlsLogging
    , tlsAllowedVersions
    , tlsCiphers
    , tlsWantClientCert
    , tlsServerHooks
    , tlsServerDHEParams
    , onInsecure
    , OnInsecure (..)
    -- * Runner
    , runTLS
    , runTLSSocket
    -- * Exception
    , WarpTLSException (..)
    , DH.Params
    , DH.generateParams
    ) where

#if __GLASGOW_HASKELL__ < 709
import Control.Applicative ((<$>))
#endif
import Control.Applicative ((<|>))
import Control.Exception (Exception, throwIO, bracket, finally, handle, fromException, try, IOException, onException, SomeException(..))
import qualified Control.Exception as E
import Control.Monad (void)
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import Data.Default.Class (def)
import qualified Data.IORef as I
import Data.Streaming.Network (bindPortTCP, safeRecv)
import Data.Typeable (Typeable)
import Network.Socket (Socket, sClose, withSocketsDo, SockAddr, accept)
import Network.Socket.ByteString (sendAll)
import qualified Network.TLS as TLS
import qualified Crypto.PubKey.DH as DH
import qualified Network.TLS.Extra as TLSExtra
import Network.Wai (Application)
import Network.Wai.Handler.Warp
import Network.Wai.Handler.Warp.Internal
import System.IO.Error (isEOFError)

----------------------------------------------------------------

-- | Settings for WarpTLS.
data TLSSettings = TLSSettings {
    certFile :: FilePath
    -- ^ File containing the certificate.
  , chainCertFiles :: [FilePath]
    -- ^ Files containing chain certificates.
  , keyFile :: FilePath
    -- ^ File containing the key
  , certMemory :: Maybe S.ByteString
  , chainCertsMemory :: [S.ByteString]
  , keyMemory :: Maybe S.ByteString
  , onInsecure :: OnInsecure
    -- ^ Do we allow insecure connections with this server as well?
    --
    -- >>> onInsecure defaultTlsSettings
    -- DenyInsecure "This server only accepts secure HTTPS connections."
    --
    -- Since 1.4.0
  , tlsLogging :: TLS.Logging
    -- ^ The level of logging to turn on.
    --
    -- Default: 'TLS.defaultLogging'.
    --
    -- Since 1.4.0
  , tlsAllowedVersions :: [TLS.Version]
    -- ^ The TLS versions this server accepts.
    --
    -- >>> tlsAllowedVersions defaultTlsSettings
    -- [TLS12,TLS11,TLS10]
    --
    -- Since 1.4.2
  , tlsCiphers :: [TLS.Cipher]
    -- ^ The TLS ciphers this server accepts.
    --
    -- >>> tlsCiphers defaultTlsSettings
    -- [ECDHE-RSA-AES128GCM-SHA256,DHE-RSA-AES128GCM-SHA256,DHE-RSA-AES256-SHA256,DHE-RSA-AES128-SHA256,DHE-RSA-AES256-SHA1,DHE-RSA-AES128-SHA1,DHE-DSA-AES128-SHA1,DHE-DSA-AES256-SHA1,RSA-aes128-sha1,RSA-aes256-sha1]
    --
    -- Since 1.4.2
  , tlsWantClientCert :: Bool
    -- ^ Whether or not to demand a certificate from the client.  If this
    -- is set to True, you must handle received certificates in a server hook
    -- or all connections will fail.
    --
    -- >>> tlsWantClientCert defaultTlsSettings
    -- False
    --
    -- Since 3.0.2
  , tlsServerHooks :: TLS.ServerHooks
    -- ^ The server-side hooks called by the tls package, including actions
    -- to take when a client certificate is received.  See the "Network.TLS"
    -- module for details.
    --
    -- Default: def
    --
    -- Since 3.0.2
  , tlsServerDHEParams :: Maybe DH.Params
    -- ^ Configuration for ServerDHEParams
    -- more function lives in `cryptonite` package
    --
    -- Default: Nothing
    --
    -- Since 3.2.2
  }

-- | Default 'TLSSettings'. Use this to create 'TLSSettings' with the field record name (aka accessors).
defaultTlsSettings :: TLSSettings
defaultTlsSettings = TLSSettings {
    certFile = "certificate.pem"
  , chainCertFiles = []
  , keyFile = "key.pem"
  , certMemory = Nothing
  , chainCertsMemory = []
  , keyMemory = Nothing
  , onInsecure = DenyInsecure "This server only accepts secure HTTPS connections."
  , tlsLogging = def
  , tlsAllowedVersions = [TLS.TLS12,TLS.TLS11,TLS.TLS10]
  , tlsCiphers = ciphers
  , tlsWantClientCert = False
  , tlsServerHooks = def
  , tlsServerDHEParams = Nothing
  }

-- taken from stunnel example in tls-extra
ciphers :: [TLS.Cipher]
ciphers =
    [ TLSExtra.cipher_ECDHE_RSA_AES128GCM_SHA256
    , TLSExtra.cipher_ECDHE_RSA_AES128CBC_SHA256
    , TLSExtra.cipher_ECDHE_RSA_AES128CBC_SHA
    , TLSExtra.cipher_DHE_RSA_AES128GCM_SHA256
    , TLSExtra.cipher_DHE_RSA_AES256_SHA256
    , TLSExtra.cipher_DHE_RSA_AES128_SHA256
    , TLSExtra.cipher_DHE_RSA_AES256_SHA1
    , TLSExtra.cipher_DHE_RSA_AES128_SHA1
    , TLSExtra.cipher_DHE_DSS_AES128_SHA1
    , TLSExtra.cipher_DHE_DSS_AES256_SHA1
    , TLSExtra.cipher_AES128_SHA1
    , TLSExtra.cipher_AES256_SHA1
    ]

----------------------------------------------------------------

-- | An action when a plain HTTP comes to HTTP over TLS/SSL port.
data OnInsecure = DenyInsecure L.ByteString
                | AllowInsecure
                deriving (Show)

----------------------------------------------------------------

-- | A smart constructor for 'TLSSettings' based on 'defaultTlsSettings'.
tlsSettings :: FilePath -- ^ Certificate file
            -> FilePath -- ^ Key file
            -> TLSSettings
tlsSettings cert key = defaultTlsSettings {
    certFile = cert
  , keyFile = key
  }

-- | A smart constructor for 'TLSSettings' that allows specifying
-- chain certificates based on 'defaultTlsSettings'.
--
-- Since 3.0.3
tlsSettingsChain
            :: FilePath -- ^ Certificate file
            -> [FilePath] -- ^ Chain certificate files
            -> FilePath -- ^ Key file
            -> TLSSettings
tlsSettingsChain cert chainCerts key = defaultTlsSettings {
    certFile = cert
  , chainCertFiles = chainCerts
  , keyFile = key
  }

-- | A smart constructor for 'TLSSettings', but uses in-memory representations
-- of the certificate and key based on 'defaultTlsSettings'.
--
-- Since 3.0.1
tlsSettingsMemory
    :: S.ByteString -- ^ Certificate bytes
    -> S.ByteString -- ^ Key bytes
    -> TLSSettings
tlsSettingsMemory cert key = defaultTlsSettings
    { certMemory = Just cert
    , keyMemory = Just key
    }

-- | A smart constructor for 'TLSSettings', but uses in-memory representations
-- of the certificate and key based on 'defaultTlsSettings'.
--
-- Since 3.0.3
tlsSettingsChainMemory
    :: S.ByteString -- ^ Certificate bytes
    -> [S.ByteString] -- ^ Chain certificate bytes
    -> S.ByteString -- ^ Key bytes
    -> TLSSettings
tlsSettingsChainMemory cert chainCerts key = defaultTlsSettings
    { certMemory = Just cert
    , chainCertsMemory = chainCerts
    , keyMemory = Just key
    }

----------------------------------------------------------------

-- | Running 'Application' with 'TLSSettings' and 'Settings'.
runTLS :: TLSSettings -> Settings -> Application -> IO ()
runTLS tset set app = withSocketsDo $
    bracket
        (bindPortTCP (getPort set) (getHost set))
        sClose
        (\sock -> runTLSSocket tset set sock app)

----------------------------------------------------------------

-- | Running 'Application' with 'TLSSettings' and 'Settings' using
--   specified 'Socket'.
runTLSSocket :: TLSSettings -> Settings -> Socket -> Application -> IO ()
runTLSSocket tlsset@TLSSettings{..} set sock app = do
    credential <- case (certMemory, keyMemory) of
        (Nothing, Nothing) ->
            either error id <$>
            TLS.credentialLoadX509Chain certFile chainCertFiles keyFile
        (mcert, mkey) -> do
            cert <- maybe (S.readFile certFile) return mcert
            key <- maybe (S.readFile keyFile) return mkey
            either error return $
              TLS.credentialLoadX509ChainFromMemory cert chainCertsMemory key
    runTLSSocket' tlsset set credential sock app

runTLSSocket' :: TLSSettings -> Settings -> TLS.Credential -> Socket -> Application -> IO ()
runTLSSocket' tlsset@TLSSettings{..} set credential sock app =
    runSettingsConnectionMakerSecure set get app
  where
    get = getter tlsset sock params
    params = def { -- TLS.ServerParams
        TLS.serverWantClientCert = tlsWantClientCert
      , TLS.serverCACertificates = []
      , TLS.serverDHEParams      = tlsServerDHEParams
      , TLS.serverHooks          = hooks
      , TLS.serverShared         = shared
      , TLS.serverSupported      = supported
      }
    -- Adding alpn to user's tlsServerHooks.
    hooks = tlsServerHooks {
        TLS.onALPNClientSuggest = TLS.onALPNClientSuggest tlsServerHooks <|>
          (if settingsHTTP2Enabled set then Just alpn else Nothing)
      }
    shared = def {
        TLS.sharedCredentials = TLS.Credentials [credential]
      }
    supported = def { -- TLS.Supported
        TLS.supportedVersions       = tlsAllowedVersions
      , TLS.supportedCiphers        = tlsCiphers
      , TLS.supportedCompressions   = [TLS.nullCompression]
      , TLS.supportedHashSignatures = [
          -- Safari 8 and go tls have bugs on SHA 512 and SHA 384.
          -- So, we don't specify them here at this moment.
          (TLS.HashSHA256, TLS.SignatureRSA)
        , (TLS.HashSHA224, TLS.SignatureRSA)
        , (TLS.HashSHA1,   TLS.SignatureRSA)
        , (TLS.HashSHA1,   TLS.SignatureDSS)
        ]
      , TLS.supportedSecureRenegotiation = True
      , TLS.supportedClientInitiatedRenegotiation = False
      , TLS.supportedSession             = True
      , TLS.supportedFallbackScsv        = True
      }

alpn :: [S.ByteString] -> IO S.ByteString
alpn xs
  | "h2"    `elem` xs = return "h2"
  | "h2-16" `elem` xs = return "h2-16"
  | "h2-15" `elem` xs = return "h2-15"
  | "h2-14" `elem` xs = return "h2-14"
  | otherwise         = return "http/1.1"

----------------------------------------------------------------

getter :: TLS.TLSParams params => TLSSettings -> Socket -> params -> IO (IO (Connection, Transport), SockAddr)
getter tlsset@TLSSettings{..} sock params = do
    (s, sa) <- accept sock
    return (mkConn tlsset s params, sa)

mkConn :: TLS.TLSParams params => TLSSettings -> Socket -> params -> IO (Connection, Transport)
mkConn tlsset s params = switch `onException` sClose s
  where
    switch = do
        firstBS <- safeRecv s 4096
        if not (S.null firstBS) && S.head firstBS == 0x16 then
            httpOverTls tlsset s firstBS params
          else
            plainHTTP tlsset s firstBS

----------------------------------------------------------------

httpOverTls :: TLS.TLSParams params => TLSSettings -> Socket -> S.ByteString -> params -> IO (Connection, Transport)
httpOverTls TLSSettings{..} s bs0 params = do
    recvN <- makePlainReceiveN s bs0
    ctx <- TLS.contextNew (backend recvN) params
    TLS.contextHookSetLogging ctx tlsLogging
    TLS.handshake ctx
    writeBuf <- allocateBuffer bufferSize
    -- Creating a cache for leftover input data.
    ref <- I.newIORef ""
    tls <- getTLSinfo ctx
    return (conn ctx writeBuf ref, tls)
  where
    backend recvN = TLS.Backend {
        TLS.backendFlush = return ()
      , TLS.backendClose = sClose s
      , TLS.backendSend  = sendAll' s
      , TLS.backendRecv  = recvN
      }
    sendAll' sock bs = sendAll sock bs `E.catch` \(SomeException _) ->
        throwIO ConnectionClosedByPeer
    conn ctx writeBuf ref = Connection {
        connSendMany         = TLS.sendData ctx . L.fromChunks
      , connSendAll          = sendall
      , connSendFile         = sendfile
      , connClose            = close
      , connRecv             = recv ref
      , connRecvBuf          = recvBuf ref
      , connWriteBuffer      = writeBuf
      , connBufferSize       = bufferSize
      }
      where
        sendall = TLS.sendData ctx . L.fromChunks . return
        sendfile fid offset len hook headers =
            readSendFile writeBuf bufferSize sendall fid offset len hook headers

        close = freeBuffer writeBuf `finally`
                void (tryIO $ TLS.bye ctx) `finally`
                TLS.contextClose ctx

        -- TLS version of recv with a cache for leftover input data.
        -- The cache is shared with recvBuf.
        recv cref = do
            cached <- I.readIORef cref
            if cached /= "" then do
                I.writeIORef cref ""
                return cached
              else
                recv'

        -- TLS version of recv (decrypting) without a cache.
        recv' = handle onEOF go
          where
            onEOF e
              | Just TLS.Error_EOF <- fromException e       = return S.empty
              | Just ioe <- fromException e, isEOFError ioe = return S.empty                  | otherwise                                   = throwIO e
            go = do
                x <- TLS.recvData ctx
                if S.null x then
                    go
                  else
                    return x

        -- TLS version of recvBuf with a cache for leftover input data.
        recvBuf cref buf siz = do
            cached <- I.readIORef cref
            (ret, leftover) <- fill cached buf siz recv'
            I.writeIORef cref leftover
            return ret

fill :: S.ByteString -> Buffer -> BufSize -> Recv -> IO (Bool,S.ByteString)
fill bs0 buf0 siz0 recv
  | siz0 <= len0 = do
      let (bs, leftover) = S.splitAt siz0 bs0
      void $ copy buf0 bs
      return (True, leftover)
  | otherwise = do
      buf <- copy buf0 bs0
      loop buf (siz0 - len0)
  where
    len0 = S.length bs0
    loop _   0   = return (True, "")
    loop buf siz = do
      bs <- recv
      let len = S.length bs
      if len == 0 then return (False, "")
        else if (len <= siz) then do
          buf' <- copy buf bs
          loop buf' (siz - len)
        else do
          let (bs1,bs2) = S.splitAt siz bs
          void $ copy buf bs1
          return (True, bs2)

getTLSinfo :: TLS.Context -> IO Transport
getTLSinfo ctx = do
    proto <- TLS.getNegotiatedProtocol ctx
    minfo <- TLS.contextGetInformation ctx
    case minfo of
        Nothing   -> return TCP
        Just TLS.Information{..} -> do
            let (major, minor) = case infoVersion of
                    TLS.SSL2  -> (2,0)
                    TLS.SSL3  -> (3,0)
                    TLS.TLS10 -> (3,1)
                    TLS.TLS11 -> (3,2)
                    TLS.TLS12 -> (3,3)
            return TLS {
                tlsMajorVersion = major
              , tlsMinorVersion = minor
              , tlsNegotiatedProtocol = proto
              , tlsChiperID = TLS.cipherID infoCipher
              }

tryIO :: IO a -> IO (Either IOException a)
tryIO = try

----------------------------------------------------------------

plainHTTP :: TLSSettings -> Socket -> S.ByteString -> IO (Connection, Transport)
plainHTTP TLSSettings{..} s bs0 = case onInsecure of
    AllowInsecure -> do
        conn' <- socketConnection s
        cachedRef <- I.newIORef bs0
        let conn'' = conn'
                { connRecv = recvPlain cachedRef (connRecv conn')
                }
        return (conn'', TCP)
    DenyInsecure lbs -> do
        -- Listening port 443 but TLS records do not arrive.
        -- We want to let the browser know that TLS is required.
        -- So, we use 426.
        --     http://tools.ietf.org/html/rfc2817#section-4.2
        --     https://tools.ietf.org/html/rfc7231#section-6.5.15
        -- FIXME: should we distinguish HTTP/1.1 and HTTP/2?
        --        In the case of HTTP/2, should we send
        --        GOAWAY + INADEQUATE_SECURITY?
        -- FIXME: Content-Length:
        -- FIXME: TLS/<version>
        sendAll s "HTTP/1.1 426 Upgrade Required\
        \r\nUpgrade: TLS/1.0, HTTP/1.1\
        \r\nConnection: Upgrade\
        \r\nContent-Type: text/plain\r\n\r\n"
        mapM_ (sendAll s) $ L.toChunks lbs
        sClose s
        throwIO InsecureConnectionDenied

----------------------------------------------------------------

-- | Modify the given receive function to first check the given @IORef@ for a
-- chunk of data. If present, takes the chunk of data from the @IORef@ and
-- empties out the @IORef@. Otherwise, calls the supplied receive function.
recvPlain :: I.IORef S.ByteString -> IO S.ByteString -> IO S.ByteString
recvPlain ref fallback = do
    bs <- I.readIORef ref
    if S.null bs
        then fallback
        else do
            I.writeIORef ref S.empty
            return bs

----------------------------------------------------------------

data WarpTLSException = InsecureConnectionDenied
    deriving (Show, Typeable)
instance Exception WarpTLSException


text:
module Pronto
  module Formatter
    def self.get(name)
      formatter = FORMATTERS[name.to_s] || TextFormatter
      formatter.new
    end

    def self.names
      FORMATTERS.keys
    end

    FORMATTERS = {
      'github' => GithubFormatter,
      'github_pr' => GithubPullRequestFormatter,
      'gitlab' => GitlabFormatter,
      'json' => JsonFormatter,
      'checkstyle' => CheckstyleFormatter,
      'text' => TextFormatter,
      'null' => NullFormatter
    }
  end
end


text:
'use strict';

angular.module('realizeChangeApp', [
  'ngCookies',
  'ngResource',
  'ngSanitize',
  'btford.socket-io',
  'ui.router',
  'ui.bootstrap',
  'angular-google-analytics',
  'leaflet-directive',
  'rzModule'
])
  .config(function ($stateProvider, $urlRouterProvider, $locationProvider, $httpProvider, AnalyticsProvider) {

    // Set analytics account
        AnalyticsProvider.setAccount('UA-66043134-1');
        // Track all routes (or not)
        AnalyticsProvider.trackPages(true);

        // Track all URL query params (default is false)
        AnalyticsProvider.trackUrlParams(true);

        // Optional set domain (Use 'none' for testing on localhost)
        AnalyticsProvider.setDomainName('https://frozen-basin-2150.herokuapp.com');

        // Use display features plugin
        AnalyticsProvider.useDisplayFeatures(true);

        // URL prefix (default is empty)
        // - for example: when an app doesn't run in the root directory
        AnalyticsProvider.trackPrefix('think-dream-tank');

        // Use analytics.js instead of ga.js
        AnalyticsProvider.useAnalytics(true);

        // Ignore first page view... helpful when using hashes and whenever your bounce rate looks obscenely low.
        AnalyticsProvider.ignoreFirstPageLoad(true);

        // Enabled eCommerce module for analytics.js (uses legacy ecommerce plugin)
        AnalyticsProvider.useECommerce(true, false);

        // Enabled enhanced eCommerce module for analytics.js (uses ec plugin instead of ecommerce plugin)
        // When enabled, legacy ecommerce plugin calls are not supported
        AnalyticsProvider.useECommerce(true, true);

        // Enable enhanced link attribution
        AnalyticsProvider.useEnhancedLinkAttribution(true);

        // Set custom cookie parameters for analytics.js
        AnalyticsProvider.setCookieConfig({
          cookieDomain: 'https://frozen-basin-2150.herokuapp.com',
          cookieName: 'Brian',
          cookieExpires: 20000
        });

        // Change page event name
        AnalyticsProvider.setPageEvent('$stateChangeSuccess');

        // Delay script tag creation
        // must manually call Analytics.createScriptTag(cookieConfig) or Analytics.createAnalyticsScriptTag(cookieConfig)
        AnalyticsProvider.delayScriptTag(true);

    $urlRouterProvider
      .otherwise('/');

    $locationProvider.html5Mode(true);
    $httpProvider.interceptors.push('authInterceptor');
    // $AnalyticsProvider.firstPageview(true);  Records pages that don't use $state or $route
    // $AnalyticsProvider.withAutoBase(true);  /* Records full path */
  })
  .factory('authInterceptor', function ($rootScope, $q, $cookieStore, $location) {
    return {
      // Add authorization token to headers
      request: function (config) {
        config.headers = config.headers || {};
        if ($cookieStore.get('token')) {
          config.headers.Authorization = 'Bearer ' + $cookieStore.get('token');
        }
        return config;
      },

      // Intercept 401s and redirect you to login
      responseError: function(response) {
        if(response.status === 401) {
          $location.path('/login');
          // remove any stale tokens
          $cookieStore.remove('token');
          return $q.reject(response);
        }
        else {
          return $q.reject(response);
        }
      }
    };
  })
  .run(function($rootScope, $location, Auth) {
    // Redirect to login if route requires auth and you're not logged in
    $rootScope.$on('$stateChangeStart', function (event, next) {
      // console.log('$stateChangeStart', event);
      // console.log('Event', event);
      // console.log('next', next);
      // console.log('next.authenticate', next.authenticate);
      $rootScope.isCollapsed = false;
      Auth.isLoggedInAsync(function(loggedIn) {
        // console.log('loggedIn',loggedIn);

        if (next.authenticate && !loggedIn) {
          $location.path('/login');
        }
      });
    });
  });


text:
                       Address Book

 Home

Address Book

    <?php
    echo form_open('/Books/addBookName', array('class' => "form-inline"));
    ?>
	<input type="text" id="addname" name="addname" class="form-control">
	<input type="submit" id="bttAdd" value="Add" />
</form>

		<?php
			if(isset($Books)){
				$template = array(
                'table_open' => '
'
            );
            $this->table->set_template($template);
            $this->table->set_heading('#', 'Book Name', 'Edit', 'Book Details');
            $count = 1;
            foreach ($Books as $value) {
                $cell1 = array('data' => $count);
                $cell2 = array('data' => $value['name']);
                $cell3 = array('data' => anchor("/Books/EditBookName/{$value['id']}", ''));
                $cell4 = array('data' => anchor("/Books/AddressBook/{$value['id']}", ''));

                $this->table->add_row($cell1, $cell2, $cell3, $cell4);
                $count++;
            }
            echo $this->table->generate();
			}

			elseif(isset($details)){
				$this->load->view('userlayout/bookdetails');
			}
		?>


text:
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using System;
using System.ComponentModel.Design;
using System.IO;
using System.Runtime.InteropServices;
using VSLangProj;

namespace Sawczyn.EFDesigner.EFModel
{
   // NOTE: This could go into the existing partial file if desired.  Might be more tidy and keep it all in one place.
   // Uncomment the following line if the extension is converted to an async package.
   //[ProvideAutoLoad(EFModelCommandSet.guidEFModelUIContextGuidString, PackageAutoLoadFlags.BackgroundLoad)]
   [ProvideUIContextRule(EFModelCommandSet.guidEFModelUIContextGuidString,
                         name : "EFModel auto load",
                         expression : "EFModel",
                         termNames : new[] {"EFModel"},
                         termValues : new[] {"HierSingleSelectionName:.efmodel$"})]
   internal sealed partial class EFModelPackage { }

   public static class CommandHelper
   {
      public static string EFModelerFileNameExtension = ".efmodel";
      private const string TextTransformationFileExtension = ".tt";

		public static string GetSingleFileSelectedPath()
		{
			if (!IsSingleProjectItemSelection(out IVsHierarchy hierarchy, out uint itemid)) return null;

			// Get the file path
         // ReSharper disable once SuspiciousTypeConversion.Global
         ((IVsProject)hierarchy).GetMkDocument(itemid, out string itemFullPath);
			return itemFullPath;
		}

		private static bool IsSingleProjectItemSelection(out IVsHierarchy hierarchy, out uint itemid)
		{
			hierarchy = null;
			itemid = VSConstants.VSITEMID_NIL;

         IVsMonitorSelection monitorSelection = Package.GetGlobalService(typeof(SVsShellMonitorSelection)) as IVsMonitorSelection;
         IVsSolution solution = Package.GetGlobalService(typeof(SVsSolution)) as IVsSolution;
			if (monitorSelection == null || solution == null)
			{
				return false;
			}

			IntPtr hierarchyPtr = IntPtr.Zero;
			IntPtr selectionContainerPtr = IntPtr.Zero;

			try
			{
				int hr = monitorSelection.GetCurrentSelection(out hierarchyPtr, out itemid, out IVsMultiItemSelect multiItemSelect, out selectionContainerPtr);

				if (ErrorHandler.Failed(hr) || hierarchyPtr == IntPtr.Zero || itemid == VSConstants.VSITEMID_NIL)
				{
					// there is no selection
					return false;
				}

				// multiple items are selected
				if (multiItemSelect != null) return false;

				// there is a hierarchy root node selected, thus it is not a single item inside a project

				if (itemid == VSConstants.VSITEMID_ROOT) return false;

				hierarchy = Marshal.GetObjectForIUnknown(hierarchyPtr) as IVsHierarchy;
				if (hierarchy == null) return false;

				if (ErrorHandler.Failed(solution.GetGuidOfProject(hierarchy, out Guid _)))
				{
					return false; // hierarchy is not a project inside the Solution if it does not have a ProjectID Guid
				}

				// if we got this far then there is a single project item selected
				return true;
			}
			finally
			{
				if (selectionContainerPtr != IntPtr.Zero)
				{
					Marshal.Release(selectionContainerPtr);
				}

				if (hierarchyPtr != IntPtr.Zero)
				{
					Marshal.Release(hierarchyPtr);
				}
			}
		}

		public static void VisibleAndEnabled(this MenuCommand menuCommand, bool visibleAndEnabled)
		{
			menuCommand.Visible = visibleAndEnabled;
			menuCommand.Enabled = visibleAndEnabled;
		}

		public static bool HasExtension(this FileInfo fileInfo, string extension)
		{
			return string.Compare(fileInfo.Extension, extension, StringComparison.OrdinalIgnoreCase) == 0;
		}

      // parameter must be EntityContainer file path
      public static void GenerateCode(string entityContainerFilepath)
      {
         DTE Dte = Package.GetGlobalService(typeof(DTE)) as DTE;
         DTE2 Dte2 = Package.GetGlobalService(typeof(SDTE)) as DTE2;

         ThreadHelper.ThrowIfNotOnUIThread();
         if (entityContainerFilepath == null)
         {
            throw new ArgumentNullException(nameof(entityContainerFilepath));
         }

         if (!entityContainerFilepath.EndsWith(EFModelerFileNameExtension))
         {
            throw new ArgumentOutOfRangeException(nameof(entityContainerFilepath));
         }

         ProjectItem modelProjectItem = Dte2.Solution.FindProjectItem(entityContainerFilepath);

         // Save file
         if (Guid.Parse(modelProjectItem.Kind) == VSConstants.GUID_ItemType_PhysicalFile && !modelProjectItem.Saved)
         {
            try
            {
               modelProjectItem.Save();
            }
            catch (Exception)
            {
               throw new Exception($"Save failed for {modelProjectItem.Name}");
            }
         }

         // TODO - clean up constant string
         string templateFilename = Path.ChangeExtension(entityContainerFilepath, TextTransformationFileExtension);

         ProjectItem templateProjectItem = Dte2.Solution.FindProjectItem(templateFilename);

         VSProjectItem templateVsProjectItem = templateProjectItem?.Object as VSProjectItem;

         if (templateVsProjectItem == null)
         {
            // TODO - place messages in output window or on PCML UI
            throw new Exception($"Tried to generate code but couldn't find {templateFilename} in the solution.");
         }

         try
         {
            Dte.StatusBar.Text = $"Generating code from {templateFilename}";
            templateVsProjectItem.RunCustomTool();
            Dte.StatusBar.Text = $"Finished generating code from {templateFilename}";
         }
         catch (COMException)
         {
            string message = $"Encountered an error generating code from {templateFilename}. Please transform T4 template manually.";
            Dte.StatusBar.Text = message;
            // TODO - place messages in output window or on PCML UI
            throw new Exception(message);
         }
      }
   }
}


text:
package com.jeta.locker.create;

import java.awt.BorderLayout;

import com.jeta.forms.components.panel.FormPanel;
import com.jeta.open.gui.framework.JETAPanel;
import static com.jeta.locker.create.CreateWizardConstants.*;

public class Wizard2 extends JETAPanel {

	public Wizard2() {
		setLayout( new BorderLayout() );
		add( new FormPanel( "wizard2.jfrm" ), BorderLayout.CENTER );
		getTextArea( ID_INFO_MESSAGE ).setBackground( getBackground() );
		setErrorMessage("");
	}

	public void setErrorMessage( String msg ) {
		setText( ID_ERROR, msg );
	}
}


text:
package com.asana.errors;

import com.google.api.client.http.HttpResponseException;

public class ServerError extends RetryableAsanaError {
    final public static String MESSAGE = "Server Error";
    final public static int STATUS = 500;

    public ServerError(HttpResponseException exception) {
        super(MESSAGE, STATUS, exception);
    }
}


text:
wiFetcher
=====================================

Web: [![Build Status](https://api.travis-ci.org/weso/wiFetcher.png?branch=web)](https://travis-ci.org/weso/wiFetcher)

MSExcel & Indaba Extractor for the World Wide Web Foundation's Web Index & ODB


text:
package org.jboss.pnc.common.json.moduleconfig;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
import org.jboss.pnc.common.json.AbstractModuleConfig;

@Getter
@Setter
public class TermdBuildDriverModuleConfig extends AbstractModuleConfig {

    public static final String MODULE_NAME = "termd-build-driver";

    private Integer internalCancelTimeoutMillis = 5000;
    private Long livenessProbeFrequencyMillis = 5000L;
    private Long livenessFailTimeoutMillis = 15000L;
    private boolean httpCallbackMode = true;

    private Integer httpRetryMaxAttempts = 10;
    /**
     * How long to wait before retry (calculated as: attempt x duration-in-millis).
     */
    private Long httpRetryWaitBeforeRetry = 500L;

    /**
     * Connect timeout in millis. See {@link java.net.URLConnection#setConnectTimeout(int)}
     */
    private int fileTransferConnectTimeout;

    /**
     * Connect timeout in millis. See {@link java.net.URLConnection#setReadTimeout(int)}
     */
    private int fileTransferReadTimeout = 60000;

    public TermdBuildDriverModuleConfig(
            @JsonProperty("internalCancelTimeoutMillis") Integer internalCancelTimeoutMillis,
            @JsonProperty("livenessProbeFrequencyMillis") Long livenessProbeFrequencyMillis,
            @JsonProperty("livenessFailTimeoutMillis") Long livenessFailTimeoutMillis,
            @JsonProperty("fileTransferConnectTimeout") Integer fileTransferConnectTimeout,
            @JsonProperty("fileTransferReadTimeout") Integer fileTransferReadTimeout,
            @JsonProperty("httpCallbackMode") Boolean httpCallbackMode,
            @JsonProperty("httpRetryMaxAttempts") Integer httpRetryMaxAttempts,
            @JsonProperty("httpRetryWaitBeforeRetry") Long httpRetryWaitBeforeRetry) {
        if (internalCancelTimeoutMillis != null) {
            this.internalCancelTimeoutMillis = internalCancelTimeoutMillis;
        }
        if (livenessProbeFrequencyMillis != null) {
            this.livenessProbeFrequencyMillis = livenessProbeFrequencyMillis;
        }
        if (livenessFailTimeoutMillis != null) {
            this.livenessFailTimeoutMillis = livenessFailTimeoutMillis;
        }
        if (fileTransferConnectTimeout != null) {
            this.fileTransferConnectTimeout = fileTransferConnectTimeout;
        }
        if (fileTransferReadTimeout != null) {
            this.fileTransferReadTimeout = fileTransferReadTimeout;
        }
        if (httpCallbackMode != null) {
            this.httpCallbackMode = httpCallbackMode;
        }
        if (httpRetryMaxAttempts != null) {
            this.httpRetryMaxAttempts = httpRetryMaxAttempts;
        }
        if (httpRetryWaitBeforeRetry != null) {
            this.httpRetryWaitBeforeRetry = httpRetryWaitBeforeRetry;
        }
    }

    @Override
    public String toString() {
        return "TermdBuildDriverModuleConfig {" + "internalCancelTimeoutMillis=" + internalCancelTimeoutMillis + "}";
    }
}


text:
"""Auto-generated file, do not edit by hand. 870 metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata

PHONE_METADATA_870 = PhoneMetadata(id='001', country_code=870, international_prefix=None,
    general_desc=PhoneNumberDesc(national_number_pattern='[35-7]\\d{8}', possible_number_pattern='\\d{9}', example_number='301234567'),
    fixed_line=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA', example_number='301234567'),
    mobile=PhoneNumberDesc(national_number_pattern='(?:[356]\\d|7[6-8])\\d{7}', possible_number_pattern='\\d{9}', example_number='301234567'),
    toll_free=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
    premium_rate=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
    shared_cost=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
    personal_number=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
    voip=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
    pager=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
    uan=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
    voicemail=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
    no_international_dialling=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
    number_format=[NumberFormat(pattern='(\\d{3})(\\d{3})(\\d{3})', format='\\1 \\2 \\3')])


text:
class MakeStateEventsPolymorphic < ActiveRecord::Migration
  def up
    rename_column :state_events, :order_id, :stateful_id
    add_column :state_events, :stateful_type, :string
    execute "UPDATE state_events SET stateful_type = 'Order'"
  end

  def down
    rename_column :state_events, :stateful_id, :order_id
    remove_column :state_events, :stateful_type
  end
end


text:
/**
 * Node.js API client for Apostle.io
 *
 * @package apostle
 * @author Andrew Sliwinski <andrewsliwinski@acm.org>
 */

/**
 * Dependencies
 */
var hyperquest = require('hyperquest');

/**
 * Sends the provided POST body to the apostle API using hyperquest.
 *
 * @param {string} API key
 * @param {object} Apostle message body
 *
 * @return {error}
 */
function send (key, container, callback) {
    var body = JSON.stringify(container);
    var req = hyperquest('http://deliver.apostle.io', {
        method: 'POST',
        headers: {
            'Authorization': 'Bearer ' + key,
            'Content-Type': 'application/json',
            'Content-Length': Buffer.byteLength(body)
        }
    });

    // Write body
    req.write(body);
    req.end();

    // Event handlers
    req.on('error', callback);
    req.on('response', function (res) {
        var buffer = '';

        res.on('data', function (chunk) {
            buffer += chunk.toString();
        });

        res.on('end', function () {
            callback(null, JSON.parse(buffer));
        });
    });
}

/**
 * Export
 */
module.exports = function (key) {

    /**
     * Delivers an email using the specified paramaters to apostle.
     *
     * @param {object}
     *      - email {string} Email address of the reciepient
     *      - template {string} Template ID
     *      - values {object, optional} Object containing any needed values
     *
     * @return {error}
     */
    return function (args, callback) {
        // Validate / parse arguments
        if (typeof args.email === 'undefined') return callback('Invalid');
        if (typeof args.template === 'undefined') return callback('Invalid');
        if (typeof args.values === 'undefined') args.values = {};

        // Build up post body
        var container       = { recipients: {} };
        var body            = {
            data: args.values,
            template_id: args.template
        };
        container.recipients[args.email] = body;

        // Deliver
        send(key, container, callback);
    };

};


text:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Amazing Cryptocurrency ICO</title>

    <title>Amazing Cryptocurrency ICO</title>

Amazing Cryptocurrency ICO

            Amazing Cryptocurrency is just amazing. Be part of the future.


text:
/* -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.
* File Name   : method_definition.js
* Created at  : 2019-09-07
* Updated at  : 2020-09-08
* Author      : jeefo
* Purpose     :
* Description :
* Reference   :
.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.*/
// ignore:start
"use strict";

/* globals*/
/* exported*/

// ignore:end

const {STRUCTURE} = require("../enums/precedence_enum");
const {
    method_definition,
    method_definition_async,
    method_definition_getter,
    method_definition_setter,
    method_definition_generator,
} = require("../enums/states_enum");
const {
    is_asterisk_token,
    is_delimiter_token,
    get_last_non_comment_node,
} = require("../../helpers");

const is_special_word = ({id, value}) =>
    id === "Identifier name" && ["get", "set", "async"].includes(value);

const parse_special_word = parser => {
};

module.exports = {
    id         : "Method definition",
    type       : "Method definitions",
    precedence : STRUCTURE,
    is         : (_, {current_state: s}) => s === method_definition,

    initialize (node, token, parser) {
        if (is_asterisk_token(token)) {
            parser.change_state("generator_method");
        } else {
            const property_name = get_last_non_comment_node(parser, true);
            if (is_special_word(property_name.expression)) {
                const next_token = parser.look_ahead(true);
                if (is_delimiter_token(next_token, '(')) {
                    parser.change_state("method");
                } else {
                    switch (property_name.expression.value) {
                        case "get" :
                            parser.change_state("getter_method");
                            break;
                        case "set" :
                            parser.change_state("setter_method");
                            break;
                        case "async" :
                            parser.change_state("async_method");
                            break;
                    }
                }
            } else {
                parser.change_state("method");
            }
        }

        const method = parser.generate_next_node();
        node.method  = method;
        node.start   = method.start;
        node.end     = method.end;
    },

    refine (node, property_name, parser) {
        if (property_name.id !== "Property name") {
            parser.throw_unexpected_refine(node, property_name);
        }

        let expression_name;
        if (is_delimiter_token(parser.next_token, '(')) {
            expression_name = "method";
        } else if (property_name.expression.id === "Identifier name") {
            switch (property_name.expression.value) {
                case "get" :
                    expression_name = "getter_method";
                    break;
                case "set" :
                    expression_name = "setter_method";
                    break;
                case "async" :
                    if (is_delimiter_token(parser.next_token, '(')) {
                        expression_name = "method";
                    } else {
                        expression_name = "async_method";
                    }
                    break;
                default:
                    expression_name = "method";
            }
        } else {
            expression_name = "method";
        }
        const expression = parser.refine(expression_name, property_name);

        node.expression = expression;
        node.start      = expression.start;
        node.end        = expression.end;
    }
};


text:
<!DocType html>

		<meta charset="UTF-8">
		<title>Vanilla.downBoy</title>
		<link rel="stylesheet" href="reset.css">
		<link rel="stylesheet" href="styles.css">

Vanilla.downBoy

Some Content

But not quite enough.

Try resizing the window, it will always stay at the bottom.

This is the footer. It should be absolutely positioned at the bottom of the page by downBoy unless it was already there.

You can download this from GitHub or get it delivered by jsDelivr (I highly recommend their multi-CDN file-combiner).


text:
package link.ideas.easya.ui.lesson_detail;

import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.ViewModel;

import link.ideas.easya.data.EasyARepository;
import link.ideas.easya.data.database.Course;
import link.ideas.easya.data.database.Lesson;

/**
 * Created by Eman on 1/15/2018.
 */

public class LessonDetailViewModel extends ViewModel {
    private final EasyARepository mRepository;
    private final LiveData<Lesson> mLesson;
    private LiveData<Course> mCourse;
    private final int lessonId;

    public LessonDetailViewModel(EasyARepository repository, int lessonId) {
        mRepository = repository;
        mLesson = mRepository.getUserLesson(lessonId);
        this.lessonId = lessonId;

    }

    public LiveData<Lesson> getUserLesson() {
        return mLesson;
    }

    public LiveData<Course> getCourse(int courseId) {
        mCourse = mRepository.getUserCourse(courseId);
        return mCourse;
    }

    public void updateFirebaseId(String courseFirebaseId) {
        mRepository.updateFirebaseId(lessonId, courseFirebaseId);
    }

    public void updateFirebaseIdL(String lessonFirebaseId) {
        mRepository.updateFirebaseIdL(lessonId, lessonFirebaseId);
    }

    public void updateFavorite(String favoriteLesson) {
        mRepository.updateFavorite(lessonId, favoriteLesson);
    }

}


text:
SSL Pool Example
----------------
In order to use the pool module you first need to install the python library, `amqpstorm-pool`.
::

    pip install amqpstorm[pool]

.. literalinclude:: ../../examples/pool/ssl_pool_example.py


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 318348 $ -->

<refentry xml:id="function.eio-poll" xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink">
 <refnamediv>
  <refname>eio_poll</refname>
  <refpurpose>Can be to be called whenever there are pending requests that need finishing.</refpurpose>
 </refnamediv>

 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <type>int</type><methodname>eio_poll</methodname>
   <void />
  </methodsynopsis>
  <para>
  <function>eio_poll</function> can be used to implement special event loop.
  For this <function>eio_nreqs</function> could be used to test if there are
  unprocessed requests.
  </para>

  <note><para>Applicable only when implementing userspace event loop.</para></note>

 </refsect1>

 <refsect1 role="parameters">
  &reftitle.parameters;
  &no.function.parameters;
 </refsect1>

 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
  If any request invocation returns a non-zero value, returns that value.
  Otherwise, it returns <constant>0</constant>.
  </para>
 </refsect1>

 <refsect1 role="examples">
  &reftitle.examples;
  <example>
   <title><function>eio_poll</function> example</title>
   <programlisting role="php">
<![CDATA[
<?php
function res_cb($data, $result) {
    var_dump($data);
    var_dump($result);
}

eio_nop(EIO_PRI_DEFAULT, "res_cb", "1");
eio_nop(EIO_PRI_DEFAULT, "res_cb", "2");
eio_nop(EIO_PRI_DEFAULT, "res_cb", "3");

while (eio_nreqs()) {
    // Some specific IPC or so
    eio_poll();
}
?>
]]>
   </programlisting>
   &example.outputs.similar;
   <screen>
<![CDATA[
string(1) "1"
int(0)
string(1) "3"
int(0)
string(1) "2"
int(0)
]]>
   </screen>
  </example>
 </refsect1>

 <refsect1 role="seealso">
  &reftitle.seealso;
  <simplelist>
   <member>eio_nreqs</member>
  </simplelist>
 </refsect1>

</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
<?php

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');

// Load the view framework
if(!class_exists('VmViewAdmin'))require(VMPATH_ADMIN.DS.'helpers'.DS.'vmviewadmin.php');

/**
 * HTML View class for maintaining the list of shipment
 *
 * @package	VirtueMart
 * @subpackage Shipment
 * @author RickG
 */
class VirtuemartViewShipmentmethod extends VmViewAdmin {

	function display($tpl = null) {

		// Load the helper(s)
		$this->addHelperPath(VMPATH_ADMIN.DS.'helpers');

		if(!class_exists('vmPSPlugin')) require(VMPATH_PLUGINLIBS.DS.'vmpsplugin.php');

		if (!class_exists('VmHTML'))
			require(VMPATH_ADMIN . DS . 'helpers' . DS . 'html.php');

		$model = VmModel::getModel();

		$layoutName = vRequest::getCmd('layout', 'default');
		$this->SetViewTitle();

		$layoutName = vRequest::getCmd('layout', 'default');
		if ($layoutName == 'edit') {
			VmConfig::loadJLang('plg_vmpsplugin', false);

			JForm::addFieldPath(VMPATH_ADMIN . DS . 'fields');

			$shipment = $model->getShipment();

			// Get the payment XML.
			$formFile	= vRequest::filterPath( VMPATH_ROOT .DS. 'plugins' .DS. 'vmshipment' .DS. $shipment->shipment_element .DS. $shipment->shipment_element . '.xml');
			if (file_exists($formFile)){
				$shipment->form = JForm::getInstance($shipment->shipment_element, $formFile, array(),false, '//vmconfig | //config[not(//vmconfig)]');
				$shipment->params = new stdClass();
				$varsToPush = vmPlugin::getVarsToPushFromForm($shipment->form);
				VmTable::bindParameterableToSubField($shipment,$varsToPush);
				$shipment->form->bind($shipment->getProperties());

			} else {
				$shipment->form = null;
			}
			if (!class_exists('VmImage'))
				require(VMPATH_ADMIN . DS . 'helpers' . DS . 'image.php');

			 if(!class_exists('VirtueMartModelVendor')) require(VMPATH_ADMIN.DS.'models'.DS.'vendor.php');

			if($this->showVendors()){
					$vendorList= ShopFunctions::renderVendorList($shipment->virtuemart_vendor_id);
					$this->assignRef('vendorList', $vendorList);
			 }

			$this->pluginList = self::renderInstalledShipmentPlugins($shipment->shipment_jplugin_id);
			$this->assignRef('shipment', $shipment);
			$this->shopperGroupList = ShopFunctions::renderShopperGroupList($shipment->virtuemart_shoppergroup_ids,true);

			$currency_model = VmModel::getModel ('currency');
			$currencies = $currency_model->getCurrencies ();

			$currency = VirtueMartModelVendor::getVendorCurrency ($shipment->virtuemart_vendor_id);
			$this->assignRef('vendor_currency', $currency->currency_symbol);

			if(empty($shipment->currency_id)) $shipment->currency_id = $currency->virtuemart_currency_id;
			$attrs['class'] = 'vm-chzn-select vm-drop';
			$this->currencyList = JHtml::_ ('select.genericlist', $currencies, 'currency_id', $attrs, 'virtuemart_currency_id', 'currency_name', $shipment->currency_id);

			$this->addStandardEditViewCommands($shipment->virtuemart_shipmentmethod_id);

		} else {
			JToolBarHelper::custom('cloneshipment', 'copy', 'copy', vmText::_('COM_VIRTUEMART_SHIPMENT_CLONE'), true);

			$this->addStandardDefaultViewCommands();
			$this->addStandardDefaultViewLists($model);

			$this->shipments = $model->getShipments();
			VmConfig::loadJLang('com_virtuemart_shoppers',TRUE);

			foreach ($this->shipments as &$data){
				// Write the first 5 shoppergroups in the list
				$data->shipmentShoppersList = shopfunctions::renderGuiList($data->virtuemart_shoppergroup_ids,'shoppergroups','shopper_group_name','shopper');
			}

			$this->pagination = $model->getPagination();

		}

		parent::display($tpl);
	}
	function getParams($raw) {

		if (!empty($raw)) {
			$params = explode('|', substr($raw, 0,-1));
			foreach($params as $param){
				$item = explode('=',$param);
				if(!empty($item[1])){
					$pair[$item[0]] = str_replace('"','', $item[1]);
				} else {
					$pair[$item[0]] ='';
				}

			}
		}
		return $pair;
	}

	function renderInstalledShipmentPlugins($selected)
	{
		$db = JFactory::getDBO();

		$table = '#__extensions';
		$enable = 'enabled';
		$ext_id = 'extension_id';

		$q = 'SELECT * FROM `'.$table.'` WHERE `folder` = "vmshipment" AND `state`="0" ORDER BY `ordering`,`name` ASC';
		$db->setQuery($q);
		$result = $db->loadAssocList($ext_id);
		if(empty($result)){
			$app = JFactory::getApplication();
			$app -> enqueueMessage(vmText::_('COM_VIRTUEMART_NO_SHIPMENT_PLUGINS_INSTALLED'));
		}

		foreach ($result as &$sh) {
			$sh['name'] = vmText::_($sh['name']);
		}
		$attribs='style= "width: 300px;"';
		return JHtml::_('select.genericlist', $result, 'shipment_jplugin_id', $attribs, $ext_id, 'name', $selected);
	}

}
// pure php no closing tag


text:
<!--
Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.

This code is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License version 2 only, as
published by the Free Software Foundation.  Oracle designates this
particular file as subject to the "Classpath" exception as provided
by Oracle in the LICENSE file that accompanied this code.

This code is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
version 2 for more details (a copy is included in the LICENSE file that
accompanied this code).

You should have received a copy of the GNU General Public License version
2 along with this work; if not, write to the Free Software Foundation,
Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.

Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
or visit www.oracle.com if you need additional information or have any
questions.
-->

<project name="benchmark-ant">
    <description>
        Ant build file for building self-contained JMH Jar.
        This script is intended to be imported from a top-level script.
    </description>

    <!--
        When this file is imported the basedir property is ignored,
        so this hack is required to retrieve it.
    -->
    <dirname property="benchmark-ant.basedir" file="${ant.file.benchmark-ant}"/>

    <property name="jmh-core.jar" location="${benchmark-ant.basedir}/jmh-core-0.9.jar"/>
    <property name="jmh-generator-annprocess.jar" location="${benchmark-ant.basedir}/jmh-generator-annprocess-0.9.jar"/>

    <property name="joptsimple.jar" location="${benchmark-ant.basedir}/jopt-simple-4.6.jar"/>
    <property name="commonsmath.jar" location="${benchmark-ant.basedir}/commons-math3-3.3.jar"/>

    <!-- private target to be overriden in importing script -->
    <target name="-init-benchmark-properties">

        <echo>The following properties must be defined:
        bench.src_dirs  : collon or semi-collon separated list of directories containing the source files
        bench.build_dir : path to the location of the compiled files
        bench.jar_file  : path to the resulting self-contained executable Jar
        </echo>
        <fail message="Must define benchmark test properties.">
            <condition>
                <not>
                    <and>
                        <isset property="bench.src_dirs"/>
                        <isset property="bench.build_dir"/>
                        <isset property="bench.jar_file"/>
                    </and>
                </not>
            </condition>
        </fail>

    </target>

    <!--
        The workflow is as follows:
          - Compile the benchmarks with JMH and JMH Annotation processor in classpath.
              * Annotation processors will run and generate synthetic code.
              * Annotation processors will create the list of discovered microbenchmarks.
          - Pack the classes, generated code, microbenchmark lists in a JAR
              * Bring the dependencies along in the JAR; Annotation processor is not
                required in final JAR
              * (You might be able to run JMH without the self-contained JAR,
                take note of the META-INF/* files in that case)
              * Filter out META-INF/services/ to disable JMH processors for the future
    -->

    <target name="-compile-with-jmh">

        <delete dir="${bench.build_dir}"/>
        <mkdir dir="${bench.build_dir}"/>

        <javac srcdir="${bench.src_dirs}" destdir="${bench.build_dir}"
               classpath=".:${jmh-core.jar}:${jmh-generator-annprocess.jar}:${jcommander.jar_file}"
               debug="${javac-debug}"
               debuglevel="${javac-debuglevel}"
               includeAntRuntime="false">
            <compilerarg value="${javac-args}" />
        </javac>

        <subant target="-benchmark-post-compile" buildpath="." failonerror="true"/>

    </target>

    <!-- private target to be overriden in importing script if necessary-->
    <target name="-benchmark-post-compile"/>

    <!-- private target to be called by importing script -->
    <target name="-benchmark-jar" depends="-init-benchmark-properties,-compile-with-jmh">

        <delete file="${bench.jar_file}"/>
        <jar jarfile="${bench.jar_file}" basedir="${bench.build_dir}">
            <manifest>
                <attribute name="Main-Class" value="org.openjdk.jmh.Main"/>
            </manifest>

            <zipfileset src="${jmh-core.jar}" excludes="**/META-INF/services/**" />
            <zipfileset src="${joptsimple.jar}" />
            <zipfileset src="${commonsmath.jar}" />
            <zipfileset src="${jcommander.jar_file}" />
        </jar>

    </target>

</project>


text:
import commonPrefix from 'common-prefix'
import randomColor from 'randomcolor'

import vb from 'viewbox'
import xid from '@tracespace/xml-id'
import {Options as GerberToSvgOptions} from 'gerber-to-svg'

// @ts-ignore: cannot figure out how to type this without breaking the import
import clone from 'gerber-to-svg/clone'
// @ts-ignore: cannot figure out how to type this without breaking the import
import render from 'gerber-to-svg/render'

import {Stackup, InputLayer, Options as StackupOptions} from 'pcb-stackup'

import {
  Optional,
  BoardRender,
  LayerRender,
  LayersMap,
  Board,
  Layer,
  LayerOptions,
  BoardUpdate,
} from '../types'

import {svgToDataUri} from '../image'
import {TYPE_DRILL} from '../layers'
import {readFiles, fetchZipFile, writeFiles, FileStream} from './files'
import {baseName} from './util'

export type InputLayerFromFile = InputLayer & {gerber: FileStream}

export type StackupFromFiles = Stackup<string, InputLayerFromFile>

const DEFAULT_BOARD_NAME = 'untitled board'
const RANDOM_ID_LENGTH = 20

const SCALE_MM_TO_IN = 1 / 25.4
const SCALE_IN_TO_MM = 25.4

// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
const getPcbStackup = () => import('pcb-stackup').then(m => m.default)

export async function filesToStackups(
  files: Array<File>
): Promise<[StackupFromFiles, StackupFromFiles]> {
  return readFiles(files).then(fileStreamsToStackups)
}

export async function urlToStackups(
  url: string
): Promise<[StackupFromFiles, StackupFromFiles]> {
  return fetchZipFile(url).then(fileStreamsToStackups)
}

export async function boardToStackups(
  board: Board
): Promise<[Stackup, Stackup]> {
  const stackupLayers = Object.values(board.layers).map(ly => ({
    filename: ly.filename,
    gerber: ly.source,
    side: ly.side,
    type: ly.type,
    options: layerToGerberToSvgOptions(ly, board),
  }))

  return getPcbStackup().then(pcbStackup => {
    const options = boardToPcbStackupOptions(board)
    const selfContainedStackup = pcbStackup(stackupLayers, options)
    const sharedStackup = selfContainedStackup.then(stackup =>
      pcbStackup(
        stackup.layers.map(ly => ({...ly, externalId: ly.options.id})),
        options
      )
    )

    return Promise.all([selfContainedStackup, sharedStackup])
  })
}

export async function stackupToZipBlob(stackup: Stackup): Promise<Blob> {
  const files = stackup.layers
    .filter(layer => layer.converter.layer.length > 0)
    .reduce(
      (result, layer) =>
        result.concat({
          name: `${layer.filename}.svg`,
          contents: render(layer.converter, layer.options.id),
        }),
      [
        {name: 'top.svg', contents: stackup.top.svg},
        {name: 'bottom.svg', contents: stackup.bottom.svg},
      ]
    )

  return writeFiles(files)
}

export function stackupToBoard(stackup: StackupFromFiles): Board {
  const layers = stackup.layers.reduce<LayersMap>((result, ly) => {
    const {name, digest, contents} = ly.gerber

    if (digest && contents) {
      result[ly.converter.id] = {
        id: ly.converter.id,
        filename: name,
        sourceId: digest,
        source: contents,
        side: ly.side,
        type: ly.type,
        color: randomColor({luminosity: 'dark'}) as string,
        initialOptions: {
          coordinateFormat: ly.converter.parser.format.places,
          zeroSuppression: ly.converter.parser.format.zero,
          units: ly.converter.units,
        },
      }
    }
    return result
  }, {})

  const board = {
    layers,
    layerIds: Object.keys(layers),
    id: stackup.id,
    name: stackupToBoardName(stackup),
    options: stackupToBoardOptions(stackup),
    gerberOptions: {},
    drillOptions: {},
    thumbnail: svgToDataUri(stackup.top.svg),
  }

  return board
}

export function updateBoard(board: Board, update: BoardUpdate): Board {
  const {id, name, options, gerberOptions, drillOptions, layers} = update

  const nextBoard = {
    ...board,
    id: id || board.id,
    name: name || board.name,
    options: options || board.options,
    gerberOptions: gerberOptions || board.gerberOptions,
    drillOptions: drillOptions || board.drillOptions,
  }

  if (layers) {
    nextBoard.layers = Object.keys(board.layers).reduce(
      (result, id) => ({...result, [id]: {...board.layers[id], ...layers[id]}}),
      {}
    )
  }

  return nextBoard
}

export function updateBoardThumbnail(board: Board, stackup: Stackup): Board {
  return {
    ...board,
    thumbnail: svgToDataUri(stackup.top.svg),
  }
}

export function stackupToBoardRender(
  stackup: Stackup,
  board: Board
): BoardRender {
  return {
    id: board.id,
    name: board.name,
    options: board.options,
    gerberOptions: board.gerberOptions,
    drillOptions: board.drillOptions,
    viewBox: vb.add(stackup.top.viewBox, stackup.bottom.viewBox),
    top: stackup.top.svg,
    bottom: stackup.bottom.svg,
    layers: stackupToLayerRenders(stackup, board),
    sourceIds: board.layerIds.map(id => board.layers[id].sourceId),
    sourceUrl: board.sourceUrl || null,
  }
}

async function fileStreamsToStackups(
  fileStreams: Array<FileStream>
): Promise<[StackupFromFiles, StackupFromFiles]> {
  const id = xid.random(RANDOM_ID_LENGTH)
  const layers = fileStreams.map(fileStreamToInputLayer)
  const options = {id, attributes: {class: 'w-100 h-100'}}

  return getPcbStackup().then(pcbStackup => {
    const selfContainedStackup = pcbStackup(layers, options)
    const sharedStackup = selfContainedStackup.then(stackup =>
      pcbStackup(
        stackup.layers.map(ly => ({...ly, externalId: ly.options.id})),
        options
      )
    )

    return Promise.all([selfContainedStackup, sharedStackup])
  })
}

function fileStreamToInputLayer(gerber: FileStream): InputLayerFromFile {
  const id = xid.random(RANDOM_ID_LENGTH)

  return {gerber, filename: gerber.name, options: {id}}
}

function stackupToBoardName(stackup: Stackup): string {
  const boardName =
    commonPrefix(
      stackup.layers
        .filter(ly => ly.converter.layer.length > 0)
        .map(ly => baseName(ly.filename || '', true))
    ) || DEFAULT_BOARD_NAME

  // strip trailing dot if present
  return boardName.endsWith('.') ? boardName.slice(0, -1) : boardName
}

function stackupToBoardOptions(stackup: Stackup): Board['options'] {
  return {
    useOutline: stackup.useOutline,
    outlineGapFill: stackup.outlineGapFill || 0.00011,
    color: stackup.color,
  }
}

function boardToPcbStackupOptions(board: Board): StackupOptions {
  return {
    id: board.id,
    attributes: {class: 'w-100 h-100'},
    outlineGapFill: board.options.outlineGapFill,
    useOutline: board.options.useOutline,
    color: board.options.color,
  }
}

function stackupToLayerRenders(
  stackup: Stackup,
  board: Board
): Array<LayerRender> {
  const stackupUnits = stackupToUnits(stackup)

  return stackup.layers.reduce<Array<LayerRender>>((result, stackupLayer) => {
    const id = stackupLayer.options.id
    const units = stackupLayer.converter.units
    const layer: Layer | undefined = board.layers[id]
    let scale = 1

    if (units === 'mm' && stackupUnits === 'in') {
      scale = SCALE_MM_TO_IN
    } else if (units === 'in' && stackupUnits === 'mm') {
      scale = SCALE_IN_TO_MM
    }

    if (layer) {
      result.push({
        id: layer.id,
        side: layer.side,
        type: layer.type,
        color: layer.color,
        filename: layer.filename,
        converter: clone(stackupLayer.converter),
        initialOptions: layer.initialOptions,
        scale,
      })
    }

    return result
  }, [])
}

function stackupToUnits(stackup: Stackup): 'mm' | 'in' {
  const count = stackup.layers.reduce(
    (result, ly) => {
      if (ly.converter.units === 'mm') return {...result, mm: result.mm + 1}
      if (ly.converter.units === 'in') return {...result, in: result.in + 1}
      return result
    },
    {mm: 0, in: 0}
  )

  return count.in > count.mm ? 'in' : 'mm'
}

function layerToGerberToSvgOptions(
  layer: Layer,
  board: Board
): GerberToSvgOptions {
  let boardLevelOptions: Optional<LayerOptions> = {}

  if (layer.type === TYPE_DRILL) {
    boardLevelOptions = board.drillOptions
  } else if (layer.type) {
    boardLevelOptions = board.gerberOptions
  }

  return {
    id: layer.id,
    places: boardLevelOptions.coordinateFormat,
    zero: boardLevelOptions.zeroSuppression,
    units: boardLevelOptions.units,
  }
}


text:
<?php

namespace Google\Service\CloudDataplex;

class GoogleCloudDataplexV1DataQualityRule extends \Google\Model
{
  /**
   * @var string
   */
  public $column;
  /**
   * @var string
   */
  public $dimension;
  /**
   * @var bool
   */
  public $ignoreNull;
  protected $nonNullExpectationType = GoogleCloudDataplexV1DataQualityRuleNonNullExpectation::class;
  protected $nonNullExpectationDataType = '';
  protected $rangeExpectationType = GoogleCloudDataplexV1DataQualityRuleRangeExpectation::class;
  protected $rangeExpectationDataType = '';
  protected $regexExpectationType = GoogleCloudDataplexV1DataQualityRuleRegexExpectation::class;
  protected $regexExpectationDataType = '';
  protected $rowConditionExpectationType = GoogleCloudDataplexV1DataQualityRuleRowConditionExpectation::class;
  protected $rowConditionExpectationDataType = '';
  protected $setExpectationType = GoogleCloudDataplexV1DataQualityRuleSetExpectation::class;
  protected $setExpectationDataType = '';
  protected $statisticRangeExpectationType = GoogleCloudDataplexV1DataQualityRuleStatisticRangeExpectation::class;
  protected $statisticRangeExpectationDataType = '';
  protected $tableConditionExpectationType = GoogleCloudDataplexV1DataQualityRuleTableConditionExpectation::class;
  protected $tableConditionExpectationDataType = '';
  public $threshold;
  protected $uniquenessExpectationType = GoogleCloudDataplexV1DataQualityRuleUniquenessExpectation::class;
  protected $uniquenessExpectationDataType = '';

  /**
   * @param string
   */
  public function setColumn($column)
  {
    $this->column = $column;
  }
  /**
   * @return string
   */
  public function getColumn()
  {
    return $this->column;
  }
  /**
   * @param string
   */
  public function setDimension($dimension)
  {
    $this->dimension = $dimension;
  }
  /**
   * @return string
   */
  public function getDimension()
  {
    return $this->dimension;
  }
  /**
   * @param bool
   */
  public function setIgnoreNull($ignoreNull)
  {
    $this->ignoreNull = $ignoreNull;
  }
  /**
   * @return bool
   */
  public function getIgnoreNull()
  {
    return $this->ignoreNull;
  }
  /**
   * @param GoogleCloudDataplexV1DataQualityRuleNonNullExpectation
   */
  public function setNonNullExpectation(GoogleCloudDataplexV1DataQualityRuleNonNullExpectation $nonNullExpectation)
  {
    $this->nonNullExpectation = $nonNullExpectation;
  }
  /**
   * @return GoogleCloudDataplexV1DataQualityRuleNonNullExpectation
   */
  public function getNonNullExpectation()
  {
    return $this->nonNullExpectation;
  }
  /**
   * @param GoogleCloudDataplexV1DataQualityRuleRangeExpectation
   */
  public function setRangeExpectation(GoogleCloudDataplexV1DataQualityRuleRangeExpectation $rangeExpectation)
  {
    $this->rangeExpectation = $rangeExpectation;
  }
  /**
   * @return GoogleCloudDataplexV1DataQualityRuleRangeExpectation
   */
  public function getRangeExpectation()
  {
    return $this->rangeExpectation;
  }
  /**
   * @param GoogleCloudDataplexV1DataQualityRuleRegexExpectation
   */
  public function setRegexExpectation(GoogleCloudDataplexV1DataQualityRuleRegexExpectation $regexExpectation)
  {
    $this->regexExpectation = $regexExpectation;
  }
  /**
   * @return GoogleCloudDataplexV1DataQualityRuleRegexExpectation
   */
  public function getRegexExpectation()
  {
    return $this->regexExpectation;
  }
  /**
   * @param GoogleCloudDataplexV1DataQualityRuleRowConditionExpectation
   */
  public function setRowConditionExpectation(GoogleCloudDataplexV1DataQualityRuleRowConditionExpectation $rowConditionExpectation)
  {
    $this->rowConditionExpectation = $rowConditionExpectation;
  }
  /**
   * @return GoogleCloudDataplexV1DataQualityRuleRowConditionExpectation
   */
  public function getRowConditionExpectation()
  {
    return $this->rowConditionExpectation;
  }
  /**
   * @param GoogleCloudDataplexV1DataQualityRuleSetExpectation
   */
  public function setSetExpectation(GoogleCloudDataplexV1DataQualityRuleSetExpectation $setExpectation)
  {
    $this->setExpectation = $setExpectation;
  }
  /**
   * @return GoogleCloudDataplexV1DataQualityRuleSetExpectation
   */
  public function getSetExpectation()
  {
    return $this->setExpectation;
  }
  /**
   * @param GoogleCloudDataplexV1DataQualityRuleStatisticRangeExpectation
   */
  public function setStatisticRangeExpectation(GoogleCloudDataplexV1DataQualityRuleStatisticRangeExpectation $statisticRangeExpectation)
  {
    $this->statisticRangeExpectation = $statisticRangeExpectation;
  }
  /**
   * @return GoogleCloudDataplexV1DataQualityRuleStatisticRangeExpectation
   */
  public function getStatisticRangeExpectation()
  {
    return $this->statisticRangeExpectation;
  }
  /**
   * @param GoogleCloudDataplexV1DataQualityRuleTableConditionExpectation
   */
  public function setTableConditionExpectation(GoogleCloudDataplexV1DataQualityRuleTableConditionExpectation $tableConditionExpectation)
  {
    $this->tableConditionExpectation = $tableConditionExpectation;
  }
  /**
   * @return GoogleCloudDataplexV1DataQualityRuleTableConditionExpectation
   */
  public function getTableConditionExpectation()
  {
    return $this->tableConditionExpectation;
  }
  public function setThreshold($threshold)
  {
    $this->threshold = $threshold;
  }
  public function getThreshold()
  {
    return $this->threshold;
  }
  /**
   * @param GoogleCloudDataplexV1DataQualityRuleUniquenessExpectation
   */
  public function setUniquenessExpectation(GoogleCloudDataplexV1DataQualityRuleUniquenessExpectation $uniquenessExpectation)
  {
    $this->uniquenessExpectation = $uniquenessExpectation;
  }
  /**
   * @return GoogleCloudDataplexV1DataQualityRuleUniquenessExpectation
   */
  public function getUniquenessExpectation()
  {
    return $this->uniquenessExpectation;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(GoogleCloudDataplexV1DataQualityRule::class, 'Google_Service_CloudDataplex_GoogleCloudDataplexV1DataQualityRule');


text:
public class Node {
	public Node next;
	public int value;
	public Node(int value){
		this.value = value;
		this.next = null;
	}
	public void printList(){
		Node head = this;
		while(head != null){
			System.out.print(head.value+" ");
			head = head.next;
		}
		System.out.println();
	}
	public Node addToTail(int d){
		Node n = new Node(d);
		Node head = this;
		while(head.next != null){
			head = head.next;
		}
		head.next = n;
		return n;
	}
	public Node deleteNode(int d){
		if(value == d){
			return next;
		}
		if(next == null)
			return null;
		Node head = next;
		Node tail = this;
		while(head != null){
			if(head.value == d){
				tail.next = head.next;
				return head;
			}
			tail = head;
			head = head.next;
		}
		return this;
	}
}


text:
using System;
using TrueCraft.API.Logic;
using TrueCraft.API;
using TrueCraft.Core.Logic.Items;
using TrueCraft.API.World;
using TrueCraft.API.Networking;
using System.Linq;

namespace TrueCraft.Core.Logic.Blocks
{
    public class TorchBlock : BlockProvider, ICraftingRecipe
    {
        public enum TorchDirection
        {
            East = 0x01,
            West = 0x02,
            South = 0x03,
            North = 0x04,
            Ground = 0x05
        }

        public static readonly byte BlockID = 0x32;

        public override byte ID { get { return 0x32; } }

        public override double BlastResistance { get { return 0; } }

        public override double Hardness { get { return 0; } }

        public override byte Luminance { get { return 13; } }

        public override bool Opaque { get { return false; } }

        public override bool RenderOpaque { get { return true; } }

        public override string DisplayName { get { return "Torch"; } }

        public override SoundEffectClass SoundEffect
        {
            get
            {
                return SoundEffectClass.Wood;
            }
        }

        public override BoundingBox? BoundingBox { get { return null; } }

        public override BoundingBox? InteractiveBoundingBox
        {
            get
            {
                return new BoundingBox(new Vector3(4 / 16.0, 0, 4 / 16.0), new Vector3(12 / 16.0, 7.0 / 16.0, 12 / 16.0));
            }
        }

        public override void BlockPlaced(BlockDescriptor descriptor, BlockFace face, IWorld world, IRemoteClient user)
        {
            TorchDirection[] preferredDirections =
            {
                TorchDirection.West, TorchDirection.East,
                TorchDirection.North, TorchDirection.South,
                TorchDirection.Ground
            };
            TorchDirection direction;
            switch (face)
            {
                case BlockFace.PositiveZ:
                    direction = TorchDirection.South;
                    break;
                case BlockFace.NegativeZ:
                    direction = TorchDirection.North;
                    break;
                case BlockFace.PositiveX:
                    direction = TorchDirection.East;
                    break;
                case BlockFace.NegativeX:
                    direction = TorchDirection.West;
                    break;
                default:
                    direction = TorchDirection.Ground;
                    break;
            }
            int i = 0;
            descriptor.Metadata = (byte)direction;
            while (!IsSupported(descriptor, user.Server, world) && i < preferredDirections.Length)
            {
                direction = preferredDirections[i++];
                descriptor.Metadata = (byte)direction;
            }
            world.SetBlockData(descriptor.Coordinates, descriptor);
        }

        public override void ItemUsedOnBlock(Coordinates3D coordinates, ItemStack item, BlockFace face, IWorld world, IRemoteClient user)
        {
            coordinates += MathHelper.BlockFaceToCoordinates(face);
            var old = world.GetBlockData(coordinates);
            byte[] overwritable =
            {
                AirBlock.BlockID,
                WaterBlock.BlockID,
                StationaryWaterBlock.BlockID,
                LavaBlock.BlockID,
                StationaryLavaBlock.BlockID
            };
            if (overwritable.Any(b => b == old.ID))
            {
                var data = world.GetBlockData(coordinates);
                data.ID = ID;
                data.Metadata = (byte)item.Metadata;

                BlockPlaced(data, face, world, user);

                if (!IsSupported(world.GetBlockData(coordinates), user.Server, world))
                    world.SetBlockData(coordinates, old);
                else
                {
                    item.Count--;
                    user.Inventory[user.SelectedSlot] = item;
                }
            }
        }

        public override Coordinates3D GetSupportDirection(BlockDescriptor descriptor)
        {
            switch ((TorchDirection)descriptor.Metadata)
            {
                case TorchDirection.Ground:
                    return Coordinates3D.Down;
                case TorchDirection.East:
                    return Coordinates3D.West;
                case TorchDirection.West:
                    return Coordinates3D.East;
                case TorchDirection.North:
                    return Coordinates3D.South;
                case TorchDirection.South:
                    return Coordinates3D.North;
            }
            return Coordinates3D.Zero;
        }

        public override Tuple<int, int> GetTextureMap(byte metadata)
        {
            return new Tuple<int, int>(0, 5);
        }

        public virtual ItemStack[,] Pattern
        {
            get
            {
                return new[,]
                {
                    { new ItemStack(CoalItem.ItemID) },
                    { new ItemStack(StickItem.ItemID) }
                };
            }
        }

        public virtual ItemStack Output
        {
            get
            {
                return new ItemStack(TorchBlock.BlockID, 4);
            }
        }

        public virtual bool SignificantMetadata
        {
            get
            {
                return false;
            }
        }
    }
}


text:
package cn.edu.hhu.reg.activity;

import java.util.ArrayList;

import cn.edu.hhu.reg.R;
import cn.edu.hhu.reg.adapter.DepartmentListViewAdapter;
import cn.edu.hhu.reg.api.ApiClient;
import cn.edu.hhu.reg.api.ResponseUtils;
import cn.edu.hhu.reg.api.SimpleResponse;
import cn.edu.hhu.reg.common.CustomProgressDialog;
import cn.edu.hhu.reg.common.ToastShow;
import cn.edu.hhu.reg.common.http.HttpException;
import cn.edu.hhu.reg.common.http.async.HttpAsync;
import cn.edu.hhu.reg.entity.Department;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

public class DepartmentListActivity extends BaseActivity {

	ListView lv;
	CustomProgressDialog progressDialog ;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_listview);
		UiHelper.goBack(this);
		((TextView)findViewById(R.id.listview_tv_title)).setText("科室列表");
		lv = (ListView) findViewById(R.id.listview_lv);
		getDepartmentList();
		lv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				DepartmentListViewAdapter adapter  = (DepartmentListViewAdapter)parent.getAdapter();
				if(adapter!=null){
					Department department = adapter.getItem(position);
					UiHelper.doctorList(DepartmentListActivity.this, department.getId());
				}
			}
		});
	}

	private void getDepartmentList() {
		HttpAsync httpAsync = new HttpAsync() {
			@Override
			protected void onSuccess(String json) {
				progressDialog.dismiss();
				try {
					SimpleResponse<ArrayList<Department>> departmentListResponse = ResponseUtils.departmentListResponse(json);
					if(departmentListResponse.isSuccess()){
						ArrayList<Department> list = departmentListResponse.getData();
						DepartmentListViewAdapter adapter = new DepartmentListViewAdapter(list, DepartmentListActivity.this);
						lv.setAdapter(adapter);
					}else{
						String msg = departmentListResponse.getMessage();
						if(msg==null){
							msg="";
						}
						ToastShow.shortT("获取列表失败!"+msg);
					}
				} catch (Exception e) {
					ToastShow.shortT(e.getMessage());
				}
			}

			@Override
			public void onError(HttpException exception) {
				progressDialog.dismiss();
				ToastShow.shortT("获取列表失败!");
			}
		};
		if(progressDialog==null){
			progressDialog = new CustomProgressDialog(this,"正在获取科室列表!");
		}
		progressDialog.show();
		ApiClient.departmentList(httpAsync);
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		progressDialog.dismiss();
	}
}


text:
<template name="articlesList">

    {{#each articles}}

        {{> article}}

    {{/each}}

</template>