text:
// Copyright © 2007 Andreas Gullberg Larsen (angularsen@gmail.com).
// https://github.com/angularsen/UnitsNet
//
// 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.

using System;
using System.Linq;
using System.Reflection;
using UnitsNet.InternalHelpers;
using UnitsNet.Units;
#if WINDOWS_UWP
using Culture = System.String;

#else
using Culture = System.IFormatProvider;

#endif

namespace UnitsNet
{
    /// <summary>
    ///     Convert between units of a quantity, such as converting from meters to centimeters of a given length.
    /// </summary>
    public static class UnitConverter
    {
        private static readonly string QuantityNamespace = typeof(Length).Namespace;
        private static readonly string UnitTypeNamespace = typeof(LengthUnit).Namespace;
        private static readonly Assembly UnitsNetAssembly = typeof(Length).GetAssembly();

        /// <summary>
        ///     Convert between any two quantity units by their names, such as converting a "Length" of N "Meter" to "Centimeter".
        ///     This is particularly useful for creating things like a generated unit conversion UI,
        ///     where you list some selectors:
        ///     a) Quantity: Length, Mass, Force etc.
        ///     b) From unit: Meter, Centimeter etc if Length is selected
        ///     c) To unit: Meter, Centimeter etc if Length is selected
        /// </summary>
        /// <param name="fromValue">
        ///     Input value, which together with <paramref name="fromUnit" /> represents the quantity to
        ///     convert from.
        /// </param>
        /// <param name="quantityName">
        ///     Name of quantity, such as "Length" and "Mass". <see cref="QuantityType" /> for all
        ///     values.
        /// </param>
        /// <param name="fromUnit">
        ///     Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as
        ///     <paramref name="quantityName" />.
        /// </param>
        /// <param name="toUnit">
        ///     Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as
        ///     <paramref name="quantityName" />.
        /// </param>
        /// <example>double centimeters = ConvertByName(5, "Length", "Meter", "Centimeter"); // 500</example>
        /// <returns>Output value as the result of converting to <paramref name="toUnit" />.</returns>
        /// <exception cref="UnitNotFoundException">No units match the abbreviation.</exception>
        /// <exception cref="AmbiguousUnitParseException">More than one unit matches the abbrevation.</exception>
        public static double ConvertByName(double fromValue, string quantityName, string fromUnit, string toUnit)
        {
            Type quantityType = GetQuantityType(quantityName);
            Type unitType = GetUnitType(quantityName);

            object fromUnitValue = ParseUnit(unitType, fromUnit); // ex: LengthUnit.Meter
            object toUnitValue = ParseUnit(unitType, toUnit); // ex: LengthUnit.Centimeter

            MethodInfo fromMethod = GetStaticFromMethod(quantityType, unitType); // ex: UnitsNet.Length.From(double inputValue, LengthUnit inputUnit)
            object fromResult = fromMethod.Invoke(null, new[] {fromValue, fromUnitValue}); // ex: Length quantity = UnitsNet.Length.From(5, LengthUnit.Meter)

            MethodInfo asMethod = GetAsMethod(quantityType, unitType); // ex: quantity.As(LengthUnit outputUnit)
            object asResult = asMethod.Invoke(fromResult, new[] {toUnitValue}); // ex: double outputValue = quantity.As(LengthUnit.Centimeter)

            return (double) asResult;
        }

        /// <summary>
        ///     Convert between any two quantity units by their names, such as converting a "Length" of N "Meter" to "Centimeter".
        ///     This is particularly useful for creating things like a generated unit conversion UI,
        ///     where you list some selectors:
        ///     a) Quantity: Length, Mass, Force etc.
        ///     b) From unit: Meter, Centimeter etc if Length is selected
        ///     c) To unit: Meter, Centimeter etc if Length is selected
        /// </summary>
        /// <param name="inputValue">
        ///     Input value, which together with <paramref name="fromUnit" /> represents the quantity to
        ///     convert from.
        /// </param>
        /// <param name="quantityName">
        ///     Name of quantity, such as "Length" and "Mass". <see cref="QuantityType" /> for all
        ///     values.
        /// </param>
        /// <param name="fromUnit">
        ///     Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as
        ///     <paramref name="quantityName" />.
        /// </param>
        /// <param name="toUnit">
        ///     Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as
        ///     <paramref name="quantityName" />.
        /// </param>
        /// <param name="result">Result if conversion was successful, 0 if not.</param>
        /// <example>bool ok = TryConvertByName(5, "Length", "Meter", "Centimeter", out double centimeters); // 500</example>
        /// <returns>True if conversion was successful.</returns>
        public static bool TryConvertByName(double inputValue, string quantityName, string fromUnit, string toUnit, out double result)
        {
            try
            {
                // TODO Reimplement to avoid exceptions where possible, as Try methods are generally recommended for performance and this is cheating
                // https://msdn.microsoft.com/en-us/library/ms229009(v=vs.100).aspx
                result = ConvertByName(inputValue, quantityName, fromUnit, toUnit);
                return true;
            }
            catch
            {
                result = 0;
                return false;
            }
        }

        /// <summary>
        ///     Convert between any two quantity units by their abbreviations, such as converting a "Length" of N "m" to "cm".
        ///     This is particularly useful for creating things like a generated unit conversion UI,
        ///     where you list some selectors:
        ///     a) Quantity: Length, Mass, Force etc.
        ///     b) From unit: Meter, Centimeter etc if Length is selected
        ///     c) To unit: Meter, Centimeter etc if Length is selected
        /// </summary>
        /// <param name="fromValue">
        ///     Input value, which together with <paramref name="fromUnitAbbrev" /> represents the quantity to
        ///     convert from.
        /// </param>
        /// <param name="quantityName">
        ///     Name of quantity, such as "Length" and "Mass". <see cref="QuantityType" /> for all
        ///     values.
        /// </param>
        /// <param name="fromUnitAbbrev">
        ///     Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as
        ///     <paramref name="quantityName" />.
        /// </param>
        /// <param name="toUnitAbbrev">
        ///     Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as
        ///     <paramref name="quantityName" />.
        /// </param>
        /// <example>double centimeters = ConvertByName(5, "Length", "m", "cm"); // 500</example>
        /// <returns>Output value as the result of converting to <paramref name="toUnitAbbrev" />.</returns>
        public static double ConvertByAbbreviation(double fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev)
        {
            // WindowsRuntimeComponent does not support default values on public methods
            // ReSharper disable once IntroduceOptionalParameters.Global
            return ConvertByAbbreviation(fromValue, quantityName, fromUnitAbbrev, toUnitAbbrev, null);
        }

        /// <summary>
        ///     Convert between any two quantity units by their abbreviations, such as converting a "Length" of N "m" to "cm".
        ///     This is particularly useful for creating things like a generated unit conversion UI,
        ///     where you list some selectors:
        ///     a) Quantity: Length, Mass, Force etc.
        ///     b) From unit: Meter, Centimeter etc if Length is selected
        ///     c) To unit: Meter, Centimeter etc if Length is selected
        /// </summary>
        /// <param name="fromValue">
        ///     Input value, which together with <paramref name="fromUnitAbbrev" /> represents the quantity to
        ///     convert from.
        /// </param>
        /// <param name="quantityName">
        ///     Name of quantity, such as "Length" and "Mass". <see cref="QuantityType" /> for all
        ///     values.
        /// </param>
        /// <param name="fromUnitAbbrev">
        ///     Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as
        ///     <paramref name="quantityName" />.
        /// </param>
        /// <param name="toUnitAbbrev">
        ///     Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as
        ///     <paramref name="quantityName" />.
        /// </param>
        /// <param name="culture">Culture to parse abbreviations with.</param>
        /// <example>double centimeters = ConvertByName(5, "Length", "m", "cm"); // 500</example>
        /// <returns>Output value as the result of converting to <paramref name="toUnitAbbrev" />.</returns>
        /// <exception cref="QuantityNotFoundException">No quantity types match the <paramref name="quantityName"/>.</exception>
        /// <exception cref="UnitNotFoundException">No unit types match the prefix of <paramref name="quantityName"/> or no units are mapped to the abbreviation.</exception>
        /// <exception cref="AmbiguousUnitParseException">More than one unit matches the abbrevation.</exception>
        public static double ConvertByAbbreviation(double fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev, string culture)
        {
            Type quantityType = GetQuantityType(quantityName);
            Type unitType = GetUnitType(quantityName);

            UnitSystem unitSystem = UnitSystem.GetCached(culture);
            object fromUnitValue = unitSystem.Parse(fromUnitAbbrev, unitType); // ex: ("m", LengthUnit) => LengthUnit.Meter
            object toUnitValue = unitSystem.Parse(toUnitAbbrev, unitType); // ex:("cm", LengthUnit) => LengthUnit.Centimeter

            MethodInfo fromMethod = GetStaticFromMethod(quantityType, unitType); // ex: UnitsNet.Length.From(double inputValue, LengthUnit inputUnit)
            object fromResult = fromMethod.Invoke(null, new[] {fromValue, fromUnitValue}); // ex: Length quantity = UnitsNet.Length.From(5, LengthUnit.Meter)

            MethodInfo asMethod = GetAsMethod(quantityType, unitType); // ex: quantity.As(LengthUnit outputUnit)
            object asResult = asMethod.Invoke(fromResult, new[] {toUnitValue}); // ex: double outputValue = quantity.As(LengthUnit.Centimeter)

            return (double) asResult;
        }

        /// <summary>
        ///     Convert between any two quantity units by their abbreviations, such as converting a "Length" of N "m" to "cm".
        ///     This is particularly useful for creating things like a generated unit conversion UI,
        ///     where you list some selectors:
        ///     a) Quantity: Length, Mass, Force etc.
        ///     b) From unit: Meter, Centimeter etc if Length is selected
        ///     c) To unit: Meter, Centimeter etc if Length is selected
        /// </summary>
        /// <param name="fromValue">
        ///     Input value, which together with <paramref name="fromUnitAbbrev" /> represents the quantity to
        ///     convert from.
        /// </param>
        /// <param name="quantityName">
        ///     Name of quantity, such as "Length" and "Mass". <see cref="QuantityType" /> for all
        ///     values.
        /// </param>
        /// <param name="fromUnitAbbrev">
        ///     Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as
        ///     <paramref name="quantityName" />.
        /// </param>
        /// <param name="toUnitAbbrev">
        ///     Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as
        ///     <paramref name="quantityName" />.
        /// </param>
        /// <param name="result">Result if conversion was successful, 0 if not.</param>
        /// <example>double centimeters = ConvertByName(5, "Length", "m", "cm"); // 500</example>
        /// <returns>True if conversion was successful.</returns>
        public static bool TryConvertByAbbreviation(double fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev, out double result)
        {
            return TryConvertByAbbreviation(fromValue, quantityName, fromUnitAbbrev, toUnitAbbrev, out result, null);
        }

        /// <summary>
        ///     Convert between any two quantity units by their abbreviations, such as converting a "Length" of N "m" to "cm".
        ///     This is particularly useful for creating things like a generated unit conversion UI,
        ///     where you list some selectors:
        ///     a) Quantity: Length, Mass, Force etc.
        ///     b) From unit: Meter, Centimeter etc if Length is selected
        ///     c) To unit: Meter, Centimeter etc if Length is selected
        /// </summary>
        /// <param name="fromValue">
        ///     Input value, which together with <paramref name="fromUnitAbbrev" /> represents the quantity to
        ///     convert from.
        /// </param>
        /// <param name="quantityName">
        ///     Name of quantity, such as "Length" and "Mass". <see cref="QuantityType" /> for all
        ///     values.
        /// </param>
        /// <param name="fromUnitAbbrev">
        ///     Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as
        ///     <paramref name="quantityName" />.
        /// </param>
        /// <param name="toUnitAbbrev">
        ///     Name of unit, such as "Meter" or "Centimeter" if "Length" was passed as
        ///     <paramref name="quantityName" />.
        /// </param>
        /// <param name="culture">Culture to parse abbreviations with.</param>
        /// <param name="result">Result if conversion was successful, 0 if not.</param>
        /// <example>double centimeters = ConvertByName(5, "Length", "m", "cm"); // 500</example>
        /// <returns>True if conversion was successful.</returns>
        public static bool TryConvertByAbbreviation(double fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev, out double result,
            string culture)
        {
            try
            {
                // TODO Reimplement to avoid exceptions where possible, as Try methods are generally recommended for performance and this is cheating
                // https://msdn.microsoft.com/en-us/library/ms229009(v=vs.100).aspx
                result = ConvertByAbbreviation(fromValue, quantityName, fromUnitAbbrev, toUnitAbbrev, culture);
                return true;
            }
            catch
            {
                result = 0;
                return false;
            }
        }

        private static MethodInfo GetAsMethod(Type quantityType, Type unitType)
        {
            // Only a single As() method as of this writing, but let's safe-guard a bit for future-proofing
            // ex: double result = quantity.As(LengthUnit outputUnit);
            return quantityType.GetDeclaredMethods()
                .Single(m => m.Name == "As" &&
                             !m.IsStatic &&
                             m.IsPublic &&
                             HasParameterTypes(m, unitType) &&
                             m.ReturnType == typeof(double));
        }

        private static MethodInfo GetStaticFromMethod(Type quantityType, Type unitType)
        {
            // Want to match: Length l = UnitsNet.Length.From(double inputValue, LengthUnit inputUnit)
            // Do NOT match : Length? UnitsNet.Length.From(double? inputValue, LengthUnit inputUnit)
            return quantityType.GetDeclaredMethods()
                .Single(m => m.Name == "From" &&
                             m.IsStatic &&
                             m.IsPublic &&
                             HasParameterTypes(m, typeof(double), unitType) &&
                             m.ReturnType == quantityType);
        }

        private static bool HasParameterTypes(MethodInfo methodInfo, params Type[] expectedTypes)
        {
            ParameterInfo[] parameters = methodInfo.GetParameters();
            if (parameters.Length != expectedTypes.Length)
                throw new ArgumentException($"The number of parameters {parameters.Length} did not match the number of types {expectedTypes.Length}.");

            for (var i = 0; i < parameters.Length; i++)
            {
                ParameterInfo p = parameters[i];
                Type t = expectedTypes[i];
                if (p.ParameterType != t)
                    return false;
            }

            return true;
        }

        /// <summary>
        ///     Parse a unit by the unit enum type <paramref name="unitType" /> and a unit enum value <paramref name="unitName" />>
        /// </summary>
        /// <param name="unitType">Unit type, such as <see cref="LengthUnit" />.</param>
        /// <param name="unitName">Unit name, such as "Meter" corresponding to <see cref="LengthUnit.Meter" />.</param>
        /// <returns>Unit enum value, such as <see cref="LengthUnit.Meter" /> boxed as an object.</returns>
        /// <exception cref="UnitNotFoundException">No unit values match the <paramref name="unitName" />.</exception>
        private static object ParseUnit(Type unitType, string unitName)
        {
            object unitValue; // ex: LengthUnit.Meter
            try
            {
                unitValue = Enum.Parse(unitType, unitName);
            }
            catch (Exception e)
            {
                var e2 = new UnitNotFoundException($"Unit not found [{unitName}].", e);
                e2.Data["unitName"] = unitName;
                throw e2;
            }
            return unitValue;
        }

        private static Type GetUnitType(string quantityName)
        {
            string unitTypeName = $"{UnitTypeNamespace}.{quantityName}Unit";
            Type unitType = UnitsNetAssembly.GetType(unitTypeName); // ex: UnitsNet.Units.LengthUnit enum
            if (unitType == null)
                throw new UnitNotFoundException($"Unit type name not found: {unitTypeName}");
            return unitType;
        }

        private static Type GetQuantityType(string quantityName)
        {
            string quantityTypeName = $"{QuantityNamespace}.{quantityName}";
            Type quantityType = UnitsNetAssembly.GetType(quantityTypeName); // ex: UnitsNet.Length struct
            if (quantityType == null)
                throw new QuantityNotFoundException($"Quantity type name not found: {quantityTypeName}");
            return quantityType;
        }
    }
}


text:
package fr.acinq.eclair.payment

import akka.actor.FSM.{CurrentState, SubscribeTransitionCallBack, Transition}
import akka.testkit.{TestActorRef, TestProbe}
import fr.acinq.bitcoin.scalacompat.ByteVector32
import fr.acinq.eclair.payment.receive.MultiPartPaymentFSM
import fr.acinq.eclair.payment.receive.MultiPartPaymentFSM._
import fr.acinq.eclair.wire.protocol
import fr.acinq.eclair.wire.protocol.{IncorrectOrUnknownPaymentDetails, UpdateAddHtlc}
import fr.acinq.eclair.{BlockHeight, CltvExpiry, MilliSatoshi, MilliSatoshiLong, NodeParams, TestConstants, TestKitBaseClass, randomBytes32}
import org.scalatest.funsuite.AnyFunSuiteLike
import scodec.bits.ByteVector

import scala.collection.immutable.Queue
import scala.concurrent.duration._

/**
 * Created by t-bast on 18/07/2019.
 */

class MultiPartPaymentFSMSpec extends TestKitBaseClass with AnyFunSuiteLike {

  import MultiPartPaymentFSMSpec._

  case class FixtureParam(nodeParams: NodeParams, handler: TestActorRef[MultiPartPaymentFSM], parent: TestProbe, eventListener: TestProbe) {
    def currentBlockHeight: BlockHeight = nodeParams.currentBlockHeight
  }

  def createFixture(paymentTimeout: FiniteDuration, totalAmount: MilliSatoshi): FixtureParam = {
    val parent = TestProbe()
    val nodeParams = TestConstants.Alice.nodeParams.copy(multiPartPaymentExpiry = paymentTimeout)
    val handler = TestActorRef[MultiPartPaymentFSM](props(nodeParams, paymentHash, totalAmount, parent.ref))
    val eventListener = TestProbe()
    system.eventStream.subscribe(eventListener.ref, classOf[PaymentEvent])
    FixtureParam(nodeParams, handler, parent, eventListener)
  }

  test("timeout waiting for first htlc") {
    val f = createFixture(2 seconds, 1000 msat)
    val monitor = TestProbe()
    f.handler ! SubscribeTransitionCallBack(monitor.ref)

    val CurrentState(_, WAITING_FOR_HTLC) = monitor.expectMsgClass(classOf[CurrentState[_]])
    val Transition(_, WAITING_FOR_HTLC, PAYMENT_FAILED) = monitor.expectMsgClass(classOf[Transition[_]])

    f.parent.expectMsg(MultiPartPaymentFailed(paymentHash, protocol.PaymentTimeout, Queue.empty))
    f.parent.expectNoMessage(50 millis)
    f.eventListener.expectNoMessage(50 millis)
  }

  test("timeout waiting for more htlcs") {
    val f = createFixture(250 millis, 1000 msat)
    val parts = Seq(
      createMultiPartHtlc(1000 msat, 150 msat, 1),
      createMultiPartHtlc(1000 msat, 100 msat, 2)
    )
    parts.foreach(p => f.parent.send(f.handler, p))

    val fail = f.parent.expectMsgType[MultiPartPaymentFailed]
    assert(fail.paymentHash == paymentHash)
    assert(fail.failure == protocol.PaymentTimeout)
    assert(fail.parts.toSet == parts.toSet)

    f.parent.expectNoMessage(50 millis)
    f.eventListener.expectNoMessage(50 millis)
  }

  test("receive additional htlcs after timeout") {
    val f = createFixture(250 millis, 1000 msat)
    f.parent.send(f.handler, createMultiPartHtlc(1000 msat, 150 msat, 1))
    f.parent.send(f.handler, createMultiPartHtlc(1000 msat, 100 msat, 2))
    assert(f.parent.expectMsgType[MultiPartPaymentFailed].parts.length == 2)

    val extraPart = createMultiPartHtlc(1000 msat, 300 msat, 3)
    f.parent.send(f.handler, extraPart)
    val fail = f.parent.expectMsgType[ExtraPaymentReceived[PaymentPart]]
    assert(fail.paymentHash == paymentHash)
    assert(fail.failure == Some(protocol.PaymentTimeout))
    assert(fail.payment == extraPart)

    f.parent.expectNoMessage(50 millis)
    f.eventListener.expectNoMessage(50 millis)
  }

  test("fail all if total amount is not consistent") {
    val f = createFixture(250 millis, 1000 msat)
    f.parent.send(f.handler, createMultiPartHtlc(1000 msat, 600 msat, 1))
    f.parent.send(f.handler, createMultiPartHtlc(1100 msat, 650 msat, 2))
    val fail = f.parent.expectMsgType[MultiPartPaymentFailed]
    assert(fail.paymentHash == paymentHash)
    assert(fail.failure == IncorrectOrUnknownPaymentDetails(1100 msat, f.currentBlockHeight))
    assert(fail.parts.length == 2)

    f.parent.expectNoMessage(50 millis)
    f.eventListener.expectNoMessage(50 millis)
  }

  test("fulfill all when total amount reached") {
    val f = createFixture(10 seconds, 1000 msat)
    val parts = Seq(
      createMultiPartHtlc(1000 msat, 300 msat, 1),
      createMultiPartHtlc(1000 msat, 340 msat, 2),
      createMultiPartHtlc(1000 msat, 360 msat, 3)
    )
    parts.foreach(p => f.parent.send(f.handler, p))

    val paymentResult = f.parent.expectMsgType[MultiPartPaymentSucceeded]
    assert(paymentResult.paymentHash == paymentHash)
    assert(paymentResult.parts.toSet == parts.toSet)
    f.parent.expectNoMessage(50 millis)
    f.eventListener.expectNoMessage(50 millis)
  }

  test("fulfill all with amount higher than total amount") {
    val f = createFixture(10 seconds, 1000 msat)
    val parts = Seq(
      createMultiPartHtlc(1000 msat, 300 msat, 1),
      createMultiPartHtlc(1000 msat, 340 msat, 2),
      createMultiPartHtlc(1000 msat, 400 msat, 3)
    )
    parts.foreach(p => f.parent.send(f.handler, p))

    val paymentResult = f.parent.expectMsgType[MultiPartPaymentSucceeded]
    assert(paymentResult.paymentHash == paymentHash)
    assert(paymentResult.parts.toSet == parts.toSet)

    f.parent.expectNoMessage(50 millis)
    f.eventListener.expectNoMessage(50 millis)
  }

  test("fulfill all with single htlc") {
    val f = createFixture(10 seconds, 1000 msat)
    val part = createMultiPartHtlc(1000 msat, 1000 msat, 1)
    f.parent.send(f.handler, part)

    val paymentResult = f.parent.expectMsgType[MultiPartPaymentSucceeded]
    assert(paymentResult.parts == Seq(part))

    f.parent.expectNoMessage(50 millis)
    f.eventListener.expectNoMessage(50 millis)
  }

  test("fulfill all with single htlc and amount higher than total amount") {
    val f = createFixture(10 seconds, 1000 msat)
    val part = createMultiPartHtlc(1000 msat, 1100 msat, 1)
    f.parent.send(f.handler, part)

    val paymentResult = f.parent.expectMsgType[MultiPartPaymentSucceeded]
    assert(paymentResult.parts == Seq(part))

    f.parent.expectNoMessage(50 millis)
    f.eventListener.expectNoMessage(50 millis)
  }

  test("receive additional htlcs after total amount reached") {
    val f = createFixture(10 seconds, 1000 msat)

    val parts = Seq(
      createMultiPartHtlc(1000 msat, 600 msat, 1),
      createMultiPartHtlc(1000 msat, 400 msat, 2)
    )
    parts.foreach(p => f.parent.send(f.handler, p))
    val paymentResult = f.parent.expectMsgType[MultiPartPaymentSucceeded]
    assert(paymentResult.parts.toSet == parts.toSet)
    f.parent.expectNoMessage(50 millis)

    val extra = createMultiPartHtlc(1000 msat, 300 msat, 3)
    f.parent.send(f.handler, extra)
    val extraneousPayment = f.parent.expectMsgType[ExtraPaymentReceived[PaymentPart]]
    assert(extraneousPayment.paymentHash == paymentHash)
    assert(extraneousPayment.payment == extra)

    f.parent.expectNoMessage(50 millis)
    f.eventListener.expectNoMessage(50 millis)
  }

  test("actor restart") {
    val f = createFixture(10 seconds, 1000 msat)
    val parts = Seq(
      createMultiPartHtlc(1000 msat, 600 msat, 1),
      createMultiPartHtlc(1000 msat, 400 msat, 2)
    )
    f.parent.send(f.handler, parts.head)

    f.handler.suspend()
    f.handler.resume(new IllegalArgumentException("something went wrong"))

    f.parent.send(f.handler, parts(1))
    val paymentResult = f.parent.expectMsgType[MultiPartPaymentSucceeded]
    assert(paymentResult.paymentHash == paymentHash)
    assert(paymentResult.parts.toSet == parts.toSet)
    f.parent.expectNoMessage(50 millis)
  }

  test("unknown message") {
    val f = createFixture(10 seconds, 1000 msat)
    val parts = Seq(
      createMultiPartHtlc(1000 msat, 600 msat, 1),
      createMultiPartHtlc(1000 msat, 400 msat, 2)
    )
    f.parent.send(f.handler, parts.head)
    f.parent.send(f.handler, "hello")
    f.parent.send(f.handler, parts(1))

    val paymentResult = f.parent.expectMsgType[MultiPartPaymentSucceeded]
    assert(paymentResult.parts.toSet == parts.toSet)
    f.parent.expectNoMessage(50 millis)
  }

}

object MultiPartPaymentFSMSpec {

  val paymentHash = randomBytes32()

  def htlcIdToChannelId(htlcId: Long) = ByteVector32(ByteVector.fromLong(htlcId).padLeft(32))

  def createMultiPartHtlc(totalAmount: MilliSatoshi, htlcAmount: MilliSatoshi, htlcId: Long): HtlcPart = {
    val htlc = UpdateAddHtlc(htlcIdToChannelId(htlcId), htlcId, htlcAmount, paymentHash, CltvExpiry(42), TestConstants.emptyOnionPacket, None)
    HtlcPart(totalAmount, htlc)
  }

}

redpajama_set_name: RedPajamaGithub


text:
namespace TemplateWebApi.Web.Api.Models.TemplateViewModels
{
    using Data.Models;
    using Infrastructure.Mappings;

    public class TemplateResponseViewModel : IMapFrom<Template>
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public string Text { get; set; }
    }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#include "pal_types.h"

#include <openssl/bio.h>

/*
Creates a new memory-backed BIO instance.
*/
extern "C" BIO* CryptoNative_CreateMemoryBio();

/*
Direct shim to BIO_new_file.
*/
extern "C" BIO* CryptoNative_BioNewFile(const char* filename, const char* mode);

/*
Cleans up and deletes a BIO instance.

Implemented by:
1) Calling BIO_free

No-op if a is null.
The given BIO pointer is invalid after this call.
*/
extern "C" int32_t CryptoNative_BioDestroy(BIO* a);

/*
Direct shim to BIO_gets.
*/
extern "C" int32_t CryptoNative_BioGets(BIO* b, char* buf, int32_t size);

/*
Direct shim to BIO_read.
*/
extern "C" int32_t CryptoNative_BioRead(BIO* b, void* buf, int32_t len);

/*
Direct shim to BIO_write.
*/
extern "C" int32_t CryptoNative_BioWrite(BIO* b, const void* buf, int32_t len);

/*
Gets the size of data available in the BIO.

Shims the BIO_get_mem_data method.
*/
extern "C" int32_t CryptoNative_GetMemoryBioSize(BIO* bio);

/*
Shims the BIO_ctrl_pending method.

Returns the number of pending characters in the BIOs read and write buffers.
*/
extern "C" int32_t CryptoNative_BioCtrlPending(BIO* bio);


text:
package com.starquestminecraft.sqtechenergy;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import org.bukkit.block.BlockFace;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;

import com.sqtechenergy.objects.AdvancedGenerator;
import com.sqtechenergy.objects.BasicGenerator;
import com.sqtechenergy.objects.BioGenerator;
import com.sqtechenergy.objects.Charger;
import com.sqtechenergy.objects.Fuel;
import com.sqtechenergy.objects.PowerCauldron;
import com.sqtechenergy.objects.RedstoneGenerator;
import com.sqtechenergy.objects.SolarPanel;
import com.sqtechenergy.objects.SteamEngine;
import com.sqtechenergy.objects.WaterTurbine;
import com.starquestminecraft.sqtechbase.SQTechBase;
import com.starquestminecraft.sqtechenergy.tasks.ChargerTask;
import com.starquestminecraft.sqtechenergy.tasks.GeneratorTask;

public class SQTechEnergy extends JavaPlugin{

	public final Logger logger = Logger.getLogger("Minecraft");
	static SQTechEnergy plugin;

	public static FileConfiguration config = null;

	public static List<Fuel> fuels = new ArrayList<Fuel>();

	boolean enabled = false;

	@Override
	public void onEnable() {

		plugin = this;

		PluginDescriptionFile pdfFile = this.getDescription();
		this.logger.info(pdfFile.getName() + " has been enabled!");

		if (!new File(this.getDataFolder(), "config.yml").exists()) {

			saveDefaultConfig();
			saveConfig();

		}

		config = getConfig();

		//Basic generator fuels
		for (String fuel : config.getConfigurationSection("basic generator.fuel").getKeys(false)) {

			String path = "basic generator.fuel." + fuel;

			Fuel fuelObject = new Fuel();

			String[] split = config.getString(path + ".id").split(":");

			if (split.length == 1) {

				fuelObject.id = Integer.parseInt(split[0]);
				fuelObject.data = (short) 0;

			} else {

				fuelObject.id = Integer.parseInt(split[0]);
				fuelObject.data = Short.parseShort(split[1]);

			}

			fuelObject.energyPerTick = config.getInt(path + ".energy per tick");
			fuelObject.burnTime = config.getInt(path + ".burn time");
			fuelObject.generator = "Basic Generator";

			fuels.add(fuelObject);

		}

		//Advanced Generator fuels
		for (String fuel : config.getConfigurationSection("advanced generator.fuel").getKeys(false)) {

			String path = "advanced generator.fuel." + fuel;

			Fuel fuelObject = new Fuel();

			String[] split = config.getString(path + ".id").split(":");

			if (split.length == 1) {

				fuelObject.id = Integer.parseInt(split[0]);
				fuelObject.data = (short) 0;

			} else {

				fuelObject.id = Integer.parseInt(split[0]);
				fuelObject.data = Short.parseShort(split[1]);

			}

			fuelObject.energyPerTick = config.getInt(path + ".energy per tick");
			fuelObject.burnTime = config.getInt(path + ".burn time");
			fuelObject.generator = "Advanced Generator";

			fuels.add(fuelObject);

		}

		//Bio Generator fuels
		for (String fuel : config.getConfigurationSection("bio generator.fuel").getKeys(false)) {

			String path = "bio generator.fuel." + fuel;

			Fuel fuelObject = new Fuel();

			String[] split = config.getString(path + ".id").split(":");

			if (split.length == 1) {

				fuelObject.id = Integer.parseInt(split[0]);
				fuelObject.data = (short) 0;

			} else {

				fuelObject.id = Integer.parseInt(split[0]);
				fuelObject.data = Short.parseShort(split[1]);

			}

			fuelObject.energyPerTick = config.getInt(path + ".energy per tick");
			fuelObject.burnTime = config.getInt(path + ".burn time");
			fuelObject.generator = "Bio Generator";

			fuels.add(fuelObject);

		}

		//Redstone Generator fuels
		for (String fuel : config.getConfigurationSection("redstone generator.fuel").getKeys(false)) {

			String path = "redstone generator.fuel." + fuel;

			Fuel fuelObject = new Fuel();

			String[] split = config.getString(path + ".id").split(":");

			if (split.length == 1) {

				fuelObject.id = Integer.parseInt(split[0]);
				fuelObject.data = (short) 0;

			} else {

				fuelObject.id = Integer.parseInt(split[0]);
				fuelObject.data = Short.parseShort(split[1]);

			}

			fuelObject.energyPerTick = config.getInt(path + ".energy per tick");
			fuelObject.burnTime = config.getInt(path + ".burn time");
			fuelObject.generator = "Redstone Generator";

			fuels.add(fuelObject);

		}

		//Steam Engine fuels
		for (String fuel : config.getConfigurationSection("steam engine.fuel").getKeys(false)) {

			String path = "steam engine.fuel." + fuel;

			Fuel fuelObject = new Fuel();

			String[] split = config.getString(path + ".id").split(":");

			if (split.length == 1) {

				fuelObject.id = Integer.parseInt(split[0]);
				fuelObject.data = (short) 0;

			} else {

				fuelObject.id = Integer.parseInt(split[0]);
				fuelObject.data = Short.parseShort(split[1]);

			}

			fuelObject.energyPerTick = config.getInt(path + ".energy per tick");
			fuelObject.burnTime = config.getInt(path + ".burn time");
			fuelObject.generator = "Steam Engine";

			fuels.add(fuelObject);

		}

		SQTechBase.addMachineType(new BasicGenerator());
		SQTechBase.addMachineType(new AdvancedGenerator());
		SQTechBase.addMachineType(new BioGenerator());
		SQTechBase.addMachineType(new RedstoneGenerator());
		SQTechBase.addMachineType(new SolarPanel());
		SQTechBase.addMachineType(new WaterTurbine());
		SQTechBase.addMachineType(new SteamEngine());
		SQTechBase.addMachineType(new Charger());
		SQTechBase.addMachineType(new PowerCauldron());

		(new GeneratorTask()).run();
		(new ChargerTask()).run();

	}

	@Override
	public void onDisable() {

		PluginDescriptionFile pdfFile = this.getDescription();
		this.logger.info(pdfFile.getName() + " has been disabled!");

		saveDefaultConfig();

	}

	public static SQTechEnergy getPluginMain() {

		return plugin;

	}

	public static BlockFace getOpposite(BlockFace blockFace) {

		switch(blockFace) {

		case NORTH: return BlockFace.SOUTH;
		case WEST: return BlockFace.EAST;
		case SOUTH: return BlockFace.NORTH;
		case EAST: return BlockFace.WEST;
		default: return BlockFace.NORTH;

		}

	}

}


text:
module Ebanx
  module Command
    class TransferCommit < Command
      def initialize(params)
        @params         = params
        @request_method = :post
        @request_action = 'transfer/commit'
        @response_type  = :json
      end

      def validate
        validate_presence_either [:transfer_code, :uid, :external_reference, :settlement_code]
      end
    end
  end
end


text:
import subprocess

from ajenti.api import plugin
from reconfigure.configs import CrontabConfig

@plugin
class CronManager (object):
    def load_tab(self, user):
        self.current_user = user
        try:
            data = subprocess.check_output(['crontab', '-l', '-u', user])
        except Exception:
            data = ''
        config = CrontabConfig(content=data)
        config.load()
        return config

    def save_tab(self, user, config):
        data = config.save()[None]
        p = subprocess.Popen(['crontab', '-', '-u', user])
        stdout, stderr = p.communicate(data + '\n')
        if stderr:
            raise Exception(stderr)


text:
/**
*
* Waiting
*
*/

import React from 'react';

import Icon from 'material-ui/svg-icons/social/people';
import { Flex } from 'react-flex';

import styles from './styles.css';

const iconStyle = {
  height: 46,
  width: 46,
};

const Waiting = () => (
  <Flex
    column
    justifyContent="center"
    className={styles.waiting}
  >
    <Flex>
      <Icon style={iconStyle} />
      <h1 className={styles.text}>
        Waiting for other users to join...
      </h1>
    </Flex>
  </Flex>
);

export default Waiting;


text:
layout: default
title: "Democratic Reform"

---

{% include interests/democratic-reform.md %}

### Who is interested in Democratic Reform?

* [Zac Goldsmith]({{ site.baseurl }}/members/zac-goldsmith.html)
* [Margaret Hodge]({{ site.baseurl }}/members/margaret-hodge.html)


text:
/*
 * |<><><><><><><><><><><><><><><><><><><><><><>|
 * | E-Destroyer McSnake 1325.2 (The Beginning) |
 * |<><><><><><><><><><><><><><><><><><><><><><>|
 *
 *   []-------A game by Tiger Festival-------[]
 */
package items;
import java.awt.Image;
import core.Window;

// TODO: Auto-generated Javadoc
/**
 * The Class LaserBolt.
 */
public class LaserBolt extends Projectile {

   // Construct a new Item segment at given (headX, headY), length and direction.
   /**
    * Instantiates a new laser bolt.
    *
    * @param headX the head x
    * @param headY the head y
    * @param length the length
    * @param direction the direction
    * @param friendlyFire the friendly fire
    * @param damage the damage
    * @param image_U the image_ u
    * @param image_D the image_ d
    * @param image_L the image_ l
    * @param image_R the image_ r
    */
   public LaserBolt(int headX, int headY, int length, Projectile.Direction direction, int friendlyFire, int damage,
		   			Image image_U, Image image_D, Image image_L, Image image_R) {
      super(headX, headY, length, direction, friendlyFire, damage, image_U, image_D, image_L, image_R);
   }

   //**UPDATE method
   /* (non-Javadoc)
    * @see items.Projectile#update()
    */
   @Override
   public void update() //doesn't shrink projectile
   {
	   if (!(Window.contentPane).contains(this.getHeadX(), this.getHeadY())) //if not in pit
	     {
		   //don't grow
	     }
	   else
		   this.grow(); //in pit
   }

   // For debugging.
   /* (non-Javadoc)
    * @see items.Projectile#toString()
    */
   @Override
   public String toString() {
      return "Head at (" + headX + "," + headY + ")" + " to (" + getTailX() + ","
            + getTailY() + ")" + ", length is " + getLength() + ", dir is " + direction;
   }
}


text:
All URIs are relative to *https://demo.looker.com:19999/api/3.0*

Method | HTTP request | Description
------------- | ------------- | -------------
[**accept_integration_hub_legal_agreement**](IntegrationApi.md#accept_integration_hub_legal_agreement) | **POST** /integration_hubs/{integration_hub_id}/accept_legal_agreement | Accept Integration Hub Legal Agreement
[**all_integration_hubs**](IntegrationApi.md#all_integration_hubs) | **GET** /integration_hubs | Get All Integration Hubs
[**all_integrations**](IntegrationApi.md#all_integrations) | **GET** /integrations | Get All Integrations
[**create_integration_hub**](IntegrationApi.md#create_integration_hub) | **POST** /integration_hubs | Create Integration Hub
[**delete_integration_hub**](IntegrationApi.md#delete_integration_hub) | **DELETE** /integration_hubs/{integration_hub_id} | Delete Integration Hub
[**fetch_integration_form**](IntegrationApi.md#fetch_integration_form) | **POST** /integrations/{integration_id}/form | Fetch Remote Integration Form
[**integration**](IntegrationApi.md#integration) | **GET** /integrations/{integration_id} | Get Integration
[**integration_hub**](IntegrationApi.md#integration_hub) | **GET** /integration_hubs/{integration_hub_id} | Get Integration Hub
[**update_integration**](IntegrationApi.md#update_integration) | **PATCH** /integrations/{integration_id} | Update Integration
[**update_integration_hub**](IntegrationApi.md#update_integration_hub) | **PATCH** /integration_hubs/{integration_hub_id} | Update Integration Hub

# **accept_integration_hub_legal_agreement**
> IntegrationHub accept_integration_hub_legal_agreement(integration_hub_id)

Accept Integration Hub Legal Agreement

Accepts the legal agreement for a given integration hub. This only works for integration hubs that have legal_agreement_required set to true and legal_agreement_signed set to false.

### Example
```python
from __future__ import print_statement
import time
import lookerapi
from lookerapi.rest import ApiException
from pprint import pprint

# create an instance of the API class
api_instance = lookerapi.IntegrationApi()
integration_hub_id = 789 # int | Id of integration_hub

try:
    # Accept Integration Hub Legal Agreement
    api_response = api_instance.accept_integration_hub_legal_agreement(integration_hub_id)
    pprint(api_response)
except ApiException as e:
    print("Exception when calling IntegrationApi->accept_integration_hub_legal_agreement: %s\n" % e)
```

### Parameters

Name | Type | Description  | Notes
------------- | ------------- | ------------- | -------------
 **integration_hub_id** | **int**| Id of integration_hub |

### Return type

[**IntegrationHub**](IntegrationHub.md)

### Authorization

No authorization required

### HTTP request headers

 - **Content-Type**: application/json
 - **Accept**: application/json

[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

# **all_integration_hubs**
> list[IntegrationHub] all_integration_hubs(fields=fields)

Get All Integration Hubs

### Get information about all Integration Hubs.

### Example
```python
from __future__ import print_statement
import time
import lookerapi
from lookerapi.rest import ApiException
from pprint import pprint

# create an instance of the API class
api_instance = lookerapi.IntegrationApi()
fields = 'fields_example' # str | Requested fields. (optional)

try:
    # Get All Integration Hubs
    api_response = api_instance.all_integration_hubs(fields=fields)
    pprint(api_response)
except ApiException as e:
    print("Exception when calling IntegrationApi->all_integration_hubs: %s\n" % e)
```

### Parameters

Name | Type | Description  | Notes
------------- | ------------- | ------------- | -------------
 **fields** | **str**| Requested fields. | [optional]

### Return type

[**list[IntegrationHub]**](IntegrationHub.md)

### Authorization

No authorization required

### HTTP request headers

 - **Content-Type**: application/json
 - **Accept**: application/json

[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

# **all_integrations**
> list[Integration] all_integrations(fields=fields, integration_hub_id=integration_hub_id)

Get All Integrations

### Get information about all Integrations.

### Example
```python
from __future__ import print_statement
import time
import lookerapi
from lookerapi.rest import ApiException
from pprint import pprint

# create an instance of the API class
api_instance = lookerapi.IntegrationApi()
fields = 'fields_example' # str | Requested fields. (optional)
integration_hub_id = 'integration_hub_id_example' # str | Filter to a specific provider (optional)

try:
    # Get All Integrations
    api_response = api_instance.all_integrations(fields=fields, integration_hub_id=integration_hub_id)
    pprint(api_response)
except ApiException as e:
    print("Exception when calling IntegrationApi->all_integrations: %s\n" % e)
```

### Parameters

Name | Type | Description  | Notes
------------- | ------------- | ------------- | -------------
 **fields** | **str**| Requested fields. | [optional]
 **integration_hub_id** | **str**| Filter to a specific provider | [optional]

### Return type

[**list[Integration]**](Integration.md)

### Authorization

No authorization required

### HTTP request headers

 - **Content-Type**: application/json
 - **Accept**: application/json

[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

# **create_integration_hub**
> IntegrationHub create_integration_hub(body=body, fields=fields)

Create Integration Hub

### Create a new Integration Hub.

### Example
```python
from __future__ import print_statement
import time
import lookerapi
from lookerapi.rest import ApiException
from pprint import pprint

# create an instance of the API class
api_instance = lookerapi.IntegrationApi()
body = lookerapi.IntegrationHub() # IntegrationHub | Integration Hub (optional)
fields = 'fields_example' # str | Requested fields. (optional)

try:
    # Create Integration Hub
    api_response = api_instance.create_integration_hub(body=body, fields=fields)
    pprint(api_response)
except ApiException as e:
    print("Exception when calling IntegrationApi->create_integration_hub: %s\n" % e)
```

### Parameters

Name | Type | Description  | Notes
------------- | ------------- | ------------- | -------------
 **body** | [**IntegrationHub**](IntegrationHub.md)| Integration Hub | [optional]
 **fields** | **str**| Requested fields. | [optional]

### Return type

[**IntegrationHub**](IntegrationHub.md)

### Authorization

No authorization required

### HTTP request headers

 - **Content-Type**: application/json
 - **Accept**: application/json

[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

# **delete_integration_hub**
> str delete_integration_hub(integration_hub_id)

Delete Integration Hub

### Delete a Integration Hub.

### Example
```python
from __future__ import print_statement
import time
import lookerapi
from lookerapi.rest import ApiException
from pprint import pprint

# create an instance of the API class
api_instance = lookerapi.IntegrationApi()
integration_hub_id = 789 # int | Id of integration_hub

try:
    # Delete Integration Hub
    api_response = api_instance.delete_integration_hub(integration_hub_id)
    pprint(api_response)
except ApiException as e:
    print("Exception when calling IntegrationApi->delete_integration_hub: %s\n" % e)
```

### Parameters

Name | Type | Description  | Notes
------------- | ------------- | ------------- | -------------
 **integration_hub_id** | **int**| Id of integration_hub |

### Return type

**str**

### Authorization

No authorization required

### HTTP request headers

 - **Content-Type**: application/json
 - **Accept**: application/json

[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

# **fetch_integration_form**
> DataActionForm fetch_integration_form(integration_id)

Fetch Remote Integration Form

Returns the Integration form for presentation to the user.

### Example
```python
from __future__ import print_statement
import time
import lookerapi
from lookerapi.rest import ApiException
from pprint import pprint

# create an instance of the API class
api_instance = lookerapi.IntegrationApi()
integration_id = 789 # int | Id of Integration

try:
    # Fetch Remote Integration Form
    api_response = api_instance.fetch_integration_form(integration_id)
    pprint(api_response)
except ApiException as e:
    print("Exception when calling IntegrationApi->fetch_integration_form: %s\n" % e)
```

### Parameters

Name | Type | Description  | Notes
------------- | ------------- | ------------- | -------------
 **integration_id** | **int**| Id of Integration |

### Return type

[**DataActionForm**](DataActionForm.md)

### Authorization

No authorization required

### HTTP request headers

 - **Content-Type**: application/json
 - **Accept**: application/json

[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

# **integration**
> Integration integration(integration_id, fields=fields)

Get Integration

### Get information about a Integration.

### Example
```python
from __future__ import print_statement
import time
import lookerapi
from lookerapi.rest import ApiException
from pprint import pprint

# create an instance of the API class
api_instance = lookerapi.IntegrationApi()
integration_id = 789 # int | Id of Integration
fields = 'fields_example' # str | Requested fields. (optional)

try:
    # Get Integration
    api_response = api_instance.integration(integration_id, fields=fields)
    pprint(api_response)
except ApiException as e:
    print("Exception when calling IntegrationApi->integration: %s\n" % e)
```

### Parameters

Name | Type | Description  | Notes
------------- | ------------- | ------------- | -------------
 **integration_id** | **int**| Id of Integration |
 **fields** | **str**| Requested fields. | [optional]

### Return type

[**Integration**](Integration.md)

### Authorization

No authorization required

### HTTP request headers

 - **Content-Type**: application/json
 - **Accept**: application/json

[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

# **integration_hub**
> IntegrationHub integration_hub(integration_hub_id, fields=fields)

Get Integration Hub

### Get information about a Integration Hub.

### Example
```python
from __future__ import print_statement
import time
import lookerapi
from lookerapi.rest import ApiException
from pprint import pprint

# create an instance of the API class
api_instance = lookerapi.IntegrationApi()
integration_hub_id = 789 # int | Id of Integration Hub
fields = 'fields_example' # str | Requested fields. (optional)

try:
    # Get Integration Hub
    api_response = api_instance.integration_hub(integration_hub_id, fields=fields)
    pprint(api_response)
except ApiException as e:
    print("Exception when calling IntegrationApi->integration_hub: %s\n" % e)
```

### Parameters

Name | Type | Description  | Notes
------------- | ------------- | ------------- | -------------
 **integration_hub_id** | **int**| Id of Integration Hub |
 **fields** | **str**| Requested fields. | [optional]

### Return type

[**IntegrationHub**](IntegrationHub.md)

### Authorization

No authorization required

### HTTP request headers

 - **Content-Type**: application/json
 - **Accept**: application/json

[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

# **update_integration**
> Integration update_integration(integration_id, body, fields=fields)

Update Integration

### Update parameters on a Integration.

### Example
```python
from __future__ import print_statement
import time
import lookerapi
from lookerapi.rest import ApiException
from pprint import pprint

# create an instance of the API class
api_instance = lookerapi.IntegrationApi()
integration_id = 789 # int | Id of Integration
body = lookerapi.Integration() # Integration | Integration
fields = 'fields_example' # str | Requested fields. (optional)

try:
    # Update Integration
    api_response = api_instance.update_integration(integration_id, body, fields=fields)
    pprint(api_response)
except ApiException as e:
    print("Exception when calling IntegrationApi->update_integration: %s\n" % e)
```

### Parameters

Name | Type | Description  | Notes
------------- | ------------- | ------------- | -------------
 **integration_id** | **int**| Id of Integration |
 **body** | [**Integration**](Integration.md)| Integration |
 **fields** | **str**| Requested fields. | [optional]

### Return type

[**Integration**](Integration.md)

### Authorization

No authorization required

### HTTP request headers

 - **Content-Type**: application/json
 - **Accept**: application/json

[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)

# **update_integration_hub**
> IntegrationHub update_integration_hub(integration_hub_id, body, fields=fields)

Update Integration Hub

### Update a Integration Hub definition.

### Example
```python
from __future__ import print_statement
import time
import lookerapi
from lookerapi.rest import ApiException
from pprint import pprint

# create an instance of the API class
api_instance = lookerapi.IntegrationApi()
integration_hub_id = 789 # int | Id of Integration Hub
body = lookerapi.IntegrationHub() # IntegrationHub | Integration Hub
fields = 'fields_example' # str | Requested fields. (optional)

try:
    # Update Integration Hub
    api_response = api_instance.update_integration_hub(integration_hub_id, body, fields=fields)
    pprint(api_response)
except ApiException as e:
    print("Exception when calling IntegrationApi->update_integration_hub: %s\n" % e)
```

### Parameters

Name | Type | Description  | Notes
------------- | ------------- | ------------- | -------------
 **integration_hub_id** | **int**| Id of Integration Hub |
 **body** | [**IntegrationHub**](IntegrationHub.md)| Integration Hub |
 **fields** | **str**| Requested fields. | [optional]

### Return type

[**IntegrationHub**](IntegrationHub.md)

### Authorization

No authorization required

### HTTP request headers

 - **Content-Type**: application/json
 - **Accept**: application/json

[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md)


text:
package com.github.javaparser.symbolsolver;

import com.github.javaparser.ParseException;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.expr.Expression;
import com.github.javaparser.ast.stmt.ExpressionStmt;
import com.github.javaparser.resolution.types.ResolvedType;
import com.github.javaparser.symbolsolver.javaparser.Navigator;
import com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade;
import com.github.javaparser.symbolsolver.model.resolution.TypeSolver;
import com.github.javaparser.symbolsolver.resolution.AbstractResolutionTest;
import com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class Issue116 extends AbstractResolutionTest {

    @Test
    public void arrayTypeIsNotPartOfTheTree() throws ParseException {
        CompilationUnit cu = parseSample("Issue116");
        ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "JavaTest");
        MethodDeclaration methodDeclaration = Navigator.demandMethod(clazz, "foo");
        TypeSolver typeSolver = new ReflectionTypeSolver();
        JavaParserFacade javaParserFacade = JavaParserFacade.get(typeSolver);
        com.github.javaparser.ast.type.Type typeNode = methodDeclaration.getParameters().get(0).getType();
        ResolvedType type = javaParserFacade.convert(typeNode, typeNode);
        assertEquals("java.lang.String[]", type.describe());

        ExpressionStmt expressionStmt = (ExpressionStmt) methodDeclaration.getBody().get().getStatements().get(0);
        Expression argRef = expressionStmt.getExpression();
        assertEquals("java.lang.String[]", javaParserFacade.getType(argRef).describe());
    }
}


text:
var Promise = require('bluebird'),
    fs = require('extfs'),
    _ = require('lodash'),
    utils = require('./utils'),
    path = require('path'),
    file_dir = 'data/ideas/';

var Xray = require('x-ray');
var x = Xray().throttle(1, 5000);

fs.removeSync(file_dir);
fs.mkdirSync(file_dir);

var fetchIdea = function (url) {
    var slug = utils.slugFromUrl(url),
        fileName = file_dir + slug + '.json';
    console.log('fetching', slug);
    fs.exists(fileName, function (exists) {
        if (exists) return;
        console.log('fetching', slug);
        x(url, {
            title: '.wrapper article h1',
            by: '.wrapper article h2',
            content: ['.wrapper article > p@html']
        }).write(fileName);
    });
};

var ideaContentMap = {
    title: '.wrapper article h1',
    by: '.wrapper article h2',
    content: ['.wrapper article > p@html']
}

var getUrlsFromPublications = function (obj, callback) {
    var urls = [];
    if (!utils.hasProperty(obj, 'content')) return urls;
    x(utils.wrapContent(obj.content), ['a@href'])(function (err, links) {
        links.forEach(function (link) {
            if (link.indexOf('ayn-rand-ideas') !== -1) {
                urls.push(link);
            }
        });
    });
    return urls;
};

var fPath = path.join(__dirname) + '/data/publications/';
utils.loadFiles(fPath, '.json')
    .map(require)
    .map(getUrlsFromPublications)
    .filter(_.isArray)
    .then(_.flatten)
    .then(_.uniq)
    .filter(utils.verifyUrl)
    .mapSeries(fetchIdea)
    .then(function () {
        console.log('done');
    })
    .catch(function () {
        console.log('catch', arguments)
    });


text:
<?php
class Model_pemilik extends CI_Model {
	function cek($username)
	{
		$query = "SELECT usernamePemilik FROM pemilik WHERE usernamePemilik = '$username'";
 		$run = $this->db->query($query);
 		return $run->num_rows();
	}

	function daftar($username, $password, $nama, $email, $telepon)
	{
	   $data = array(
	   		'USERNAMEPEMILIK' => $username,
	   		'PASSWORDPEMILIK' => $password,
	   		'NAMAPEMILIK' => $nama,
	   		'EMAILPEMILIK' => $email,
	   		'TELEPONPEMILIK' => $telepon
	   	);

		$run = $this->db->insert('pemilik', $data);
		if($run)
			return "Berhasil";
		else
			return "Gagal";
 	}

 	function login($username, $password)
 	{
 		$query = "SELECT * FROM pemilik p WHERE p.usernamepemilik = '$username' AND p.passwordpemilik = '$password'";
		$run = $this->db->query($query);
		if($run->num_rows() == 1)
			return $run->result();
		else
			return false;
 	}

 	function jumlahPemilik()
 	{
 		$query = "SELECT COUNT(*) as total from pemilik";
 		$run = $this->db->query($query);
 		return $run->result();
 	}

}


text:
<?php defined('BX_DOL') or die('hack attempt');

class BxMailchimpStudioPage extends BxTemplStudioModule
{
    function getHelp ()
    {
        $oModule = BxDolModule::getInstance('bx_mailchimp');
        return _t('_bx_mailchimp_information_block', BX_DOL_URL_ROOT . $oModule->_oConfig->getBaseUri() . 'bulk_add', BX_MAILCHIMP_LIMIT);
    }

    protected function getPageCaptionHelp()
    {
        $oTemplate = BxDolStudioTemplate::getInstance();
        $sContent = '' . _t('_bx_mailchimp_information') . "";
        return $oTemplate->parseHtmlByName('page_caption_help.html', array('content' => $sContent));
    }
}

/** @} */


text:
package io.hekate.partition;

import io.hekate.HekateTestBase;
import io.hekate.cluster.ClusterNode;
import io.hekate.cluster.ClusterTopology;
import org.junit.Test;

import static java.util.Arrays.asList;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

public class UpdatablePartitionMapperTest extends HekateTestBase {
    @Test
    public void testEmpty() {
        UpdatablePartitionMapper mapper = new UpdatablePartitionMapper(16, 2);

        for (int i = 0; i < mapper.partitions(); i++) {
            Partition part = mapper.partition(i);

            assertEquals(i, part.id());
            assertNull(part.primaryNode());
            assertTrue(part.backupNodes().isEmpty());
            assertTrue(part.nodes().isEmpty());
        }
    }

    @Test
    public void testUpdate() throws Exception {
        ClusterNode n1 = newNode();
        ClusterNode n2 = newNode();
        ClusterNode n3 = newNode();

        ClusterTopology topology = ClusterTopology.of(1, toSet(n1, n2, n3));

        UpdatablePartitionMapper mapper = new UpdatablePartitionMapper(16, 2);

        mapper.update(topology, old -> new DefaultPartition(old.id(), n1, asList(n2, n3), topology));

        assertEquals(topology, mapper.topology());

        for (int i = 0; i < mapper.partitions(); i++) {
            Partition part = mapper.partition(i);

            assertEquals(i, part.id());
            assertEquals(n1, part.primaryNode());
            assertEquals(asList(n2, n3), part.backupNodes());
            assertEquals(asList(n1, n2, n3), part.nodes());
            assertEquals(topology, part.topology());
        }
    }
}


text:
package java.lang;
public class NoSuchFieldError extends java.lang.IncompatibleClassChangeError {
	public NoSuchFieldError() { }
	public NoSuchFieldError(java.lang.String var0) { }
}


text:
classifiers = """\
Development Status :: 4 - Beta
Intended Audience :: Developers
License :: OSI Approved :: Apache Software License
Programming Language :: Python :: 2.6
Programming Language :: Python :: 2.7
Programming Language :: Python :: 3.3
Programming Language :: Python :: 3.4
Programming Language :: Python :: 3.5
Topic :: Database
Topic :: Software Development :: Libraries :: Python Modules
Operating System :: Unix
Operating System :: MacOS :: MacOS X
Operating System :: Microsoft :: Windows
Operating System :: POSIX
"""

import os
import platform
import sys
from distutils.core import Command
from distutils.dir_util import mkpath, remove_tree
from distutils.file_util import copy_file

try:
    from setuptools import setup
except ImportError:
    from ez_setup import use_setuptools

    use_setuptools()
    from setuptools import setup

extra_opts = {"test_suite": "tests",
              "tests_require": ["mongo-orchestration>=0.6.7,<1.0",
                                "requests>=2.5.1"]}

if sys.version_info[:2] == (2, 6):
    # Need unittest2 to run unittests in Python 2.6
    extra_opts["tests_require"].append("unittest2")
    extra_opts["test_suite"] = "unittest2.collector"

try:
    with open("README.rst", "r") as fd:
        extra_opts['long_description'] = fd.read()
except IOError:
    pass  # Install without README.rst

class InstallService(Command):
    description = "Installs Mongo Connector as a Linux system daemon"

    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        if platform.system() != 'Linux':
            print("Must be running Linux")
        elif os.geteuid() > 0:
            print("Must be root user")
        else:
            mkpath("/var/log/mongo-connector")
            mkpath("/etc/init.d")
            copy_file("./config.json", "/etc/mongo-connector.json")
            copy_file("./scripts/mongo-connector",
                      "/etc/init.d/mongo-connector")

class UninstallService(Command):
    description = "Uninstalls Mongo Connector as a Linux system daemon"

    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def remove_file(self, path):
        if os.path.exists(path):
            os.remove(path)
            print("removing '%s'" % path)

    def run(self):
        if platform.system() != 'Linux':
            print("Must be running Linux")
        elif os.geteuid() > 0:
            print("Must be root user")
        else:
            if os.path.exists("/var/log/mongo-connector"):
                remove_tree("/var/log/mongo-connector")
            self.remove_file("/etc/mongo-connector.json")
            self.remove_file("/etc/init.d/mongo-connector")

extra_opts['cmdclass'] = {
    "install_service": InstallService,
    "uninstall_service": UninstallService
}

setup(name='mongo-connector',
      version="2.5.2.dev0",
      author="MongoDB, Inc.",
      author_email='mongodb-user@googlegroups.com',
      description='Mongo Connector',
      keywords=['mongo-connector', 'mongo', 'mongodb', 'solr', 'elasticsearch'],
      url='https://github.com/10gen-labs/mongo-connector',
      license="http://www.apache.org/licenses/LICENSE-2.0.html",
      platforms=["any"],
      classifiers=filter(None, classifiers.split("\n")),
      install_requires=['pymongo >= 2.9'],
      packages=["mongo_connector", "mongo_connector.doc_managers"],
      package_data={
          'mongo_connector.doc_managers': ['schema.xml']
      },
      entry_points={
          'console_scripts': [
              'mongo-connector = mongo_connector.connector:main',
          ],
      },
      extras_require={
          "solr": ["solr-doc-manager"],
          "elastic": ["elastic-doc-manager"],
          "elastic-aws": ["elastic-doc-manager[aws]"],
          "elastic2": ["elastic2-doc-manager[elastic2]"],
          "elastic5": ["elastic2-doc-manager[elastic5]"],
          "elastic2-aws": ["elastic2-doc-manager[elastic2,aws]"],
      },
      **extra_opts
      )


text:
<?php
namespace Jasekz\RentalsUnitedCaching\DataLoaders;

use DB;
use Exception;

class PropertyReviews extends Base {

    /**
     * RU API function to call
     *
     * @var string
     */
    protected $ruFunction = 'ListPropertyReviews';

    /**
     * DB table where we'll be caching the data
     *
     * @var string
     */
    protected $table = 'RentalsUnited_PropertyReviews';

    /**
     * Cached file name
     *
     * @var string
     */
    protected $fileName = 'PropertyReviews.xml';

    /**
     * Cache RU data to DB
     *
     * @throws Exception
     * @return void
     */
    public function cacheInDb($propertyID)
    {
        $this->downloadXML($this->fileName, $propertyID);

        try {
            $sql = "delete from {$this->table} where PropID=?;";
            DB::statement($sql, array(
                $propertyID
            ));

            foreach ($this->getFileContents($this->fileName)->Reviews->Review as $record) {

                $sql = "insert into
                            {$this->table}
                            set PropID=?,
                                ReviewID=?,
                                FirstName=?,
                                LastName=?,
                                DisplayName=?,
                                Email=?,
                                Rating=?,
                                ArrivalDate=?,
                                Submitted=?,
                                created_at=?;";
                DB::statement($sql, array(
                    $propertyID,
                    (string) $record->attributes()->ID,
                    (string) $record->FirstName,
                    (string) $record->LastName,
                    (string) $record->DisplayName,
                    (string) $record->Email,
                    (string) $record->Rating,
                    (string) $record->ArrivalDate,
                    (string) $record->Submitted,
                    date('Y-m-d G:i:s')
                ));
            }

            $this->deleteXML($this->fileName);
        }

        catch (Exception $e) {
            throw $e;
        }
    }
}


text:
local skynet = require "skynet"
local socket = require "skynet.socket"
local utils = require "utils"
require "skynet.manager"

local CMD = {}

function CMD.quit(argv)
    if argv[2] == nil then
        skynet.abort()
        return true
    end
    local timeout = tonumber(argv[2])
    if not timeout then
        return false
    end
    skynet.timeout(math.modf(100 * timeout), function()
        skynet.abort()
    end)
    return true
end

function CMD.launch(argv)
    if #argv <= 3 then
        return false
    end
    if argv[2] == "lua" then
        skynet.newservice(argv[3], table.unpack(argv, 4))
    elseif argv[2] == "c" then
        skynet.launch(argv[3], table.unpack(argv, 4))
    else
        return false
    end
    return true
end

local function console_main_loop()
	local stdin = socket.stdin()
	socket.lock(stdin)
	while true do
        local cmdline = socket.readline(stdin, "\n")
        local argv = utils.strsplit(cmdline, ' ')
        if #argv > 0 then
            local c = argv[1]
            local f = CMD[c]
            if f then
                local ret = f(argv)
                if not ret then
                    skynet.error("Command '"..argv[1].."' execute error.")
                else
                    skynet.error("Command '"..argv[1].."' execute success.")
                end
            end
        end
	end
    socket.unlock(stdin)
end

skynet.start(function()
    skynet.fork(console_main_loop)
end)


text:
cask 'utools' do
  version '0.8.9-beta'
  sha256 'f4c206ee440974d1b3386333f28533d603bbfd0a0878f00c6721b74765a1c967'

  # resource.u-tools.cn was verified as official when first introduced to the cask
  url "https://resource.u-tools.cn/currentversion/uTools-#{version}.dmg"
  appcast 'https://resource.u-tools.cn/currentversion/latest-mac.yml'
  name 'uTools'
  homepage 'https://u.tools/index.html'

  auto_updates true
  depends_on macos: '>= :yosemite'

  app 'uTools.app'

  zap trash: [
               '~/Library/Application Support/uTools',
               '~/Library/Logs/uTools',
             ]
end


text:
<?php

ignore_user_abort(true);
set_time_limit(0);

include_once(dirname(__FILE__) . "/../../../modules/database/database.php");
include_once(dirname(__FILE__) . "/../../../modules/crawl/fetchdata.php");
include_once(dirname(__FILE__) . "/../../../modules/utils.php");

$character = array_key_exists("character", $_GET) ? mb_strtolower($_GET['character'], 'UTF-8') : "";
$server = array_key_exists("server", $_GET) ? mb_strtolower($_GET['server'], 'UTF-8') : "";
$region = array_key_exists("region", $_GET) ? mb_strtolower($_GET['region'], 'UTF-8') : "";
$metric = array_key_exists("metric", $_GET) ? (empty($_GET['metric']) ? "" : mb_strtolower($_GET['metric'], 'UTF-8')) : "";
$raid = array_key_exists("raid", $_GET) ? intval($_GET['raid']) : "";

if( empty($character) || empty($server) || empty($region) || empty($raid) ) {
	INTERNAL_SERVER_ERROR();
}

try {
	$db = Database::getInstance();

	if(!$db->is_member($character, $server, $region)) {
		INTERNAL_SERVER_ERROR("Character not found!");
	}

	$total = 0;
	try {
		switch($metric) {
		case Metric::$DPS:
			$data = fetch_character($character, $server, $region, $raid, Metric::$DPS);
			if( $data !== false ) {
				$total += $db->insert_dps_rankings($character, $server, $region, $data);
			}
			break;
		case Metric::$HPS:
			$data = fetch_character($character, $server, $region, $raid, Metric::$HPS);
			if( $data !== false ) {
				$total += $db->insert_hps_rankings($character, $server, $region, $data);
			}
			break;
		case Metric::$KRSI:
			break;
		case "":
			$data = fetch_character($character, $server, $region, $raid, Metric::$DPS);
			if( $data !== false ) {
				$total += $db->insert_dps_rankings($character, $server, $region, $data);
			}
			$data = fetch_character($character, $server, $region, $raid, Metric::$HPS);
			if( $data !== false ) {
				$total += $db->insert_hps_rankings($character, $server, $region, $data);
			}
		default:
		}

	} catch (Exception $e) {
		INTERNAL_SERVER_ERROR("You suck: " . $e->getMessage());
	}

	$db->disconnect();

	$result = array(
		"total" => $total
	);

	SEND_OK($result);

} catch (Exception $e) {
	INTERNAL_SERVER_ERROR("Even harder: " . $e->getMessage());
}

?>


text:
<!DOCTYPE html>

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

    <title>mne.epochs.combine_event_ids — MNE 0.13.1 documentation</title>

    <link rel="stylesheet" href="../_static/basic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../_static/gallery.css" type="text/css" />
    <link rel="stylesheet" href="../_static/bootswatch-3.3.6/flatly/bootstrap.min.css" type="text/css" />
    <link rel="stylesheet" href="../_static/bootstrap-sphinx.css" type="text/css" />
    <link rel="stylesheet" href="../_static/style.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/favicon.ico"/>
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="top" title="MNE 0.13.1 documentation" href="../index.html" />
    <link rel="up" title="Python API Reference" href="../python_reference.html" />
    <link rel="next" title="mne.epochs.equalize_epoch_counts" href="mne.epochs.equalize_epoch_counts.html" />
    <link rel="prev" title="mne.epochs.average_movements" href="mne.epochs.average_movements.html" />

<link href='http://fonts.googleapis.com/css?family=Open+Sans:400italic,700italic,400,700' rel='stylesheet' type='text/css'>

  <link rel="canonical" href="https://mne.tools/stable/index.html" />

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">

        </button>

        0.13.1

Get started

Tutorials

Gallery

API

Manual

FAQ

  Site

Getting started

Tutorials

Examples Gallery

Frequently Asked Questions

Contribute to MNE

Python API Reference

User Manual

What’s new

How to cite MNE

Related publications

Publications from MNE users

  Page

mne.epochs.combine_event_ids

<form class="navbar-form navbar-right" action="../search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

mne.epochs.combine_event_ids

    « mne.epochs.av...

    mne.epochs.eq... »

<form action="../search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

mne.epochs.combine_event_ids¶

mne.epochs.combine_event_ids(epochs, old_event_ids, new_event_id, copy=True)¶

Collapse event_ids from an epochs instance into a new event_id

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

Parameters:
epochs : instance of Epochs

The epochs to operate on.

old_event_ids : str, or list

Conditions to collapse together.

new_event_id : dict, or int

A one-element dict (or a single integer) for the new
condition. Note that for safety, this cannot be any
existing id (in epochs.event_id.values()).

copy : bool

Whether to return a new instance or modify in place.

Notes

This For example (if epochs.event_id was {‘Left’: 1, ‘Right’: 2}:

combine_event_ids(epochs, [‘Left’, ‘Right’], {‘Directional’: 12})

would create a ‘Directional’ entry in epochs.event_id replacing
‘Left’ and ‘Right’ (combining their trials).

      Back to top

        © Copyright 2012-2016, MNE Developers. Last updated on 2016-11-21.


text:
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;

public class Driver {

	public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
		System.out.println("Beginning PageRank Hadoop job");
		long start = System.nanoTime();
		DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		System.out.println(dateFormat.format(new Date()));

		if (args.length < 3) {
			System.out.println("HadoopPageRank Usage: <number_of_vertices> <number_of_iterations> <input_path> [output_path]");
			System.exit(0);
		}

			int amountOfVertices = Integer.parseInt(args[0]);
			int numberOfIterations = Integer.parseInt(args[1]);
			String inputPath = args[2];
			String outputPath = "output_hadoop";

		if (args.length == 4) {
			outputPath = args[3];
		}

		System.out.println("Amount of Vertices: " + amountOfVertices);
		System.out.println("Number of Iterations: " + numberOfIterations);
		System.out.println("Input Path: " + inputPath);
		System.out.println("Initial Output Path: " + outputPath);

		System.out.println("Initial Job");
		Driver.startInitialJob(inputPath, outputPath + "0", amountOfVertices);

		for (int i = 0; i < numberOfIterations; i++) {
			System.out.println("PageRank Job #" + (i + 1));

			Driver.startPageRankJob(
					outputPath + i + "/part-r-*",
					outputPath + (i + 1) + "/",
					amountOfVertices
			);

			FileSystem fs = FileSystem.get(new Configuration());
			fs.delete(new Path(outputPath + i), true);
		}

		double elapsedTimeInSec = (System.nanoTime() - start) * 1.0e-9;
		System.out.println("<" + elapsedTimeInSec + "s> " + dateFormat.format(new Date()));
	}

	/**
	 * Reads the initial Adjacency List and sets the initial PageRank values, i.e. (1 / amountOfOuterEdges).
	 *
	 * @param inputPath
	 * @param outputPath
	 * @param amountOfVertices
	 * @throws IOException
	 * @throws InterruptedException
	 * @throws ClassNotFoundException
	 */
	private static void startInitialJob(String inputPath, String outputPath, int amountOfVertices) throws IOException, InterruptedException, ClassNotFoundException {
		Configuration conf = new Configuration();

		conf.set("AMOUNT_OF_VERTICES", String.valueOf(amountOfVertices));

		Job job = new Job(conf, "Initial Job");

		job.setJarByClass(Driver.class);
		job.setMapperClass(InitialMapper.class);
		job.setReducerClass(InitialReducer.class);

		job.setNumReduceTasks(1);

		job.setOutputKeyClass(LongWritable.class);
		job.setOutputValueClass(Text.class);

		job.setInputFormatClass(KeyValueTextInputFormat.class);
		job.setOutputFormatClass(TextOutputFormat.class);

		TextInputFormat.addInputPath(job, new Path(inputPath));
		TextOutputFormat.setOutputPath(job, new Path(outputPath));

		job.waitForCompletion(true);
	}

	/**
	 * Reads the Adjacency List and the PageRank value of each Vertex and updates it.
	 *
	 * @param inputPath
	 * @param outputPath
	 * @param amountOfVertices
	 * @throws IOException
	 * @throws InterruptedException
	 * @throws ClassNotFoundException
	 */
	private static void startPageRankJob(String inputPath, String outputPath, int amountOfVertices) throws IOException, InterruptedException, ClassNotFoundException {
		Configuration conf = new Configuration();

		conf.set("AMOUNT_OF_VERTICES", String.valueOf(amountOfVertices));

		Job job = new Job(conf, "PageRank Job");

		job.setJarByClass(Driver.class);
		job.setMapperClass(PageRankMapper.class);
		job.setReducerClass(PageRankReducer.class);

		job.setNumReduceTasks(1);

		job.setOutputKeyClass(LongWritable.class);
		job.setOutputValueClass(Text.class);

		job.setInputFormatClass(KeyValueTextInputFormat.class);
		job.setOutputFormatClass(TextOutputFormat.class);

		TextInputFormat.addInputPath(job, new Path(inputPath));
		TextOutputFormat.setOutputPath(job, new Path(outputPath));

		job.waitForCompletion(true);
	}

}


text: If you can find a situation, where the tcc-conjecture is false, feel free to share it here.


text:
/* Number of extra dynamic section entries for this architecture.  By
   default there are none.  */
#define DT_THISPROCNUM	0