text:
/*
  Copyright 2011  Dean Camera (dean [at] fourwalledcubicle [dot] com)

  Permission to use, copy, modify, distribute, and sell this
  software and its documentation for any purpose is hereby granted
  without fee, provided that the above copyright notice appear in
  all copies and that both that the copyright notice and this
  permission notice and warranty disclaimer appear in supporting
  documentation, and that the name of the author not be used in
  advertising or publicity pertaining to distribution of the
  software without specific, written prior permission.

  The author disclaim all warranties with regard to this
  software, including all implied warranties of merchantability
  and fitness.  In no event shall the author be liable for any
  special, indirect or consequential damages or any damages
  whatsoever resulting from loss of use, data or profits, whether
  in an action of contract, negligence or other tortious action,
  arising out of or in connection with the use or performance of
  this software.
*/

/** \file
 *  \brief USB Device definitions for the AVR8 microcontrollers.
 *  \copydetails Group_Device_AVR8
 *
 *  \note This file should not be included directly. It is automatically included as needed by the USB driver
 *        dispatch header located in LUFA/Drivers/USB/USB.h.
 */

/** \ingroup Group_Device
 *  \defgroup Group_Device_AVR8 Device Management (AVR8)
 *  \brief USB Device definitions for the AVR8 microcontrollers.
 *
 *  Architecture specific USB Device definitions for the Atmel 8-bit AVR microcontrollers.
 *
 *  @{
 */

#ifndef __USBDEVICE_AVR8_H__
#define __USBDEVICE_AVR8_H__

	/* Includes: */
		#include "../../../../Common/Common.h"
		#include "../USBController.h"
		#include "../StdDescriptors.h"
		#include "../USBInterrupt.h"
		#include "../Endpoint.h"

	/* Enable C linkage for C++ Compilers: */
		#if defined(__cplusplus)
			extern "C" {
		#endif

	/* Preprocessor Checks: */
		#if !defined(__INCLUDE_FROM_USB_DRIVER)
			#error Do not include this file directly. Include LUFA/Drivers/USB/USB.h instead.
		#endif

		#if (defined(USE_RAM_DESCRIPTORS) && defined(USE_EEPROM_DESCRIPTORS))
			#error USE_RAM_DESCRIPTORS and USE_EEPROM_DESCRIPTORS are mutually exclusive.
		#endif

	/* Public Interface - May be used in end-application: */
		/* Macros: */
			/** \name USB Device Mode Option Masks */
			//@{
			#if defined(USB_SERIES_4_AVR) || defined(USB_SERIES_6_AVR) || defined(USB_SERIES_7_AVR) || defined(__DOXYGEN__)
				/** Mask for the Options parameter of the \ref USB_Init() function. This indicates that the
				 *  USB interface should be initialized in low speed (1.5Mb/s) mode.
				 *
				 *  \note Low Speed mode is not available on all USB AVR models.
				 *        \n
				 *
				 *  \note Restrictions apply on the number, size and type of endpoints which can be used
				 *        when running in low speed mode - refer to the USB 2.0 specification.
				 */
				#define USB_DEVICE_OPT_LOWSPEED            (1 << 0)
			#endif

			/** Mask for the Options parameter of the \ref USB_Init() function. This indicates that the
			 *  USB interface should be initialized in full speed (12Mb/s) mode.
			 */
			#define USB_DEVICE_OPT_FULLSPEED               (0 << 0)
			//@}

			#if (!defined(NO_INTERNAL_SERIAL) && \
			     (defined(USB_SERIES_7_AVR) || defined(USB_SERIES_6_AVR) || defined(USB_SERIES_4_AVR) || \
			      (defined(USB_SERIES_2_AVR) && (!defined(__AVR_AT90USB82__) || defined(__AVR_AT90USB162__))) || \
				  defined(__DOXYGEN__)))
				/** String descriptor index for the device's unique serial number string descriptor within the device.
				 *  This unique serial number is used by the host to associate resources to the device (such as drivers or COM port
				 *  number allocations) to a device regardless of the port it is plugged in to on the host. Some microcontrollers contain
				 *  a unique serial number internally, and setting the device descriptors serial number string index to this value
				 *  will cause it to use the internal serial number.
				 *
				 *  On unsupported devices, this will evaluate to \ref NO_DESCRIPTOR and so will force the host to create a pseudo-serial
				 *  number for the device.
				 */
				#define USE_INTERNAL_SERIAL            0xDC

				/** Length of the device's unique internal serial number, in bits, if present on the selected microcontroller
				 *  model.
				 */
				#define INTERNAL_SERIAL_LENGTH_BITS    80

				/** Start address of the internal serial number, in the appropriate address space, if present on the selected microcontroller
				 *  model.
				 */
				#define INTERNAL_SERIAL_START_ADDRESS  0x0E
			#else
				#define USE_INTERNAL_SERIAL            NO_DESCRIPTOR

				#define INTERNAL_SERIAL_LENGTH_BITS    0
				#define INTERNAL_SERIAL_START_ADDRESS  0
			#endif

		/* Function Prototypes: */
			/** Sends a Remote Wakeup request to the host. This signals to the host that the device should
			 *  be taken out of suspended mode, and communications should resume.
			 *
			 *  Typically, this is implemented so that HID devices (mice, keyboards, etc.) can wake up the
			 *  host computer when the host has suspended all USB devices to enter a low power state.
			 *
			 *  \note This macro should only be used if the device has indicated to the host that it
			 *        supports the Remote Wakeup feature in the device descriptors, and should only be
			 *        issued if the host is currently allowing remote wakeup events from the device (i.e.,
			 *        the \ref USB_Device_RemoteWakeupEnabled flag is set). When the \c NO_DEVICE_REMOTE_WAKEUP
			 *        compile time option is used, this macro is unavailable.
			 *        \n\n
			 *
			 *  \note The USB clock must be running for this function to operate. If the stack is initialized with
			 *        the \ref USB_OPT_MANUAL_PLL option enabled, the user must ensure that the PLL is running
			 *        before attempting to call this function.
			 *
			 *  \see \ref Group_StdDescriptors for more information on the RMWAKEUP feature and device descriptors.
			 */
			void USB_Device_SendRemoteWakeup(void);

		/* Inline Functions: */
			/** Returns the current USB frame number, when in device mode. Every millisecond the USB bus is active (i.e. enumerated to a host)
			 *  the frame number is incremented by one.
			 *
			 *  \return Current USB frame number from the USB controller.
			 */
			static inline uint16_t USB_Device_GetFrameNumber(void) ATTR_ALWAYS_INLINE ATTR_WARN_UNUSED_RESULT;
			static inline uint16_t USB_Device_GetFrameNumber(void)
			{
				return UDFNUM;
			}

			#if !defined(NO_SOF_EVENTS)
				/** Enables the device mode Start Of Frame events. When enabled, this causes the
				 *  \ref EVENT_USB_Device_StartOfFrame() event to fire once per millisecond, synchronized to the USB bus,
				 *  at the start of each USB frame when enumerated in device mode.
				 *
				 *  \note Not available when the \c NO_SOF_EVENTS compile time token is defined.
				 */
				static inline void USB_Device_EnableSOFEvents(void) ATTR_ALWAYS_INLINE;
				static inline void USB_Device_EnableSOFEvents(void)
				{
					USB_INT_Enable(USB_INT_SOFI);
				}

				/** Disables the device mode Start Of Frame events. When disabled, this stops the firing of the
				 *  \ref EVENT_USB_Device_StartOfFrame() event when enumerated in device mode.
				 *
				 *  \note Not available when the \c NO_SOF_EVENTS compile time token is defined.
				 */
				static inline void USB_Device_DisableSOFEvents(void) ATTR_ALWAYS_INLINE;
				static inline void USB_Device_DisableSOFEvents(void)
				{
					USB_INT_Disable(USB_INT_SOFI);
				}
			#endif

	/* Private Interface - For use in library only: */
	#if !defined(__DOXYGEN__)
		/* Inline Functions: */
			#if defined(USB_DEVICE_OPT_LOWSPEED)
			static inline void USB_Device_SetLowSpeed(void) ATTR_ALWAYS_INLINE;
			static inline void USB_Device_SetLowSpeed(void)
			{
				UDCON |=  (1 << LSM);
			}

			static inline void USB_Device_SetFullSpeed(void) ATTR_ALWAYS_INLINE;
			static inline void USB_Device_SetFullSpeed(void)
			{
				UDCON &= ~(1 << LSM);
			}
			#endif

			static inline void USB_Device_SetDeviceAddress(const uint8_t Address) ATTR_ALWAYS_INLINE;
			static inline void USB_Device_SetDeviceAddress(const uint8_t Address)
			{
				uint8_t Temp = (UDADDR & (1 << ADDEN)) | (Address & 0x7F);

				UDADDR = Temp;
				UDADDR = Temp | (1 << ADDEN);
			}

			static inline bool USB_Device_IsAddressSet(void) ATTR_ALWAYS_INLINE ATTR_WARN_UNUSED_RESULT;
			static inline bool USB_Device_IsAddressSet(void)
			{
				return (UDADDR & (1 << ADDEN));
			}

			#if (USE_INTERNAL_SERIAL != NO_DESCRIPTOR)
			static inline void USB_Device_GetSerialString(uint16_t* const UnicodeString) ATTR_NON_NULL_PTR_ARG(1);
			static inline void USB_Device_GetSerialString(uint16_t* const UnicodeString)
			{
				uint_reg_t CurrentGlobalInt = GetGlobalInterruptMask();
				GlobalInterruptDisable();

				uint8_t SigReadAddress = INTERNAL_SERIAL_START_ADDRESS;

				for (uint8_t SerialCharNum = 0; SerialCharNum < (INTERNAL_SERIAL_LENGTH_BITS / 4); SerialCharNum++)
				{
					uint8_t SerialByte = boot_signature_byte_get(SigReadAddress);

					if (SerialCharNum & 0x01)
					{
						SerialByte >>= 4;
						SigReadAddress++;
					}

					SerialByte &= 0x0F;

					UnicodeString[SerialCharNum] = cpu_to_le16((SerialByte >= 10) ?
															   (('A' - 10) + SerialByte) : ('0' + SerialByte));
				}

				SetGlobalInterruptMask(CurrentGlobalInt);
			}
			#endif

	#endif

	/* Disable C linkage for C++ Compilers: */
		#if defined(__cplusplus)
			}
		#endif

#endif

/** @} */


text:
using System;
using System.Collections.Generic;
using System.Text;
using Tests.Core;
using Core = NetOffice;
using Office = NetOffice.OfficeApi;
using Excel = NetOffice.ExcelApi;

namespace ExcelTestsCSharp
{
    /// <summary>
    /// foreach enumeration
    /// </summary>
    public class Test07 : ITestPackage
    {
        #region TestPackage Member

        public string Name
        {
            get { return "Test07"; }
        }

        public string Description
        {
            get { return "Range ForEach enumeration"; }
        }

        public string OfficeProduct
        {
            get { return "Excel"; }
        }

        public string Language
        {
            get { return "C#"; }
        }

        public TestResult DoTest()
        {
            Excel.Application application = null;
            DateTime startTime = DateTime.Now;
            try
            {
                application = new NetOffice.ExcelApi.Application();
                application.DisplayAlerts = false;
                application.Workbooks.Add();
                Excel.Worksheet sheet = application.Workbooks[1].Sheets[1] as Excel.Worksheet;

                foreach (Excel.Range item in sheet.Range("$A1:$B100"))
                    item.Value = DateTime.Now;

                return new TestResult(true, DateTime.Now.Subtract(startTime), "", null, "");
            }
            catch (Exception exception)
            {
                return new TestResult(false, DateTime.Now.Subtract(startTime), exception.Message, exception, "");
            }
            finally
            {
                if (null != application)
                {
                    application.Quit();
                    application.Dispose();
                }
            }
        }

        #endregion
    }
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * @file : spline_1d_constraint.h
 * @brief: wrapp up solver constraint interface with direct methods and preset
 *methods
 **/

#pragma once

#include <algorithm>
#include <vector>

#include "Eigen/Core"

#include "modules/planning/math/smoothing_spline/affine_constraint.h"
#include "modules/planning/math/smoothing_spline/spline_1d.h"

namespace apollo {
namespace planning {

class Spline1dConstraint {
 public:
  explicit Spline1dConstraint(const Spline1d& pss);
  Spline1dConstraint(const std::vector<double>& x_knots, const uint32_t order);

  // direct methods
  bool AddInequalityConstraint(const Eigen::MatrixXd& constraint_matrix,
                               const Eigen::MatrixXd& constraint_boundary);
  bool AddEqualityConstraint(const Eigen::MatrixXd& constraint_matrix,
                             const Eigen::MatrixXd& constraint_boundary);

  // preset method
  /**
   * @brief: inequality boundary constraints
   * if no boundary, do specify either by std::infinity or
   * let vector.size() = 0
   **/
  bool AddBoundary(const std::vector<double>& x_coord,
                   const std::vector<double>& lower_bound,
                   const std::vector<double>& upper_bound);

  bool AddDerivativeBoundary(const std::vector<double>& x_coord,
                             const std::vector<double>& lower_bound,
                             const std::vector<double>& upper_bound);

  bool AddSecondDerivativeBoundary(const std::vector<double>& x_coord,
                                   const std::vector<double>& lower_bound,
                                   const std::vector<double>& upper_bound);

  bool AddThirdDerivativeBoundary(const std::vector<double>& x_coord,
                                  const std::vector<double>& lower_bound,
                                  const std::vector<double>& upper_bound);

  /**
   * @brief: equality constraint to guarantee joint smoothness
   * boundary equality constriant constraint on fx, dfx, ddfx ... in vector
   * form; up to third order
   **/
  bool AddPointConstraint(const double x, const double fx);
  bool AddPointDerivativeConstraint(const double x, const double dfx);
  bool AddPointSecondDerivativeConstraint(const double x, const double ddfx);
  bool AddPointThirdDerivativeConstraint(const double x, const double dddfx);

  bool AddPointConstraintInRange(const double x, const double fx,
                                 const double range);
  bool AddPointDerivativeConstraintInRange(const double x, const double dfx,
                                           const double range);
  bool AddPointSecondDerivativeConstraintInRange(const double x,
                                                 const double ddfx,
                                                 const double range);
  bool AddPointThirdDerivativeConstraintInRange(const double x,
                                                const double dddfx,
                                                const double range);
  // guarantee up to values are joint
  bool AddSmoothConstraint();

  // guarantee up to derivative are joint
  bool AddDerivativeSmoothConstraint();

  // guarantee up to second order derivative are joint
  bool AddSecondDerivativeSmoothConstraint();

  // guarantee up to third order derivative are joint
  bool AddThirdDerivativeSmoothConstraint();

  /**
   * @brief: Add monotone constraint inequality, guarantee the monotone city at
   * evaluated point. customized monotone inequality constraint at x_coord
   **/
  bool AddMonotoneInequalityConstraint(const std::vector<double>& x_coord);

  // default inequality constraint at knots
  bool AddMonotoneInequalityConstraintAtKnots();

  /**
   * @brief: output interface inequality constraint
   **/
  const AffineConstraint& inequality_constraint() const;
  const AffineConstraint& equality_constraint() const;

 private:
  uint32_t FindIndex(const double x) const;

  bool FilterConstraints(const std::vector<double>& x_coord,
                         const std::vector<double>& lower_bound,
                         const std::vector<double>& upper_bound,
                         std::vector<double>* const filtered_lower_bound_x,
                         std::vector<double>* const filtered_lower_bound,
                         std::vector<double>* const filtered_upper_bound_x,
                         std::vector<double>* const filtered_upper_bound);
  void GeneratePowerX(const double x, const uint32_t order,
                      std::vector<double>* const power_x) const;

  using AddConstraintInRangeFunc =
      std::function<bool(const std::vector<double>&, const std::vector<double>&,
                         const std::vector<double>&)>;
  bool AddConstraintInRange(AddConstraintInRangeFunc func, const double x,
                            const double val, const double range);

 private:
  AffineConstraint inequality_constraint_;
  AffineConstraint equality_constraint_;
  std::vector<double> x_knots_;
  uint32_t spline_order_;
};

}  // namespace planning
}  // namespace apollo


text:
<?php

namespace Twig\Tests\Node;

use Twig\Node\Expression\AssignNameExpression;
use Twig\Node\Expression\ConstantExpression;
use Twig\Node\Expression\NameExpression;
use Twig\Node\Node;
use Twig\Node\PrintNode;
use Twig\Node\SetNode;
use Twig\Node\TextNode;
use Twig\Test\NodeTestCase;

class SetTest extends NodeTestCase
{
    public function testConstructor()
    {
        $names = new Node([new AssignNameExpression('foo', 1)], [], 1);
        $values = new Node([new ConstantExpression('foo', 1)], [], 1);
        $node = new SetNode(false, $names, $values, 1);

        $this->assertEquals($names, $node->getNode('names'));
        $this->assertEquals($values, $node->getNode('values'));
        $this->assertFalse($node->getAttribute('capture'));
    }

    public function getTests()
    {
        $tests = [];

        $names = new Node([new AssignNameExpression('foo', 1)], [], 1);
        $values = new Node([new ConstantExpression('foo', 1)], [], 1);
        $node = new SetNode(false, $names, $values, 1);
        $tests[] = [$node, <<<EOF
// line 1
\$context["foo"] = "foo";
EOF
        ];

        $names = new Node([new AssignNameExpression('foo', 1)], [], 1);
        $values = new Node([new PrintNode(new ConstantExpression('foo', 1), 1)], [], 1);
        $node = new SetNode(true, $names, $values, 1);
        $tests[] = [$node, <<<EOF
// line 1
ob_start(function () { return ''; });
echo "foo";
\$context["foo"] = ('' === \$tmp = ob_get_clean()) ? '' : new Markup(\$tmp, \$this->env->getCharset());
EOF
        ];

        $names = new Node([new AssignNameExpression('foo', 1)], [], 1);
        $values = new TextNode('foo', 1);
        $node = new SetNode(true, $names, $values, 1);
        $tests[] = [$node, <<<EOF
// line 1
\$context["foo"] = ('' === \$tmp = "foo") ? '' : new Markup(\$tmp, \$this->env->getCharset());
EOF
        ];

        $names = new Node([new AssignNameExpression('foo', 1), new AssignNameExpression('bar', 1)], [], 1);
        $values = new Node([new ConstantExpression('foo', 1), new NameExpression('bar', 1)], [], 1);
        $node = new SetNode(false, $names, $values, 1);
        $tests[] = [$node, <<<EOF
// line 1
list(\$context["foo"], \$context["bar"]) = ["foo", {$this->getVariableGetter('bar')}];
EOF
        ];

        return $tests;
    }
}


text:
// **********
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// **********

#include <stdlib.h>

#include "window.h"
#include "world.h"

GameWindow::GameWindow()
	: keysDown(KB_SIZE)
{
}

GameWindow::~GameWindow()
{
}

void GameWindow::emitKeyDown(KeyboardKey key)
{
	keysDown[key]++;

	if (keysDown[KBEscape] &&
			(keysDown[KBLeftShift] || keysDown[KBRightShift])) {
		exit(0);
	}

	if (keysDown[key])
		World::instance().buttonDown(key);
}

void GameWindow::emitKeyUp(KeyboardKey key)
{
	keysDown[key]--;

	if (!keysDown[key])
		World::instance().buttonUp(key);
}

bool GameWindow::isKeyDown(KeyboardKey key)
{
	return keysDown[key] != false;
}

BitRecord GameWindow::getKeysDown()
{
	return keysDown;
}


text:
#pragma once

#include "Script.h"
#include "TCPClient.h"

class LUATCPClient : private TCPClient {
public:
	static const char* Name;

	static int Get(lua_State* pState);
	static int Set(lua_State* pState);

	static void ID(std::string& id){}

	static void	Create(SocketManager& manager,lua_State* pState);
private:
	LUATCPClient(SocketManager& manager,lua_State* pState);
	virtual ~LUATCPClient();

	static int	Destroy(lua_State* pState);

	Poco::UInt32	onReception(const Poco::UInt8* data,Poco::UInt32 size);
	void			onDisconnection();

	static int	Send(lua_State* pState);
	static int  Connect(lua_State* pState);
	static int  Disconnect(lua_State* pState);

	lua_State*			_pState;
};


text:
var masterUserList = require('../masterUserList.json');

exports.updateStatuses = function(req, res){
	res.json(masterUserList);
};


text:
package org.andorp.quicky.generator.combinator;

import java.util.Collection;

import org.andorp.quicky.Choose;
import org.andorp.quicky.CollectionUtils;
import org.andorp.quicky.IGenerator;
import org.andorp.quicky.Pair;
import org.andorp.quicky.PrimitiveRandomGen;
import org.andorp.quicky.Sanity;
import org.andorp.quicky.engine.RandomAndSize;

public final class Frequency<T> implements IGenerator<IGenerator<T>> {

    private final Collection<Pair<Integer, IGenerator<T>>> pairs;
    private final Choose<Integer> choose;

    public Frequency(Collection<Pair<Integer, IGenerator<T>>> pairs) {
        Sanity.notNull(pairs, "Frequency: pairs can't be null");
        Sanity.nonEmptyCollection(pairs, "Frequency: pairs can't be empty");
        checkPairs(pairs);
        this.pairs = CollectionUtils.shallowCopy(pairs);
        final int total = total(pairs);
        this.choose = new Choose<Integer>(
                PrimitiveRandomGen.integer(),
                0,
                total
                );
    }

    /* Chooses one of the given generators, with weighted random distribution. */
    public IGenerator<T> next(RandomAndSize random) {
        return pick(choose.next(random));
    }

    private IGenerator<T> pick(int n) {
        for(Pair<Integer, IGenerator<T>> pair : pairs) {
            final int k = pair.first();
            if(n <= k) {
                return pair.second();
            }
            n -= k;
        }
        throw new IllegalArgumentException("Invalid generator list in Frequency was given.");
    }

    private static <X> int total(Collection<Pair<Integer,X>> pairs) {
        int sum = 0;
        for(Pair<Integer,?> pair : pairs) {
            sum += pair.first();
        }
        return sum;
    }

    private static <X> void checkPairs(Collection<Pair<Integer,X>> pairs) {
        for(Pair<Integer, X> pair : pairs) {
            if(pair.first() <= 0) {
                throw new IllegalArgumentException("Frequency value is less than equal to zero");
            }
            if(pair.second() == null) {
                throw new IllegalArgumentException("Generator is null");
            }
        }
    }
}


text:
package defaultrpc

import "github.com/liangdas/mqant/rpc/pb"

type ClinetCallInfo struct {
	correlation_id string
	timeout        int64 //超时
	call           chan *rpcpb.ResultInfo
}


text:
using System.Data.Entity;
using System.Threading.Tasks;

namespace Tournaments.EntityModels
{
    /// <summary>
    /// This provides interfaces to the <see cref="TournamentDbContext"/> class.
    /// </summary>
    public interface ITournamentDbContext
    {
        /// <summary>
        /// Gets or sets the set of <see cref="Player"/> instances.
        /// </summary>
        DbSet<Player> Players { get; set; }

        /// <summary>
        /// Gets or sets the set of <see cref="PlayerTournament"/> instances.
        /// </summary>
        DbSet<PlayerTournament> PlayerTournaments { get; set; }

        /// <summary>
        /// Gets or sets the set of <see cref="Tournament"/> instances.
        /// </summary>
        DbSet<Tournament> Tournaments { get; set; }

        /// <summary>
        /// Gets the <see cref="System.Data.Entity.Database"/> instance.
        /// </summary>
        Database Database { get; }

        /// <summary>
        /// Saves all changes made in this context to the underlying database.
        /// </summary>
        /// <returns>
        /// The number of state entries written to the underlying database. This can include
        /// state entries for entities and/or relationships. Relationship state entries are created for
        /// many-to-many relationships and relationships where there is no foreign key property
        /// included in the entity class (often referred to as independent associations).
        /// </returns>
        int SaveChanges();

        /// <summary>
        /// Asynchronously saves all changes made in this context to the underlying database.
        /// </summary>
        /// <remarks>
        /// Multiple active operations on the same context instance are not supported.  Use 'await' to ensure
        /// that any asynchronous operations have completed before calling another method on this context.
        /// </remarks>
        /// <returns>
        /// A task that represents the asynchronous save operation.
        /// The task result contains the number of state entries written to the underlying database. This can include
        /// state entries for entities and/or relationships. Relationship state entries are created for
        /// many-to-many relationships and relationships where there is no foreign key property
        /// included in the entity class (often referred to as independent associations).
        /// </returns>
        Task<int> SaveChangesAsync();
    }
}


text:
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2007 Mark Joshi

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <http://quantlib.org/license.shtml>.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

#include <ql/models/marketmodels/models/alphafinder.hpp>
#include <ql/math/quadratic.hpp>

namespace QuantLib {

namespace
{

    template<class T>
    Real Bisection(Real target,
                   Real low,
                   Real high,
                   Real tolerance,
                   T& theObject,
                   Real (T::*Value)(Real)) {

        Real x=0.5*(low+high);
        Real y=(theObject.*Value)(x);

        do {
            if (y < target) low = x;
            else if (y > target) high = x;

            x = 0.5*(low+high);
            y = (theObject.*Value)(x);
        } while ((std::fabs(high-low) > tolerance));

        return x;
    }

    template<class T>
    Real FindHighestOK(Real low,
                       Real high,
                       Real tolerance,
                       T& theObject,
                       bool (T::*Value)(Real)) {

        Real x=0.5*(low+high);
        bool ok=(theObject.*Value)(x);

        do {
            if (ok) low = x;
            else    high = x;

            x = 0.5*(low+high);
            ok = (theObject.*Value)(x);
        } while ((std::fabs(high-low) > tolerance));

        return x;
    }

    template<class T>
    Real FindLowestOK(Real low,
                      Real high,
                      Real tolerance,
                      T& theObject,
                      bool (T::*Value)(Real)) {

        Real x=0.5*(low+high);
        bool ok=(theObject.*Value)(x);

        do {
            if (ok) high = x;
            else    low = x;

            x = 0.5*(low+high);
            ok = (theObject.*Value)(x);
        } while ( (std::fabs(high-low) > tolerance) );

        return x;
    }

    template<class T>
    Real Minimize(Real low,
                  Real high,
                  Real tolerance,
                  T& theObject,
                  Real (T::*Value)(Real),
                  bool (T::*Condition)(Real),
                  bool& failed) {

        Real leftValue = (theObject.*Value)(low);
        Real rightValue = (theObject.*Value)(high);
        Real W = 0.5*(3.0-std::sqrt(5.0));
        Real x=W*low+(1-W)*high;
        Real midValue =  (theObject.*Value)(x);

        failed = true;

        while(high - low > tolerance) {

            if (x - low > high -x) // left interval is bigger
            {
                Real tentativeNewMid = W*low+(1-W)*x;
                Real tentativeNewMidValue =  (theObject.*Value)(tentativeNewMid);
                bool conditioner = (theObject.*Condition)(tentativeNewMidValue);
                if (!conditioner) {
                    if  ((theObject.*Condition)(x))
                        return x;
                    else
                        if (leftValue < rightValue)
                            return low;
                        else
                            return high;
                }

                if (tentativeNewMidValue < midValue) // go left
                {
                    high =x;
                    rightValue = midValue;
                    x = tentativeNewMid;
                    midValue = tentativeNewMidValue;
                }
                else // go right
                {
                    low = tentativeNewMid;
                    leftValue = tentativeNewMidValue;
                }
            }
            else
            {
                Real tentativeNewMid = W*x+(1-W)*high;
                Real tentativeNewMidValue =  (theObject.*Value)(tentativeNewMid);
                bool conditioner = (theObject.*Condition)(tentativeNewMidValue);
                if (!conditioner) {
                    if  ((theObject.*Condition)(x))
                        return x;
                    else
                        if (leftValue < rightValue)
                            return low;
                        else
                            return high;
                }

                if (tentativeNewMidValue < midValue) // go right
                {
                    low =x;
                    leftValue = midValue;
                    x = tentativeNewMid;
                    midValue = tentativeNewMidValue;
                }
                else // go left
                {
                    high = tentativeNewMid;
                    rightValue = tentativeNewMidValue;
                }
            }

            }
        failed = false;
        return x;
    }
}

    AlphaFinder::AlphaFinder(boost::shared_ptr<AlphaForm> parametricform)
    : parametricform_(parametricform) {}

    Real AlphaFinder::computeLinearPart(Real alpha) {
        Real cov =0.0;
        parametricform_->setAlpha(alpha);

        for (Integer i=0; i < stepindex_+1; ++i) {
            Real vol1 = ratetwohomogeneousvols_[i]*(*parametricform_)(i);
            cov += vol1*rateonevols_[i]*correlations_[i];
        }

        cov *= 2*w0_*w1_;
        return cov;
    }

    Real AlphaFinder::computeQuadraticPart(Real alpha) {
        Real var =0.0;
        parametricform_->setAlpha(alpha);

        for (Integer i=0; i < stepindex_+1; ++i) {
            Real vol = ratetwohomogeneousvols_[i]*(*parametricform_)(i);
            var+= vol*vol;
        }

        var *= w1_*w1_;
        return var;
    }

    Real AlphaFinder::homogeneityfailure(Real alpha) {
        Real dum1, dum2, dum3;
        finalPart(alpha,
                  stepindex_,
                  ratetwohomogeneousvols_,
                  computeQuadraticPart(alpha),
                  computeLinearPart(alpha),
                  constantPart_,
                  dum1,
                  dum2,
                  dum3,
                  putativevols_);

    Real result=0.0;
    for (Size i=0; i<=static_cast<Size>(stepindex_)+1; ++i) {
        Real val =  putativevols_[i]-ratetwohomogeneousvols_[i];
        result +=val*val;
    }

    return result;
}

    bool AlphaFinder::finalPart(Real alphaFound,
                                Integer stepindex,
                                const std::vector<Volatility>& ratetwohomogeneousvols,
                                Real quadraticPart,
                                Real linearPart,
                                Real constantPart,
                                Real& alpha,
                                Real& a,
                                Real& b,
                                std::vector<Volatility>& ratetwovols) {
            alpha = alphaFound;
            quadratic q2(quadraticPart, linearPart, constantPart-targetVariance_ );
            parametricform_->setAlpha(alpha);
            Real y; // dummy
            q2.roots(a,y);

            Real varSoFar=0.0;
            for (Integer i =0; i < stepindex+1; ++i) {
                ratetwovols[i] = ratetwohomogeneousvols[i] *
                                            (*parametricform_)(i) * a;
                varSoFar += ratetwovols[i]* ratetwovols[i];
            }

            Real VarToFind = totalVar_-varSoFar;
            if (VarToFind < 0)
                return false;
            Real requiredSd = std::sqrt(VarToFind);
            b = requiredSd / (ratetwohomogeneousvols[stepindex+1] *
                                            (*parametricform_)(stepindex));
            ratetwovols[stepindex+1] = requiredSd;
            return true;
    }

    Real AlphaFinder::valueAtTurningPoint(Real alpha) {

        linearPart_ = computeLinearPart(alpha);
        quadraticPart_ = computeQuadraticPart(alpha);

        quadratic q(quadraticPart_, linearPart_, constantPart_);
        Real valueAtTP =q.valueAtTurningPoint();
        return valueAtTP;
    }

    Real AlphaFinder::minusValueAtTurningPoint(Real alpha) {
        return -valueAtTurningPoint(alpha);
    }

    bool AlphaFinder::testIfSolutionExists(Real alpha) {
        bool aExists =  valueAtTurningPoint(alpha)<targetVariance_;
        if (!aExists)
            return false;

        Real dum1, dum2, dum3;
        return finalPart(alpha,
                         stepindex_,
                         ratetwohomogeneousvols_,
                         computeQuadraticPart(alpha),
                         computeLinearPart(alpha),
                         constantPart_,
                         dum1,
                         dum2,
                         dum3,
                         putativevols_);
    }

    bool AlphaFinder::solve(Real alpha0,
                            Integer stepindex, // caplet index
                            const std::vector<Volatility>& rateonevols,
                            const std::vector<Volatility>& ratetwohomogeneousvols,
                            const std::vector<Real>& correlations,
                            Real w0,
                            Real w1,
                            Real targetVariance,
                            Real tolerance,
                            Real alphaMax,
                            Real alphaMin,
                            Integer steps,
                            Real& alpha,
                            Real& a,
                            Real& b,
                            std::vector<Volatility>& ratetwovols) {
        stepindex_=stepindex;
        rateonevols_=rateonevols;
        ratetwohomogeneousvols_=ratetwohomogeneousvols;
        correlations_=correlations;
        w0_=w0;
        w1_=w1;
        totalVar_=0;
        for (Size i=0; i <=static_cast<Size>(stepindex)+1; ++i)
            totalVar_+=ratetwohomogeneousvols[i]*ratetwohomogeneousvols[i];
        targetVariance_ = targetVariance;

        // constant part will not depend on alpha

        constantPart_ =0.0;
        for (Integer i=0; i < stepindex+1; ++i)
                constantPart_+=rateonevols[i]*rateonevols[i];

        constantPart_ *= w0*w0;

        // compute linear part with initial alpha
        Real valueAtTP = valueAtTurningPoint(alpha0);

        if (valueAtTP <= targetVariance) {
            finalPart(alpha0,
                      stepindex,
                      ratetwohomogeneousvols,
                      quadraticPart_,
                      linearPart_,
                      constantPart_,
                      alpha,
                      a,
                      b,
                      ratetwovols);
            return true;
        }

        // we now have to solve
        Real bottomValue = valueAtTurningPoint(alphaMin);
        Real bottomAlpha = alphaMin;
        Real topValue = valueAtTurningPoint(alphaMax);
        Real topAlpha = alphaMax;
        Real bilimit = alpha0;

        if (bottomValue > targetVariance && topValue > targetVariance) {
            // see if if ok at some intermediate point by stepping through
            Integer i=1;
            while ( i < steps && topValue> targetVariance) {
                topAlpha = alpha0 + (alphaMax-alpha0)*(i+0.0)/(steps+0.0);
                topValue=valueAtTurningPoint(topAlpha);
                ++i;
            }

            if (topValue <= targetVariance)
                bilimit = alpha0 + (topAlpha-alpha0)*(i-2.0)/(steps+0.0);
        }

        if (bottomValue > targetVariance && topValue > targetVariance) {
            // see if if ok at some intermediate point by stepping through
            Integer i=1;
            while ( i < steps && topValue> targetVariance) {
                bottomAlpha = alpha0 + (alphaMin-alpha0)*(i+0.0)/(steps+0.0);
                bottomValue=valueAtTurningPoint(bottomAlpha);
                ++i;
            }

            if (bottomValue <= targetVariance)
                bilimit = alpha0 +(bottomAlpha-alpha0)*(i-2.0)/(steps+0.0);
        }

        if (bottomValue > targetVariance && topValue > targetVariance)
            return false;

        if (bottomValue <= targetVariance) {
            // then find root of increasing function
            // (or as if increasing function)
            alpha = Bisection<AlphaFinder>(
                                           targetVariance,
                                           bottomAlpha,
                                           bilimit,
                                           tolerance,
                                           *this,
                                           &AlphaFinder::valueAtTurningPoint);
        } else {
            // find root of decreasing function (or as if decreasing function)
            alpha=Bisection<AlphaFinder>(
                                         -targetVariance,
                                         bilimit,
                                         topAlpha,
                                         tolerance,
                                         *this,
                                         &AlphaFinder::minusValueAtTurningPoint);
        }
        finalPart(alpha,
                  stepindex,
                  ratetwohomogeneousvols,
                  quadraticPart_,
                  linearPart_,
                  constantPart_,
                  alpha,
                  a,
                  b,
                  ratetwovols);
        return true;
    }

    bool AlphaFinder::solveWithMaxHomogeneity(
                        Real alpha0,
                        Integer stepindex, // caplet index
                        const std::vector<Volatility>& rateonevols,
                        const std::vector<Volatility>& ratetwohomogeneousvols,
                        const std::vector<Real>& correlations,
                        Real w0,
                        Real w1,
                        Real targetVariance,
                        Real tolerance,
                        Real alphaMax,
                        Real alphaMin,
                        Integer steps,
                        Real& alpha,
                        Real& a,
                        Real& b,
                        std::vector<Volatility>& ratetwovols) {

        stepindex_=stepindex;
        rateonevols_=rateonevols;
        ratetwohomogeneousvols_=ratetwohomogeneousvols;
        putativevols_.resize(ratetwohomogeneousvols_.size());
        correlations_=correlations;
        w0_=w0;
        w1_=w1;
        totalVar_=0;
        for (Size i=0; i <=static_cast<Size>(stepindex)+1; ++i)
            totalVar_+=ratetwohomogeneousvols[i]*ratetwohomogeneousvols[i];
        targetVariance_=targetVariance;

        // constant part will not depend on alpha

        constantPart_ =0.0;
        for (Integer i=0; i < stepindex+1; ++i)
            constantPart_+=rateonevols[i]*rateonevols[i];

        constantPart_ *= w0*w0;

        Real alpha1 = alphaMin;
        Real alpha2 = alphaMax;

        // compute linear part with initial alpha
        bool alpha0OK = testIfSolutionExists(alpha0);
        bool alphaMaxOK = testIfSolutionExists(alphaMax);
        bool alphaMinOK = testIfSolutionExists(alphaMin);

        bool foundOKPoint = alpha0OK || alphaMaxOK || alphaMinOK;

        if (foundOKPoint) {
            if (!alphaMinOK) {
                // lower alpha is bad
                if (alpha0OK) {
                    // must die somewhere in between
                    alpha1 = FindLowestOK<AlphaFinder>(
                         alphaMin,
                         alpha0,
                         tolerance,
                        *this,
                         &AlphaFinder::testIfSolutionExists);
                } else {
                    // alphaMaxOK must be true to get here
                    alpha1 = FindLowestOK<AlphaFinder>(
                         alpha0,
                         alphaMax,
                         tolerance,
                        *this,
                         &AlphaFinder::testIfSolutionExists);
                }
            }

            if (!alphaMaxOK) {
                // higher alpha is bad
                alpha2 = FindHighestOK<AlphaFinder>(
                     alpha1,
                     alphaMax,
                     tolerance,
                     *this,
                     &AlphaFinder::testIfSolutionExists);
            } else
                alpha2= alphaMax;
            }
        else {
            // ok let's see if we can find a value of alpha that works
            bool foundUpOK = false;
            bool foundDownOK = false;
            Real alphaUp = alpha0, alphaDown = alpha0;
            Real stepSize = (alphaMax-alpha0)/steps;

            for (Size j=0;
                 j<static_cast<Size>(steps) && !foundUpOK && !foundDownOK;
                 ++j) {
                alphaUp = alpha0+j*stepSize;
                foundUpOK=testIfSolutionExists(alphaUp);
                alphaDown = alpha0-j*stepSize;
                foundDownOK=testIfSolutionExists(alphaDown);
            }
            foundOKPoint = foundUpOK || foundDownOK;
            if (!foundOKPoint)
                return false;

            if (foundUpOK) {
                alpha1 = alphaUp;
                alpha2 = FindHighestOK<AlphaFinder>(
                     alpha1,
                     alphaMax,
                     tolerance,
                     *this,
                     &AlphaFinder::testIfSolutionExists);
            } else {
                alpha2 = alphaDown;
                alpha1 = FindLowestOK<AlphaFinder>(
                     alphaMin,
                     alpha2,
                     tolerance,
                    *this,
                     &AlphaFinder::testIfSolutionExists);
            }
        }

        // we have now found alpha1, alpha2 such that solution exists
        // at endpoints. we now want to minimize within that interval
        bool failed;
        alpha =  Minimize<AlphaFinder>(
                                        alpha1,
                                        alpha2,
                                        tolerance,
                                        *this,
                                        &AlphaFinder::homogeneityfailure,
                                        &AlphaFinder::testIfSolutionExists,
                                        failed) ;

        finalPart(alpha,
                  stepindex,
                  ratetwohomogeneousvols,
                  computeQuadraticPart(alpha),
                  computeLinearPart(alpha),
                  constantPart_,
                  alpha,
                  a,
                  b,
                  ratetwovols);

        return true;;
    }
}


text:
package org.apache.sling.auth.core.impl.engine;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.sling.auth.core.impl.AbstractAuthenticationHandlerHolder;
import org.apache.sling.auth.core.spi.AuthenticationFeedbackHandler;
import org.apache.sling.auth.core.spi.AuthenticationInfo;
import org.apache.sling.engine.auth.AuthenticationHandler;
import org.osgi.framework.ServiceReference;

/**
 * The EngineAuthenticationHandlerHolder class represents an
 * old-style Sling {@link AuthenticationHandler} service in the internal data
 * structure of the
 * {@link org.apache.sling.auth.core.impl.SlingAuthenticator}.
 */
@SuppressWarnings("deprecation")
public final class EngineAuthenticationHandlerHolder extends
        AbstractAuthenticationHandlerHolder {

    // the actual authentication handler
    private final AuthenticationHandler handler;

    public EngineAuthenticationHandlerHolder(final String fullPath,
            final AuthenticationHandler handler,
            final ServiceReference serviceReference) {
        super(fullPath, serviceReference);
        this.handler = handler;
    }

    @Override
    protected AuthenticationFeedbackHandler getFeedbackHandler() {
        if (handler instanceof AuthenticationFeedbackHandler) {
            return (AuthenticationFeedbackHandler) handler;
        }
        return null;
    }

    public AuthenticationInfo doExtractCredentials(HttpServletRequest request,
            HttpServletResponse response) {

        org.apache.sling.engine.auth.AuthenticationInfo engineAuthInfo = handler.authenticate(
            request, response);
        if (engineAuthInfo == null) {
            return null;
        } else if (engineAuthInfo == org.apache.sling.engine.auth.AuthenticationInfo.DOING_AUTH) {
            return AuthenticationInfo.DOING_AUTH;
        }

        // backwards compatibility support for JCR credentials and workspace
        // name now encapsulated in the JCR Resource bundle
        AuthenticationInfo info = new AuthenticationInfo(
            engineAuthInfo.getAuthType());
        info.put("user.jcr.credentials", engineAuthInfo.getCredentials());
        info.put("user.jcr.workspace", engineAuthInfo.getWorkspaceName());

        return info;
    }

    public boolean doRequestCredentials(HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        return handler.requestAuthentication(request, response);
    }

    public void doDropCredentials(HttpServletRequest request,
            HttpServletResponse response) {
        // Engine AuthenticationHandler does not have this method
    }

    @Override
    public boolean equals(Object obj) {

        // equality is the base class equality (based on the fullpath)
        // and the encapsulated holders being the same.
        if (super.equals(obj)) {
            if (obj.getClass() == getClass()) {
                EngineAuthenticationHandlerHolder other = (EngineAuthenticationHandlerHolder) obj;
                return other.handler == handler;
            }
        }

        // handlers are not the same, so the holders are not the same
        return false;
    }

    @Override
    public String toString() {
        return handler.toString() + " (Legacy API Handler)";
    }

}


text:
Crash versus Byzantine Fault Tolerance

Leader Based Systems

Voting Based Systems

Gossip Protocol

Gossip about Gossip

Gossip Period


text:
class AddLimitToImage < ActiveRecord::Migration[4.2]

  def up
    change_column :gend_images, :image, :binary, limit: 16.megabytes
    change_column :gend_thumbs, :image, :binary, limit: 16.megabytes
    change_column :src_images, :image, :binary, limit: 16.megabytes
    change_column :src_thumbs, :image, :binary, limit: 16.megabytes
  end

  def down
    raise ActiveRecord::IrreversibleMigration, 'Reducing the limit of binary columns can cause data loss'
  end

end


text:
<template>

A component which has documentation, and examples

</template>


text:
import { ToModelConverter } from './converter.js';
import { ASTToModel, ToModelConvertableASTNode, ConvertToModelOptions } from './types.js';

/**
 * @group Convert AST to Model
 * @beta
 */
export function toModel<T extends ToModelConvertableASTNode>(ast: T, options?: ConvertToModelOptions): ASTToModel<T> {
  return new ToModelConverter(options).convert(ast);
}


text:
using System;
using Antlr4.Runtime.Misc;
using Antlr4.Runtime.Sharpen;
using Antlr4.Runtime.Tree.Pattern;

namespace Antlr4.Runtime.Tree.Pattern
{
    /// Represents a placeholder tag in a tree pattern.
    /// <remarks>
    /// Represents a placeholder tag in a tree pattern. A tag can have any of the
    /// following forms.
    ///

    ///

    /// <c>expr</c>
    /// : An unlabeled placeholder for a parser rule
    /// <c>expr</c>
    /// .

    ///

    /// <c>ID</c>
    /// : An unlabeled placeholder for a token of type
    /// <c>ID</c>
    /// .

    ///

    /// <c>e:expr</c>
    /// : A labeled placeholder for a parser rule
    /// <c>expr</c>
    /// .

    ///

    /// <c>id:ID</c>
    /// : A labeled placeholder for a token of type
    /// <c>ID</c>
    /// .

    ///

    /// This class does not perform any validation on the tag or label names aside
    /// from ensuring that the tag is a non-null, non-empty string.
    /// </remarks>
    internal class TagChunk : Chunk
    {
        ///
        /// This is the backing field for
        /// <see cref="Tag()"/>
        /// .
        ///
        private readonly string tag;

        ///
        /// This is the backing field for
        /// <see cref="Label()"/>
        /// .
        ///
        private readonly string label;

        ///
        /// Construct a new instance of
        /// <see cref="TagChunk"/>
        /// using the specified tag and
        /// no label.
        ///
        /// <param name="tag">
        /// The tag, which should be the name of a parser rule or token
        /// type.
        /// </param>
        /// <exception>
        /// IllegalArgumentException
        /// if
        /// <paramref name="tag"/>
        /// is
        /// <see langword="null"/>
        /// or
        /// empty.
        /// </exception>
        public TagChunk(string tag)
            : this(null, tag)
        {
        }

        ///
        /// Construct a new instance of
        /// <see cref="TagChunk"/>
        /// using the specified label
        /// and tag.
        ///
        /// <param name="label">
        /// The label for the tag. If this is
        /// <see langword="null"/>
        /// , the
        /// <see cref="TagChunk"/>
        /// represents an unlabeled tag.
        /// </param>
        /// <param name="tag">
        /// The tag, which should be the name of a parser rule or token
        /// type.
        /// </param>
        /// <exception>
        /// IllegalArgumentException
        /// if
        /// <paramref name="tag"/>
        /// is
        /// <see langword="null"/>
        /// or
        /// empty.
        /// </exception>
        public TagChunk(string label, string tag)
        {
            if (string.IsNullOrEmpty(tag))
            {
                throw new ArgumentException("tag cannot be null or empty");
            }
            this.label = label;
            this.tag = tag;
        }

        /// Get the tag for this chunk.
        /// <remarks>Get the tag for this chunk.</remarks>
        /// <returns>The tag for the chunk.</returns>
        [NotNull]
        public string Tag
        {
            get
            {
                return tag;
            }
        }

        /// Get the label, if any, assigned to this chunk.
        /// <remarks>Get the label, if any, assigned to this chunk.</remarks>
        /// <returns>
        /// The label assigned to this chunk, or
        /// <see langword="null"/>
        /// if no label is
        /// assigned to the chunk.
        /// </returns>
        [Nullable]
        public string Label
        {
            get
            {
                return label;
            }
        }

        /// This method returns a text representation of the tag chunk.
        /// <remarks>
        /// This method returns a text representation of the tag chunk. Labeled tags
        /// are returned in the form
        /// <c>label:tag</c>
        /// , and unlabeled tags are
        /// returned as just the tag name.
        /// </remarks>
        public override string ToString()
        {
            if (label != null)
            {
                return label + ":" + tag;
            }
            return tag;
        }
    }
}


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports System.Composition
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.RemoveUnnecessaryParentheses
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax

Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessaryParentheses
    <ExportCodeFixProvider(LanguageNames.VisualBasic), [Shared]>
    Friend Class VisualBasicRemoveUnnecessaryParenthesesCodeFixProvider
        Inherits AbstractRemoveUnnecessaryParenthesesCodeFixProvider(Of ParenthesizedExpressionSyntax)

        <ImportingConstructor>
        Public Sub New()
        End Sub

        Protected Overrides Function CanRemoveParentheses(current As ParenthesizedExpressionSyntax, semanticModel As SemanticModel) As Boolean
            Return VisualBasicRemoveUnnecessaryParenthesesDiagnosticAnalyzer.CanRemoveParenthesesHelper(
                current, semanticModel, precedence:=Nothing, clarifiesPrecedence:=Nothing)
        End Function
    End Class
End Namespace


text:
/* globals -$ */
"use strict";

// Add classes to an element based on its current location relative to top and
// or bottom offsets.
// Useful for affixing an element on the page within a certain vertical range.
// Based largely off of the bootstrap affix plugin
// https://github.com/twbs/bootstrap/blob/master/js/affix.js
(function ($) {
    var Affix = function (element, options) {
        this.options = $.extend({}, $.fn.wymAffix.defaults, options);
        this.$window = $(window);

        this.$window.bind(
            'scroll.affix.data-api',
            $.proxy(this.checkPosition, this)
        );
        this.$window.bind(
            'click.affix.data-api',
            $.proxy(
                function () {
                    setTimeout(
                        $.proxy(this.checkPosition, this),
                        1
                    );
                },
                this
            )
        );
        this.$element = $(element);
        this.checkPosition();
    };

    Affix.prototype.checkPosition = function () {
        if (!this.$element.is(':visible')) {
            return;
        }

        var scrollTop = this.$window.scrollTop()
          , offset = this.options.offset
          , offsetBottom = offset.bottom
          , offsetTop = offset.top
          , reset = 'affix affix-top affix-bottom'
          , desiredAffixType
          , isBelowTop = true
          , isAboveBottom = true;

        if (typeof offset !== 'object') {
            offsetBottom = offsetTop = offset;
        }
        if (typeof offsetTop === 'function') {
            offsetTop = offset.top();
        }
        if (typeof offsetBottom === 'function') {
            offsetBottom = offset.bottom();
        }

        if (offsetTop !== null) {
            isBelowTop = scrollTop > offsetTop;
        }
        if (offsetBottom !== null) {
            isAboveBottom = scrollTop + this.$element.height() < offsetBottom;
        }

        if (isBelowTop && isAboveBottom) {
            desiredAffixType = 'affix';
        } else if (isAboveBottom === false) {
            // We're below the bottom offset
            desiredAffixType = 'affix-bottom';
        } else {
            desiredAffixType = 'affix-top';
        }

        if (this.currentAffixType === desiredAffixType) {
            // We're already properly-affixed. No changes required.
            return;
        }

        this.$element.removeClass(reset).addClass(desiredAffixType);

        this.currentAffixType = desiredAffixType;
    };

 /* AFFIX PLUGIN DEFINITION
  * ======================= */

    $.fn.wymAffix = function (option) {
        return this.each(function () {
            var $this = $(this)
                , data = $this.data('affix')
                , options = typeof option === 'object' && option;

            if (!data) {
                $this.data(
                    'affix',
                    (data = new Affix(this, options))
                );
            }
            if (typeof option === 'string') {
                data[option]();
            }
        });
    };

    $.fn.wymAffix.Constructor = Affix;

    $.fn.wymAffix.defaults = {
        offset: 0
    };
}(jQuery));

WYMeditor.SKINS.seamless = {
    OPTS: {
        iframeHtml: [""
        , '
'
            , ''
            , ''
        , '
'
        ].join(""),
        // After Iframe initialization, check if we're ready to perform the
        // first resize every this many ms
        initIframeCheckFrequency: 50
    },
    init: function (wym) {
        var This = WYMeditor.SKINS.seamless;

        wym.seamlessSkinOpts = {
            initIframeCheckFrequency: This.initIframeCheckFrequency,
            initialIframeResizeTimer: null
        };
        This.initUIChrome(wym);

        // The Iframe isn't initialized at this point, so we'll need to wait
        // until it is before attempting to use it.
        jQuery(wym._element).bind(
            WYMeditor.EVENTS.postIframeInitialization,
            This.postIframeInit
        );
    },
    postIframeInit: function (e, wym) {
        var This = WYMeditor.SKINS.seamless;

        // Perform an initial resize, if necessary
        This.resizeIframeOnceBodyExists(wym);

        // Detect possible Block creation so that we can always keep the iframe
        // properly resized and the current container in view
        jQuery(wym._element).bind(
            WYMeditor.EVENTS.postBlockMaybeCreated,
            This.resizeAndScrollIfNeeded
        );
    },
    initUIChrome: function (wym) {
        // Initialize the toolbar and classes/containers selectors

        // The classes and containers sections are dropdowns to the right of
        // the toolbar at the top
        var This = WYMeditor.SKINS.seamless,
            $dropdowns = jQuery(
            [
                wym._options.containersSelector
                , wym._options.classesSelector
            ].join(', '),
            wym._box
        ),
            $toolbar,
            $areaTop;

        $areaTop = jQuery("div.wym_area_top", wym._box);

        $dropdowns.appendTo($areaTop);
        $dropdowns.addClass("wym_dropdown");
        $dropdowns.css({
            "margin-right": "10px",
            "width": "120px",
            "float": "left"
        });
        // Make dropdowns also work on click, for mobile devices
        jQuery(".wym_dropdown", wym._box).click(
            function () {
                jQuery(this).toggleClass("hover");
            }
        );

        // The toolbar uses buttons
        $toolbar = jQuery(wym._options.toolsSelector, wym._box);
        $toolbar.addClass("wym_buttons");
        $toolbar.css({"margin-right": "10px", "float": "left"});

        This.affixTopControls(wym);

    },
    affixTopControls: function (wym) {
        // Affix the top area, which contains the toolbar and containers, to
        // the top of the screen so that we can see it, even if we're scrolled
        // down.
        var $areaTop,
            $offsetWrapper,
            earlyScrollPixels = 5,
            usePlaceholderWidth,
            $placeholder;

        $areaTop = jQuery("div.wym_area_top", wym._box);

        // Use a wrapper so we can keep the toolbar styling consistent
        $offsetWrapper = jQuery(
            '
'
        );
        $areaTop.wrap($offsetWrapper);
        $offsetWrapper = $areaTop.parent();

        // Add another, non-affixed wrapper to stick around and hold vertical
        // space. This avoids the "jump" when the toolbar switches to being
        // affixed
        $offsetWrapper.wrap('
');
        $placeholder = $offsetWrapper.parent();
        $placeholder.height($areaTop.height());

        usePlaceholderWidth = function () {
            // Hard-code the offsetWrapper width so that when this floats to
            // the top, it doesn't expand to take up all of the room to the
            // right
            $offsetWrapper.width($placeholder.width());
        };
        usePlaceholderWidth();
        jQuery(window).resize(usePlaceholderWidth);

        $offsetWrapper.wymAffix({
            offset: {
                top: function () {
                    return $placeholder.offset().top - earlyScrollPixels;
                },
                bottom: function () {
                    return $placeholder.offset().top +
                        wym.seamlessSkinIframeHeight;
                }
            }
        });
    },
    resizeIframeOnceBodyExists: function (wym) {
        // In IE, the wym._doc DOMLoaded event doesn't mean the iframe will
        // actually have a body. We need to wait until the body actually exists
        // before trying to set the initial hight of the iframe, so we hack
        // this together with setTimeout.
        var This = WYMeditor.SKINS.seamless,
            scrollHeightCalcFix;

        if (wym.seamlessSkinOpts.initialIframeResizeTimer) {
            // We're handling a timer, clear it
            window.clearTimeout(
                wym.seamlessSkinOpts.initialIframeResizeTimer
            );
            wym.seamlessSkinOpts.initialIframeResizeTimer = null;
        }

        if (typeof wym._doc.body === "undefined" || wym._doc.body === null) {
            // Body isn't ready
            wym.seamlessSkinOpts.initialIframeResizeTimer = window.setTimeout(
                function () {
                    This.resizeIframeOnceBodyExists(wym);
                },
                wym.seamlessSkinOpts.initIframeCheckFrequency
            );
            return;
        }
        // The body is ready, so let's get to resizing
        // For some reason, at least IE7 requires at least one access to the
        // scrollHeight before it gives a real value. I was unable to find any
        // kind of feature detection that would work here and the fix of adding
        // an extra access here doesn't have any real negative impact on the
        // other browsers, but does fix IE7's behavior.
        scrollHeightCalcFix = wym._doc.body.scrollHeight;
        This.resizeIframe(wym);
    },
    resizeIframe: function (wym) {
        var desiredHeight,
            $innerDoc,
            $iframe = jQuery(wym._iframe),
            currentHeight = $iframe.height(),
            iframeHtmlHeight;

        if (typeof WYMeditor.BODY_SCROLLHEIGHT_MISMATCH === "undefined") {
            // For some browsers (IE8+ and FF), the scrollHeight of the body
            // doesn't seem to include the top and bottom margins of the body
            // relative to the HTML. This leaves the editing "window" smaller
            // than required, which results in weird overlaps at the start/end.
            // For those browsers, the HTML element's scrollHeight is more
            // reliable.
            // Let's detect which kind of browser we're dealing with one time
            // so we can just do the right thing in the future.
            desiredHeight = wym._doc.body.scrollHeight;

            $innerDoc = jQuery(wym._doc);
            iframeHtmlHeight = $innerDoc.children()[0].scrollHeight;

            if (iframeHtmlHeight > desiredHeight) {
                // We use greater than because IE7 starts with an
                // iframeHtmlHeight smaller than its body
                WYMeditor.BODY_SCROLLHEIGHT_MISMATCH = true;
            } else {
                WYMeditor.BODY_SCROLLHEIGHT_MISMATCH = false;
            }
        }

        if (WYMeditor.BODY_SCROLLHEIGHT_MISMATCH === true) {
            $innerDoc = jQuery(wym._doc);
            desiredHeight = $innerDoc.children()[0].scrollHeight;
        } else {
            desiredHeight = wym._doc.body.scrollHeight;
        }

        if (currentHeight !== desiredHeight) {
            $iframe.height(desiredHeight);
            wym.seamlessSkinIframeHeight = desiredHeight;
            return true;
        }
        return false;
    },
    scrollIfNeeded: function (wym) {
        var iframeOffset = jQuery(wym._iframe).offset(),
            iframeOffsetTop = iframeOffset.top,
            $container = jQuery(wym.selected()),
            containerOffset = $container.offset(),
            viewportLowestY,
            containerLowestY,
            newScrollTop,
            extraScroll = 20,
            scrollDiff,
            $window = jQuery(window),
            $body = jQuery(document.body);

        containerLowestY = iframeOffsetTop + containerOffset.top;
        containerLowestY += $container.outerHeight();
        viewportLowestY = $window.scrollTop() + $window.height();
        scrollDiff = containerLowestY - viewportLowestY;
        if (scrollDiff > 0) {
            // Part of our selected container isn't
            // visible, so we need to scroll down.
            newScrollTop = $body.scrollTop() + scrollDiff + extraScroll;
            $body.scrollTop(newScrollTop);
        }
    },
    resizeAndScrollIfNeeded: function (e, wym) {
        // Scroll the page so that our current selection
        // within the iframe is actually in view.
        var This = WYMeditor.SKINS.seamless,
            resizeOccurred = This.resizeIframe(wym);
        if (resizeOccurred !== true) {
            return;
        }
        This.scrollIfNeeded(wym);
    }
};


text:
{-# LANGUAGE ScopedTypeVariables #-}
{-# OPTIONS_GHC -Wno-orphans #-}
module HaskellCI.Prelude (
    module Prelude.Compat,
    module X,
    module HaskellCI.Prelude,
    ) where

import Prelude.Compat hiding (head, tail)

import Algebra.Lattice         as X (BoundedJoinSemiLattice (..), BoundedLattice, BoundedMeetSemiLattice (..), Lattice (..))
import Control.Applicative     as X (liftA2, (<|>))
import Control.Exception       as X (Exception (..), IOException, handle)
import Control.Monad           as X (ap, unless, void, when)
import Control.Monad.Catch     as X (MonadCatch, MonadMask, MonadThrow)
import Control.Monad.IO.Class  as X (MonadIO (..))
import Data.Bifoldable         as X (Bifoldable (..))
import Data.Bifunctor          as X (Bifunctor (..))
import Data.Binary             as X (Binary)
import Data.Bitraversable      as X (Bitraversable (..), bifoldMapDefault, bimapDefault)
import Data.ByteString         as X (ByteString)
import Data.Char               as X (isSpace, isUpper, toLower)
import Data.Coerce             as X (coerce)
import Data.Either             as X (partitionEithers)
import Data.Foldable           as X (for_, toList, traverse_)
import Data.Foldable.WithIndex as X (ifoldr)
import Data.Function           as X (on)
import Data.Functor.Compat     as X ((<&>))
import Data.Functor.Identity   as X (Identity (..))
import Data.List               as X (foldl', intercalate, isPrefixOf, nub, stripPrefix, tails)
import Data.List.NonEmpty      as X (NonEmpty (..), groupBy)
import Data.Maybe              as X (fromMaybe, isJust, isNothing, mapMaybe)
import Data.Proxy              as X (Proxy (..))
import Data.Set                as X (Set)
import Data.String             as X (IsString (fromString))
import Data.Text               as X (Text)
import Data.Typeable           as X (Typeable)
import Data.Void               as X (Void)
import GHC.Generics            as X (Generic)
import Network.URI             as X (URI, parseURI, uriToString)
import Text.Read               as X (readMaybe)

import Data.Generics.Lens.Lite  as X (field)
import Distribution.Compat.Lens as X (over, toListOf, (&), (.~), (^.))

import Distribution.Parsec  as X (simpleParsec)
import Distribution.Pretty  as X (prettyShow)
import Distribution.Version as X (Version, VersionRange, anyVersion, mkVersion, noVersion)

import qualified Distribution.Version as C

import Data.Functor.WithIndex.Instances ()

-------------------------------------------------------------------------------
-- Extras
-------------------------------------------------------------------------------

mapped :: forall f a b. Functor f => (a -> Identity b) -> f a -> Identity (f b)
mapped = coerce (fmap :: (a -> b) -> f a -> f b)

head :: NonEmpty a -> a
head (x :| _) = x

-- $setup
-- >>> import Text.Read (readMaybe)

-- | Return the part after the first argument
--
-- >>> afterInfix "BAR" "FOOBAR XYZZY"
-- Just " XYZZY"
--
afterInfix :: Eq a => [a] -> [a] -> Maybe [a]
afterInfix needle haystack = findMaybe (afterPrefix needle) (tails haystack)

-- |
--
-- >>> afterPrefix "FOO" "FOOBAR"
-- Just "BAR"
--
afterPrefix :: Eq a => [a] -> [a] -> Maybe [a]
afterPrefix needle haystack
    | needle `isPrefixOf` haystack = Just (drop (length needle) haystack)
    | otherwise                    = Nothing

-- |
--
-- >>> findMaybe readMaybe ["foo", "1", "bar"] :: Maybe Int
-- Just 1
--
findMaybe :: (a -> Maybe b) -> [a] -> Maybe b
findMaybe f = foldr (\a b -> f a <|> b) Nothing

-- | Whether two ranges are equivalent.
equivVersionRanges :: C.VersionRange -> C.VersionRange -> Bool
equivVersionRanges = on (==) C.asVersionIntervals

-------------------------------------------------------------------------------
-- Orphans
-------------------------------------------------------------------------------

instance Lattice VersionRange where
    (/\) = C.intersectVersionRanges
    (\/) = C.unionVersionRanges


text:
title: "About me"
layout: page
path: "/about"
---

# About me

## My Motivation

The internet was imagined as a global network of information shared and enriched by millions of people.
The internet of today contrasts drastically from this open and accessible web of knowledge. Massive global organisations like Google, Facebook and Amazon (the Tripoly) control over 70% of the internet traffic. They effectively wrap users in their cocoon of services and sell an 'improved' experience of the internet.

I work for a web that is open, accessible by all, and in which every voice has it's place.
I strive to keep the internet inclusive and weird, rather than a streamlined consumer experience of the corporate giants. The web is a medium for artistic expression and voicing ideas - a virtual channel to connect people around the world.

I refuse to work in certain domains which I think exploit the internet users through channels imposed by the monopolies imposed by the Tripoly. These areas are advertisment technology, and financial technology.

I support grassroot projects, NGOs, cooperatives, artists, Open-source projects, small to medium-sized companies and institutions which make resources available to the public, like universities working towards the Open Access pubication scheme.

Don't hesitate to contact me to get to know more!
___

## References

> "I worked with Pitt at FriendNGo, where he was the CTO and Backend developer, and I can say it was one of the best coworkers I could ever wish for.
He's an excellent team player, always thinking about 'us' before 'I' and is highly skilled on the technical side. He's a easy fit for any team that wants to succeed together, easily manages to position himself in situations of conflict and find a solution that works for both sides with the vision of the best interest of the project in mind.
*Also if you have a chance, don't hesitate to go climbing with him! he's one of the best I have ever seen"
 - Guilherme Lisboa, Senior Mobile Developer @ Techbanx

>"It was a real pleasure working with Pitt. He did an exceptional job on the recent project, creative, intelligent, hardworking and passionate. Always takes care of the job. He is very talented at his work and he is always ready to help and support his team. He is a good listener, great team player, a great asset to any team. I highly recommend Pitt."
 - Rafik Hammad, ETL Developer @ Altitude Sports

>"As a teammate at Altitude-sports, I had the opportunity to appreciate Pitt's abilities to deliver high quality and well-documented code. He is a very dedicated and volunteer Developer, always willing to pick up new challenges, as well as an attentive and responsive team player."
 - Thomas Ragot, Back-end Web Developer @ Altitude Sports

> "Pitt and I had the pleasure of working together to redesign a client's online presence and build new landing pages. Pitt is fantastic to work with; focussed on the problem at hand with a wealth of tools at his disposal to write easily readable and usable code. Pitt is a great in a team, not afraid to take responsibility and easy to get along with."
 - Jonathan Riise, Research Engineer/EngD Studentin robotics and NDE


text:
package sinalgo.tools.storage;

/**
 * Thrown by the linked list implementation upon failure.
 */
@SuppressWarnings("serial")
public class DoublyLinkedListErrorException extends Exception {

	/**
	 * Thrown by the linked list implementation upon failure.
	 * @param msg Description of the reason for this exception.
	 */
	public DoublyLinkedListErrorException(String msg) {
		super(msg);
	}

	/**
	 * Thrown by the linked list implementation upon failure.
	 * @param msg Description of the reason for this exception.
	 * @param e The reason / causing exception for this exception
	 */
	public DoublyLinkedListErrorException(String msg, Throwable e) {
		super(msg, e);
	}
}


text:
require_relative '../lib/the_tvdb'
# For Ruby < 1.9.3, use this instead of require_relative
# require(File.expand_path('../../lib/dish', __FILE__))

#require 'rspec'
require 'rspec/autorun'
require 'webmock/rspec'
require 'vcr'

#VCR config
VCR.configure do |config|
  config.cassette_library_dir = 'spec/fixtures/tvdb_cassettes'
  config.hook_into :webmock
end

TheTvdb.setup do |config|
  config.api_key = '1234567898765432'
end


text:
<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[FromUser]]></FromUserName>
<CreateTime>123456789</CreateTime>
<MsgType><![CDATA[event]]></MsgType>
<Event><![CDATA[VIEW]]></Event>
<EventKey><![CDATA[www.qq.com]]></EventKey>
</xml>


text:
package example.com.coolweather;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.litepal.crud.DataSupport;

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

import example.com.coolweather.db.City;
import example.com.coolweather.db.County;
import example.com.coolweather.db.Province;
import example.com.coolweather.util.Httputil;
import example.com.coolweather.util.Utiltool;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by Adminstrator on 2017/5/5.
 */

public class ChooseAreaFragment extends Fragment {
    public static final int LEVEL_PROVINCE=0;
    public static final int LEVEL_CITY=1;
    public static final int LEVEL_COUNTY=2;
    private List<City> cities;
    private List<County> counties;
    private List<Province> provinces;
    private  City selectcity;
    private TextView textView;
    private Button button;
    private ProgressDialog progressDialog;
    private County selectcounty;
    private Province selectprovince;
    private ListView listView;
    private ArrayAdapter<String> adapter;
    private List<String> datalist=new ArrayList<>();
    private int currentlevel;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.choose_area,container,false);
        textView= (TextView) view.findViewById(R.id.title_text);
        button= (Button) view.findViewById(R.id.back_button);
        listView= (ListView) view.findViewById(R.id.list_view);
        adapter=new ArrayAdapter<>(getContext(),android.R.layout.simple_expandable_list_item_1,datalist);
        listView.setAdapter(adapter);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (currentlevel==LEVEL_PROVINCE){
                    selectprovince=provinces.get(i);
                    queryCities();
                }else if (currentlevel==LEVEL_CITY){
                    selectcity=cities.get(i);
                    queryCounties();
                }else if (currentlevel==LEVEL_COUNTY){
                    selectcounty=counties.get(i);
                    String weather_id=selectcounty.getWeatherid();
                    if (getActivity() instanceof MainActivity) {
                        Intent intent = new Intent(getActivity(), WeatherActivity.class);
                        intent.putExtra("weather_id", weather_id);
                        getActivity().startActivity(intent);
                        getActivity().finish();
                    }else if (getActivity() instanceof WeatherActivity){
                        WeatherActivity weather= (WeatherActivity) getActivity();
                        weather.drawerLayout.closeDrawers();
                        weather.swipeRefresh.setRefreshing(true);
                        weather.sendrequest(weather_id);
                    }
                }
            }
        });
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (currentlevel==LEVEL_COUNTY){
                    queryCities();
                }
                if (currentlevel==LEVEL_CITY){
                    queryProvince();
                }
            }
        });
        queryProvince();
    }
    private void queryCounties(){
        button.setVisibility(View.VISIBLE);
        textView.setText(selectcity.getCityname());
        counties=DataSupport.where("cityid=?",String.valueOf(selectcity.getId())).find(County.class);
        if (counties.size()>0){
            datalist.clear();
            for (County county:counties){
                datalist.add(county.getCountyname());
            }
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            currentlevel=LEVEL_COUNTY;
        }else {
            int provincecode=selectprovince.getProvincecode();
            int citycode=selectcity.getCitycode();
            String address="http://guolin.tech/api/china/"+provincecode+"/"+citycode;
            queryFromservice(address,"county");
        }
    }
    private void queryProvince() {
        textView.setText("中国");
        button.setVisibility(View.GONE);
        provinces= DataSupport.findAll(Province.class);
        if (provinces.size()>0){
            datalist.clear();
            for (Province procince:provinces){
                datalist.add(procince.getProvincename());
            }
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            currentlevel=LEVEL_PROVINCE;
        }else{
            String address="http://guolin.tech/api/china";
            queryFromservice(address,"province");
        }
    }

    private void queryCities() {
        button.setVisibility(View.VISIBLE);
        textView.setText(selectprovince.getProvincename());
        cities=DataSupport.where("proviceid=?", String.valueOf(selectprovince.getId())).find(City.class);
        if (cities.size()>0){
            datalist.clear();
            for (City city:cities){
                datalist.add(city.getCityname());
            }
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            currentlevel=LEVEL_CITY;
        }else {
            int provincecode=selectprovince.getProvincecode();
            String address="http://guolin.tech/api/china/"+provincecode;
            queryFromservice(address,"city");
        }

    }
    private void queryFromservice(String address, final String type){
        showProgressDialog();
        Httputil.sendHttpuriRequest(address, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        closeProgressDialog();
                        Toast.makeText(getContext(),"加载失败...",Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responsetext=response.body().string();
                boolean result=false;
                if ("province".equals(type)){
                    result=Utiltool.handleProvinceResponse(responsetext);
                }else if ("city".equals(type)){
                    result=Utiltool.handleCityResponse(responsetext,selectprovince.getId());
                }else if ("county".equals(type)){
                    result=Utiltool.handleCountyResponse(responsetext,selectcity.getId());
                }
                if (result){
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            closeProgressDialog();
                            if ("province".equals(type)){
                                queryProvince();
                            }else if ("city".equals(type)){
                                queryCities();
                            }else if ("county".equals(type)){
                                queryCounties();
                            }
                        }
                    });

                }
            }
        });
    }

    private void showProgressDialog() {
        if (progressDialog==null) {
            progressDialog = new ProgressDialog(getActivity());
            progressDialog.setMessage("正在加载...");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }
    private void closeProgressDialog(){
        if (progressDialog!=null){
            progressDialog.dismiss();
        }
    }
}


text:
ULL Project. The player sprite will use A* to find the shortest path to the destination. Monsters have not been implemented and they are only aesthetic. Controls:
 - W, A, S, D: Move camera
 - Scroll: Zoom
 - Mouse click: Remove tile contents
 - Mouse click while pressing key 1: Add wall to tile
 - Mouse click while pressing key 2: Move player sprite
 - Mouse click while pressing key 3: Move treasure sprite
 - Mouse click while pressing key 4,5,6,7: Add monster to tile

Menu controls:

 - Top eye button: Track player (currently not working)
 - Vertical bar: Click on any position of the vertical bar to set a simulation speed (0 for step by step)
 - Step by step: Click to run a single step (speed must be 0)
 - Run/Pause: Run/pause simulation (speed must be > 0)
 - Restart
 - Randomize map

 ![](docs/sample.png)

 **Check the video, [docs/ia-coche.mp4](docs/ia-coche.mp4) !**

## Compilation

Make file should be ready to compile on linux and windows. Allegro 5 must be installed, compilation is made with shared libraries. To install on Linux:

```
~$ sudo add-apt-repository ppa:allegro/5.2
~$ sudo apt update

# The core library.
~$ sudo apt install liballegro5-dev

# The addons.
~$ sudo apt install liballegro-acodec5-dev liballegro-audio5-dev \
       liballegro-image5-dev liballegro-dialog5-dev liballegro-ttf5-dev \
       liballegro-physfs5-dev

# Check that it is installed with:
~$ pkg-config --list-all | grep allegro
allegro_ttf-5                  allegro_ttf - Allegro game programming library, TrueType fonts addon
allegro_color-5                allegro_color - Allegro game programming library, colors addon
allegro_dialog-5               allegro_dialog - Allegro game programming library, native dialog addon
allegro_video-5                allegro_video - Allegro game programming library, video player addon
allegro_acodec-5               allegro_acodec - Allegro game programming library, audio codec addon
allegro_main-5                 allegro_main - Allegro game programming library, magic main addon
allegro_font-5                 allegro_font - Allegro game programming library, font addon
allegro_memfile-5              allegro_memfile - Allegro game programming library, memory files addon
allegro_image-5                allegro_image - Allegro game programming library, image I/O addon
allegro-5                      allegro - Allegro game programming library
allegro_physfs-5               allegro_physfs - Allegro game programming library, PhysicsFS addon
allegro_primitives-5           allegro_primitives - Allegro game programming library, primitives addon
allegro_audio-5                allegro_audio - Allegro game programming library, audio addon
```


text:
![alt text](app/assets/images/logo.png)

`Owen Jow, Sagang Wee, Kavi Mehta`

Down to Split is a web application that helps people manage their finances. Users can track the purchases they make, compare expenses to a weekly budget, split costs with their friends, and find the lowest price for an item at nearby stores.

Setup (for new devs!)
---
### Installation (for OS X)
#### Ruby, Rails, and SQLite
You will need Ruby 2.2+, Ruby on Rails 4.2.0, and SQLite 3.

To install RVM and Ruby 2.2:
```
\curl -sSL https://get.rvm.io | bash -s stable --ruby=2.2.4
```

To install Rails 4.2.0:
```
gem install rails -v 4.2.0
```

To install SQLite 3:
Follow the instructions [here](http://www.tutorialspoint.com/sqlite/sqlite_installation.htm).

#### Files and Dependencies
Download the project files. Then `cd` into the newly created `down-to-split` directory:
```
git clone https://github.com/ohjay/down-to-split.git
cd down-to-split
```

Install dependencies:
```ruby
gem install bundler
bundle install
```

### Database Initialization
If you don't have it already, you'll need to install Postgres (yes, the actual application!). Download the appropriate package [here](https://www.postgresql.org/), then follow the steps below in order to create and seed the database:
```ruby
rake db:create
rake db:migrate
rake db:seed
```

### Running the Application
Make sure that Postgres is running on port 5432. Usually, this is as simple as launching the Postgres app that you installed [in the previous section](#database-initialization). On OS X, you should see a little elephant pop up in the status bar if the launch is successful.

Once that's done, you'll want to start the server:
```ruby
rails s # uses the default Rails port (3000)
```

At this point, you should be able to open the website by visiting [localhost:3000](http://127.0.0.1:3000/) in your browser. Congratulations!

License
---
The project is distributed under the terms of the [Apache License](LICENSE).

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


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Create simple website using codeigniter</title>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

                                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> Toggle navigation</button> <a class="navbar-brand" href="<?php echo base_url() ?>">CodeIgniter integration with php excel

<a href="<?php echo base_url()?>index.php/assessment_risk/assessment_risk_controller/excel">  Export Excel

S N	Country code	Country name

    <?php foreach ($rs->result() as $row): ?>

	<?php echo $row->chem_no ?>

    <?php endforeach; ?>


text:
@implementation FLEnumSet

- (id) init {
	self = [super init];
	if(self) {
		_enumValues = [[NSMutableArray alloc] init];
	}
	return self;
}

+ (id) enumSet {
    return FLAutorelease([[[self class] alloc] init]);
}

#if FL_MRC
- (void) dealloc {
	[_enumValues release];
	[super dealloc];
}
#endif

- (NSUInteger) count {
    return [_enumValues count];
}

- (NSUInteger) enumForIndex:(NSUInteger) enumIndex {
    return [[_enumValues objectAtIndex:enumIndex] enumValue];
}

- (NSString*) stringForIndex:(NSUInteger) enumIndex{
    return [[_enumValues objectAtIndex:enumIndex] enumName];
}

- (FLEnumPair*) pairForIndex:(NSUInteger) enumIndex {
    return [_enumValues objectAtIndex:enumIndex];
}

- (BOOL) hasEnum:(NSUInteger) theEnum {
    for(FLEnumPair* pair in _enumValues) {
        if(pair.enumValue == theEnum) {
            return YES;
        }
    }
    return NO;
}

- (BOOL) hasEnumString:(NSString*) theEnumName {
    theEnumName = [theEnumName lowercaseString];
    for(FLEnumPair* pair in _enumValues) {
        if(FLStringsAreEqual(theEnumName, pair.enumName)) {
            return YES;
        }
    }

    return NO;
}

- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id __unsafe_unretained [])buffer count:(NSUInteger)len {
    return [_enumValues countByEnumeratingWithState:state objects:buffer count:len];
}

- (void) addEnum:(NSInteger) theEnum withName:(NSString*) name {
    [_enumValues addObject:[FLEnumPair enumPair:name enumValue:theEnum]];
}

- (void) removeAllEnums {
    [_enumValues removeAllObjects];
}

@end


text:
package org.onepf.store;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class BillingService extends Service {

    BillingBinder _binder;

    @Override
    public void onCreate() {
        super.onCreate();
        _binder = new BillingBinder(this, ((StoreApplication)getApplication()).getDatabase());
    }

    @Override
    public IBinder onBind(Intent intent) {
        return _binder;
    }
}


text:
package com.agenthun.eseal.utils;

import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

/**
 * This provides methods to help Activities load their UI.
 */
public class ActivityUtils {

    /**
     * The {@code fragment} is added to the container view with id {@code frameId}. The operation is
     * performed by the {@code fragmentManager}.
     */
    public static void addFragmentToActivity(@NonNull FragmentManager fragmentManager,
                                             @NonNull Fragment fragment, int frameId) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.add(frameId, fragment);
        transaction.commit();
    }

    public static void replaceFragmentToActivity(@NonNull FragmentManager fragmentManager,
                                                 @NonNull Fragment fragment, int frameId) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(frameId, fragment);
        transaction.commit();
    }

}


text:
package javax.crypto;

import java.security.*;
import java.security.spec.*;

import java.nio.ByteBuffer;

/**
 * This class defines the Service Provider Interface (SPI)
 * for the Mac class.
 * All the abstract methods in this class must be implemented by each
 * cryptographic service provider who wishes to supply the implementation
 * of a particular MAC algorithm.
 *
 *
 Implementations are free to implement the Cloneable interface.
 *
 * @author Jan Luehe
 *
 * @since 1.4
 */

public abstract class MacSpi {

    /**
     * Constructor for subclasses to call.
     */
    public MacSpi() {}

    /**
     * Returns the length of the MAC in bytes.
     *
     * @return the MAC length in bytes.
     */
    protected abstract int engineGetMacLength();

    /**
     * Initializes the MAC with the given (secret) key and algorithm
     * parameters.
     *
     * @param key the (secret) key.
     * @param params the algorithm parameters.
     *
     * @exception InvalidKeyException if the given key is inappropriate for
     * initializing this MAC.
     * @exception InvalidAlgorithmParameterException if the given algorithm
     * parameters are inappropriate for this MAC.
     */
    protected abstract void engineInit(Key key,
                                       AlgorithmParameterSpec params)
        throws InvalidKeyException, InvalidAlgorithmParameterException ;

    /**
     * Processes the given byte.
     *
     * @param input the input byte to be processed.
     */
    protected abstract void engineUpdate(byte input);

    /**
     * Processes the first len bytes in input,
     * starting at offset inclusive.
     *
     * @param input the input buffer.
     * @param offset the offset in input where the input starts.
     * @param len the number of bytes to process.
     */
    protected abstract void engineUpdate(byte[] input, int offset, int len);

    /**
     * Processes input.remaining() bytes in the ByteBuffer
     * input, starting at input.position().
     * Upon return, the buffer's position will be equal to its limit;
     * its limit will not have changed.
     *
     *
Subclasses should consider overriding this method if they can
     * process ByteBuffers more efficiently than byte arrays.
     *
     * @param input the ByteBuffer
     * @since 1.5
     */
    protected void engineUpdate(ByteBuffer input) {
        if (input.hasRemaining() == false) {
            return;
        }
        if (input.hasArray()) {
            byte[] b = input.array();
            int ofs = input.arrayOffset();
            int pos = input.position();
            int lim = input.limit();
            engineUpdate(b, ofs + pos, lim - pos);
            input.position(lim);
        } else {
            int len = input.remaining();
            byte[] b = new byte[CipherSpi.getTempArraySize(len)];
            while (len > 0) {
                int chunk = Math.min(len, b.length);
                input.get(b, 0, chunk);
                engineUpdate(b, 0, chunk);
                len -= chunk;
            }
        }
    }

    /**
     * Completes the MAC computation and resets the MAC for further use,
     * maintaining the secret key that the MAC was initialized with.
     *
     * @return the MAC result.
     */
    protected abstract byte[] engineDoFinal();

    /**
     * Resets the MAC for further use, maintaining the secret key that the
     * MAC was initialized with.
     */
    protected abstract void engineReset();

    /**
     * Returns a clone if the implementation is cloneable.
     *
     * @return a clone if the implementation is cloneable.
     *
     * @exception CloneNotSupportedException if this is called
     * on an implementation that does not support Cloneable.
     */
    public Object clone() throws CloneNotSupportedException {
        if (this instanceof Cloneable) {
            return super.clone();
        } else {
            throw new CloneNotSupportedException();
        }
    }
}


text:
package commands

import (
	"io/ioutil"
	"testing"

	"github.com/bryanl/doit"
	"github.com/digitalocean/godo"
	"github.com/stretchr/testify/assert"
)

func TestImageActionsGet(t *testing.T) {
	client := &godo.Client{
		ImageActions: &doit.ImageActionsServiceMock{
			GetFn: func(imageID, actionID int) (*godo.Action, *godo.Response, error) {
				assert.Equal(t, imageID, 1)
				assert.Equal(t, actionID, 2)
				return &testAction, nil, nil
			},
		},
	}

	withTestClient(client, func(c *TestConfig) {
		ns := "test"
		c.Set(ns, doit.ArgImageID, 1)
		c.Set(ns, doit.ArgActionID, 2)

		RunImageActionsGet(ns, ioutil.Discard)
	})

}

func TestImageActionsTransfer(t *testing.T) {
	client := &godo.Client{
		ImageActions: &doit.ImageActionsServiceMock{
			TransferFn: func(imageID int, req *godo.ActionRequest) (*godo.Action, *godo.Response, error) {
				assert.Equal(t, imageID, 1)

				region := (*req)["region"]
				assert.Equal(t, region, "dev0")

				return &testAction, nil, nil
			},
		},
	}

	withTestClient(client, func(c *TestConfig) {
		ns := "test"
		c.Set(ns, doit.ArgImageID, 1)
		c.Set(ns, doit.ArgRegionSlug, "dev0")

		RunImageActionsTransfer(ns, ioutil.Discard)
	})
}


text:
<?php

class Aschroder_SMTPPro_Model_Email_Log extends Mage_Core_Model_Abstract
{

    /**
     * Model initialization
     *
     */
    protected function _construct()
    {
        $this->_init('smtppro/email_log');
    }

    /**
     * clean up log table
     *
     * @param int|null $lifetime Lifetime of entries in days
     */
    public function clean($lifetime = null)
    {
        $this->getResource()->clean($lifetime);
        return $this;
    }
}


text:
package com.stabilise.network.protocol;

/**
 * Superinterface for specific packet handlers.
 */
public interface PacketHandler {
    // blank interface
}