text:
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <string>
#include <vector>

#include "base/containers/flat_map.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/scoped_feature_list.h"
#include "chrome/browser/autofill/personal_data_manager_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/test/base/chrome_test_utils.h"
#include "chrome/test/payments/payment_request_platform_browsertest_base.h"
#include "chrome/test/payments/personal_data_manager_test_util.h"
#include "components/autofill/core/browser/autofill_test_utils.h"
#include "components/autofill/core/browser/data_model/credit_card.h"
#include "components/autofill/core/browser/personal_data_manager.h"
#include "components/autofill/core/browser/personal_data_manager_observer.h"
#include "components/payments/core/features.h"
#include "components/sync/driver/test_sync_service.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_test.h"

namespace payments {

class PaymentRequestCanMakePaymentTestBase
    : public PaymentRequestPlatformBrowserTestBase {
 public:
  PaymentRequestCanMakePaymentTestBase(
      const PaymentRequestCanMakePaymentTestBase&) = delete;
  PaymentRequestCanMakePaymentTestBase& operator=(
      const PaymentRequestCanMakePaymentTestBase&) = delete;

 protected:
  PaymentRequestCanMakePaymentTestBase() = default;

  void SetUpOnMainThread() override {
    PaymentRequestPlatformBrowserTestBase::SetUpOnMainThread();
    Profile* profile = Profile::FromBrowserContext(
        GetActiveWebContents()->GetBrowserContext());
    autofill::PersonalDataManager* personal_data_manager =
        autofill::PersonalDataManagerFactory::GetForProfile(profile);
    personal_data_manager->OnSyncServiceInitialized(&sync_service_);
  }

  void NavigateTo(const std::string& file_path) {
    PaymentRequestPlatformBrowserTestBase::NavigateTo("a.com", file_path);
  }

 private:
  syncer::TestSyncService sync_service_;
};

class PaymentRequestCanMakePaymentQueryTest
    : public PaymentRequestCanMakePaymentTestBase {
 protected:
  PaymentRequestCanMakePaymentQueryTest() = default;

  PaymentRequestCanMakePaymentQueryTest(
      const PaymentRequestCanMakePaymentQueryTest&) = delete;
  PaymentRequestCanMakePaymentQueryTest& operator=(
      const PaymentRequestCanMakePaymentQueryTest&) = delete;

  void CallCanMakePayment() {
    ResetEventWaiterForEventSequence(
        {TestEvent::kCanMakePaymentCalled, TestEvent::kCanMakePaymentReturned});
    ASSERT_TRUE(content::ExecuteScript(GetActiveWebContents(), "buy();"));
    WaitForObservedEvent();
  }

  void CallHasEnrolledInstrument() {
    ResetEventWaiterForEventSequence(
        {TestEvent::kHasEnrolledInstrumentCalled,
         TestEvent::kHasEnrolledInstrumentReturned});
    ASSERT_TRUE(content::ExecuteScript(GetActiveWebContents(),
                                       "hasEnrolledInstrument();"));
    WaitForObservedEvent();
  }
};

// Visa is required, and user has a visa instrument.
IN_PROC_BROWSER_TEST_F(PaymentRequestCanMakePaymentQueryTest,
                       CanMakePayment_Supported) {
  NavigateTo("/payment_request_can_make_payment_query_test.html");
  const autofill::CreditCard card = autofill::test::GetCreditCard();  // Visa.
  AddCreditCard(card);

  CallCanMakePayment();
  ExpectBodyContains("true");

  CallHasEnrolledInstrument();
  ExpectBodyContains("true");
}

// Visa is required, and user has a visa instrument, but canMakePayment is
// disabled by user preference.
IN_PROC_BROWSER_TEST_F(PaymentRequestCanMakePaymentQueryTest,
                       CanMakePayment_SupportedButDisabled) {
  test_controller()->SetCanMakePaymentEnabledPref(false);
  NavigateTo("/payment_request_can_make_payment_query_test.html");
  const autofill::CreditCard card = autofill::test::GetCreditCard();  // Visa.
  AddCreditCard(card);

  CallCanMakePayment();
  ExpectBodyContains("false");

  CallHasEnrolledInstrument();
  ExpectBodyContains("false");
}

// Pages without a valid SSL certificate always get "false" from
// .canMakePayment().
IN_PROC_BROWSER_TEST_F(PaymentRequestCanMakePaymentQueryTest,
                       CanMakePayment_InvalidSSL) {
  NavigateTo("/payment_request_can_make_payment_query_test.html");
  test_controller()->SetValidSsl(false);

  const autofill::CreditCard card = autofill::test::GetCreditCard();  // Visa.
  AddCreditCard(card);

  ResetEventWaiterForEventSequence({TestEvent::kConnectionTerminated});
  ASSERT_TRUE(content::ExecuteScript(GetActiveWebContents(), "buy();"));
  WaitForObservedEvent();
  ExpectBodyContains("false");
}

// Pages without a valid SSL certificate always get NotSupported error from
// .show().
IN_PROC_BROWSER_TEST_F(PaymentRequestCanMakePaymentQueryTest, Show_InvalidSSL) {
  NavigateTo("/payment_request_can_make_payment_query_test.html");
  test_controller()->SetValidSsl(false);

  const autofill::CreditCard card = autofill::test::GetCreditCard();  // Visa.
  AddCreditCard(card);

  ResetEventWaiterForEventSequence({TestEvent::kConnectionTerminated});
  ASSERT_TRUE(content::ExecuteScript(GetActiveWebContents(), "show();"));
  WaitForObservedEvent();
  ExpectBodyContains("NotSupportedError: Invalid SSL certificate");
}

// Pages without a valid SSL certificate always get "false" from
// .hasEnrolledInstrument().
IN_PROC_BROWSER_TEST_F(PaymentRequestCanMakePaymentQueryTest,
                       HasEnrolledInstrument_InvalidSSL) {
  NavigateTo("/payment_request_can_make_payment_query_test.html");
  test_controller()->SetValidSsl(false);

  const autofill::CreditCard card = autofill::test::GetCreditCard();  // Visa.
  AddCreditCard(card);

  ResetEventWaiterForEventSequence({TestEvent::kConnectionTerminated});
  ASSERT_TRUE(content::ExecuteScript(GetActiveWebContents(),
                                     "hasEnrolledInstrument();"));
  WaitForObservedEvent();
  ExpectBodyContains("false");
}

// Visa is required, user has a visa instrument, and user is in incognito
// mode.
IN_PROC_BROWSER_TEST_F(PaymentRequestCanMakePaymentQueryTest,
                       CanMakePayment_Supported_InIncognitoMode) {
  NavigateTo("/payment_request_can_make_payment_query_test.html");
  test_controller()->SetOffTheRecord(true);

  const autofill::CreditCard card = autofill::test::GetCreditCard();  // Visa.
  AddCreditCard(card);

  CallCanMakePayment();
  ExpectBodyContains("true");

  CallHasEnrolledInstrument();
  ExpectBodyContains("true");
}

// Visa is required, and user doesn't have a visa instrument.
IN_PROC_BROWSER_TEST_F(PaymentRequestCanMakePaymentQueryTest,
                       CanMakePayment_NotSupported) {
  NavigateTo("/payment_request_can_make_payment_query_test.html");
  const autofill::CreditCard card = autofill::test::GetCreditCard2();  // Amex.
  AddCreditCard(card);

  CallCanMakePayment();
  ExpectBodyContains("true");

  CallHasEnrolledInstrument();
  ExpectBodyContains("false");
}

// Visa is required, user doesn't have a visa instrument and the user is in
// incognito mode. In this case canMakePayment returns false as in a normal
// profile.
IN_PROC_BROWSER_TEST_F(PaymentRequestCanMakePaymentQueryTest,
                       CanMakePayment_NotSupported_InIncognitoMode) {
  NavigateTo("/payment_request_can_make_payment_query_test.html");
  test_controller()->SetOffTheRecord(true);

  const autofill::CreditCard card = autofill::test::GetCreditCard2();  // Amex.
  AddCreditCard(card);

  CallCanMakePayment();
  ExpectBodyContains("true");

  CallHasEnrolledInstrument();
  ExpectBodyContains("false");
}

class PaymentRequestCanMakePaymentQueryCCTest
    : public PaymentRequestCanMakePaymentTestBase {
 public:
  PaymentRequestCanMakePaymentQueryCCTest(
      const PaymentRequestCanMakePaymentQueryCCTest&) = delete;
  PaymentRequestCanMakePaymentQueryCCTest& operator=(
      const PaymentRequestCanMakePaymentQueryCCTest&) = delete;

 protected:
  PaymentRequestCanMakePaymentQueryCCTest() = default;

  // If |visa| is true, then the method data is:
  //
  //   [{supportedMethods: ['visa']}]
  //
  // If |visa| is false, then the method data is:
  //
  //   [{supportedMethods: ['mastercard']}]
  void CallCanMakePayment(bool visa) {
    ResetEventWaiterForEventSequence(
        {TestEvent::kCanMakePaymentCalled, TestEvent::kCanMakePaymentReturned});
    ASSERT_TRUE(content::ExecuteScript(GetActiveWebContents(),
                                       visa ? "buy();" : "other_buy();"));
    WaitForObservedEvent();
  }

  void CallHasEnrolledInstrument(bool visa) {
    ResetEventWaiterForEventSequence(
        {TestEvent::kHasEnrolledInstrumentCalled,
         TestEvent::kHasEnrolledInstrumentReturned});
    ASSERT_TRUE(content::ExecuteScript(
        GetActiveWebContents(), visa ? "hasEnrolledInstrument('visa');"
                                     : "hasEnrolledInstrument('mastercard');"));
    WaitForObservedEvent();
  }
};

// Test that repeated canMakePayment and hasEnrolledInstrument queries are
// allowed when the payment method specifics don't change.
IN_PROC_BROWSER_TEST_F(PaymentRequestCanMakePaymentQueryCCTest,
                       QueryQuotaDoesNotApplyToSameMethod) {
  NavigateTo("/payment_request_can_make_payment_query_cc_test.html");

  CallCanMakePayment(/*visa=*/true);
  ExpectBodyContains("true");

  CallHasEnrolledInstrument(/*visa=*/true);
  ExpectBodyContains("false");

  CallCanMakePayment(/*visa=*/false);
  ExpectBodyContains("true");

  CallHasEnrolledInstrument(/*visa=*/true);
  ExpectBodyContains("false");

  AddCreditCard(autofill::test::GetCreditCard());  // visa

  CallCanMakePayment(/*visa=*/true);
  ExpectBodyContains("true");

  CallHasEnrolledInstrument(/*visa=*/true);
  ExpectBodyContains("true");

  CallCanMakePayment(/*visa=*/false);
  ExpectBodyContains("true");

  CallHasEnrolledInstrument(/*visa=*/true);
  ExpectBodyContains("true");
}

IN_PROC_BROWSER_TEST_F(PaymentRequestCanMakePaymentQueryCCTest,
                       QueryQuotaAppliesToDifferentMethods) {
  NavigateTo("/payment_request_can_make_payment_query_cc_test.html");

  CallHasEnrolledInstrument(/*visa=*/true);
  ExpectBodyContains("false");

  CallCanMakePayment(/*visa=*/true);
  ExpectBodyContains("true");

  // Check hasEnrolledInstrument on a different method hits the query quota.
  CallHasEnrolledInstrument(/*visa=*/false);
  ExpectBodyContains("NotAllowedError");

  // canMakePayment doesn't have query quota.
  CallCanMakePayment(/*visa=*/false);
  ExpectBodyContains("true");

  AddCreditCard(autofill::test::GetCreditCard());  // visa

  CallHasEnrolledInstrument(/*visa=*/true);
  ExpectBodyContains("true");

  CallCanMakePayment(/*visa=*/true);
  ExpectBodyContains("true");

  // Check hasEnrolledInstrument on a different method hits the query quota.
  CallHasEnrolledInstrument(/*visa=*/false);
  ExpectBodyContains("NotAllowedError");

  // canMakePayment doesn't have query quota and is not affected by enrolled
  // instrument.
  CallCanMakePayment(/*visa=*/false);
  ExpectBodyContains("true");
}

// canMakePayment should return result in incognito mode as in normal mode to
// avoid incognito mode detection.
IN_PROC_BROWSER_TEST_F(PaymentRequestCanMakePaymentQueryCCTest,
                       QueryQuotaInIncognito) {
  NavigateTo("/payment_request_can_make_payment_query_cc_test.html");
  test_controller()->SetOffTheRecord(true);

  CallHasEnrolledInstrument(/*visa=*/true);
  ExpectBodyContains("false");

  CallCanMakePayment(/*visa=*/true);
  ExpectBodyContains("true");

  // Check hasEnrolledInstrument on a different method hits the query quota.
  CallHasEnrolledInstrument(/*visa=*/false);
  ExpectBodyContains("NotAllowedError");

  // canMakePayment doesn't have query quota.
  CallCanMakePayment(/*visa=*/false);
  ExpectBodyContains("true");

  AddCreditCard(autofill::test::GetCreditCard());  // visa

  CallHasEnrolledInstrument(/*visa=*/true);
  ExpectBodyContains("true");

  CallCanMakePayment(/*visa=*/true);
  ExpectBodyContains("true");

  // Check hasEnrolledInstrument on a different method hits the query quota.
  CallHasEnrolledInstrument(/*visa=*/false);
  ExpectBodyContains("NotAllowedError");

  // canMakePayment doesn't have query quota and is not affected by enrolled
  // instrument.
  CallCanMakePayment(/*visa=*/false);
  ExpectBodyContains("true");
}

class PaymentRequestCanMakePaymentQueryPMITest
    : public PaymentRequestCanMakePaymentTestBase {
 protected:
  enum class CheckFor {
    BASIC_VISA,
    BASIC_CARD,
    ALICE_PAY,
    BOB_PAY,
    BOB_PAY_AND_BASIC_CARD,
    BOB_PAY_AND_VISA,
  };

  PaymentRequestCanMakePaymentQueryPMITest() {
    script_[CheckFor::BASIC_VISA] = "[basicVisaMethod]";
    script_[CheckFor::BASIC_CARD] = "[basicCardMethod]";
    script_[CheckFor::ALICE_PAY] = "[alicePayMethod]";
    script_[CheckFor::BOB_PAY] = "[bobPayMethod]";
    script_[CheckFor::BOB_PAY_AND_BASIC_CARD] =
        "[bobPayMethod, basicCardMethod]";
    script_[CheckFor::BOB_PAY_AND_VISA] = "[bobPayMethod, basicVisaMethod]";
  }

  PaymentRequestCanMakePaymentQueryPMITest(
      const PaymentRequestCanMakePaymentQueryPMITest&) = delete;
  PaymentRequestCanMakePaymentQueryPMITest& operator=(
      const PaymentRequestCanMakePaymentQueryPMITest&) = delete;

  void CallCanMakePayment(CheckFor check_for) {
    ResetEventWaiterForEventSequence(
        {TestEvent::kCanMakePaymentCalled, TestEvent::kCanMakePaymentReturned});
    ASSERT_TRUE(content::ExecuteScript(
        GetActiveWebContents(),
        "checkCanMakePayment(" + script_[check_for] + ");"));
    WaitForObservedEvent();
  }

  void CallHasEnrolledInstrument(CheckFor check_for) {
    ResetEventWaiterForEventSequence(
        {TestEvent::kHasEnrolledInstrumentCalled,
         TestEvent::kHasEnrolledInstrumentReturned});
    ASSERT_TRUE(content::ExecuteScript(
        GetActiveWebContents(),
        "checkHasEnrolledInstrument(" + script_[check_for] + ");"));
    WaitForObservedEvent();
  }

 private:
  base::flat_map<CheckFor, std::string> script_;
};

IN_PROC_BROWSER_TEST_F(PaymentRequestCanMakePaymentQueryPMITest,
                       QueryQuotaForBasicCards) {
  NavigateTo("/payment_request_payment_method_identifier_test.html");

  // User starts off without having a visa card.
  CallCanMakePayment(CheckFor::BASIC_VISA);
  ExpectBodyContains("true");
  CallHasEnrolledInstrument(CheckFor::BASIC_VISA);
  ExpectBodyContains("false");

  // Query "basic-card" payment method without "supportedNetworks" parameter.
  // This is considered a different method, so hasEnrolledInstrument() will be
  // throttled.
  CallCanMakePayment(CheckFor::BASIC_CARD);
  ExpectBodyContains("true");
  CallHasEnrolledInstrument(CheckFor::BASIC_CARD);
  ExpectBodyContains("NotAllowedError");

  // Add a visa card to the user profile.
  AddCreditCard(autofill::test::GetCreditCard());

  CallCanMakePayment(CheckFor::BASIC_VISA);
  ExpectBodyContains("true");
  CallHasEnrolledInstrument(CheckFor::BASIC_VISA);
  ExpectBodyContains("true");

  CallCanMakePayment(CheckFor::BASIC_CARD);
  ExpectBodyContains("true");
  CallHasEnrolledInstrument(CheckFor::BASIC_CARD);
  ExpectBodyContains("NotAllowedError");
}

// canMakePayment() should return result as in normal mode to avoid incognito
// mode detection.
IN_PROC_BROWSER_TEST_F(PaymentRequestCanMakePaymentQueryPMITest,
                       QueryQuotaForBasicCardsInIncognito) {
  NavigateTo("/payment_request_payment_method_identifier_test.html");
  test_controller()->SetOffTheRecord(true);

  // User starts off without having a visa card.
  CallCanMakePayment(CheckFor::BASIC_VISA);
  ExpectBodyContains("true");
  CallHasEnrolledInstrument(CheckFor::BASIC_VISA);
  ExpectBodyContains("false");

  // Query "basic-card" payment method without "supportedNetworks" parameter.
  // This is considered a different method, so hasEnrolledInstrument() will be
  // throttled.
  CallCanMakePayment(CheckFor::BASIC_CARD);
  ExpectBodyContains("true");
  CallHasEnrolledInstrument(CheckFor::BASIC_CARD);
  ExpectBodyContains("NotAllowedError");

  // Add a visa card to the user profile.
  AddCreditCard(autofill::test::GetCreditCard());

  CallCanMakePayment(CheckFor::BASIC_VISA);
  ExpectBodyContains("true");
  CallHasEnrolledInstrument(CheckFor::BASIC_VISA);
  ExpectBodyContains("true");

  CallCanMakePayment(CheckFor::BASIC_CARD);
  ExpectBodyContains("true");
  CallHasEnrolledInstrument(CheckFor::BASIC_CARD);
  ExpectBodyContains("NotAllowedError");
}

// If the device does not have any payment apps installed,
// hasEnrolledInstrument() queries for both payment apps and basic-card depend
// only on what cards the user has on file.
// TODO(https://crbug.com/1233940): The test is flaky.
IN_PROC_BROWSER_TEST_F(PaymentRequestCanMakePaymentQueryPMITest,
                       DISABLED_QueryQuotaForPaymentAppsAndCards) {
  NavigateTo("/payment_request_payment_method_identifier_test.html");

  CallCanMakePayment(CheckFor::BOB_PAY_AND_VISA);
  ExpectBodyContains("true");
  CallHasEnrolledInstrument(CheckFor::BOB_PAY_AND_VISA);
  ExpectBodyContains("false");

  CallCanMakePayment(CheckFor::BOB_PAY_AND_BASIC_CARD);
  ExpectBodyContains("true");
  CallHasEnrolledInstrument(CheckFor::BOB_PAY_AND_BASIC_CARD);
  ExpectBodyContains("NotAllowedError");

  AddCreditCard(autofill::test::GetCreditCard2());  // Amex

  CallCanMakePayment(CheckFor::BOB_PAY_AND_VISA);
  ExpectBodyContains("true");
  CallHasEnrolledInstrument(CheckFor::BOB_PAY_AND_VISA);
  ExpectBodyContains("false");

  CallCanMakePayment(CheckFor::BOB_PAY_AND_BASIC_CARD);
  ExpectBodyContains("true");
  CallHasEnrolledInstrument(CheckFor::BOB_PAY_AND_BASIC_CARD);
  ExpectBodyContains("NotAllowedError");

  AddCreditCard(autofill::test::GetCreditCard());  // Visa

  CallCanMakePayment(CheckFor::BOB_PAY_AND_VISA);
  ExpectBodyContains("true");
  CallHasEnrolledInstrument(CheckFor::BOB_PAY_AND_VISA);
  ExpectBodyContains("true");

  CallCanMakePayment(CheckFor::BOB_PAY_AND_BASIC_CARD);
  ExpectBodyContains("true");
  CallHasEnrolledInstrument(CheckFor::BOB_PAY_AND_BASIC_CARD);
  ExpectBodyContains("NotAllowedError");
}

}  // namespace payments


text:
package org.apache.lucene.index;

import java.io.IOException;
import java.util.Iterator;
import java.util.NoSuchElementException;

import org.apache.lucene.codecs.DocValuesConsumer;
import org.apache.lucene.util.Counter;
import org.apache.lucene.util.FixedBitSet;
import org.apache.lucene.util.RamUsageEstimator;
import org.apache.lucene.util.packed.AppendingDeltaPackedLongBuffer;
import org.apache.lucene.util.packed.PackedInts;

/** Buffers up pending long per doc, then flushes when
 *  segment flushes. */
class NumericDocValuesWriter extends DocValuesWriter {

  private final static long MISSING = 0L;

  private AppendingDeltaPackedLongBuffer pending;
  private final Counter iwBytesUsed;
  private long bytesUsed;
  private FixedBitSet docsWithField;
  private final FieldInfo fieldInfo;

  public NumericDocValuesWriter(FieldInfo fieldInfo, Counter iwBytesUsed, boolean trackDocsWithField) {
    pending = new AppendingDeltaPackedLongBuffer(PackedInts.COMPACT);
    docsWithField = trackDocsWithField ? new FixedBitSet(64) : null;
    bytesUsed = pending.ramBytesUsed() + docsWithFieldBytesUsed();
    this.fieldInfo = fieldInfo;
    this.iwBytesUsed = iwBytesUsed;
    iwBytesUsed.addAndGet(bytesUsed);
  }

  public void addValue(int docID, long value) {
    if (docID < pending.size()) {
      throw new IllegalArgumentException("DocValuesField \"" + fieldInfo.name + "\" appears more than once in this document (only one value is allowed per field)");
    }

    // Fill in any holes:
    for (int i = (int)pending.size(); i < docID; ++i) {
      pending.add(MISSING);
    }

    pending.add(value);
    if (docsWithField != null) {
      docsWithField = FixedBitSet.ensureCapacity(docsWithField, docID);
      docsWithField.set(docID);
    }

    updateBytesUsed();
  }

  private long docsWithFieldBytesUsed() {
    // size of the long[] + some overhead
    return docsWithField == null ? 0 : RamUsageEstimator.sizeOf(docsWithField.getBits()) + 64;
  }

  private void updateBytesUsed() {
    final long newBytesUsed = pending.ramBytesUsed() + docsWithFieldBytesUsed();
    iwBytesUsed.addAndGet(newBytesUsed - bytesUsed);
    bytesUsed = newBytesUsed;
  }

  @Override
  public void finish(int maxDoc) {
  }

  @Override
  public void flush(SegmentWriteState state, DocValuesConsumer dvConsumer) throws IOException {

    final int maxDoc = state.segmentInfo.getDocCount();

    dvConsumer.addNumericField(fieldInfo,
                               new Iterable<Number>() {
                                 @Override
                                 public Iterator<Number> iterator() {
                                   return new NumericIterator(maxDoc);
                                 }
                               });
  }

  // iterates over the values we have in ram
  private class NumericIterator implements Iterator<Number> {
    final AppendingDeltaPackedLongBuffer.Iterator iter = pending.iterator();
    final int size = (int)pending.size();
    final int maxDoc;
    int upto;

    NumericIterator(int maxDoc) {
      this.maxDoc = maxDoc;
    }

    @Override
    public boolean hasNext() {
      return upto < maxDoc;
    }

    @Override
    public Number next() {
      if (!hasNext()) {
        throw new NoSuchElementException();
      }
      Long value;
      if (upto < size) {
        long v = iter.next();
        if (docsWithField == null || docsWithField.get(upto)) {
          value = v;
        } else {
          value = null;
        }
      } else {
        value = docsWithField != null ? null : MISSING;
      }
      upto++;
      return value;
    }

    @Override
    public void remove() {
      throw new UnsupportedOperationException();
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
namespace klib
{

class API_EXPORT Thread
{
public:
	///////////////////////////////////////////////////////////
	/// \biref Default Constructor
	///
	/// Creates a new thread object: not an actual thread, but
	/// a wrapper for one. (C++11)
	///
	///////////////////////////////////////////////////////////
	Thread() : mRunning(false), mDetached(false) {};

	///////////////////////////////////////////////////////////
	/// \brief Default Destructor
	///
	/// Gracefully stops a thread, detaching it if's still running
	///
	///////////////////////////////////////////////////////////
	virtual ~Thread()
	{
		if (mRunning)
		{
			mRunning = false;
			if (!mDetached)
				Detach();
		}
	}

	///////////////////////////////////////////////////////////
	/// \brief Start the thread
	///
	/// Checks if the thread is already running or not, and
	/// returns false if it is. If the thread has been started
	/// successfully, returns true.
	///
	/// \return Started succesfully
	///
	/// \see Thread::Run
	///
	///////////////////////////////////////////////////////////
	inline bool Start()
	{
		if (mRunning)
		{
			KL_WARNING("Attempted to Start() a Thread which is already running");

			return false;
		}
		else
		{
			mRunning = true;
			mThread = std::thread(&Thread::Run, this);

			KL_WARNING("Thread", "Created a new thread (" + ToHexString(mThread.get_id().hash()) + ")");

			return true;
		}
	}

	///////////////////////////////////////////////////////////
	/// \brief Stop the thread
	///
	/// The param immediate controls whether the thread will
	/// be left to finish it's Run() function detaching it, or
	/// forcibly joining it.
	///
	/// \param immediate Stop thread immediately or leave to exit
	///
	///////////////////////////////////////////////////////////
	inline void Stop(bool immediate = false)
	{
		if (mRunning)
		{
			mRunning = false;

			if (immediate)
			{
				Detach();
			}
			else
			{
				Join();
			}
		}
		else
		{
			KL_WARNING("Attempted to Stop() a Thread which isn't running");
		}
	}

	///////////////////////////////////////////////////////////
	/// \brief Join thread to the thread it was created on
	///
	/// Stops execution on caling thread and makes it wait until
	/// this thread finishes execution.
	///
	/// \return Joined
	///
	///////////////////////////////////////////////////////////
	inline bool Join()
	{
		if (mRunning)
		{
			mThread.join();
			mDetached = false;
			return true;
		}
		return false;
	}

	///////////////////////////////////////////////////////////
	/// \brief Detach a thread
	///
	/// Detach this thread from the thread it was created on,
	/// causing them to lose references of eachother.
	///
	/// \return Detached
	///
	///////////////////////////////////////////////////////////
	inline bool Detach()
	{
		if (mRunning && !mDetached)
		{
			mThread.detach();
			mDetached = true;
			return true;
		}
		return false;
	}

	///////////////////////////////////////////////////////////
	/// \brief Get the thread id as a std::thread::id
	///
	/// \return Thread ID
	///
	///////////////////////////////////////////////////////////
	inline std::thread::id GetThreadID() const
	{
		return mThread.get_id();
	}

	///////////////////////////////////////////////////////////
	/// \brief Check if thread is running
	///
	/// \return Running
	///
	///////////////////////////////////////////////////////////
	bool IsRunning(void) const
	{
		return mRunning;
	}

	///////////////////////////////////////////////////////////
	/// \brief Thread entry-point/Thread function
	///
	/// This is the function that will be run on the actual
	/// thread, so anything which is supposed to be threaded
	/// should be in this function.
	///
	/// The function can contain a loop, the thread should either
	/// clean up itself, or be cleaned up by a manager of it.
	///
	/// Otherwise, if the function is not a loop, or finishes
	/// on it's own, the thread will simply terminate while the
	/// Thread object remains.
	///
	/// For a loop, the loop should continue as long as mRunning
	/// is true. For function which is not a loop, it should
	/// set mRunning to false when it exists.
	///
	///////////////////////////////////////////////////////////
	virtual void* Run() = 0;

protected:
	std::thread mThread;
	std::atomic<bool> mRunning;
	std::atomic<bool> mDetached;
};
///////////////////////////////////////////////////////////
/// \class Thread
/// \brief Baseclass for threads with a nice interface.
///
/// The subclass which is intended to be threaded, should
/// overload the Run method with it's own routine.
/// See Thread::Run for a detailed explanation.
///
/// Accessing the thread from outside (Start, Stop, IsRunning)
/// is thread-safe because of the use of atomics
///
/// Example usage in subclass:
/// \code
/// class ThreadedIO : Thread
/// {
///     void* Run() override;
/// }
///
/// void* ThreadedIO::Run()
/// {
///     while (mRunning)
///     {
///          ProcessQueueAsync();
///     }
/// }
///
/// ThreadedIO tio;
/// tio.Start();
/// ...
/// tio.Stop();
/// \endcode
///
///////////////////////////////////////////////////////////

} // klib


text:
package org.nd4j.linalg.api.dimensionfunctions;

import com.google.common.base.Function;
import org.nd4j.linalg.api.buffer.DataBuffer;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.ops.reduceops.Ops;

/**
 * Dimension wise functions
 *
 * @author Adam Gibson
 */
public class DimensionFunctions {
    public static Function<INDArray,INDArray> normmax(final int dimension) {
        return new Function<INDArray, INDArray>() {
            @Override
            public INDArray apply(INDArray input) {
                return input.normmax(dimension);
            }
        };
    }
    public static Function<INDArray,INDArray> norm2(final int dimension) {
        return new Function<INDArray, INDArray>() {
            @Override
            public INDArray apply(INDArray input) {
                return input.norm2(dimension);
            }
        };
    }

    public static Function<INDArray,INDArray> norm1(final int dimension) {
        return new Function<INDArray, INDArray>() {
            @Override
            public INDArray apply(INDArray input) {
                return input.norm1(dimension);
            }
        };
    }

    public static Function<INDArray,INDArray> sum(final int dimension) {
        return new Function<INDArray, INDArray>() {
            @Override
            public INDArray apply(INDArray input) {

                return input.sum(dimension);
            }
        };
    }

    public static Function<INDArray,INDArray> var(final int dimension) {
        return new Function<INDArray, INDArray>() {
            @Override
            public INDArray apply(INDArray input) {

                return input.var(dimension);
            }
        };
    }

    public static Function<INDArray,INDArray> std(final int dimension) {
        return new Function<INDArray, INDArray>() {
            @Override
            public INDArray apply(INDArray input) {

                return input.std(dimension);
            }
        };
    }

    public static Function<INDArray,INDArray> prod(final int dimension) {
        return new Function<INDArray, INDArray>() {
            @Override
            public INDArray apply(INDArray input) {
                return input.prod(dimension);
            }
        };
    }

    public static Function<INDArray,INDArray> cumsum(final int dimension) {
        return new Function<INDArray, INDArray>() {
            @Override
            public INDArray apply(INDArray input) {
                return input.cumsum(dimension);
            }
        };
    }

    public static Function<INDArray,INDArray> mean(final int dimension) {
        return new Function<INDArray, INDArray>() {
            @Override
            public INDArray apply(INDArray input) {
                return input.mean(dimension);
            }
        };
    }

    public static Function<INDArray,INDArray> min(final int dimension) {
        return new Function<INDArray, INDArray>() {
            @Override
            public INDArray apply(INDArray input) {
                return input.min(dimension);
            }
        };
    }

    public static Function<INDArray,INDArray> max(final int dimension) {
        return new Function<INDArray, INDArray>() {
            @Override
            public INDArray apply(INDArray input) {
                return input.max(dimension);
            }
        };
    }

    public static Function<INDArray,INDArray> norm2() {
        return new Function<INDArray, INDArray>() {
            @Override
            public INDArray apply(INDArray input) {
                return  Nd4j.scalar(Ops.norm2(input));
            }
        };
    }

    public static Function<INDArray,INDArray> norm1() {
        return new Function<INDArray, INDArray>() {
            @Override
            public INDArray apply(INDArray input) {
                return Nd4j.scalar(Ops.norm1(input));
            }
        };
    }

    public static Function<INDArray,INDArray> sum() {
        return new Function<INDArray, INDArray>() {
            @Override
            public INDArray apply(INDArray input) {
                return Nd4j.scalar(Ops.sum(input));
            }
        };
    }

    public static Function<INDArray,INDArray> var() {
        return new Function<INDArray, INDArray>() {
            @Override
            public INDArray apply(INDArray input) {

                return  Nd4j.scalar(Ops.var(input));
            }
        };
    }

    public static Function<INDArray,INDArray> std() {
        return new Function<INDArray, INDArray>() {
            @Override
            public INDArray apply(INDArray input) {
                return Nd4j.scalar(Ops.std(input));
            }
        };
    }

    public static Function<INDArray,INDArray> prod() {
        return new Function<INDArray, INDArray>() {
            @Override
            public INDArray apply(INDArray input) {
                return Nd4j.scalar(Ops.prod(input));
            }
        };
    }

    public static Function<INDArray,INDArray> cumsum() {
        return new Function<INDArray, INDArray>() {
            @Override
            public INDArray apply(INDArray input) {
                double s = 0.0;
                for (int i = 0; i < input.length(); i++) {
                    if(input.data().dataType().equals(DataBuffer.FLOAT))
                        s += input.getDouble(i);
                    else
                        s+= input.getDouble(i);
                    input.putScalar(i, s);
                }

                return input;
            }
        };
    }

    public static Function<INDArray,INDArray> mean() {
        return new Function<INDArray, INDArray>() {
            @Override
            public INDArray apply(INDArray input) {
                return Nd4j.scalar(Ops.mean(input));
            }
        };
    }

    public static Function<INDArray,INDArray> min() {
        return new Function<INDArray, INDArray>() {
            @Override
            public INDArray apply(INDArray input) {
                return Nd4j.scalar(Ops.min(input));
            }
        };
    }

    public static Function<INDArray,INDArray> max() {
        return new Function<INDArray, INDArray>() {
            @Override
            public INDArray apply(INDArray input) {
                return Nd4j.scalar(Ops.max(input));
            }
        };
    }

    public static Function<INDArray,INDArray> normmax() {
        return new Function<INDArray, INDArray>() {
            @Override
            public INDArray apply(INDArray input) {
                return Nd4j.scalar(Ops.normmax(input));
            }
        };
    }

}


text:
package org.jetbrains.idea.svn.history;

import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.vcs.ConcurrentTasks;
import com.intellij.util.Consumer;
import org.jetbrains.idea.svn.SvnVcs;
import org.tmatesoft.svn.core.*;
import org.tmatesoft.svn.core.internal.util.SVNPathUtil;
import org.tmatesoft.svn.core.wc.SVNLogClient;
import org.tmatesoft.svn.core.wc.SVNRevision;

import java.util.Map;

public class FirstInBranch implements Runnable {
  private final SvnVcs myVcs;
  private final String myFullBranchUrl;
  private final String myFullTrunkUrl;
  private final String myBranchUrl;
  private final String myTrunkUrl;
  private final Consumer<CopyData> myConsumer;

  public FirstInBranch(final SvnVcs vcs, final String repositoryRoot, final String branchUrl, final String trunkUrl, final Consumer<CopyData> consumer) {
    myVcs = vcs;
    myConsumer = consumer;

    myFullBranchUrl = branchUrl;
    myFullTrunkUrl = trunkUrl;
    myBranchUrl = relativePath(repositoryRoot, branchUrl);
    myTrunkUrl = relativePath(repositoryRoot, trunkUrl);
  }

  private String relativePath(final String parent, final String child) {
    String path = SVNPathUtil.getRelativePath(parent, child);
    return path.startsWith("/") ? path : "/" + path;
  }

  public void run() {
    final SVNURL branchURL;
    final SVNURL trunkURL;
    try {
      branchURL = SVNURL.parseURIEncoded(myFullBranchUrl);
      trunkURL = SVNURL.parseURIEncoded(myFullTrunkUrl);
    }
    catch (SVNException e) {
      myConsumer.consume(null);
      return;
    }

    final ConcurrentTasks<CopyData> tasks =
      new ConcurrentTasks<CopyData>(ProgressManager.getInstance().getProgressIndicator(), createTask(branchURL), createTask(trunkURL));
    tasks.compute();
    if (tasks.isResultKnown()) {
      myConsumer.consume(tasks.getResult());
    } else {
      myConsumer.consume(null);
    }
  }

  private Consumer<Consumer<CopyData>> createTask(final SVNURL branchURL) {
    return new Consumer<Consumer<CopyData>>() {
      public void consume(final Consumer<CopyData> copyDataConsumer) {
        final SVNLogClient logClient = myVcs.createLogClient();
        final long start1 = getStart(logClient, branchURL);
        if (start1 > 0) {
          final SVNRevision start1Rev = SVNRevision.create(start1);
          try {
            logClient.doLog(branchURL, null, SVNRevision.UNDEFINED, start1Rev, start1Rev, true, true, 1, new ISVNLogEntryHandler() {
              public void handleLogEntry(SVNLogEntry logEntry) throws SVNException {
                checkForCopy(logEntry, copyDataConsumer);
              }
            });
          } catch (SVNException e) {
            //
          }
        }
      }
    };
  }

  private static long getStart(final SVNLogClient logClient, final SVNURL url) {
    final Ref<Long> myRevisionCandidate = new Ref<Long>(0L);
    try {
      logClient.doLog(url, null, SVNRevision.UNDEFINED, SVNRevision.HEAD, SVNRevision.create(0),
                      true, false, 0, new ISVNLogEntryHandler() {
          public void handleLogEntry(SVNLogEntry logEntry) throws SVNException {
            ProgressManager.checkCanceled();

            myRevisionCandidate.set(logEntry.getRevision());
          }
        });
    }
    catch (SVNException e) {
      //
    }
    return myRevisionCandidate.get();
  }

  private void checkForCopy(final SVNLogEntry logEntry, final Consumer<CopyData> result) {
    final Map map = logEntry.getChangedPaths();
    for (Object o : map.values()) {
      final SVNLogEntryPath path = (SVNLogEntryPath) o;
      final String localPath = path.getPath();
      final String copyPath = path.getCopyPath();

      if ('A' == path.getType()) {
        if ((myBranchUrl.equals(localPath) || SVNPathUtil.isAncestor(localPath, myBranchUrl)) &&
            ((myTrunkUrl.equals(copyPath)) || SVNPathUtil.isAncestor(copyPath, myTrunkUrl))) {
          result.consume(new CopyData(path.getCopyRevision(), logEntry.getRevision(), true));
        } else {
          if ((myBranchUrl.equals(copyPath) || SVNPathUtil.isAncestor(copyPath, myBranchUrl)) &&
              ((myTrunkUrl.equals(localPath)) || SVNPathUtil.isAncestor(localPath, myTrunkUrl))) {
            result.consume(new CopyData(path.getCopyRevision(), logEntry.getRevision(), false));
          }
        }
      }
    }
  }
}


text:
using Assets.Scripts.GameScripts.GameLogic.Skills.SkillCasters;
using StateMachine.Condition;

namespace Assets.Scripts.AIStateMachine.StateMachineCondition{
	[Info (category = "Custom",
	description = "AICaster does not have any skill to cast",
	url = "")]
	public class NoSkillToCast : StateCondition
	{
		public override void OnEnter()
		{

		}

		public override bool Validate()
		{
            return !stateMachine.owner.gameObject.GetComponent<AISkillCaster>().CanCastAnySkill()
                && !stateMachine.owner.gameObject.GetComponent<AISkillCaster>().CastingActiveSkill;
		}
	}
}


text:
import * as ts from 'typescript';

// TOOD: Remove when tools directory is upgraded to support es6 target
interface Map<K, V> {
  has(v: V): boolean;
  set(k: K, v: V): void;
  get(k: K): V;
}
interface MapConstructor {
  new<K, V>(): Map<K, V>;
}
declare var Map: MapConstructor;

var a: Array<number>;

/**
 * A symbol table of ts.Symbol to a folded value used during expression folding in Evaluator.
 *
 * This is a thin wrapper around a Map<> using the first declaration location instead of the symbol
 * itself as the key. In the TypeScript binder and type checker, mulitple symbols are sometimes
 * created for a symbol depending on what scope it is in (e.g. export vs. local). Using the
 * declaration node as the key results in these duplicate symbols being treated as identical.
 */
export class Symbols {
  private map = new Map<ts.Node, any>();

  public has(symbol: ts.Symbol): boolean { return this.map.has(symbol.getDeclarations()[0]); }

  public set(symbol: ts.Symbol, value: any): void { this.map.set(symbol.getDeclarations()[0], value); }

  public get(symbol: ts.Symbol): any { return this.map.get(symbol.getDeclarations()[0]); }

  static empty: Symbols = new Symbols();
}


text:
<?php

namespace mcc\obj\news\repositories;

class news extends \mcc\obj\repo\repobase {

  // database variables (end with _ and are protected)
  protected $title_;
  protected $ingress_;
  protected $contents_;
  protected $published_;

  /**
   * @type: timestamp
   */
  protected $time_;

  /**
   * @type: timestamp
   */
  protected $edited_;

  // constant
  const TABLE = 'news';

  public function getComments() {
    return $this->getChildrennews_comments()['obj'];
  }

  public function getNext() {
    $db = self::getDB();
    $table = self::TABLE;
    $query = $db->prepare("select * from $table where time > '{$this->time_}' and published=1 order by time limit 0,1");
    try {
      $next = $db->getDataRow($query);
    } catch (\Exception $e) {
      return null;
    }
    $news = new self();
    $news->initByData($next);
    return $news;
  }

  public function getPrevious() {
    $db = self::getDB();
    $table = self::TABLE;
    $query = $db->prepare("select * from $table where time < '{$this->time_}' and published=1 order by time desc limit 0,1");
    try {
      $prev = $db->getDataRow($query);
    } catch (\Exception $e) {
      return null;
    }
    $news = new self();
    $news->initByData($prev);
    return $news;
  }

  public function getTitleData() {
    return array('id' => $this->id_, 'title' => $this->title_);
  }

  public function setTimeToCurrent(){
    $db = self::getDB();
    $table = self::TABLE;
    $db->execute("update $table set time=CURRENT_TIMESTAMP where id={$this->id_}");
  }

}


text:
.class public final Lo/Ey;
.super Lo/CU;
.source ""

# annotations
.annotation system Ldalvik/annotation/Signature;
    value = {
        "<K:Ljava/lang/Enum<TK;>;V:Ljava/lang/Object;>Lo/CU<TK;TV;>;"
    }
.end annotation

.annotation build Lo/Ai;
    ˋ = true
.end annotation

# static fields
.field private static final ˎ:J = 0x0L
    .annotation build Lo/Aj;
        ˊ = "only needed in emulated source."
    .end annotation
.end field

# instance fields
.field private transient ˋ:Ljava/lang/Class;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/lang/Class<TK;>;"
        }
    .end annotation
.end field

# direct methods
.method private constructor <init>(Ljava/lang/Class;)V
    .locals 2
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(Ljava/lang/Class<TK;>;)V"
        }
    .end annotation

    .line 79
    new-instance v0, Ljava/util/EnumMap;

    invoke-direct {v0, p1}, Ljava/util/EnumMap;-><init>(Ljava/lang/Class;)V

    invoke-static {v0}, Lo/LI;->ˊ(Ljava/util/Map;)Lo/LI;

    move-result-object v0

    invoke-virtual {p1}, Ljava/lang/Class;->getEnumConstants()[Ljava/lang/Object;

    move-result-object v1

    check-cast v1, [Ljava/lang/Enum;

    array-length v1, v1

    invoke-static {v1}, Lo/In;->ˊ(I)Ljava/util/HashMap;

    move-result-object v1

    invoke-direct {p0, v0, v1}, Lo/CU;-><init>(Ljava/util/Map;Ljava/util/Map;)V

    .line 83
    iput-object p1, p0, Lo/Ey;->ˋ:Ljava/lang/Class;

    .line 84
    return-void
.end method

.method private readObject(Ljava/io/ObjectInputStream;)V
    .locals 4
    .annotation build Lo/Aj;
        ˊ = "java.io.ObjectInputStream"
    .end annotation

    .line 121
    invoke-virtual {p1}, Ljava/io/ObjectInputStream;->defaultReadObject()V

    .line 122
    invoke-virtual {p1}, Ljava/io/ObjectInputStream;->readObject()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Ljava/lang/Class;

    iput-object v0, p0, Lo/Ey;->ˋ:Ljava/lang/Class;

    .line 123
    new-instance v0, Ljava/util/EnumMap;

    iget-object v1, p0, Lo/Ey;->ˋ:Ljava/lang/Class;

    invoke-direct {v0, v1}, Ljava/util/EnumMap;-><init>(Ljava/lang/Class;)V

    invoke-static {v0}, Lo/LI;->ˊ(Ljava/util/Map;)Lo/LI;

    move-result-object v0

    new-instance v1, Ljava/util/HashMap;

    iget-object v2, p0, Lo/Ey;->ˋ:Ljava/lang/Class;

    invoke-virtual {v2}, Ljava/lang/Class;->getEnumConstants()[Ljava/lang/Object;

    move-result-object v2

    check-cast v2, [Ljava/lang/Enum;

    array-length v2, v2

    mul-int/lit8 v2, v2, 0x3

    div-int/lit8 v2, v2, 0x2

    invoke-direct {v1, v2}, Ljava/util/HashMap;-><init>(I)V

    invoke-virtual {p0, v0, v1}, Lo/Ey;->ˊ(Ljava/util/Map;Ljava/util/Map;)V

    .line 125
    invoke-static {p0, p1}, Lo/Ke;->ˊ(Ljava/util/Map;Ljava/io/ObjectInputStream;)V

    .line 126
    return-void
.end method

.method private writeObject(Ljava/io/ObjectOutputStream;)V
    .locals 1
    .annotation build Lo/Aj;
        ˊ = "java.io.ObjectOutputStream"
    .end annotation

    .line 112
    invoke-virtual {p1}, Ljava/io/ObjectOutputStream;->defaultWriteObject()V

    .line 113
    iget-object v0, p0, Lo/Ey;->ˋ:Ljava/lang/Class;

    invoke-virtual {p1, v0}, Ljava/io/ObjectOutputStream;->writeObject(Ljava/lang/Object;)V

    .line 114
    invoke-static {p0, p1}, Lo/Ke;->ˊ(Ljava/util/Map;Ljava/io/ObjectOutputStream;)V

    .line 115
    return-void
.end method

.method public static ˊ(Ljava/lang/Class;)Lo/Ey;
    .locals 1
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "<K:Ljava/lang/Enum<TK;>;V:Ljava/lang/Object;>(Ljava/lang/Class<TK;>;)Lo/Ey<TK;TV;>;"
        }
    .end annotation

    .line 58
    new-instance v0, Lo/Ey;

    invoke-direct {v0, p0}, Lo/Ey;-><init>(Ljava/lang/Class;)V

    return-object v0
.end method

.method public static ˊ(Ljava/util/Map;)Lo/Ey;
    .locals 2
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "<K:Ljava/lang/Enum<TK;>;V:Ljava/lang/Object;>(Ljava/util/Map<TK;+TV;>;)Lo/Ey<TK;TV;>;"
        }
    .end annotation

    .line 73
    invoke-static {p0}, Lo/Ex;->ˋ(Ljava/util/Map;)Ljava/lang/Class;

    move-result-object v0

    invoke-static {v0}, Lo/Ey;->ˊ(Ljava/lang/Class;)Lo/Ey;

    move-result-object v1

    .line 74
    invoke-virtual {v1, p0}, Lo/Ey;->putAll(Ljava/util/Map;)V

    .line 75
    return-object v1
.end method

# virtual methods
.method public bridge synthetic L_()Ljava/util/Set;
    .locals 1

    .line 46
    invoke-super {p0}, Lo/CU;->L_()Ljava/util/Set;

    move-result-object v0

    return-object v0
.end method

.method public bridge synthetic N_()Lo/DD;
    .locals 1

    .line 46
    invoke-super {p0}, Lo/CU;->N_()Lo/DD;

    move-result-object v0

    return-object v0
.end method

.method public bridge synthetic clear()V
    .locals 0

    .line 46
    invoke-super {p0}, Lo/CU;->clear()V

    return-void
.end method

.method public bridge synthetic containsValue(Ljava/lang/Object;)Z
    .locals 1

    .line 46
    invoke-super {p0, p1}, Lo/CU;->containsValue(Ljava/lang/Object;)Z

    move-result v0

    return v0
.end method

.method public bridge synthetic entrySet()Ljava/util/Set;
    .locals 1

    .line 46
    invoke-super {p0}, Lo/CU;->entrySet()Ljava/util/Set;

    move-result-object v0

    return-object v0
.end method

.method public bridge synthetic keySet()Ljava/util/Set;
    .locals 1

    .line 46
    invoke-super {p0}, Lo/CU;->keySet()Ljava/util/Set;

    move-result-object v0

    return-object v0
.end method

.method public synthetic put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
    .locals 1

    .line 46
    move-object v0, p1

    check-cast v0, Ljava/lang/Enum;

    invoke-virtual {p0, v0, p2}, Lo/Ey;->ˊ(Ljava/lang/Enum;Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v0

    return-object v0
.end method

.method public bridge synthetic putAll(Ljava/util/Map;)V
    .locals 0

    .line 46
    invoke-super {p0, p1}, Lo/CU;->putAll(Ljava/util/Map;)V

    return-void
.end method

.method public bridge synthetic remove(Ljava/lang/Object;)Ljava/lang/Object;
    .locals 1

    .line 46
    invoke-super {p0, p1}, Lo/CU;->remove(Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v0

    return-object v0
.end method

.method ˊ(Ljava/lang/Enum;)Ljava/lang/Enum;
    .locals 1
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(TK;)TK;"
        }
    .end annotation

    .line 90
    invoke-static {p1}, Lo/Bk;->ˊ(Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Ljava/lang/Enum;

    return-object v0
.end method

.method public ˊ(Ljava/lang/Enum;Ljava/lang/Object;)Ljava/lang/Object;
    .locals 1
    .param p2    # Ljava/lang/Object;
        .annotation runtime Ljavax/annotation/Nullable;
        .end annotation
    .end param
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(TK;TV;)TV;"
        }
    .end annotation

    .line 94
    invoke-super {p0, p1, p2}, Lo/CU;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v0

    return-object v0
.end method

.method bridge synthetic ˊ(Ljava/lang/Object;)Ljava/lang/Object;
    .locals 1

    .line 46
    move-object v0, p1

    check-cast v0, Ljava/lang/Enum;

    invoke-virtual {p0, v0}, Lo/Ey;->ˊ(Ljava/lang/Enum;)Ljava/lang/Enum;

    move-result-object v0

    return-object v0
.end method

.method public synthetic ˊ(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
    .locals 1

    .line 46
    move-object v0, p1

    check-cast v0, Ljava/lang/Enum;

    invoke-virtual {p0, v0, p2}, Lo/Ey;->ˋ(Ljava/lang/Enum;Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v0

    return-object v0
.end method

.method public ˋ(Ljava/lang/Enum;Ljava/lang/Object;)Ljava/lang/Object;
    .locals 1
    .param p2    # Ljava/lang/Object;
        .annotation runtime Ljavax/annotation/Nullable;
        .end annotation
    .end param
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(TK;TV;)TV;"
        }
    .end annotation

    .line 98
    invoke-super {p0, p1, p2}, Lo/CU;->ˊ(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v0

    return-object v0
.end method

.method public ˏ()Ljava/lang/Class;
    .locals 1
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()Ljava/lang/Class<TK;>;"
        }
    .end annotation

    .line 103
    iget-object v0, p0, Lo/Ey;->ˋ:Ljava/lang/Class;

    return-object v0
.end method


text:
import {Component, OnInit} from 'angular2/core';
import {ROUTER_DIRECTIVES, RouteConfig, Router} from "angular2/router";
import {AboutComponent} from "./content/about.component";
import {WorkComponent} from "./content/work.component";
import {CvComponent} from "./content/cv.component";
import {WorkDetails} from "./content/work/workdetails.component";
import {CvNewComponent} from "./content/cvNew.component";

@Component({
    selector: 'my-app',
    template: `

MARKUS MØRLAND

post@markusmorland.no

+47 90840628

markusmorland.no

Linkedin

                            <button id="toggleNavBtn" type="button" (click)="showNav = !showNav">
                                Toggle navigation

                            </button>

Om meg

Arbeid

CV

		    <router-outlet></router-outlet>

		`,
    // Add dependent directives
    directives: [AboutComponent, ROUTER_DIRECTIVES]
})

// Setup router config / hrefs
@RouteConfig([
    {path: '/ommeg', name: 'About', component: AboutComponent, useAsDefault: true},
    {path: '/arbeid', name: 'Work', component: WorkComponent},
    {path: '/cv', name: 'Cv', component: CvComponent},
    {path: '/cvNew', name: 'CvNew', component: CvNewComponent},
    {path: '/arbeid/:id', name: 'WorkDetails', component: WorkDetails}
])

export class AppComponent implements OnInit {
    // Hide nav as default. Show nav on nav-bar click
    showNav = false;

    constructor(private _router:Router){}

    // Display navigation on click - Different size on css-padding depending on screen width
    showNavStyle() {
        if (this.showNav) {
            if (window.innerWidth < 767) {
                return "345px 0 0";
            } else {
                return "172px 0 0";
            }

        } else {
            return "100px 0 0";
        }
    }

    ngOnInit():any {
        // Add scroll to top of page when route is changed
        this._router.subscribe(() => {
            window.scrollTo(0,0);
        })
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Michelia 1(no. 5): 471 (1879)

#### Original name
Dermatea stegioides Speg.

### Remarks
null


text:
"use strict";

module.exports = function (grunt) {

  var bower,
    path,
    async,
    colors,
    rimraf,
    validator,
    BowerAssets,
    AssetCopier,
    LayoutsManager;

    /* ===============================================
                      Helper Methods
       =============================================*/
    function requireDependencies() {
    bower = require("bower");
    path = require("path");
    async = require("async");
    colors = require("colors");
    rimraf = require("rimraf").sync;
    validator = require('bower-json');
    BowerAssets = require("./lib/bower_assets");
    AssetCopier = require("./lib/asset_copier");
    LayoutsManager = require("./lib/layouts_manager");
  }

  function log(message) {
    log.logger.writeln(message);
  }

  function validate(options) {
    var bowerFile = bower.config.json || "bower.json";

    validator.read(bowerFile, function (error, json) {
      if (error) {
        console.error("bower.json validation: Failed - " + error.message);
      }
      else {
        if (options.verbose) {
          console.info("bower.json validation: Passed");
        }
      }
    });
  }

  /* ===============================================
                    Core Methods
    =============================================*/

  function clean(dir, callback) {
    rimraf(dir);
    callback();
  }

  function copy(options, callback) {
    var bowerAssets = new BowerAssets(bower, options.cwd);
    bowerAssets.on("end", function (assets) {
      var copier = new AssetCopier(assets, options, function (source, destination, isFile) {
        log("grunt-bower " + "copying ".cyan + ((isFile ? "" : " dir ") + source + " -> " + destination).grey);
      });

      copier.once("copied", callback);
      copier.copy();
    }).get();
  }

  function fail(error) {
    grunt.fail.fatal(error);
  }

  function install(options, callback) {

    validate(options);

    bower.commands.install([], options.bowerOptions)
      .on("log", function(result) {
        log(["bower", result.id.cyan, result.message].join(" "));
      })
      .on("error", fail)
      .on("end", callback);
  }

  function prune(options, callback) {
    bower.commands.prune([], options.bowerOptions)
      .on("log", function (result) {
        log(["bower", result.id.cyan, result.message].join(" "));
      })
      .on("error", fail)
      .on("end", callback);
  }

  grunt.registerMultiTask("bower", "Install Bower packages.", function () {
    var tasks = [],
      done = this.async(),
      options = this.options({
        cleanTargetDir: false,
        cleanBowerDir: false,
        targetDir: "./lib",
        layout: "byType",
        install: true,
        prune: false,
        verbose: false,
        copy: false,
        bowerOptions: {}
      }),
      add = function (successMessage, fn) {
        tasks.push(function (callback) {
          fn(function () {
            grunt.log.ok(successMessage);
            callback();
          });
        });
      },
      bowerDir,
      targetDir;

    // calling require on the dependencies has been delayed to prevent slow
    // dependencies delaying the startup of grunt even if this task is not used
    // at all
    requireDependencies();

    bowerDir = path.resolve(bower.config.directory);
    targetDir = path.resolve(options.targetDir);

    log.logger = options.verbose ? grunt.log : grunt.verbose;
    options.layout = LayoutsManager.getLayout(options.layout, fail);
    options.cwd = grunt.option("base") || process.cwd();

    if (options.cleanup !== undefined) {
      options.cleanTargetDir = options.cleanBowerDir = options.cleanup;
    }

    if (options.cleanTargetDir) {
      add("Cleaned target dir " + targetDir.grey, function (callback) {
        clean(targetDir, callback);
      });
    }

    if (options.install) {
      add("Installed bower packages", function (callback) {
        install(options, callback);
      });
    }

    if (options.prune) {
      add("Pruned bower packages", function (callback) {
        prune(options, callback);
      });
    }

    if (options.copy) {
      add("Copied packages to " + targetDir.grey, function (callback) {
        copy(options, callback);
      });
    }

    if (options.cleanBowerDir) {
      add("Cleaned bower dir " + bowerDir.grey, function (callback) {
        clean(bowerDir, callback);
      });
    }

    async.series(tasks, done);
  });

};


text:
nomes=["Denis","Giovane","Luciano"]

nomes.append("Renzo")

for i in range(len(nomes)):
    print(nomes[i])

print("Imprimir com enumerate")

for indice,valor in enumerate(nomes):
    print("%s: %s"%(indice,valor))

sobrenomes=["Costa","Liberato","Ramalho","Nuccitelli"]

pares_ordenados=zip(nomes,sobrenomes)

dicionario_de_nomes=dict(pares_ordenados)

for chave,valor in dicionario_de_nomes.items():
    print("O sobrenome do %s é %s"%(chave,valor))


text:
require 'zlib'

rd, wr = IO.pipe

if fork
  rd.close
  zipper = Zlib::Deflate.new
  zipper << "This is a string "
  data = zipper.deflate("to compress", Zlib::FINISH)
  wr.write(data)
  wr.close
  Process.wait
else
  wr.close
  unzipper = Zlib::Inflate.new
  unzipper << rd.read
  puts "We got: #{unzipper.inflate(nil)}"
end


text:
🎉 Thanks for your interest in contributing! 🎉

## Ramping Up

### Intro

- There are three ways for SDK to be loaded
  - Standard NPM package
  - Snippet in `<script>` tag
  - RequireJS (may be dropped in future)
- Workflow is facilitated with both `make` and `yarn` (legacy, may possibly be updated to full `yarn`)
- Chek out the [Amplitude Instrumentation Explorer]((https://chrome.google.com/webstore/detail/amplitude-instrumentation/acehfjhnmhbmgkedjmjlobpgdicnhkbp)) to help logging events during development

### Architecture

- `index.js` is the main entrypoint of SDK
- Stubbed methods are used when client imports via `<script>` snippet
  - Allows app to not be blocked while real JS SDK is loaded in
  - Sent events and identifys are tracked with queues
- Metadata storage (new) vs cookie (old) storage
  - more of issue with anonymous id, because it uses device id instead of user id
- UA Parser: Helps identify browsers
  - might be able to use upstream library and convert results, rather than our fork
- sameSiteCookie: Sets how public the cookie reading is
  - `amplitude.getInstance() is necessary even during reuse because of snippet stubbed
    - only applicable to snippet import

### Setting Up Development

- Cloning, installing, and building
```
git clone git@github.com:amplitude/Amplitude-JavaScript.git
cd Amplitude-JavaScript
make # Runs tests and generate builds
yarn dev # Start development utility. Open localhost:9000 in your browser to access
```

### PR Commit Title Conventions

PR titles should follow [conventional commit standards](https://www.conventionalcommits.org/en/v1.0.0/). This helps automate the [release](#release) process.

#### Commit Types ([related to release conditions](#release))

- **Special Case**: Any commit with `BREAKING CHANGES` in the body: Creates major release
- `feat(<optional scope>)`: New features (minimum minor release)
- `fix(<optional scope>)`: Bug fixes (minimum patch release)
- `perf(<optional scope>)`: Performance improvement
- `docs(<optional scope>)`: Documentation updates
- `test(<optional scope>)`: Test updates
- `refactor(<optional scope>)`: Code change that neither fixes a bug nor adds a feature
- `style(<optional scope>)`: Code style changes (e.g. formatting, commas, semi-colons)
- `build(<optional scope>)`: Changes that affect the build system or external dependencies (e.g. Yarn, Npm)
- `ci(<optional scope>)`: Changes to our CI configuration files and scripts
- `chore(<optional scope>)`: Other changes that don't modify src or test files
- `revert(<optional scope>)`: Revert commit

### Release [Amplitude Internal]

Releases are managed by [semantic-release](https://github.com/semantic-release/semantic-release). It is a tool that will scan commits since the last release, determine the next [semantic version number](https://semver.org/), publish, and create changelogs.

#### Release Conditions [Amplitude Internal]

- `BREAKING CHANGES` in the body will do a major release
  ```
  feat(cookies): Create new cookie format

  BREAKING CHANGES: Breaks old cookie format
  ```
- Else `feat` in title will do a `minor` release
  `feat(cookies): some changes`
- Else `fix` or `perf` in title will do a `patch` release
  `fix: null check bug`
- Else no release
  `docs: update website`


text:
import { nanoid } from 'nanoid'
import Joi from 'joi'
import boom from '@hapi/boom'
import { logger } from '@libp2p/logger'
import { tmpDir } from '../utils.js'

/**
 * @typedef {import('../types').Factory} Factory
 */

const debug = logger('ipfsd-ctl:routes')

const routeOptions = {
  validate: {
    query: Joi.object({
      id: Joi.string().required()
    })
  }
}

/**
 * @param {Error & { stdout?: string }} err
 */
const badRequest = err => {
  let msg
  if (err.stdout) {
    msg = err.stdout + ' - ' + err.message
  } else {
    msg = err.message
  }
  debug(err)
  throw boom.badRequest(msg)
}

/**
 * @type {Record<string, any>}
 */
const nodes = {}

/**
 * @namespace EndpointServerRoutes
 * @ignore
 * @param {import('@hapi/hapi').Server} server
 * @param {() => Factory | Promise<Factory>} createFactory
 * @returns {void}
 */
export default (server, createFactory) => {
  server.route({
    method: 'GET',
    path: '/util/tmp-dir',
    handler: async (request) => {
      const type = request.query.type || 'go'
      try {
        return { tmpDir: await tmpDir(type) }
      } catch (/** @type {any} */ err) {
        badRequest(err)
      }
    }
  })

  server.route({
    method: 'GET',
    path: '/version',
    handler: async (request) => {
      const id = request.query.id

      try {
        return { version: await nodes[id].version() }
      } catch (/** @type {any} */ err) {
        badRequest(err)
      }
    },
    options: routeOptions
  })

  server.route({
    method: 'POST',
    path: '/spawn',
    handler: async (request) => {
      const opts = request.payload || {}
      try {
        const ipfsd = await createFactory()
        const id = nanoid()
        // @ts-expect-error opts is a json object
        nodes[id] = await ipfsd.spawn(opts)
        return {
          id: id,
          apiAddr: nodes[id].apiAddr ? nodes[id].apiAddr.toString() : '',
          gatewayAddr: nodes[id].gatewayAddr ? nodes[id].gatewayAddr.toString() : '',
          grpcAddr: nodes[id].grpcAddr ? nodes[id].grpcAddr.toString() : '',
          initialized: nodes[id].initialized,
          started: nodes[id].started,
          disposable: nodes[id].disposable,
          env: nodes[id].env,
          path: nodes[id].path,
          clean: nodes[id].clean
        }
      } catch (/** @type {any} */ err) {
        badRequest(err)
      }
    }
  })

  /*
   * Initialize a repo.
   */
  server.route({
    method: 'POST',
    path: '/init',
    handler: async (request) => {
      const id = request.query.id
      const payload = request.payload || {}

      try {
        await nodes[id].init(payload)

        return {
          initialized: nodes[id].initialized
        }
      } catch (/** @type {any} */ err) {
        badRequest(err)
      }
    },
    options: routeOptions
  })

  /*
   * Start the daemon.
   */
  server.route({
    method: 'POST',
    path: '/start',
    handler: async (request) => {
      const id = request.query.id

      try {
        await nodes[id].start()

        return {
          apiAddr: nodes[id].apiAddr ? nodes[id].apiAddr.toString() : '',
          gatewayAddr: nodes[id].gatewayAddr ? nodes[id].gatewayAddr.toString() : '',
          grpcAddr: nodes[id].grpcAddr ? nodes[id].grpcAddr.toString() : ''
        }
      } catch (/** @type {any} */ err) {
        badRequest(err)
      }
    },
    options: routeOptions
  })

  /*
   * Delete the repo that was being used.
   * If the node was marked as `disposable` this will be called
   * automatically when the process is exited.
   */
  server.route({
    method: 'POST',
    path: '/cleanup',
    handler: async (request, h) => {
      const id = request.query.id

      try {
        await nodes[id].cleanup()

        return h.response().code(200)
      } catch (/** @type {any} */ err) {
        badRequest(err)
      }
    },
    options: routeOptions
  })

  /*
   * Stop the daemon.
   */
  server.route({
    method: 'POST',
    path: '/stop',
    handler: async (request, h) => {
      const id = request.query.id

      try {
        await nodes[id].stop()

        return h.response().code(200)
      } catch (/** @type {any} */ err) {
        badRequest(err)
      }
    },
    options: routeOptions
  })

  /*
   * Get the pid of the `ipfs daemon` process.
   */
  server.route({
    method: 'GET',
    path: '/pid',
    handler: async (request) => {
      const id = request.query.id

      return { pid: await nodes[id].pid() }
    },
    options: routeOptions
  })
}


text:
test_run = require('test_run')
inspector = test_run.new()
engine = inspector:get_cfg('engine')

-- space create/drop
space = box.schema.space.create('test', { engine = engine })
space:drop()

-- space index create/drop
space = box.schema.space.create('test', { engine = engine })
index = space:create_index('primary')
space:drop()

-- space index create/drop alter
space = box.schema.space.create('test', { engine = engine })
index = space:create_index('primary')
_index = box.space[box.schema.INDEX_ID]
_index:delete{102, 0}
space:drop()

-- space index create/drop tree string
space = box.schema.space.create('test', { engine = engine })
index = space:create_index('primary', {type = 'tree', parts = {1, 'STR'}})
_ = space:insert({'test'})
space:drop()

-- space index create/drop tree num
space = box.schema.space.create('test', { engine = engine })
index = space:create_index('primary', {type = 'tree', parts = {1, 'num'}})
_ = space:insert({13})
space:drop()

-- space index create/drop tree multi-part num
space = box.schema.space.create('test', { engine = engine })
index = space:create_index('primary', {type = 'tree', parts = {1, 'num', 2, 'num'}})
_ = space:insert({13})
space:drop()

-- space index size
space = box.schema.space.create('test', { engine = engine })
index = space:create_index('primary')
primary = space.index[0]
primary:len()
_ = space:insert({13})
_ = space:insert({14})
_ = space:insert({15})
primary:len()
space:drop()


text:
<!DOCTYPE html>

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta http-equiv="X-UA-Compatible" content="IE=edge" />
	<meta name="viewport" content="width=device-width,initial-scale=1">

	<title>SLIDER REVOLUTION -  The Responsive Slider Plugin</title>

    <link rel="stylesheet" type="text/css" href="../examples/css/style.css" media="screen" />

    <link rel="stylesheet" type="text/css" href="../examples/css/navstylechange.css" media="screen" />
    <link rel="stylesheet" type="text/css" href="../examples/css/noneed.css" media="screen" />

	<link rel="stylesheet" type="text/css" href="../examples/rs-plugin/css/settings.css" media="screen" />

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

BUY NOW

Left Top

Center Top

Right Top

Left Center

Center Center

Right Center

Left Bottom

Center Bottom

Right Bottom

Left Top (x+50, y+100)

Center Top (x-50, y+40)

Right Top (x-90, y+20)

Left Center (x+30, y-20)

Center Center (x-30,y+20)

Right Center (x-50, y-40)

Left Bottom (x+15,y-20)

Center Bottom (y-10)

Right Bottom (x-30, y-30)

					<div class="tp-caption mediumlarge_light_white_center customin customout start"
						data-x="right"
						data-hoffset="-60"
						data-y="bottom"
						data-voffset="-120"

						data-customin="x:0;y:0;z:0;rotationX:90;rotationY:0;rotationZ:0;scaleX:1;scaleY:1;skewX:0;skewY:0;opacity:0;transformPerspective:200;transformOrigin:50% 0%;"
						data-customout="x:0;y:0;z:0;rotationX:0;rotationY:0;rotationZ:0;scaleX:0.75;scaleY:0.75;skewX:0;skewY:0;opacity:0;transformPerspective:600;transformOrigin:50% 50%;"
						data-speed="1000"
						data-start="500"
						data-easing="Back.easeInOut"
						data-endspeed="300">TRY THE
CAPTION ANIMATION
 BUILDER BELOW

GO AND GIVE A TRY

CREATE AWESOME ANIMATIONS

How to Align Captions ?

Each Caption is positioned via Absolute Position relative to the left/top corner of the Grid. The Grid is the Caption holder. It can but must not be the same size as the Slider itself. Since fullwidth and fullscreen slider can have a higher width or height dimension then the caption Grid itself. Still you can help yourself and position the captions on the center or bottom / right positions in the Grid. For this take a look on the following Settings in the Captions

In case you wish to force the Aligns go to the real corners of the Slide and break the Grid size, you can do this via some special options. See example: 04B.Sample-AlignForce.html

Caption at Center Center

			<div class="tp-caption medium_bg_asbestos lft"
				data-x="center"
				data-y="center"
				data-hoffset="0"
				data-voffset="0"
				data-speed="800"
				data-start="3300"
				data-easing="Power4.easeOut"
				data-endspeed="300"
				data-endeasing="Power1.easeIn"
				data-captionhidden="off"
				style="z-index: 6">Center Center
			</div>

To move vertical or horizontal the caption from that aligned position, you can use the hoffset and voffset settings

Center Center with -30px in the horizontal and +20px in the vertical direction

			<div class="tp-caption medium_bg_asbestos lft"
				data-x="center"
				data-y="center"
				data-hoffset="-30"
				data-voffset="20"
				data-speed="800"
				data-start="3300"
				data-easing="Power4.easeOut"
				data-endspeed="300"
				data-endeasing="Power1.easeIn"
				data-captionhidden="off"
				style="z-index: 6">Center Center
			</div>

In case you set the data-x and data-y with a value (not like center, right or vertical top, center, bottom) the captions will be aligned to the left top corner.

Left Top (default) Align, and simple positions

			<div class="tp-caption medium_bg_asbestos lft"
				data-x="250"
				data-y="180"
				data-speed="800"
				data-start="3300"
				data-easing="Power4.easeOut"
				data-endspeed="300"
				data-endeasing="Power1.easeIn"
				data-captionhidden="off"
				style="z-index: 6">Center Center
			</div>


text:
@interface MSEditAction : MSBaseAction
{
}
- (id)tooltip;
- (BOOL)isSelectable;
- (void)performAction:(id)arg1;
- (void)edit:(id)arg1;
- (id)validation;
@end


text:
@implementation PKTApp

#pragma mark - PKTModel

+ (NSDictionary *)dictionaryKeyPathsForPropertyNames {
  return @{
           @"appID" : @"app_id",
           @"spaceID" : @"space_id",
           @"iconID" : @"config.icon_id",
           @"name": @"config.name",
           @"itemName": @"config.item_name",
           @"appDescription": @"config.description",
           @"link" : @"link",
           @"fields" : @"fields"
  };
}

+ (NSValueTransformer *)linkValueTransformer {
  return [NSValueTransformer pkt_URLTransformer];
}

+ (NSValueTransformer *)fieldsValueTransformer {
  return [NSValueTransformer pkt_transformerWithModelClass:[PKTAppField class]];
}

#pragma mark - API

+ (PKTAsyncTask *)fetchAppWithID:(NSUInteger)appID {
  PKTRequest *request = [PKTAppsAPI requestForAppWithID:appID];
  PKTAsyncTask *requestTask = [[PKTClient currentClient] performRequest:request];

  Class objectClass = [self class];

  PKTAsyncTask *task = [requestTask map:^id(PKTResponse *response) {
    return [[objectClass alloc] initWithDictionary:response.body];
  }];

  return task;
}

+ (PKTAsyncTask *)fetchAppsInWorkspaceWithID:(NSUInteger)spaceID {
  PKTRequest *request = [PKTAppsAPI requestForAppsInWorkspaceWithID:spaceID];
  PKTAsyncTask *requestTask = [[PKTClient currentClient] performRequest:request];

  Class objectClass = [self class];

  PKTAsyncTask *task = [requestTask map:^id(PKTResponse *response) {
    return [response.body pkt_mappedArrayWithBlock:^id(NSDictionary *dict) {
      return [[objectClass alloc] initWithDictionary:dict];
    }];
  }];

  return task;
}

+ (PKTAsyncTask *)fetchAppInWorkspaceWithID:(NSUInteger)spaceID urlLabel:(NSString *)urlLabel {
  PKTRequest *request = [PKTAppsAPI requestForAppInWorkspaceWithID:spaceID urlLabel:urlLabel];
  PKTAsyncTask *requestTask = [[PKTClient currentClient] performRequest:request];

  Class objectClass = [self class];

  PKTAsyncTask *task = [requestTask map:^id(PKTResponse *response) {
    return [[objectClass alloc] initWithDictionary:response.body];
  }];

  return task;
}

#pragma mark - Public

- (PKTAppField *)fieldWithExternalID:(NSString *)externalID {
  __block PKTAppField *field = nil;

  [self.fields enumerateObjectsUsingBlock:^(PKTAppField *currentField, NSUInteger idx, BOOL *stop) {
    if ([currentField.externalID isEqualToString:externalID]) {
      field = currentField;
      *stop = YES;
    }
  }];

  return field;
}

@end


text:
<!DOCTYPE html>

    <title>WebAuthn Codelab</title>
    <meta name="description" content="WebAuthn Codelab">
    <link id="favicon" rel="icon" href="https://glitch.com/edit/favicon-app.ico" type="image/x-icon">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="/bundle.css">
    <link rel="stylesheet" href="https://unpkg.com/material-components-web@7.0.0/dist/material-components-web.min.css">

    <mwc-top-app-bar-fixed>
      WebAuthn codelab
    </mwc-top-app-bar-fixed>

          Verify your identity

          <mwc-button id="reauth" raised>Authenticate</mwc-button>

          <mwc-button id="cancel">Sign-in with password</mwc-button>

      <form id="form" method="POST" action="/auth/password" class="hidden">

          Enter a password

        <input type="hidden" name="username" value="{{username}}" />

          password
          <input type="password" class="mdc-text-field__input" aria-labelledby="password-label" name="password" />

        <input type="submit" class="mdc-button mdc-button--raised" value="Sign-In" />

password will be ignored in this demo.

      </form>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. Soc. mycol. Fr. 22: 57 (1906)

#### Original name
Rhizopus rachidis Pat.

### Remarks
null


text:
package uk.ac.ebi.eva.pipeline.io.writers;

import com.mongodb.BasicDBObject;
import com.mongodb.BulkWriteException;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import uk.ac.ebi.eva.commons.models.data.Variant;
import uk.ac.ebi.eva.pipeline.configuration.MongoConfiguration;
import uk.ac.ebi.eva.pipeline.model.converters.data.VariantToMongoDbObjectConverter;
import uk.ac.ebi.eva.pipeline.parameters.MongoConnection;
import uk.ac.ebi.eva.test.rules.TemporaryMongoRule;
import uk.ac.ebi.eva.utils.MongoDBHelper;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static junit.framework.TestCase.assertTrue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.when;

/**
 * Testing {@link VariantMongoWriter}
 */
@RunWith(SpringRunner.class)
@TestPropertySource({"classpath:test-mongo.properties"})
@ContextConfiguration(classes = {MongoConnection.class, MongoMappingContext.class})
public class VariantMongoWriterTest {

    private static final List<? extends Variant> EMPTY_LIST = new ArrayList<>();

    private VariantToMongoDbObjectConverter variantToMongoDbObjectConverter =
            Mockito.mock(VariantToMongoDbObjectConverter.class);

    private final String collectionName = "variants";

    @Autowired
    private MongoConnection mongoConnection;

    @Autowired
    private MongoMappingContext mongoMappingContext;

    @Rule
    public TemporaryMongoRule mongoRule = new TemporaryMongoRule();

    @Test
    public void noVariantsNothingShouldBeWritten() throws UnknownHostException {
        String dbName = mongoRule.getRandomTemporaryDatabaseName();
        MongoOperations mongoOperations = MongoConfiguration.getMongoOperations(dbName, mongoConnection,
                mongoMappingContext);
        DBCollection dbCollection = mongoOperations.getCollection(collectionName);

        VariantMongoWriter variantMongoWriter = new VariantMongoWriter(collectionName, mongoOperations,
                                                                       variantToMongoDbObjectConverter);
        variantMongoWriter.doWrite(EMPTY_LIST);

        assertEquals(0, dbCollection.count());
    }

    @Test
    public void variantsShouldBeWrittenIntoMongoDb() throws Exception {
        Variant variant1 = new Variant("1", 1, 2, "A", "T");
        Variant variant2 = new Variant("2", 3, 4, "C", "G");

        String dbName = mongoRule.getRandomTemporaryDatabaseName();
        MongoOperations mongoOperations = MongoConfiguration.getMongoOperations(dbName, mongoConnection,
                mongoMappingContext);
        DBCollection dbCollection = mongoOperations.getCollection(collectionName);

        BasicDBObject dbObject = new BasicDBObject();

        when(variantToMongoDbObjectConverter.convert(any(Variant.class))).thenReturn(dbObject).thenReturn(dbObject);

        VariantMongoWriter variantMongoWriter = new VariantMongoWriter(collectionName, mongoOperations,
                                                                       variantToMongoDbObjectConverter);
        variantMongoWriter.write(Collections.singletonList(variant1));
        variantMongoWriter.write(Collections.singletonList(variant2));

        assertEquals(2, dbCollection.count());
    }

    @Test
    public void indexesShouldBeCreatedInBackground() throws UnknownHostException {
        String dbName = mongoRule.getRandomTemporaryDatabaseName();
        MongoOperations mongoOperations = MongoConfiguration.getMongoOperations(dbName, mongoConnection,
                mongoMappingContext);
        DBCollection dbCollection = mongoOperations.getCollection(collectionName);

        VariantMongoWriter variantMongoWriter = new VariantMongoWriter(collectionName, mongoOperations,
                                                                       variantToMongoDbObjectConverter);

        List<DBObject> indexInfo = dbCollection.getIndexInfo();

        Set<String> createdIndexes = indexInfo.stream().map(index -> index.get("name").toString())
                .collect(Collectors.toSet());
        Set<String> expectedIndexes = new HashSet<>();
        expectedIndexes.addAll(Arrays.asList("annot.ct.so_1", "annot.xrefs.id_1", "chr_1_start_1_end_1",
                                             "files.sid_1_files.fid_1", "_id_", "ids_1"));
        assertEquals(expectedIndexes, createdIndexes);

        indexInfo.stream().filter(index -> !("_id_".equals(index.get("name").toString())))
                          .forEach(index -> assertEquals("true",
                                                         index.get(MongoDBHelper.BACKGROUND_INDEX).toString()));
    }

    @Test
    public void testNoDuplicatesCanBeInserted() throws Exception {
        Variant variant1 = new Variant("1", 1, 2, "A", "T");

        String dbName = mongoRule.getRandomTemporaryDatabaseName();
        MongoOperations mongoOperations = MongoConfiguration.getMongoOperations(dbName, mongoConnection,
                mongoMappingContext);

        BasicDBObject dbObject = new BasicDBObject();

        when(variantToMongoDbObjectConverter.convert(any(Variant.class))).thenReturn(dbObject).thenReturn(dbObject);

        VariantMongoWriter variantMongoWriter = new VariantMongoWriter(collectionName, mongoOperations,
                                                                       variantToMongoDbObjectConverter);
        variantMongoWriter.write(Collections.singletonList(variant1));

        try {
            variantMongoWriter.write(Collections.singletonList(variant1));
            fail("Should have thrown a mongo write exception due to duplicate key");
        } catch (BulkWriteException e) {
            assertTrue(e.getMessage().contains("duplicate key"));
        }
    }

}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.12"/>
<title>OpenCV: cv::superres::BroxOpticalFlow Class Reference</title>
<link href="../../opencv.ico" rel="shortcut icon" type="image/x-icon" />
<link href="../../tabs.css" rel="stylesheet" type="text/css"/>

<link href="../../search/search.css" rel="stylesheet" type="text/css"/>

<link href="../../doxygen.css" rel="stylesheet" type="text/css" />
<link href="../../stylesheet.css" rel="stylesheet" type="text/css"/>

OpenCV
    3.2.0

Open Source Computer Vision

cv

superres

BroxOpticalFlow

Public Member Functions |
List of all members

cv::superres::BroxOpticalFlow Class Referenceabstract
Super Resolution

#include "optical_flow.hpp"

Inheritance diagram for cv::superres::BroxOpticalFlow:

  <map id="cv::superres::BroxOpticalFlow_map" name="cv::superres::BroxOpticalFlow_map">
<area href="../../d1/d21/classcv_1_1superres_1_1DenseOpticalFlowExt.html" alt="cv::superres::DenseOpticalFlowExt" shape="rect" coords="0,56,208,80"/>
<area href="../../d3/d46/classcv_1_1Algorithm.html" title="This is a base class for all more or less complex algorithms in OpenCV. " alt="cv::Algorithm" shape="rect" coords="0,0,208,24"/>
</map>

Public Member Functions

virtual double 	getAlpha () const =0

 	Flow smoothness.  More...

virtual double 	getGamma () const =0

 	Gradient constancy importance.  More...

virtual int 	getInnerIterations () const =0

 	Number of lagged non-linearity iterations (inner loop)  More...

virtual int 	getOuterIterations () const =0

 	Number of warping iterations (number of pyramid levels)  More...

virtual double 	getScaleFactor () const =0

 	Pyramid scale factor.  More...

virtual int 	getSolverIterations () const =0

 	Number of linear system solver iterations.  More...

virtual void 	setAlpha (double val)=0

 	Flow smoothness.  More...

virtual void 	setGamma (double val)=0

 	Gradient constancy importance.  More...

virtual void 	setInnerIterations (int val)=0

 	Number of lagged non-linearity iterations (inner loop)  More...

virtual void 	setOuterIterations (int val)=0

 	Number of warping iterations (number of pyramid levels)  More...

virtual void 	setScaleFactor (double val)=0

 	Pyramid scale factor.  More...

virtual void 	setSolverIterations (int val)=0

 	Number of linear system solver iterations.  More...

 Public Member Functions inherited from cv::superres::DenseOpticalFlowExt

virtual void 	calc (InputArray frame0, InputArray frame1, OutputArray flow1, OutputArray flow2=noArray())=0

virtual void 	collectGarbage ()=0

 Public Member Functions inherited from cv::Algorithm

 	Algorithm ()

virtual 	~Algorithm ()

virtual void 	clear ()

 	Clears the algorithm state.  More...

virtual bool 	empty () const

 	Returns true if the Algorithm is empty (e.g. in the very beginning or after unsuccessful read.  More...

virtual String 	getDefaultName () const

virtual void 	read (const FileNode &fn)

 	Reads algorithm parameters from a file storage.  More...

virtual void 	save (const String &filename) const

virtual void 	write (FileStorage &fs) const

 	Stores algorithm parameters in a file storage.  More...

Additional Inherited Members

 Static Public Member Functions inherited from cv::Algorithm

template<typename _Tp >

static Ptr< _Tp > 	load (const String &filename, const String &objname=String())

 	Loads algorithm from the file.  More...

template<typename _Tp >

static Ptr< _Tp > 	loadFromString (const String &strModel, const String &objname=String())

 	Loads algorithm from a String.  More...

template<typename _Tp >

static Ptr< _Tp > 	read (const FileNode &fn)

 	Reads algorithm from the file node.  More...

 Protected Member Functions inherited from cv::Algorithm

void 	writeFormat (FileStorage &fs) const

Member Function Documentation

§ getAlpha()

          virtual double cv::superres::BroxOpticalFlow::getAlpha
          (
          	)
           const

pure virtual

Flow smoothness.

See also

setAlpha

§ getGamma()

          virtual double cv::superres::BroxOpticalFlow::getGamma
          (
          	)
           const

pure virtual

Gradient constancy importance.

See also

setGamma

§ getInnerIterations()

          virtual int cv::superres::BroxOpticalFlow::getInnerIterations
          (
          	)
           const

pure virtual

Number of lagged non-linearity iterations (inner loop)

See also

setInnerIterations

§ getOuterIterations()

          virtual int cv::superres::BroxOpticalFlow::getOuterIterations
          (
          	)
           const

pure virtual

Number of warping iterations (number of pyramid levels)

See also

setOuterIterations

§ getScaleFactor()

          virtual double cv::superres::BroxOpticalFlow::getScaleFactor
          (
          	)
           const

pure virtual

Pyramid scale factor.

See also

setScaleFactor

§ getSolverIterations()

          virtual int cv::superres::BroxOpticalFlow::getSolverIterations
          (
          	)
           const

pure virtual

Number of linear system solver iterations.

See also

setSolverIterations

§ setAlpha()

          virtual void cv::superres::BroxOpticalFlow::setAlpha
          (
          double
          val	)

pure virtual

Flow smoothness.

See also

getAlpha

§ setGamma()

          virtual void cv::superres::BroxOpticalFlow::setGamma
          (
          double
          val	)

pure virtual

Gradient constancy importance.

See also

getGamma

§ setInnerIterations()

          virtual void cv::superres::BroxOpticalFlow::setInnerIterations
          (
          int
          val	)

pure virtual

Number of lagged non-linearity iterations (inner loop)

See also

getInnerIterations

§ setOuterIterations()

          virtual void cv::superres::BroxOpticalFlow::setOuterIterations
          (
          int
          val	)

pure virtual

Number of warping iterations (number of pyramid levels)

See also

getOuterIterations

§ setScaleFactor()

          virtual void cv::superres::BroxOpticalFlow::setScaleFactor
          (
          double
          val	)

pure virtual

Pyramid scale factor.

See also

getScaleFactor

§ setSolverIterations()

          virtual void cv::superres::BroxOpticalFlow::setSolverIterations
          (
          int
          val	)

pure virtual

Number of linear system solver iterations.

See also

getSolverIterations

The documentation for this class was generated from the following file:

superres/include/opencv2/superres/optical_flow.hpp

<address class="footer">
Generated on Fri Dec 23 2016 13:00:29 for OpenCV by

 1.8.12
</address>


text:
package nl.gridline.zieook.workflow.rest;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.File;

import javax.ws.rs.core.Response;

import nl.gridline.zieook.workflow.api.ContentProviderCRUD;
import nl.gridline.zieook.workflow.api.Recommender;
import nl.gridline.zieook.workflow.model.ContentProvider;
import nl.gridline.zieook.workflow.model.RecommenderConfig;

import org.jboss.resteasy.client.ProxyFactory;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.webapp.WebAppContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * These test only test for sending data and marshall / unmarshall exceptions, they should fail because they are
 * dependent on a content provider that does not exists in this context.
 *

 * Project zieook-backend-workflow

 * RecommenderImplTest.java created 11 feb. 2011
 *

 * Copyright, all rights reserved 2011 GridLine Amsterdam
 * @author Job
 * @version $Revision$, $Date$
 */
public class RecommenderImplTest
{

	private static final Logger LOG = LoggerFactory.getLogger(RecommenderImplTest.class);

	private static final int port = 20100;
	private static Server server;
	private static String uri;

	/**
	 * @throws java.lang.Exception
	 */
	@BeforeClass
	public static void setUpBeforeClass() throws Exception
	{

		// start the server:
		server = new Server(port);
		WebAppContext context = new WebAppContext();

		uri = "http://localhost:20100";

		// see if this can be set more dynamically:
		context.setContextPath("/");
		context.setResourceBase(new File("src/main/webapp/").getCanonicalPath());
		context.setDescriptor(new File("src/main/webapp/").getCanonicalPath() + "/WEB-INF/web.xml");

		server.setHandler(context);
		server.start();
	}

	/**
	 * @throws java.lang.Exception
	 */
	@AfterClass
	public static void tearDownAfterClass() throws Exception
	{
		// shutdown the server:
		server.stop();
	}

	@Before
	public void setup()
	{
		// create content provider:
		ContentProviderCRUD cprovider = ProxyFactory.create(ContentProviderCRUD.class, uri);
		cprovider.createContentProvider(ConstantsTest.getContentProvider());

		ContentProvider newcp = cprovider.readContentProvider(ConstantsTest.CP);
		assertEquals(ConstantsTest.getContentProvider(), newcp);
	}

	@After
	public void after()
	{
		ContentProviderCRUD cprovider = ProxyFactory.create(ContentProviderCRUD.class, uri);
		cprovider.deleteContentProvider(ConstantsTest.CP);
		try
		{
			cprovider.readContentProvider(ConstantsTest.CP);
		}
		catch (org.jboss.resteasy.client.ClientResponseFailure e)
		{
			assertEquals(404, e.getResponse().getStatus());
		}
	}

	/**
	 * Test method for
	 * {@link nl.gridline.zieook.workflow.rest.RecommenderImpl#createRecommender(java.lang.String, nl.gridline.zieook.workflow.model.RecommenderConfig)}
	 * .
	 */
	@Test
	public final void testCreateReadDeleteConfiguration()
	{
		LOG.info("CREATE recommenders test");

		Recommender proxy = ProxyFactory.create(Recommender.class, uri);

		Response response = proxy.createRecommender(ConstantsTest.CP, ConstantsTest.getRecommenderConfig());
		assertEquals(201, response.getStatus());

		RecommenderConfig newconfig = proxy.readConfiguration(ConstantsTest.CP, ConstantsTest.RECOMMENDER);
		LOG.info("recommender created: {}", newconfig.toJSON());
		assertEquals(ConstantsTest.getRecommenderConfig(), newconfig);

		Response deleted = proxy.deleteRecommender(ConstantsTest.CP, ConstantsTest.RECOMMENDER);
		assertEquals(200, deleted.getStatus());

		try
		{
			RecommenderConfig empty = proxy.readConfiguration(ConstantsTest.CP, ConstantsTest.RECOMMENDER);

			// this line should not be executed:
			assertTrue(empty == null);
		}
		catch (org.jboss.resteasy.client.ClientResponseFailure e)
		{
			assertEquals(404, e.getResponse().getStatus());
		}
	}

	/**
	 * Test method for
	 * {@link nl.gridline.zieook.workflow.rest.RecommenderImpl#updateRecommender(java.lang.String, java.lang.String, nl.gridline.zieook.workflow.model.RecommenderConfig)}
	 * .
	 */
	@Test
	@Ignore
	public final void testUpdateConfiguration()
	{
		LOG.info("UPDATE recommenders test");

		Recommender proxy = ProxyFactory.create(Recommender.class, uri);

		Response created = proxy.createRecommender(ConstantsTest.CP, ConstantsTest.getRecommenderConfig());
		assertEquals(201, created.getStatus());

		RecommenderConfig recommender = ConstantsTest.getRecommenderConfig();
		recommender.setCp(ConstantsTest.RECOMMENDER2);

		Response updated = proxy.updateRecommender(ConstantsTest.CP, ConstantsTest.RECOMMENDER, recommender);
		assertEquals(200, updated.getStatus());

		RecommenderConfig recommendernew = proxy.readConfiguration(ConstantsTest.CP, ConstantsTest.RECOMMENDER2);
		assertEquals(recommender, recommendernew);

		Response deleted = proxy.deleteRecommender(ConstantsTest.CP, ConstantsTest.RECOMMENDER);
		assertEquals(200, deleted.getStatus());

		try
		{
			RecommenderConfig empty = proxy.readConfiguration(ConstantsTest.CP, ConstantsTest.RECOMMENDER);

			// this line should not be executed, or null
			assertTrue(empty == null);
		}
		catch (org.jboss.resteasy.client.ClientResponseFailure e)
		{
			assertEquals(404, e.getResponse().getStatus());
		}
	}

	@Test
	public final void testInvalidGetTasks()
	{
		Recommender proxy = ProxyFactory.create(Recommender.class, uri);
		try
		{
			proxy.getTasks(ConstantsTest.CP, ConstantsTest.RECOMMENDER, ConstantsTest.STARTTIME, ConstantsTest.ENDTIME);
			fail("A 400 should have been thrown.");
		}
		catch (org.jboss.resteasy.client.ClientResponseFailure e)
		{
			assertEquals(400, e.getResponse().getStatus());
		}
	}
}


text:
var sqlite3 = require('sqlite3').verbose();
var fs = require('fs');
var db = new sqlite3.Database(':memory:');
var datas = JSON.parse(fs.readFileSync('datas/datas.json', 'utf8')); // get datas synchronously

db.serialize(function() {

/* CREATE TABLES */
  db.run("CREATE TABLE IF NOT EXISTS hotel (num_hotel INT NOT NULL PRIMARY KEY, nom_hotel TEXT, ville TEXT)"); // hotel
  db.run("CREATE TABLE IF NOT EXISTS chambre (num_chambre INT NOT NULL PRIMARY KEY, num_hotel INT, type TEXT, prix INT)"); // chambre
  db.run("CREATE TABLE IF NOT EXISTS reservation (num_hotel INT NOT NULL, num_hote INT NOT NULL, date_debut TEXT NOT NULL, date_fin TEXT, num_chambre INT, PRIMARY KEY (num_hotel,num_hote,date_debut))"); // reservation
  db.run("CREATE TABLE IF NOT EXISTS hote (num_hote INT NOT NULL PRIMARY KEY, nom_hote TEXT, adresse_hote TEXT)"); // hote

  /* INSERT DATAS */
	var stmt = db.prepare("INSERT INTO hotel VALUES (?,?,?)"); // hotel
	datas["hotel"].forEach( (item) => {
  		stmt.run([item.num_hotel, item.nom_hotel, item.ville]);
	});

	stmt = db.prepare("INSERT INTO chambre VALUES (?,?,?,?)"); // chambre
	datas["chambre"].forEach( (item) => {
  	stmt.run([item.num_chambre, item.num_hotel, item.type, item.prix]);
	});

	stmt = db.prepare("INSERT INTO reservation VALUES (?,?,?,?,?)"); // reservation
	datas["reservation"].forEach( (item) => {
  	stmt.run([item.num_hotel, item.num_hote, item.date_debut, item.date_fin, item.num_chambre]);
	});

	stmt = db.prepare("INSERT INTO hote VALUES (?,?,?)"); // hote
	datas["hote"].forEach( (item) => {
  	stmt.run([item.num_hote, item.nom_hote, item.adresse_hote]);
	});

	stmt.finalize();

  /* SELECT DATAS */
  db.each(  'SELECT num_hotel FROM chambre ' +
            'WHERE (chambre.prix > 50)'
            , function(err, row) {
    console.log(JSON.stringify(row));
  });

  db.each(  'SELECT * FROM hotel,chambre ' +
            'WHERE (hotel.num_hotel = chambre.num_hotel)'
            , function(err, row) {
    console.log(JSON.stringify(row));
  });

  db.each(  'SELECT nom_hotel FROM hotel,chambre ' +
            'WHERE (hotel.num_hotel = chambre.num_hotel '+
            'AND chambre.prix > 50)'
            , function(err, row) {
    console.log(JSON.stringify(row));
  });

  db.each("SELECT num_hotel, nom_hotel FROM hotel", function(err, row) {
    console.log(JSON.stringify(row));
  });

  db.each(  'SELECT num_hotel, num_chambre FROM chambre ' +
            'WHERE (chambre.prix < 50)'
            , function(err, row) {
    console.log(JSON.stringify(row));
  });

  db.each(  'SELECT nom_hote, adresse_hote FROM hote', function(err, row) {
    console.log(JSON.stringify(row));
  });

  db.each(  'SELECT prix, type ' +
            'FROM hotel , chambre ' +
            'WHERE ( ' +
            'hotel.nom_hotel = "hotel Gouverneur" ' +
            'AND hotel.num_hotel = chambre.num_hotel )'
            , function(err, row) {
    console.log(JSON.stringify(row));
  });

  db.each(  'SELECT num_hote, nom_hote ' +
            'FROM hotel , reservation, hote ' +
            'WHERE ( ' +
            'hotel.nom_hotel = "hotel Gouverneur" ' +
            'AND hotel.num_hotel = reservation.num_hotel ' +
            'AND reservation.num_hote = hote.num_hote ' +
            'AND reservation.date_debut >= DATETIME(\'now\') ' +
            'AND reservation.date_fin <= DATETIME(\'now\'))'
            , function(err, row) {
    console.log(JSON.stringify(row));
  });

  db.each(  'SELECT num_chambre, num_hotel, type, prix, nom_hote ' +
            'FROM hotel , chambre, reservation, hote ' +
            'WHERE ( ' +
            'hotel.nom_hotel = "hotel Gouverneur" ' +
            'AND hotel.num_hotel = chambre.num_hotel ' +
            'AND hote.num_hote = reservation.num_hote ' +
            'AND reservation.num_chambre = chambre.num_chambre ' +
            ')'
            , function(err, row) {
    console.log(JSON.stringify(row));
  });

  db.each(  'SELECT num_hote, nom_hote, adresse_hote ' +
            'FROM hotel , reservation, hote ' +
            'WHERE ( ' +
            'hotel.nom_hotel = "hotel Gouverneur" ' +
            'AND hotel.num_hotel = reservation.num_hotel ' +
            'AND reservation.num_hote = hote.num_hote ' +
            'AND reservation.date_debut >= DATETIME(\'now\') ' +
            'AND reservation.date_fin <= DATETIME(\'now\'))'
            , function(err, row) {
    console.log(JSON.stringify(row));
  });

});

db.close();


text:
/* global P */
/**
 *
 * @author mg
 * @resident
 * @public
 * @constructor
 */
function Accounter() {
    var self = this;//, model = P.loadModel(this.constructor.name);

    self.execute = function (aCycles, onSuccess, onFailure) {
        var worker = new P.ServerModule("Worker");
        var calls = 0;
        var errors = [];
        var sinusesSum = 0;
        function complete(aSin) {
            sinusesSum += aSin;
            if (++calls === aCycles) {
                if (errors.length > 0)
                    onFailure(errors.join('\n'));
                else
                    onSuccess(sinusesSum);
            }
        }
        function sinusCalcSucceded(aRes) {
            complete(aRes);
        }
        function sinusCalcFailed(aError) {
            P.Logger.severe(aError);
            errors.push(aError);
            complete(0);
        }
        for (var i = 0; i < aCycles; i++) {
            worker.execute(30 + i, sinusCalcSucceded, sinusCalcFailed);
        }
    };
}