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

using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Extensions;
using Roslyn.Test.Utilities;
using Xunit;
using System.Linq;

namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
    public class TypeofTests : CSharpTestBase
    {
        [Fact, WorkItem(1720, "https://github.com/dotnet/roslyn/issues/1720")]
        public void GetSymbolsOnResultOfTypeof()
        {
            var source = @"
class C
{
    public C(int i)
    {
        typeof(C).GetField("" "").SetValue(null, new C(0));
    }
}
";
            var compilation = CreateCompilationWithMscorlib45(source);
            var tree = compilation.SyntaxTrees[0];
            var model = compilation.GetSemanticModel(tree);
            var node = (ObjectCreationExpressionSyntax)tree.GetRoot().DescendantNodes().Where(n => n.ToString() == "new C(0)").Last();
            var identifierName = node.Type;

            var symbolInfo = model.GetSymbolInfo(node);
            Assert.Equal("C..ctor(System.Int32 i)", symbolInfo.Symbol.ToTestDisplayString());
            var typeInfo = model.GetTypeInfo(node);
            Assert.Equal("C", typeInfo.Type.ToTestDisplayString());

        }
    }
}


text:
package org.apache.asterix.lang.sqlpp.visitor;

import java.util.List;

import org.apache.asterix.common.exceptions.CompilationException;
import org.apache.asterix.lang.common.base.Expression;
import org.apache.asterix.lang.common.base.ILangExpression;
import org.apache.asterix.lang.common.clause.GroupbyClause;
import org.apache.asterix.lang.common.clause.LetClause;
import org.apache.asterix.lang.common.clause.LimitClause;
import org.apache.asterix.lang.common.clause.OrderbyClause;
import org.apache.asterix.lang.common.clause.WhereClause;
import org.apache.asterix.lang.common.expression.CallExpr;
import org.apache.asterix.lang.common.expression.FieldAccessor;
import org.apache.asterix.lang.common.expression.FieldBinding;
import org.apache.asterix.lang.common.expression.GbyVariableExpressionPair;
import org.apache.asterix.lang.common.expression.IfExpr;
import org.apache.asterix.lang.common.expression.IndexAccessor;
import org.apache.asterix.lang.common.expression.ListConstructor;
import org.apache.asterix.lang.common.expression.LiteralExpr;
import org.apache.asterix.lang.common.expression.OperatorExpr;
import org.apache.asterix.lang.common.expression.QuantifiedExpression;
import org.apache.asterix.lang.common.expression.RecordConstructor;
import org.apache.asterix.lang.common.expression.UnaryExpr;
import org.apache.asterix.lang.common.expression.VariableExpr;
import org.apache.asterix.lang.common.statement.FunctionDecl;
import org.apache.asterix.lang.common.statement.Query;
import org.apache.asterix.lang.common.struct.Identifier;
import org.apache.asterix.lang.common.struct.QuantifiedPair;
import org.apache.asterix.lang.sqlpp.clause.AbstractBinaryCorrelateClause;
import org.apache.asterix.lang.sqlpp.clause.FromClause;
import org.apache.asterix.lang.sqlpp.clause.FromTerm;
import org.apache.asterix.lang.sqlpp.clause.HavingClause;
import org.apache.asterix.lang.sqlpp.clause.JoinClause;
import org.apache.asterix.lang.sqlpp.clause.NestClause;
import org.apache.asterix.lang.sqlpp.clause.Projection;
import org.apache.asterix.lang.sqlpp.clause.SelectBlock;
import org.apache.asterix.lang.sqlpp.clause.SelectClause;
import org.apache.asterix.lang.sqlpp.clause.SelectElement;
import org.apache.asterix.lang.sqlpp.clause.SelectRegular;
import org.apache.asterix.lang.sqlpp.clause.SelectSetOperation;
import org.apache.asterix.lang.sqlpp.clause.UnnestClause;
import org.apache.asterix.lang.sqlpp.expression.CaseExpression;
import org.apache.asterix.lang.sqlpp.expression.IndependentSubquery;
import org.apache.asterix.lang.sqlpp.expression.SelectExpression;
import org.apache.asterix.lang.sqlpp.struct.SetOperationRight;
import org.apache.asterix.lang.sqlpp.visitor.base.AbstractSqlppQueryExpressionVisitor;
import org.apache.hyracks.algebricks.common.utils.Pair;

/**
 * This visitor recursively checks if there is a subquery in the argument language construct.
 */
public class CheckSubqueryVisitor extends AbstractSqlppQueryExpressionVisitor<Boolean, ILangExpression> {

    @Override
    public Boolean visit(FromClause fromClause, ILangExpression arg) throws CompilationException {
        for (FromTerm fromTerm : fromClause.getFromTerms()) {
            if (fromTerm.accept(this, arg)) {
                return false;
            }
        }
        return true;
    }

    @Override
    public Boolean visit(FromTerm fromTerm, ILangExpression arg) throws CompilationException {
        if (visit(fromTerm.getLeftExpression(), arg)) {
            return true;
        }
        for (AbstractBinaryCorrelateClause correlateClause : fromTerm.getCorrelateClauses()) {
            if (correlateClause.accept(this, arg)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Boolean visit(JoinClause joinClause, ILangExpression arg) throws CompilationException {
        return visit(joinClause.getRightExpression(), arg) || visit(joinClause.getConditionExpression(), arg);
    }

    @Override
    public Boolean visit(NestClause nestClause, ILangExpression arg) throws CompilationException {
        return nestClause.accept(this, arg);
    }

    @Override
    public Boolean visit(Projection projection, ILangExpression arg) throws CompilationException {
        if (projection.star()) {
            return false;
        }
        return visit(projection.getExpression(), arg);
    }

    @Override
    public Boolean visit(SelectBlock selectBlock, ILangExpression arg) throws CompilationException {
        boolean hasSubquery = visit(selectBlock.getFromClause(), arg) || visit(selectBlock.getGroupbyClause(), arg)
                || visit(selectBlock.getHavingClause(), arg) || visit(selectBlock.getWhereClause(), arg);
        return hasSubquery || visit(selectBlock.getSelectClause(), arg) || visit(selectBlock.getLetList(), arg)
                || visit(selectBlock.getLetListAfterGroupby(), arg);
    }

    @Override
    public Boolean visit(SelectClause selectClause, ILangExpression arg) throws CompilationException {
        return visit(selectClause.getSelectElement(), arg) || visit(selectClause.getSelectRegular(), arg);
    }

    @Override
    public Boolean visit(SelectElement selectElement, ILangExpression arg) throws CompilationException {
        return visit(selectElement.getExpression(), arg);
    }

    @Override
    public Boolean visit(SelectRegular selectRegular, ILangExpression arg) throws CompilationException {
        return visit(selectRegular.getProjections(), arg);
    }

    @Override
    public Boolean visit(SelectSetOperation selectSetOperation, ILangExpression arg) throws CompilationException {
        if (selectSetOperation.getLeftInput().accept(this, arg)) {
            return true;
        }
        for (SetOperationRight right : selectSetOperation.getRightInputs()) {
            if (right.getSetOperationRightInput().accept(this, arg)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Boolean visit(SelectExpression selectStatement, ILangExpression arg) throws CompilationException {
        if (selectStatement.isSubquery()) {
            return true;
        }
        return visit(selectStatement.getLetList(), arg) || visit(selectStatement.getSelectSetOperation(), arg)
                || visit(selectStatement.getOrderbyClause(), arg) || visit(selectStatement.getLimitClause(), arg);

    }

    @Override
    public Boolean visit(UnnestClause unnestClause, ILangExpression arg) throws CompilationException {
        return visit(unnestClause.getRightExpression(), arg);
    }

    @Override
    public Boolean visit(HavingClause havingClause, ILangExpression arg) throws CompilationException {
        return visit(havingClause.getFilterExpression(), arg);
    }

    @Override
    public Boolean visit(IndependentSubquery independentSubquery, ILangExpression arg) throws CompilationException {
        return visit(independentSubquery.getExpr(), arg);
    }

    @Override
    public Boolean visit(CaseExpression caseExpression, ILangExpression arg) throws CompilationException {
        return visit(caseExpression.getConditionExpr(), arg) || visit(caseExpression.getWhenExprs(), arg)
                || visit(caseExpression.getThenExprs(), arg) || visit(caseExpression.getElseExpr(), arg);
    }

    @Override
    public Boolean visit(Query q, ILangExpression arg) throws CompilationException {
        return visit(q.getBody(), arg);
    }

    @Override
    public Boolean visit(FunctionDecl fd, ILangExpression arg) throws CompilationException {
        return fd.getFuncBody().accept(this, arg);
    }

    @Override
    public Boolean visit(LiteralExpr l, ILangExpression arg) throws CompilationException {
        return false;
    }

    @Override
    public Boolean visit(VariableExpr v, ILangExpression arg) throws CompilationException {
        return false;
    }

    @Override
    public Boolean visit(ListConstructor lc, ILangExpression arg) throws CompilationException {
        return visit(lc.getExprList(), arg);
    }

    @Override
    public Boolean visit(RecordConstructor rc, ILangExpression arg) throws CompilationException {
        for (FieldBinding fb : rc.getFbList()) {
            if (visit(fb.getLeftExpr(), arg)) {
                return true;
            }
            if (visit(fb.getRightExpr(), arg)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Boolean visit(OperatorExpr operatorExpr, ILangExpression arg) throws CompilationException {
        return visit(operatorExpr.getExprList(), arg);
    }

    @Override
    public Boolean visit(FieldAccessor fa, ILangExpression arg) throws CompilationException {
        return visit(fa.getExpr(), arg);
    }

    @Override
    public Boolean visit(IndexAccessor ia, ILangExpression arg) throws CompilationException {
        return visit(ia.getExpr(), arg) || visit(ia.getIndexExpr(), arg);
    }

    @Override
    public Boolean visit(IfExpr ifexpr, ILangExpression arg) throws CompilationException {
        return visit(ifexpr.getCondExpr(), arg) || visit(ifexpr.getThenExpr(), arg) || visit(ifexpr.getElseExpr(), arg);
    }

    @Override
    public Boolean visit(QuantifiedExpression qe, ILangExpression arg) throws CompilationException {
        for (QuantifiedPair qf : qe.getQuantifiedList()) {
            if (visit(qf.getExpr(), arg)) {
                return true;
            }
        }
        return visit(qe.getSatisfiesExpr(), arg);
    }

    @Override
    public Boolean visit(LetClause lc, ILangExpression arg) throws CompilationException {
        return visit(lc.getBindingExpr(), arg);
    }

    @Override
    public Boolean visit(WhereClause wc, ILangExpression arg) throws CompilationException {
        return visit(wc.getWhereExpr(), arg);
    }

    @Override
    public Boolean visit(OrderbyClause oc, ILangExpression arg) throws CompilationException {
        return visit(oc.getOrderbyList(), arg);
    }

    @Override
    public Boolean visit(GroupbyClause gc, ILangExpression arg) throws CompilationException {
        for (GbyVariableExpressionPair key : gc.getGbyPairList()) {
            if (visit(key.getExpr(), arg)) {
                return true;
            }
        }
        for (GbyVariableExpressionPair key : gc.getDecorPairList()) {
            if (visit(key.getExpr(), arg)) {
                return true;
            }
        }
        for (Pair<Expression, Identifier> field : gc.getGroupFieldList()) {
            if (visit(field.first, arg)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Boolean visit(LimitClause lc, ILangExpression arg) throws CompilationException {
        return visit(lc.getLimitExpr(), arg) || visit(lc.getOffset(), arg);
    }

    @Override
    public Boolean visit(UnaryExpr u, ILangExpression arg) throws CompilationException {
        return visit(u.getExpr(), arg);
    }

    @Override
    public Boolean visit(CallExpr callExpr, ILangExpression arg) throws CompilationException {
        return visit(callExpr.getExprList(), arg);
    }

    private boolean visit(List<?> langExprs, ILangExpression arg) throws CompilationException {
        for (Object o : langExprs) {
            ILangExpression langExpr = (ILangExpression) o;
            if (langExpr.accept(this, arg)) {
                return true;
            }
        }
        return false;
    }

    private boolean visit(ILangExpression langExpr, ILangExpression arg) throws CompilationException {
        if (langExpr == null) {
            return false;
        }
        return langExpr.accept(this, arg);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

declare(strict_types=1);

namespace Sphp\Tests\Validators;

use PHPUnit\Framework\TestCase;
use Sphp\Validators\AbstractValidator;
use Sphp\Validators\Validator;

class AbstractValidatorTest extends TestCase {

  public function createValidator(string $message): AbstractValidator {
    $validator = $this->getMockBuilder(AbstractValidator::class)
            ->setMethods(['isValid'])
            ->setConstructorArgs([$message])
            ->enableOriginalConstructor()
            ->getMock();
    return $validator;
  }

  public function testDefault(): AbstractValidator {
    $validator = $this->createValidator('Foo is broken');
    $this->assertEquals('Foo is broken', $validator->getMessages()->getTemplate(Validator::INVALID));
    return $validator;
  }

  /**
   * @depends testDefault
   *
   * @param  AbstractValidator $validator
   * @return void
   */
  public function testClone(AbstractValidator $validator): void {
    $clone = clone $validator;
    $clone->getMessages()->setTemplate(Validator::INVALID, 'Foo is fixed');
    $this->assertEquals('Foo is fixed', $clone->getMessages()->getTemplate(Validator::INVALID));
    $this->assertEquals('Foo is broken', $validator->getMessages()->getTemplate(Validator::INVALID));
  }

}


text:
package org.fineract.module.stellar;

import com.jayway.restassured.RestAssured;
import org.fineract.module.stellar.configuration.BridgeConfiguration;
import org.fineract.module.stellar.fineractadapter.Adapter;
import org.junit.*;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.stereotype.Component;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

import static org.fineract.module.stellar.AccountListener.*;
import static org.fineract.module.stellar.AccountListener.vaultMatcher;
import static org.fineract.module.stellar.StellarBridgeTestHelpers.*;

@Component
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(BridgeConfiguration.class)
@WebIntegrationTest({
    "server.port=0", //randomPort = true
    "stellar.installation-account-private-key="
        + StellarDocker.MASTER_ACCOUNT_PRIVATE_KEY,
    "stellar.new-account-initial-balance=1020",
    "stellar.local-federation-domain=" + TEST_ADDRESS_DOMAIN
})
public class TestPaymentInSimpleNetwork {

  public static final String ASSET_CODE = "XXX";
  public static final BigDecimal TRUST_LIMIT   = BigDecimal.valueOf(1000);
  public static final BigDecimal VAULT_BALANCE = BigDecimal.valueOf(10000);
  public static final int PAY_WAIT = 30000;

  static FineractStellarTestRig testRig;

  @Value("${local.server.port}")
  int bridgePort;

  @Value("${stellar.horizon-address}")
  String serverAddress;

  @Autowired Adapter adapter;

  private Logger logger = LoggerFactory.getLogger(TestPaymentInSimpleNetwork.class.getName());
  private Cleanup testCleanup = new Cleanup();
  private String firstTenantId;
  private String firstTenantApiKey;
  private String secondTenantId;
  private String secondTenantApiKey;

  @BeforeClass
  public static void setupSystem() throws Exception {
    testRig = new FineractStellarTestRig();
  }

  @Before
  public void setupTest() {
    RestAdapterProviderMockProvider.mockFineract(adapter, testRig.getMifosAddress());

    RestAssured.port = bridgePort;

    firstTenantId = UUID.randomUUID().toString();
    firstTenantApiKey = createAndDestroyBridge(
        firstTenantId, testCleanup, testRig.getMifosAddress());
    setVaultSize(firstTenantId, firstTenantApiKey, ASSET_CODE, VAULT_BALANCE);
    final String firstTenantVaultAddress = tenantVaultStellarAddress(firstTenantId);
    logger.info("First tenant setup {} with vault size {}.", firstTenantId, VAULT_BALANCE);

    secondTenantId = UUID.randomUUID().toString();
    secondTenantApiKey = createAndDestroyBridge(
        secondTenantId, testCleanup, testRig.getMifosAddress());
    setVaultSize(secondTenantId, secondTenantApiKey, ASSET_CODE, VAULT_BALANCE);
    final String secondTenantVaultAddress = tenantVaultStellarAddress(secondTenantId);
    logger.info("Second tenant setup {} with vault size {}.", secondTenantId, VAULT_BALANCE);

    createAndDestroyTrustLine(
        secondTenantId, secondTenantApiKey, firstTenantVaultAddress, ASSET_CODE, TRUST_LIMIT,
        testCleanup);

    createAndDestroyTrustLine(
        firstTenantId, firstTenantApiKey, secondTenantVaultAddress, ASSET_CODE, TRUST_LIMIT,
        testCleanup);
  }

  @After
  public void tearDownTest() throws Exception {
    logger.info("TestPaymentInSimpleNetwork.tearDownTest");
    testCleanup.cleanup();
  }

  @AfterClass
  public static void tearDownSystem() throws Exception {
    testRig.close();
  }

  @Test
  public void paymentAboveCreditLimit() throws Exception
  {
    logger.info("paymentAboveCreditLimit test begin");

    final AccountListener accountListener =
        new AccountListener(serverAddress, secondTenantId, firstTenantId);

    BigDecimal transferAmount = TRUST_LIMIT.add(BigDecimal.ONE);
    makePayment(firstTenantId, firstTenantApiKey,
        secondTenantId,
        ASSET_CODE, transferAmount);

    accountListener.waitForCredits(PAY_WAIT,
        creditMatcher(secondTenantId, transferAmount, ASSET_CODE, firstTenantId));

    checkBalance(secondTenantId, secondTenantApiKey,
        ASSET_CODE, tenantVaultStellarAddress(firstTenantId),
        BigDecimal.ZERO);
  }

  @Test
  public void cancellingPayments() throws Exception
  {
    logger.info("cancellingPayments test begin");

    final AccountListener accountListener =
        new AccountListener(serverAddress, firstTenantId, secondTenantId);

    final BigDecimal transferAmount = BigDecimal.TEN;
    makePayment(firstTenantId, firstTenantApiKey,
        secondTenantId,
        ASSET_CODE, transferAmount);

    accountListener.waitForCredits(PAY_WAIT,
        creditMatcher(secondTenantId, BigDecimal.TEN, ASSET_CODE, firstTenantId));

    checkBalance(secondTenantId, secondTenantApiKey,
        ASSET_CODE, tenantVaultStellarAddress(firstTenantId),
        transferAmount);

    makePayment(secondTenantId, secondTenantApiKey,
        firstTenantId,
        ASSET_CODE, transferAmount);

    accountListener.waitForCredits(PAY_WAIT,
        creditMatcher(firstTenantId, BigDecimal.TEN, ASSET_CODE,
            vaultMatcher(secondTenantId, firstTenantId)));

    checkBalance(firstTenantId, firstTenantApiKey,
        ASSET_CODE, tenantVaultStellarAddress(secondTenantId),
        BigDecimal.ZERO);

    checkBalance(firstTenantId, firstTenantApiKey,
        ASSET_CODE, tenantVaultStellarAddress(firstTenantId),
        VAULT_BALANCE);

    checkBalance(secondTenantId, secondTenantApiKey,
        ASSET_CODE, tenantVaultStellarAddress(firstTenantId),
        BigDecimal.ZERO);

    checkBalance(secondTenantId, secondTenantApiKey,
        ASSET_CODE, tenantVaultStellarAddress(secondTenantId),
        VAULT_BALANCE);
  }

  @Test
  public void overlappingPayments() throws Exception {
    logger.info("overlappingPayments test begin");

    final AccountListener accountListener =
        new AccountListener(serverAddress, firstTenantId, secondTenantId);

    final BigDecimal transferAmount = BigDecimal.TEN;
    final BigDecimal doubleTransferAmount = transferAmount.add(transferAmount);
    makePayment(firstTenantId, firstTenantApiKey,
        secondTenantId,
        ASSET_CODE, transferAmount);
    makePayment(secondTenantId, secondTenantApiKey,
        firstTenantId,
        ASSET_CODE, doubleTransferAmount);

    accountListener
        .waitForCredits(PAY_WAIT,
            creditMatcher(firstTenantId, doubleTransferAmount, ASSET_CODE, secondTenantId),
            creditMatcher(secondTenantId, transferAmount, ASSET_CODE, vaultMatcher(firstTenantId, secondTenantId)),
            creditMatcher(secondTenantId, transferAmount, ASSET_CODE, secondTenantId));

    checkBalance(firstTenantId, firstTenantApiKey,
        ASSET_CODE, tenantVaultStellarAddress(secondTenantId),
        transferAmount);
    checkBalance(secondTenantId, secondTenantApiKey,
        ASSET_CODE, tenantVaultStellarAddress(firstTenantId),
        BigDecimal.ZERO);

    //Return balances to zero for next test.
    makePayment(firstTenantId, firstTenantApiKey,
        secondTenantId,
        ASSET_CODE, transferAmount);

    accountListener.waitForCredits(PAY_WAIT,
        creditMatcher(secondTenantId, transferAmount, ASSET_CODE, vaultMatcher(firstTenantId, secondTenantId)));
  }

  @Test
  public void paymentSumApproachesCreditLimit() throws Exception
  {
    logger.info("paymentSumApproachesCreditLimit test begin");

    final BigDecimal transferIncrement = BigDecimal.valueOf(99.99);
    final BigDecimal lastBit = BigDecimal.valueOf(0.1);

    final AccountListener accountListener =
        new AccountListener(serverAddress, firstTenantId, secondTenantId);

    //Approach the creditMatcher limit, then go back down to zero.
    Collections.nCopies(10, transferIncrement).parallelStream().forEach(
        (transferAmount) -> makePayment(firstTenantId, firstTenantApiKey, secondTenantId,
            ASSET_CODE, transferAmount));

    {
      final List<AccountListener.CreditMatcher> transfers = new ArrayList<>();
      transfers.addAll(Collections.nCopies(10,
          creditMatcher(secondTenantId, transferIncrement, ASSET_CODE, firstTenantId)));

      accountListener.waitForCredits(PAY_WAIT * 3, transfers);
    }

    checkBalance(secondTenantId, secondTenantApiKey,
        ASSET_CODE, tenantVaultStellarAddress(secondTenantId),
        VAULT_BALANCE);

    checkBalance(secondTenantId, secondTenantApiKey,
        ASSET_CODE, tenantVaultStellarAddress(firstTenantId),
        transferIncrement.multiply(BigDecimal.TEN));

    logger.info("paymentSumApproachesCreditLimit transfers back");
    Collections.nCopies(10, transferIncrement).parallelStream().forEach(
        (transferAmount) -> makePayment(secondTenantId, secondTenantApiKey, firstTenantId,
            ASSET_CODE, transferAmount));

    {
      final List<AccountListener.CreditMatcher> transfers = new ArrayList<>();
      transfers.addAll(Collections.nCopies(10,
          creditMatcher(firstTenantId, transferIncrement, ASSET_CODE, vaultMatcher(firstTenantId, secondTenantId))));

      accountListener.waitForCredits(PAY_WAIT * 3, transfers);

      accountListener.waitForCreditsToAccumulate(PAY_WAIT * 3,
          creditMatcher(secondTenantId, transferIncrement.multiply(BigDecimal.TEN), ASSET_CODE,
              vaultMatcher(firstTenantId, secondTenantId)));

      accountListener.waitForCreditsToAccumulate(PAY_WAIT * 3,
          creditMatcher(firstTenantId, transferIncrement.multiply(BigDecimal.TEN), ASSET_CODE,
              vaultMatcher(firstTenantId, secondTenantId)));
    }

    checkBalance(firstTenantId, firstTenantApiKey, ASSET_CODE, tenantVaultStellarAddress(secondTenantId),
        BigDecimal.ZERO);
    checkBalance(secondTenantId, secondTenantApiKey, ASSET_CODE, tenantVaultStellarAddress(firstTenantId),
        BigDecimal.ZERO);

    //Approach the creditMatcher limit again, then go to exactly the creditMatcher limit
    Collections.nCopies(10, transferIncrement).parallelStream().forEach(
        (transferAmount) -> makePayment(firstTenantId, firstTenantApiKey, secondTenantId,
            ASSET_CODE, transferAmount));
    makePayment(firstTenantId, firstTenantApiKey, secondTenantId, ASSET_CODE,
        lastBit);

    {
      final List<AccountListener.CreditMatcher> transfers = new ArrayList<>();
      transfers.addAll(Collections.nCopies(10, creditMatcher(secondTenantId, transferIncrement, ASSET_CODE,
          firstTenantId)));
      transfers.add(creditMatcher(secondTenantId, lastBit, ASSET_CODE, firstTenantId));

      accountListener.waitForCredits(PAY_WAIT * 3, transfers);
    }

    checkBalance(secondTenantId, secondTenantApiKey, ASSET_CODE, tenantVaultStellarAddress(firstTenantId),
        TRUST_LIMIT);

    //Now try to go over the creditMatcher limit.
    makePayment(firstTenantId, firstTenantApiKey, secondTenantId, ASSET_CODE, lastBit);

    accountListener.waitForCredits(PAY_WAIT,
        creditMatcher(secondTenantId, lastBit, ASSET_CODE, vaultMatcher(firstTenantId, secondTenantId)));

    checkBalance(secondTenantId, secondTenantApiKey, ASSET_CODE, tenantVaultStellarAddress(firstTenantId),
        TRUST_LIMIT);

    //Zero out balance for next test.
    makePayment(secondTenantId, secondTenantApiKey, firstTenantId, ASSET_CODE, TRUST_LIMIT);
    accountListener.waitForCredits(PAY_WAIT,
          creditMatcher(firstTenantId, TRUST_LIMIT, ASSET_CODE, vaultMatcher(firstTenantId, secondTenantId)));
  }

  //TODO: add a test for installation balance.
  //TODO: add a test for simple balance.
  //TODO: add a test for transferring XLM.
  //TODO: add a test which pays to an invalid stellar address.
  //TODO: add a test with a mock for external federation containing external domain addresses.

  //TODO: test transferring to a user account.
  //TODO: add a test with enough paths to provoke paging in find path pay.
  //TODO: still needed a test which stops and starts the bridge component, but makes transactions
  //TODO: need to add check of Mifos balance to all these test cases.
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Paulo
 * Date: 08/06/2015
 * Time: 08:40
 */

namespace Market\Factory;

use Market\Controller\IndexController;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class IndexControllerFactory implements FactoryInterface
{

    /**
     * Create service
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @return mixed
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        //pego todos os serviços
        $svAll = $serviceLocator->getServiceLocator();
        $sm = $svAll->get('ServiceManager');
        //$categories = $sm->get('categories');
        //$postForm = $sm->get('market-post-form');

        //crio um objeto de postController
        $indexController = new IndexController();
        //seto as categorias
        //$indexController->setCategories($categories);
        //$indexController->setPostForm($postForm);
        $indexController->setListingsTable($sm->get('listings-table'));

        return $indexController;
    }
}


text:
echo compile\($1\). >input
echo compile\($2\). >>input
echo compile\(ocl2pddl_p\). >>input
echo convert. >>input
echo convert_p. >>input
echo halt.>>input
# Check arguments
sicstus -l ocl2pddl< input >pddl_domain
rm input


text:
package de.danoeh.antennapod.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.FileObserver;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

import de.danoeh.antennapod.BuildConfig;
import de.danoeh.antennapod.R;
import de.danoeh.antennapod.core.preferences.UserPreferences;

/**
 * Let's the user choose a directory on the storage device. The selected folder
 * will be sent back to the starting activity as an activity result.
 */
public class DirectoryChooserActivity extends ActionBarActivity {
    private static final String TAG = "DirectoryChooserActivit";

    private static final String CREATE_DIRECTORY_NAME = "AntennaPod";

    public static final String RESULT_SELECTED_DIR = "selected_dir";
    public static final int RESULT_CODE_DIR_SELECTED = 1;

    private Button butConfirm;
    private Button butCancel;
    private ImageButton butNavUp;
    private TextView txtvSelectedFolder;
    private ListView listDirectories;

    private ArrayAdapter<String> listDirectoriesAdapter;
    private ArrayList<String> filenames;
    /** The directory that is currently being shown. */
    private File selectedDir;
    private File[] filesInDir;

    private FileObserver fileObserver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(UserPreferences.getTheme());
        super.onCreate(savedInstanceState);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        setContentView(R.layout.directory_chooser);
        butConfirm = (Button) findViewById(R.id.butConfirm);
        butCancel = (Button) findViewById(R.id.butCancel);
        butNavUp = (ImageButton) findViewById(R.id.butNavUp);
        txtvSelectedFolder = (TextView) findViewById(R.id.txtvSelectedFolder);
        listDirectories = (ListView) findViewById(R.id.directory_list);

        butConfirm.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (isValidFile(selectedDir)) {
                    if (selectedDir.list().length == 0) {
                        returnSelectedFolder();
                    } else {
                        showNonEmptyDirectoryWarning();
                    }
                }
            }

            private void showNonEmptyDirectoryWarning() {
                AlertDialog.Builder adb = new AlertDialog.Builder(
                        DirectoryChooserActivity.this);
                adb.setTitle(R.string.folder_not_empty_dialog_title);
                adb.setMessage(R.string.folder_not_empty_dialog_msg);
                adb.setNegativeButton(R.string.cancel_label,
                        (dialog, which) -> {
                            dialog.dismiss();
                        });
                adb.setPositiveButton(R.string.confirm_label,
                        (dialog, which) -> {
                            dialog.dismiss();
                            returnSelectedFolder();
                        });
                adb.create().show();
            }
        });

        butCancel.setOnClickListener(v -> {
            setResult(Activity.RESULT_CANCELED);
            finish();
        });

        listDirectories.setOnItemClickListener((adapter, view, position, id) -> {
            Log.d(TAG, "Selected index: " + position);
            if (filesInDir != null && position >= 0
                    && position < filesInDir.length) {
                changeDirectory(filesInDir[position]);
            }
        });

        butNavUp.setOnClickListener(v -> {
            File parent = null;
            if (selectedDir != null
                    && (parent = selectedDir.getParentFile()) != null) {
                changeDirectory(parent);
            }
        });

        filenames = new ArrayList<>();
        listDirectoriesAdapter = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, filenames);
        listDirectories.setAdapter(listDirectoriesAdapter);
        changeDirectory(Environment.getExternalStorageDirectory());
    }

    /**
     * Finishes the activity and returns the selected folder as a result. The
     * selected folder can also be null.
     */
    private void returnSelectedFolder() {
        if (selectedDir != null && BuildConfig.DEBUG)
            Log.d(TAG, "Returning " + selectedDir.getAbsolutePath()
                    + " as result");
        Intent resultData = new Intent();
        if (selectedDir != null) {
            resultData.putExtra(RESULT_SELECTED_DIR,
                    selectedDir.getAbsolutePath());
        }
        setResult(Activity.RESULT_OK, resultData);
        finish();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (fileObserver != null) {
            fileObserver.stopWatching();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (fileObserver != null) {
            fileObserver.startWatching();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        listDirectoriesAdapter = null;
        fileObserver = null;
    }

    /**
     * Change the directory that is currently being displayed.
     *
     * @param dir
     *            The file the activity should switch to. This File must be
     *            non-null and a directory, otherwise the displayed directory
     *            will not be changed
     */
    private void changeDirectory(File dir) {
        if (dir != null && dir.isDirectory()) {
            File[] contents = dir.listFiles();
            if (contents != null) {
                int numDirectories = 0;
                for (File f : contents) {
                    if (f.isDirectory()) {
                        numDirectories++;
                    }
                }
                filesInDir = new File[numDirectories];
                filenames.clear();
                for (int i = 0, counter = 0; i < numDirectories; counter++) {
                    if (contents[counter].isDirectory()) {
                        filesInDir[i] = contents[counter];
                        filenames.add(contents[counter].getName());
                        i++;
                    }
                }
                Arrays.sort(filesInDir);
                Collections.sort(filenames);
                selectedDir = dir;
                txtvSelectedFolder.setText(dir.getAbsolutePath());
                listDirectoriesAdapter.notifyDataSetChanged();
                fileObserver = createFileObserver(dir.getAbsolutePath());
                fileObserver.startWatching();
                Log.d(TAG, "Changed directory to " + dir.getAbsolutePath());
            } else {
                Log.d(TAG, "Could not change folder: contents of dir were null");
            }
        } else {
            if (dir == null) {
                Log.d(TAG, "Could not change folder: dir was null");
            } else {
                Log.d(TAG, "Could not change folder: dir is no directory");
            }
        }
        refreshButtonState();
    }

    /**
     * Changes the state of the buttons depending on the currently selected file
     * or folder.
     */
    private void refreshButtonState() {
        if (selectedDir != null) {
            butConfirm.setEnabled(isValidFile(selectedDir));
            supportInvalidateOptionsMenu();
        }
    }

    /** Refresh the contents of the directory that is currently shown. */
    private void refreshDirectory() {
        if (selectedDir != null) {
            changeDirectory(selectedDir);
        }
    }

    /** Sets up a FileObserver to watch the current directory. */
    private FileObserver createFileObserver(String path) {
        return new FileObserver(path, FileObserver.CREATE | FileObserver.DELETE
                | FileObserver.MOVED_FROM | FileObserver.MOVED_TO) {

            @Override
            public void onEvent(int event, String path) {
                Log.d(TAG, "FileObserver received event " + event);
                runOnUiThread(() -> refreshDirectory());
            }
        };
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        menu.findItem(R.id.new_folder_item)
                .setVisible(isValidFile(selectedDir));
        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.directory_chooser, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
        case R.id.new_folder_item:
            openNewFolderDialog();
            return true;
        case R.id.set_to_default_folder_item:
            selectedDir = null;
            returnSelectedFolder();
            return true;
        default:
            return false;
        }
    }

    /**
     * Shows a confirmation dialog that asks the user if he wants to create a
     * new folder.
     */
    private void openNewFolderDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.create_folder_label);
        builder.setMessage(String.format(getString(R.string.create_folder_msg),
                CREATE_DIRECTORY_NAME));
        builder.setNegativeButton(R.string.cancel_label,
                (dialog, which) -> {
                    dialog.dismiss();
                });
        builder.setPositiveButton(R.string.confirm_label,
                (dialog, which) -> {
                    dialog.dismiss();
                    int msg = createFolder();
                    Toast t = Toast.makeText(DirectoryChooserActivity.this,
                            msg, Toast.LENGTH_SHORT);
                    t.show();
                });
        builder.create().show();
    }

    /**
     * Creates a new folder in the current directory with the name
     * CREATE_DIRECTORY_NAME.
     */
    private int createFolder() {
        if (selectedDir == null) {
            return R.string.create_folder_error;
        } else if (selectedDir.canWrite()) {
            File newDir = new File(selectedDir, CREATE_DIRECTORY_NAME);
            if (!newDir.exists()) {
                boolean result = newDir.mkdir();
                if (result) {
                    return R.string.create_folder_success;
                } else {
                    return R.string.create_folder_error;
                }
            } else {
                return R.string.create_folder_error_already_exists;
            }
        } else {
            return R.string.create_folder_error_no_write_access;
        }
    }

    /** Returns true if the selected file or directory would be valid selection. */
    private boolean isValidFile(File file) {
        return file != null && file.isDirectory() && file.canRead() && file.canWrite();
    }
}


text:
/**
 *
 */
package br.com.swconsultoria.efd.icms.bo.blocoE;

import br.com.swconsultoria.efd.icms.registros.blocoE.RegistroE531;
import br.com.swconsultoria.efd.icms.util.Util;

/**
 * @author Samuel Oliveira, Sidnei Klein
 *
 */
public class GerarRegistroE531 {

    public static StringBuilder gerar(RegistroE531 registroE531, StringBuilder sb) {

        sb.append("|").append(Util.preencheRegistro(registroE531.getReg()));
        sb.append("|").append(Util.preencheRegistro(registroE531.getCod_part()));
        sb.append("|").append(Util.preencheRegistro(registroE531.getCod_mod()));
        sb.append("|").append(Util.preencheRegistro(registroE531.getSer()));
        sb.append("|").append(Util.preencheRegistro(registroE531.getSub()));
        sb.append("|").append(Util.preencheRegistro(registroE531.getNum_doc()));
        sb.append("|").append(Util.preencheRegistro(registroE531.getDt_doc()));
        sb.append("|").append(Util.preencheRegistro(registroE531.getCod_item()));
        sb.append("|").append(Util.preencheRegistro(registroE531.getVl_aj_item()));
        sb.append("|").append(Util.preencheRegistro(registroE531.getChv_nfe()));
        sb.append("|").append('\n');

        return sb;
    }
}


text:
package org.apache.hadoop.hive.ql.exec.vector.expressions;

import java.sql.Timestamp;
import java.util.Arrays;
import java.util.HashSet;

import org.apache.hadoop.hive.ql.exec.vector.TimestampColumnVector;
import org.apache.hadoop.hive.ql.exec.vector.VectorExpressionDescriptor.Descriptor;
import org.apache.hadoop.hive.ql.exec.vector.VectorizedRowBatch;

/**
 * Evaluate IN filter on a batch for a vector of timestamps.
 */
public class FilterTimestampColumnInList extends VectorExpression implements ITimestampInExpr {
  private static final long serialVersionUID = 1L;
  private int inputCol;
  private Timestamp[] inListValues;

  // The set object containing the IN list.
  private transient HashSet<Timestamp> inSet;

  public FilterTimestampColumnInList() {
    super();
    inSet = null;
  }

  /**
   * After construction you must call setInListValues() to add the values to the IN set.
   */
  public FilterTimestampColumnInList(int colNum) {
    this.inputCol = colNum;
    inSet = null;
  }

  @Override
  public void evaluate(VectorizedRowBatch batch) {

    if (childExpressions != null) {
      super.evaluateChildren(batch);
    }

    if (inSet == null) {
      inSet = new HashSet<Timestamp>(inListValues.length);
      for (Timestamp val : inListValues) {
        inSet.add(val);
      }
    }

    TimestampColumnVector inputColVector = (TimestampColumnVector) batch.cols[inputCol];
    int[] sel = batch.selected;
    boolean[] nullPos = inputColVector.isNull;
    int n = batch.size;

    // return immediately if batch is empty
    if (n == 0) {
      return;
    }

    if (inputColVector.noNulls) {
      if (inputColVector.isRepeating) {

        // All must be selected otherwise size would be zero
        // Repeating property will not change.

        if (!(inSet.contains(inputColVector.asScratchTimestamp(0)))) {
          //Entire batch is filtered out.
          batch.size = 0;
        }
      } else if (batch.selectedInUse) {
        int newSize = 0;
        for(int j = 0; j != n; j++) {
          int i = sel[j];
          if (inSet.contains(inputColVector.asScratchTimestamp(i))) {
            sel[newSize++] = i;
          }
        }
        batch.size = newSize;
      } else {
        int newSize = 0;
        for(int i = 0; i != n; i++) {
          if (inSet.contains(inputColVector.asScratchTimestamp(i))) {
            sel[newSize++] = i;
          }
        }
        if (newSize < n) {
          batch.size = newSize;
          batch.selectedInUse = true;
        }
      }
    } else {
      if (inputColVector.isRepeating) {

        //All must be selected otherwise size would be zero
        //Repeating property will not change.
        if (!nullPos[0]) {
          if (!inSet.contains(inputColVector.asScratchTimestamp(0))) {

            //Entire batch is filtered out.
            batch.size = 0;
          }
        } else {
          batch.size = 0;
        }
      } else if (batch.selectedInUse) {
        int newSize = 0;
        for(int j = 0; j != n; j++) {
          int i = sel[j];
          if (!nullPos[i]) {
           if (inSet.contains(inputColVector.asScratchTimestamp(i))) {
             sel[newSize++] = i;
           }
          }
        }

        // Change the selected vector
        batch.size = newSize;
      } else {
        int newSize = 0;
        for(int i = 0; i != n; i++) {
          if (!nullPos[i]) {
            if (inSet.contains(inputColVector.asScratchTimestamp(i))) {
              sel[newSize++] = i;
            }
          }
        }
        if (newSize < n) {
          batch.size = newSize;
          batch.selectedInUse = true;
        }
      }
    }
  }

  @Override
  public String getOutputType() {
    return "boolean";
  }

  @Override
  public int getOutputColumn() {
    return -1;
  }

  @Override
  public Descriptor getDescriptor() {

    // This VectorExpression (IN) is a special case, so don't return a descriptor.
    return null;
  }

  public void setInListValues(Timestamp[] a) {
    this.inListValues = a;
  }

  @Override
  public String vectorExpressionParameters() {
    return "col " + inputCol + ", values " + Arrays.toString(inListValues);
  }

}


text:
namespace WpfApp.Context
{
    using System;
    using System.Reflection;
    using System.Windows.Markup;
    using OmniXaml.Metadata;

    public class MetadataProvider : IMetadataProvider
    {
        public Metadata Get(Type type)
        {
            return new Metadata
            {
                ContentProperty = GetContentProperty(type),
            };
        }

        private string GetContentProperty(Type type)
        {
            var contentPropertyAttribute = type.GetTypeInfo().GetCustomAttribute<ContentPropertyAttribute>();
            return contentPropertyAttribute?.Name;
        }
    }
}


text:
class DummyXMLHTTPRequest {
    constructor() {

    }
    open(methodName, url) {
        this.url = url;
    }
    setRequestHeader() {}
    send() {
        var self = this;
        if (window.__ajax) {
            window.__ajax(this.url, (status, responseText) => {
                self.onreadystatechange.bind({
                    readyState: 4,
                    status: status,
                    statusText: status === 404 ? "Not Found" : null,
                    responseText: responseText
                })()
            })
        }
    }
    getResponseHeader(req) {
        if (req === "Content-Type" && this.url) {
            if (this.url.match(/\.js$/)) {
                return "text/javascript"
            }
            if (this.url.match(/\.json$/)) {
                return "text/json"
            }
            if (this.url.match(/\.css$/)) {
                return "text/css"
            }
        }
    }
}
window.XMLHttpRequest = DummyXMLHTTPRequest;


text:
<?php

namespace Scheb\TwoFactorBundle\Model\Google;

interface TwoFactorInterface
{
    /**
     * Return the user name.
     *
     * @return string
     */
    public function getUsername();

    /**
     * Return the Google Authenticator secret
     * When an empty string or null is returned, the Google authentication is disabled.
     *
     * @return string|null
     */
    public function getGoogleAuthenticatorSecret();

    /**
     * Set the Google Authenticator secret.
     *
     * @param int $googleAuthenticatorSecret
     */
    public function setGoogleAuthenticatorSecret($googleAuthenticatorSecret);
}


text:
layout: post
title:  "Meet the Speaker: Seb Rose"
date:   2018-07-25 17:19:00:00
isStaticPost: false
---

#### Meet the Speaker: Seb Rose.

<img src="/img/people/SebRose.jpg"/>

#### What's your session topic?
Whatever your job title, you're actually being paid to think!

#### Why is your topic important?*

Books, conference talks, the internet are all awash with heuristics, patterns, models and acronyms to help us solve problems. They document how other people have overcome challenges in a way that makes those solutions accessible to others.

They're not magic formulae. They help us think, but they don't make thinking unnecessary. The ability to think is our 'secret sauce' and we need to start realising that, while experts have valuable things to say, we need to filter their insights through our own experience.

#### What are the prerequisites should the audience have for attending your session?

None

#### How long have you been in this industry?

35 years

#### What is one of those things you wish you knew when you started out in this industry?

Not a thing.

#### Have you spoken at or attended SwanseaCon before?

Yes

#### What made you want to speak at SwanseaCon this year?

I really enjoyed it last year

#### Are there any sessions other than your own which you are looking forward to at SwanseaCon?

Probably.... but I haven't looked yet

#### Did you enjoy this post?
[Get your tickets today to see Seb Rose and many others at SwanseaCon 2018](http://www.swanseacon.co.uk/)


text:
package com.intellij.codeInspection.ui;

import consulo.ui.image.Image;

/**
 * @author max
 */
public class InspectionGroupNode extends InspectionTreeNode {
  private static final Image EMPTY = Image.empty(0, Image.DEFAULT_ICON_SIZE);

  public InspectionGroupNode(String groupTitle) {
    super(groupTitle);
  }

  public String getGroupTitle() {
    return (String) getUserObject();
  }

  @Override
  public Image getIcon() {
    return EMPTY;
  }

  @Override
  public boolean appearsBold() {
    return true;
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="eu.kanade.tachiyomi.extension">

    <application>
        <activity
            android:name=".ru.libmanga.LibMangaActivity"
            android:excludeFromRecents="true"
            android:theme="@android:style/Theme.NoDisplay">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <!-- LibMangaActivity sites can be added here. -->
                <data
                    android:host="mangalib.me"
                    android:pathPattern="/..*/v..*"
                    android:scheme="https" />
                <data
                    android:host="mangalib.org"
                    android:pathPattern="/..*/v..*"
                    android:scheme="https" />
            </intent-filter>
        </activity>
    </application>
</manifest>


text:
log_level        :info
log_location     STDOUT
node_name        'ubee'
cookbook_path    ["cookbooks"]
ssl_verify_mode  :verify_peer

knife[:berkshelf_path] = "cookbooks"


text:
<?php

namespace Euskadi31\Component\Security\Core\Exception;

use Euskadi31\Component\Security\Core\Exception\OAuthInvalidGrantException;

class OAuthInvalidGrantExceptionTest extends \PHPUnit_Framework_TestCase
{
    public function testException()
    {
        $exception = new OAuthInvalidGrantException('Invalid facebook grant.');

        $this->assertInstanceOf('Euskadi31\Component\Security\Core\Exception\OAuthExceptionInterface', $exception);

        $this->assertEquals('Invalid facebook grant.', $exception->getMessage());
        $this->assertEquals(400, $exception->getStatusCode());
        $this->assertEquals('invalid_grant', $exception->getErrorCode());
        $this->assertEquals('API', $exception->getRealmName());
        $this->assertEquals([], $exception->getScopes());
        $this->assertEquals([
            'Cache-Control'     => 'no-store',
            'Pragma'            => 'no-cache',
            'WWW-Authenticate'  => 'Bearer realm="API", error="invalid_grant", error_description="Invalid facebook grant."'
        ], $exception->getHeaders());

        $exception = new OAuthInvalidGrantException('foo', 403, null, 'Test');

        $this->assertInstanceOf('Euskadi31\Component\Security\Core\Exception\OAuthExceptionInterface', $exception);

        $this->assertEquals('foo', $exception->getMessage());
        $this->assertEquals(403, $exception->getStatusCode());
        $this->assertEquals('invalid_grant', $exception->getErrorCode());
        $this->assertEquals('Test', $exception->getRealmName());
        $this->assertEquals([], $exception->getScopes());
        $this->assertEquals([
            'Cache-Control'     => 'no-store',
            'Pragma'            => 'no-cache',
            'WWW-Authenticate'  => 'Bearer realm="Test", error="invalid_grant", error_description="foo"'
        ], $exception->getHeaders());
    }
}


text:
package org.webrtc;

import org.webrtc.CameraEnumerationAndroid.CaptureFormat;

import android.content.Context;
import android.test.InstrumentationTestCase;
import android.test.suitebuilder.annotation.SmallTest;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.LargeTest;

public class Camera1CapturerUsingTextureTest extends InstrumentationTestCase {
  static final String TAG = "Camera1CapturerUsingTextureTest";

  private class TestObjectFactory
      extends CameraVideoCapturerTestFixtures.TestObjectFactory {
    @Override
    public CameraEnumerator getCameraEnumerator() {
      return new Camera1Enumerator();
    }

    @Override
    public Context getAppContext() {
      return getInstrumentation().getTargetContext();
    }

    @SuppressWarnings("deprecation")
    @Override
    public Object rawOpenCamera(String cameraName) {
      return android.hardware.Camera.open(Camera1Enumerator.getCameraIndex(cameraName));
    }

    @SuppressWarnings("deprecation")
    @Override
    public void rawCloseCamera(Object camera) {
      ((android.hardware.Camera) camera).release();
    }
  }

  private CameraVideoCapturerTestFixtures fixtures;

  @Override
  protected void setUp() {
    fixtures = new CameraVideoCapturerTestFixtures(new TestObjectFactory());
  }

  @Override
  protected void tearDown() {
    fixtures.dispose();
  }

  @SmallTest
  public void testCreateAndDispose() {
    fixtures.createCapturerAndDispose();
  }

  @SmallTest
  public void testCreateNonExistingCamera() {
    fixtures.createNonExistingCamera();
  }

  // This test that the camera can be started and that the frames are forwarded
  // to a Java video renderer using a "default" capturer.
  // It tests both the Java and the C++ layer.
  @MediumTest
  public void testCreateCapturerAndRender() throws InterruptedException {
    fixtures.createCapturerAndRender();
  }

  // This test that the camera can be started and that the frames are forwarded
  // to a Java video renderer using the front facing video capturer.
  // It tests both the Java and the C++ layer.
  @MediumTest
  public void testStartFrontFacingVideoCapturer() throws InterruptedException {
    fixtures.createFrontFacingCapturerAndRender();
  }

  // This test that the camera can be started and that the frames are forwarded
  // to a Java video renderer using the back facing video capturer.
  // It tests both the Java and the C++ layer.
  @MediumTest
  public void testStartBackFacingVideoCapturer() throws InterruptedException {
    fixtures.createBackFacingCapturerAndRender();
  }

  // This test that the default camera can be started and that the camera can
  // later be switched to another camera.
  // It tests both the Java and the C++ layer.
  @MediumTest
  public void testSwitchVideoCapturer() throws InterruptedException {
    fixtures.switchCamera();
  }

  @MediumTest
  public void testCameraEvents() throws InterruptedException {
    fixtures.cameraEventsInvoked();
  }

  // Test what happens when attempting to call e.g. switchCamera() after camera has been stopped.
  @MediumTest
  public void testCameraCallsAfterStop() throws InterruptedException {
    fixtures.cameraCallsAfterStop();
  }

  // This test that the VideoSource that the CameraVideoCapturer is connected to can
  // be stopped and restarted. It tests both the Java and the C++ layer.
  @LargeTest
  public void testStopRestartVideoSource() throws InterruptedException {
    fixtures.stopRestartVideoSource();
  }

  // This test that the camera can be started at different resolutions.
  // It does not test or use the C++ layer.
  @LargeTest
  public void testStartStopWithDifferentResolutions() throws InterruptedException {
    fixtures.startStopWithDifferentResolutions();
  }

  // This test what happens if buffers are returned after the capturer have
  // been stopped and restarted. It does not test or use the C++ layer.
  @LargeTest
  public void testReturnBufferLate() throws InterruptedException {
    fixtures.returnBufferLateEndToEnd();
  }

  // This test that we can capture frames, keep the frames in a local renderer, stop capturing,
  // and then return the frames. The difference between the test testReturnBufferLate() is that we
  // also test the JNI and C++ AndroidVideoCapturer parts.
  @MediumTest
  public void testReturnBufferLateEndToEnd() throws InterruptedException {
    fixtures.returnBufferLateEndToEnd();
  }

  // This test that CameraEventsHandler.onError is triggered if video buffers are not returned to
  // the capturer.
  @LargeTest
  public void testCameraFreezedEventOnBufferStarvation() throws InterruptedException {
    fixtures.cameraFreezedEventOnBufferStarvation();
  }

  // This test that frames forwarded to a renderer is scaled if onOutputFormatRequest is
  // called. This test both Java and C++ parts of of the stack.
  @MediumTest
  public void testScaleCameraOutput() throws InterruptedException {
    fixtures.scaleCameraOutput();
  }

  // This test that an error is reported if the camera is already opened
  // when CameraVideoCapturer is started.
  @LargeTest
  public void testStartWhileCameraIsAlreadyOpen() throws InterruptedException {
    fixtures.startWhileCameraIsAlreadyOpen();
  }

  // This test that CameraVideoCapturer can be started, even if the camera is already opened
  // if the camera is closed while CameraVideoCapturer is re-trying to start.
  @LargeTest
  public void testStartWhileCameraIsAlreadyOpenAndCloseCamera() throws InterruptedException {
    fixtures.startWhileCameraIsAlreadyOpenAndCloseCamera();
  }

  // This test that CameraVideoCapturer.stop can be called while CameraVideoCapturer is
  // re-trying to start.
  @MediumTest
  public void testStartWhileCameraIsAlreadyOpenAndStop() throws InterruptedException {
    fixtures.startWhileCameraIsAlreadyOpenAndStop();
  }
}


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

const TEST_URL = "http://www.mozilla.org";
const TEST_TITLE = "example_title";

var gBookmarksToolbar = window.document.getElementById("PlacesToolbar");
var dragDirections = { LEFT: 0, UP: 1, RIGHT: 2, DOWN: 3 };

/**
 * Tests dragging on toolbar.
 *
 * We must test these 2 cases:
 *   - Dragging toward left, top, right should start a drag.
 *   - Dragging toward down should should open the container if the item is a
 *     container, drag the item otherwise.
 *
 * @param aElement
 *        DOM node element we will drag
 * @param aExpectedDragData
 *        Array of flavors and values in the form:
 *        [ ["text/plain: sometext", "text/html: <b>sometext</b>"], [...] ]
 *        Pass an empty array to check that drag even has been canceled.
 * @param aDirection
 *        Direction for the dragging gesture, see dragDirections helper object.
 */
function synthesizeDragWithDirection(aElement, aExpectedDragData, aDirection, aCallback) {
  // Dragstart listener function.
  gBookmarksToolbar.addEventListener("dragstart", function(event)
  {
    info("A dragstart event has been trapped.");
    var dataTransfer = event.dataTransfer;
    is(dataTransfer.mozItemCount, aExpectedDragData.length,
       "Number of dragged items should be the same.");

    for (var t = 0; t < dataTransfer.mozItemCount; t++) {
      var types = dataTransfer.mozTypesAt(t);
      var expecteditem = aExpectedDragData[t];
      is(types.length, expecteditem.length,
        "Number of flavors for item " + t + " should be the same.");

      for (var f = 0; f < types.length; f++) {
        is(types[f], expecteditem[f].substring(0, types[f].length),
           "Flavor " + types[f] + " for item " + t + " should be the same.");
        is(dataTransfer.mozGetDataAt(types[f], t),
           expecteditem[f].substring(types[f].length + 2),
           "Contents for item " + t + " with flavor " + types[f] + " should be the same.");
      }
    }

    if (!aExpectedDragData.length)
      ok(event.defaultPrevented, "Drag has been canceled.");

    event.preventDefault();
    event.stopPropagation();

    gBookmarksToolbar.removeEventListener("dragstart", arguments.callee, false);

    // This is likely to cause a click event, and, in case we are dragging a
    // bookmark, an unwanted page visit.  Prevent the click event.
    aElement.addEventListener("click", prevent, false);
    EventUtils.synthesizeMouse(aElement,
                               startingPoint.x + xIncrement * 9,
                               startingPoint.y + yIncrement * 9,
                               { type: "mouseup" });
    aElement.removeEventListener("click", prevent, false);

    // Cleanup eventually opened menus.
    if (aElement.localName == "menu" && aElement.open)
      aElement.open = false;
    aCallback()
  }, false);

  var prevent = function(aEvent) {aEvent.preventDefault();}

  var xIncrement = 0;
  var yIncrement = 0;

  switch (aDirection) {
    case dragDirections.LEFT:
      xIncrement = -1;
      break;
    case dragDirections.RIGHT:
      xIncrement = +1;
      break;
    case dragDirections.UP:
      yIncrement = -1;
      break;
    case dragDirections.DOWN:
      yIncrement = +1;
      break;
  }

  var rect = aElement.getBoundingClientRect();
  var startingPoint = { x: (rect.right - rect.left)/2,
                        y: (rect.bottom - rect.top)/2 };

  EventUtils.synthesizeMouse(aElement,
                             startingPoint.x,
                             startingPoint.y,
                             { type: "mousedown" });
  EventUtils.synthesizeMouse(aElement,
                             startingPoint.x + xIncrement * 1,
                             startingPoint.y + yIncrement * 1,
                             { type: "mousemove" });
  EventUtils.synthesizeMouse(aElement,
                             startingPoint.x + xIncrement * 9,
                             startingPoint.y + yIncrement * 9,
                             { type: "mousemove" });
}

function getToolbarNodeForItemId(aItemId) {
  var children = document.getElementById("PlacesToolbarItems").childNodes;
  var node = null;
  for (var i = 0; i < children.length; i++) {
    if (aItemId == children[i]._placesNode.itemId) {
      node = children[i];
      break;
    }
  }
  return node;
}

function getExpectedDataForPlacesNode(aNode) {
  var wrappedNode = [];
  var flavors = ["text/x-moz-place",
                 "text/x-moz-url",
                 "text/plain",
                 "text/html"];

  flavors.forEach(function(aFlavor) {
    var wrappedFlavor = aFlavor + ": " +
                        PlacesUtils.wrapNode(aNode, aFlavor);
    wrappedNode.push(wrappedFlavor);
  });

  return [wrappedNode];
}

var gTests = [

//------------------------------------------------------------------------------

  {
    desc: "Drag a folder on toolbar",
    run: function() {
      // Create a test folder to be dragged.
      var folderId = PlacesUtils.bookmarks
                                .createFolder(PlacesUtils.toolbarFolderId,
                                              TEST_TITLE,
                                              PlacesUtils.bookmarks.DEFAULT_INDEX);
      var element = getToolbarNodeForItemId(folderId);
      isnot(element, null, "Found node on toolbar");

      isnot(element._placesNode, null, "Toolbar node has an associated Places node.");
      var expectedData = getExpectedDataForPlacesNode(element._placesNode);

      info("Dragging left");
      synthesizeDragWithDirection(element, expectedData, dragDirections.LEFT,
        function ()
        {
          info("Dragging right");
          synthesizeDragWithDirection(element, expectedData, dragDirections.RIGHT,
            function ()
            {
              info("Dragging up");
              synthesizeDragWithDirection(element, expectedData, dragDirections.UP,
                function ()
                {
                  info("Dragging down");
                  synthesizeDragWithDirection(element, new Array(), dragDirections.DOWN,
                    function () {
                      // Cleanup.
                      PlacesUtils.bookmarks.removeItem(folderId);
                      nextTest();
                    });
                });
            });
        });
    }
  },

//------------------------------------------------------------------------------

  {
    desc: "Drag a bookmark on toolbar",
    run: function() {
      // Create a test bookmark to be dragged.
      var itemId = PlacesUtils.bookmarks
                              .insertBookmark(PlacesUtils.toolbarFolderId,
                                              PlacesUtils._uri(TEST_URL),
                                              PlacesUtils.bookmarks.DEFAULT_INDEX,
                                              TEST_TITLE);
      var element = getToolbarNodeForItemId(itemId);
      isnot(element, null, "Found node on toolbar");

      isnot(element._placesNode, null, "Toolbar node has an associated Places node.");
      var expectedData = getExpectedDataForPlacesNode(element._placesNode);

      info("Dragging left");
      synthesizeDragWithDirection(element, expectedData, dragDirections.LEFT,
        function ()
        {
          info("Dragging right");
          synthesizeDragWithDirection(element, expectedData, dragDirections.RIGHT,
            function ()
            {
              info("Dragging up");
              synthesizeDragWithDirection(element, expectedData, dragDirections.UP,
                function ()
                {
                  info("Dragging down");
                  synthesizeDragWithDirection(element, expectedData, dragDirections.DOWN,
                    function () {
                      // Cleanup.
                      PlacesUtils.bookmarks.removeItem(itemId);
                      nextTest();
                    });
                });
            });
        });
    }
  },
];

function nextTest() {
  if (gTests.length) {
    var test = gTests.shift();
    waitForFocus(function() {
      info("Start of test: " + test.desc);
      test.run();
    });
  }
  else {
    // Collapse the personal toolbar if needed.
    if (wasCollapsed)
      setToolbarVisibility(toolbar, false);
    finish();
  }
}

let toolbar = document.getElementById("PersonalToolbar");
let wasCollapsed = toolbar.collapsed;

function test() {
  waitForExplicitFinish();

  // Uncollapse the personal toolbar if needed.
  if (wasCollapsed)
    setToolbarVisibility(toolbar, true);

  nextTest();
}


text:
@implementation NSManagedObjectContext (ActiveRecord)

+ (NSManagedObjectContext *)defaultContext {
    return [[CoreDataManager sharedManager] managedObjectContext];

    // Instead, return custom CoreData Stack
    //return [[WBCoreDataStack shareStack] managedObjectContext];
}

@end

@implementation NSObject(null)

- (BOOL)exists {
    return self && self != [NSNull null];
}

@end

@implementation NSManagedObject (ActiveRecord)

#pragma mark - Finders

+ (NSArray *)all {
    return [self allInContext:[NSManagedObjectContext defaultContext]];
}

+ (NSArray *)allWithOrder:(id)order {
    return [self allInContext:[NSManagedObjectContext defaultContext] order:order];
}

+ (NSArray *)allInContext:(NSManagedObjectContext *)context {
    return [self allInContext:context order:nil];
}

+ (NSArray *)allInContext:(NSManagedObjectContext *)context order:(id)order {
    return [self fetchWithCondition:nil inContext:context withOrder:order fetchLimit:nil];
}

+ (instancetype)findOrCreate:(NSDictionary *)properties {
    return [self findOrCreate:properties inContext:[NSManagedObjectContext defaultContext]];
}

+ (instancetype)findOrCreate:(NSDictionary *)properties inContext:(NSManagedObjectContext *)context {
    NSDictionary *transformed = [[self class] transformProperties:properties withObject:nil context:context];

    NSManagedObject *existing = [self where:transformed inContext:context].firstObject;
    return existing ?: [self create:transformed inContext:context];
}

+ (instancetype)find:(id)condition, ... {
    va_list va_arguments;
    va_start(va_arguments, condition);
    NSPredicate *predicate = [self predicateFromObject:condition arguments:va_arguments];
    va_end(va_arguments);

    return [self find:predicate inContext:[NSManagedObjectContext defaultContext]];
}

+ (instancetype)find:(id)condition inContext:(NSManagedObjectContext *)context {
    return [self where:condition inContext:context limit:@1].firstObject;
}

+ (NSArray *)where:(id)condition, ... {
    va_list va_arguments;
    va_start(va_arguments, condition);
    NSPredicate *predicate = [self predicateFromObject:condition arguments:va_arguments];
    va_end(va_arguments);

    return [self where:predicate inContext:[NSManagedObjectContext defaultContext]];
}

+ (NSArray *)where:(id)condition order:(id)order {
    return [self where:condition inContext:[NSManagedObjectContext defaultContext] order:order];
}

+ (NSArray *)where:(id)condition limit:(NSNumber *)limit {
    return [self where:condition inContext:[NSManagedObjectContext defaultContext] limit:limit];
}

+ (NSArray *)where:(id)condition order:(id)order limit:(NSNumber *)limit {
    return [self where:condition inContext:[NSManagedObjectContext defaultContext] order:order limit:limit];
}

+ (NSArray *)where:(id)condition inContext:(NSManagedObjectContext *)context {
    return [self where:condition inContext:context order:nil limit:nil];
}

+ (NSArray *)where:(id)condition inContext:(NSManagedObjectContext *)context order:(id)order {
    return [self where:condition inContext:context order:order limit:nil];
}

+ (NSArray *)where:(id)condition inContext:(NSManagedObjectContext *)context limit:(NSNumber *)limit {
    return [self where:condition inContext:context order:nil limit:limit];
}

+ (NSArray *)where:(id)condition inContext:(NSManagedObjectContext *)context order:(id)order limit:(NSNumber *)limit {
    return [self fetchWithCondition:condition inContext:context withOrder:order fetchLimit:limit];
}

#pragma mark - Aggregation

+ (NSUInteger)count {
    return [self countInContext:[NSManagedObjectContext defaultContext]];
}

+ (NSUInteger)countWhere:(id)condition, ... {
    va_list va_arguments;
    va_start(va_arguments, condition);
    NSPredicate *predicate = [self predicateFromObject:condition arguments:va_arguments];
    va_end(va_arguments);

    return [self countWhere:predicate inContext:[NSManagedObjectContext defaultContext]];
}

+ (NSUInteger)countInContext:(NSManagedObjectContext *)context {
    return [self countForFetchWithPredicate:nil inContext:context];
}

+ (NSUInteger)countWhere:(id)condition inContext:(NSManagedObjectContext *)context {
    NSPredicate *predicate = [self predicateFromObject:condition];

    return [self countForFetchWithPredicate:predicate inContext:context];
}

#pragma mark - Creation / Deletion

+ (id)create {
    return [self createInContext:[NSManagedObjectContext defaultContext]];
}

+ (id)create:(NSDictionary *)attributes {
    return [self create:attributes inContext:[NSManagedObjectContext defaultContext]];
}

+ (id)create:(NSDictionary *)attributes inContext:(NSManagedObjectContext *)context {
    unless([attributes exists]) return nil;

    NSManagedObject *newEntity = [self createInContext:context];
    [newEntity update:attributes];

    return newEntity;
}

+ (id)createInContext:(NSManagedObjectContext *)context {
    return [NSEntityDescription insertNewObjectForEntityForName:[self entityName]
                                         inManagedObjectContext:context];
}

- (void)update:(NSDictionary *)attributes {
    unless([attributes exists]) return;

    NSDictionary *transformed = [[self class] transformProperties:attributes withObject:self context:self.managedObjectContext];

    for (NSString *key in transformed) [self willChangeValueForKey:key];
    [transformed each:^(NSString *key, id value) {
        [self setSafeValue:value forKey:key];
    }];
    for (NSString *key in transformed) [self didChangeValueForKey:key];
}

- (BOOL)save {
    return [self saveTheContext];
}

- (void)delete {
    [self.managedObjectContext deleteObject:self];
}

+ (void)deleteAll {
    [self deleteAllInContext:[NSManagedObjectContext defaultContext]];
}

+ (void)deleteAllInContext:(NSManagedObjectContext *)context {
    [[self allInContext:context] each:^(id object) {
        [object delete];
    }];
}

#pragma mark - Naming

+ (NSString *)entityName {
    return NSStringFromClass(self);
}

#pragma mark - Private

+ (NSDictionary *)transformProperties:(NSDictionary *)properties withObject:(NSManagedObject *)object context:(NSManagedObjectContext *)context {
    NSEntityDescription *entity = [NSEntityDescription entityForName:[self entityName] inManagedObjectContext:context];

    NSDictionary *attributes = [entity attributesByName];
    NSDictionary *relationships = [entity relationshipsByName];

    NSMutableDictionary *transformed = [NSMutableDictionary dictionaryWithCapacity:[properties count]];

    for (NSString *key in properties) {
        NSString *localKey = [self keyForRemoteKey:key inContext:context];
        if (attributes[localKey] || relationships[localKey]) {
            id value = [[self class] transformValue:properties[key] forRemoteKey:key inContext:context];
            if (object) {
                id localValue = [object primitiveValueForKey:localKey];
                if ([localValue isEqual:value] || (localValue == nil && value == [NSNull null]))
                    continue;
            }
            transformed[localKey] = value;
        } else {
#if DEBUG
            NSLog(@"Discarding key ('%@') from properties on class ('%@'): no attribute or relationship found",
                  key, [self class]);
#endif
        }
    }

    return transformed;
}

+ (NSPredicate *)predicateFromDictionary:(NSDictionary *)dict {
    NSArray *subpredicates = [dict map:^(NSString *key, id value) {
        return [NSPredicate predicateWithFormat:@"%K = %@", key, value];
    }];

    return [NSCompoundPredicate andPredicateWithSubpredicates:subpredicates];
}

+ (NSPredicate *)predicateFromObject:(id)condition {
    return [self predicateFromObject:condition arguments:NULL];
}

+ (NSPredicate *)predicateFromObject:(id)condition arguments:(va_list)arguments {
    if ([condition isKindOfClass:[NSPredicate class]])
        return condition;

    if ([condition isKindOfClass:[NSString class]])
        return [NSPredicate predicateWithFormat:condition arguments:arguments];

    if ([condition isKindOfClass:[NSDictionary class]])
        return [self predicateFromDictionary:condition];

    return nil;
}

+ (NSSortDescriptor *)sortDescriptorFromDictionary:(NSDictionary *)dict {
    BOOL isAscending = ![[dict.allValues.firstObject uppercaseString] isEqualToString:@"DESC"];
    return [NSSortDescriptor sortDescriptorWithKey:dict.allKeys.firstObject
                                         ascending:isAscending];
}

+ (NSSortDescriptor *)sortDescriptorFromString:(NSString *)order {
    NSArray *components = [order split];

    NSString *key = [components firstObject];
    NSString *value = [components count] > 1 ? components[1] : @"ASC";

    return [self sortDescriptorFromDictionary:@{key: value}];

}

+ (NSSortDescriptor *)sortDescriptorFromObject:(id)order {
    if ([order isKindOfClass:[NSSortDescriptor class]])
        return order;

    if ([order isKindOfClass:[NSString class]])
        return [self sortDescriptorFromString:order];

    if ([order isKindOfClass:[NSDictionary class]])
        return [self sortDescriptorFromDictionary:order];

    return nil;
}

+ (NSArray *)sortDescriptorsFromObject:(id)order {
    if ([order isKindOfClass:[NSString class]])
        order = [order componentsSeparatedByString:@","];

    if ([order isKindOfClass:[NSArray class]])
        return [order map:^id (id object) {
            return [self sortDescriptorFromObject:object];
        }];

    return @[[self sortDescriptorFromObject:order]];
}

+ (NSFetchRequest *)createFetchRequestInContext:(NSManagedObjectContext *)context {
    NSFetchRequest *request = [NSFetchRequest new];
    NSEntityDescription *entity = [NSEntityDescription entityForName:[self entityName]
                                              inManagedObjectContext:context];
    [request setEntity:entity];
    return request;
}

+ (NSArray *)fetchWithCondition:(id)condition
                      inContext:(NSManagedObjectContext *)context
                      withOrder:(id)order
                     fetchLimit:(NSNumber *)fetchLimit {

    NSFetchRequest *request = [self createFetchRequestInContext:context];

    if (condition)
        [request setPredicate:[self predicateFromObject:condition]];

    if (order)
        [request setSortDescriptors:[self sortDescriptorsFromObject:order]];

    if (fetchLimit)
        [request setFetchLimit:[fetchLimit integerValue]];

    return [context executeFetchRequest:request error:nil];
}

+ (NSUInteger)countForFetchWithPredicate:(NSPredicate *)predicate
                               inContext:(NSManagedObjectContext *)context {
    NSFetchRequest *request = [self createFetchRequestInContext:context];
    [request setPredicate:predicate];

    return [context countForFetchRequest:request error:nil];
}

- (BOOL)saveTheContext {
    if (self.managedObjectContext == nil ||
        ![self.managedObjectContext hasChanges]) return YES;

    NSError *error = nil;
    BOOL save = [self.managedObjectContext save:&error];

    if (!save || error) {
        NSLog(@"Unresolved error in saving context for entity:\n%@!\nError: %@", self, error);
        return NO;
    }

    return YES;
}

- (void)setSafeValue:(id)value forKey:(NSString *)key {
    if (value == nil || value == [NSNull null]) {
        [self setNilValueForKey:key];
        return;
    }

    NSAttributeDescription *attribute = [[self entity] attributesByName][key];
    NSAttributeType attributeType = [attribute attributeType];

    if ((attributeType == NSStringAttributeType) && ([value isKindOfClass:[NSNumber class]]))
        value = [value stringValue];

    else if ([value isKindOfClass:[NSString class]]) {

        if ([self isIntegerAttributeType:attributeType])
            value = [NSNumber numberWithInteger:[value integerValue]];

        else if (attributeType == NSBooleanAttributeType)
            value = [NSNumber numberWithBool:[value boolValue]];

        else if (attributeType == NSFloatAttributeType)
            value = [NSNumber numberWithDouble:[value doubleValue]];

        else if (attributeType == NSDateAttributeType)
            value = [self.defaultFormatter dateFromString:value];
    }

    [self setPrimitiveValue:value forKey:key];
}

- (BOOL)isIntegerAttributeType:(NSAttributeType)attributeType {
    return (attributeType == NSInteger16AttributeType) ||
           (attributeType == NSInteger32AttributeType) ||
           (attributeType == NSInteger64AttributeType);
}

#pragma mark - Date Formatting

- (NSDateFormatter *)defaultFormatter {
    static NSDateFormatter *sharedFormatter;
    static dispatch_once_t singletonToken;
    dispatch_once(&singletonToken, ^{
        sharedFormatter = [[NSDateFormatter alloc] init];
        [sharedFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss z"];
    });

    return sharedFormatter;
}

@end


text:
layout: post
status: publish
published: true
title: !binary |-
  McOocmUgUGhvdG8gZGUgbCdIaXN0b2lyZSBkdSBXZWI=
author: mick
author_login: mick
author_email: mickael@flochlay.com
wordpress_id: 2435
wordpress_url: http://morningcoffee.deadrooster.org/?p=2435
date: 2012-08-15 14:24:31.000000000 +02:00
categories:
- Geek
tags: []
comments: []
---

But as it turns out, that photoshopped picture of a half-joke musical act is special. About twenty years ago, it became the first photograph ever used on the World Wide Web.

via Les Horribles Cernettes « Now I Know Archives.


text:
from setuptools import setup, find_packages

setup_args = dict(
    name="picosvg",
    use_scm_version={"write_to": "src/picosvg/_version.py"},
    package_dir={"": "src"},
    packages=find_packages(where="src"),
    entry_points={
        "console_scripts": [
            "picosvg=picosvg.picosvg:main",
        ],
    },
    setup_requires=["setuptools_scm"],
    install_requires=[
        "absl-py>=0.9.0",
        "lxml>=4.0",
        "skia-pathops>=0.6.0",
    ],
    extras_require={
        "dev": [
            "pytest",
            "pytest-clarity",
            "black==22.3.0",
            "pytype==2020.11.23; python_version < '3.9'",
        ],
    },
    # this is so we can use the built-in dataclasses module
    python_requires=">=3.7",
    # this is for type checker to use our inline type hints:
    # https://www.python.org/dev/peps/pep-0561/#id18
    package_data={"picosvg": ["py.typed"]},
    # metadata to display on PyPI
    author="Rod S",
    author_email="rsheeter@google.com",
    description=(
        "Exploratory utility for svg simplification, "
        "meant for use playing with COLR fonts"
    ),
)

if __name__ == "__main__":
    setup(**setup_args)


text:
require 'backports'
require 'data_mapper'
require 'adamantium'

# Library namespace
module Taxi
end

# DataMapper::Logger.new($stdout, :debug)
DataMapper.setup(:default, "sqlite3://#{Dir.pwd}/db/dev_database.sqlite")

require "taxi/person"
require "taxi/license"
require "taxi/vehicle"
require "taxi/address"
require "taxi/organisation"
require "taxi/subscription"

DataMapper.finalize
DataMapper.auto_migrate!
# DataMapper.auto_upgrade!


text:
package app.ui.cbrobbi.com.trips;

import android.content.Intent;
import android.net.Uri;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;

public class BuddyLayActivity extends AppCompatActivity {
    Button sms, email, call;
    Button sms2, email2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buddy_layout);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

//        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
//        fab.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();
//            }
//        });
//        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        sms = (Button) findViewById(R.id.buttonSms);
        email= (Button) findViewById(R.id.buttonEmail);
        call = (Button) findViewById(R.id.buttonCall);

        sms2 = (Button) findViewById(R.id.buttonSms2);
        email2 = (Button) findViewById(R.id.buttonEmail2);

        //set onclick listener for the sms button
        sms.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                sendSMS();
            }

        });
        //set onclick listener for the sms button

        sms2.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                sendSMS2();
            }
        });
        email.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                sendEmail();
            }
        });
        email2.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                sendEmail2();
            }
        });
        call.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                callMeth();
            }
        });
    }
    //methods to send sms
    public void sendSMS(){
        Intent intent = new Intent(Intent.ACTION_SENDTO);
        intent.setData(Uri.parse("smsto:"+ Uri.encode("17248242135")));
        intent.putExtra("sms_body","hello");
        startActivity(intent);
    }
    public void sendSMS2(){
        Intent intent = new Intent(Intent.ACTION_SENDTO);
        intent.setData(Uri.parse("smsto:"+Uri.encode("17248242154")));
        intent.putExtra("sms_body","hello");
        startActivity(intent);
    }
    // methods for the two buttons to send email
    public void sendEmail(){
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/html");
        intent.putExtra(Intent.EXTRA_EMAIL,"ba8768@gmail.com");
        intent.putExtra(Intent.EXTRA_SUBJECT, "Buddy olPal!");
        intent.putExtra(Intent.EXTRA_TEXT, "I'm emailing you.");
        startActivity(Intent.createChooser(intent, "Send Email"));
    }
    public void sendEmail2(){
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/html");
        intent.putExtra(Intent.EXTRA_EMAIL,"redman@gmail.com");
        intent.putExtra(Intent.EXTRA_SUBJECT, "Buddy olPal!");
        intent.putExtra(Intent.EXTRA_TEXT, "I'm emailing you.");
        startActivity(Intent.createChooser(intent, "Send Email"));
    }
    //method to call
    public void callMeth(){
        Intent intent = new Intent(Intent.ACTION_DIAL);
        intent.setData(Uri.parse("tel:2124325566"));
        startActivity(intent);

    }

}


text:
/*********************************************************************/
/* Copyright 2009, 2010 The University of Texas at Austin.           */
/* All rights reserved.                                              */
/*                                                                   */
/* Redistribution and use in source and binary forms, with or        */
/* without modification, are permitted provided that the following   */
/* conditions are met:                                               */
/*                                                                   */
/*   1. Redistributions of source code must retain the above         */
/*      copyright notice, this list of conditions and the following  */
/*      disclaimer.                                                  */
/*                                                                   */
/*   2. Redistributions in binary form must reproduce the above      */
/*      copyright notice, this list of conditions and the following  */
/*      disclaimer in the documentation and/or other materials       */
/*      provided with the distribution.                              */
/*                                                                   */
/*    THIS  SOFTWARE IS PROVIDED  BY THE  UNIVERSITY OF  TEXAS AT    */
/*    AUSTIN  ``AS IS''  AND ANY  EXPRESS OR  IMPLIED WARRANTIES,    */
/*    INCLUDING, BUT  NOT LIMITED  TO, THE IMPLIED  WARRANTIES OF    */
/*    MERCHANTABILITY  AND FITNESS FOR  A PARTICULAR  PURPOSE ARE    */
/*    DISCLAIMED.  IN  NO EVENT SHALL THE UNIVERSITY  OF TEXAS AT    */
/*    AUSTIN OR CONTRIBUTORS BE  LIABLE FOR ANY DIRECT, INDIRECT,    */
/*    INCIDENTAL,  SPECIAL, EXEMPLARY,  OR  CONSEQUENTIAL DAMAGES    */
/*    (INCLUDING, BUT  NOT LIMITED TO,  PROCUREMENT OF SUBSTITUTE    */
/*    GOODS  OR  SERVICES; LOSS  OF  USE,  DATA,  OR PROFITS;  OR    */
/*    BUSINESS INTERRUPTION) HOWEVER CAUSED  AND ON ANY THEORY OF    */
/*    LIABILITY, WHETHER  IN CONTRACT, STRICT  LIABILITY, OR TORT    */
/*    (INCLUDING NEGLIGENCE OR OTHERWISE)  ARISING IN ANY WAY OUT    */
/*    OF  THE  USE OF  THIS  SOFTWARE,  EVEN  IF ADVISED  OF  THE    */
/*    POSSIBILITY OF SUCH DAMAGE.                                    */
/*                                                                   */
/* The views and conclusions contained in the software and           */
/* documentation are those of the authors and should not be          */
/* interpreted as representing official policies, either expressed   */
/* or implied, of The University of Texas at Austin.                 */
/*********************************************************************/

#include <stdio.h>
#include <ctype.h>
#include "common.h"
#ifdef FUNCTION_PROFILE
#include "functable.h"
#endif

#ifdef XDOUBLE
#define ERROR_NAME "QSPR  "
#elif defined(DOUBLE)
#define ERROR_NAME "DSPR  "
#else
#define ERROR_NAME "SSPR  "
#endif

static int (*spr[])(BLASLONG, FLOAT, FLOAT *, BLASLONG, FLOAT *, FLOAT *) = {
#ifdef XDOUBLE
  qspr_U, qspr_L,
#elif defined(DOUBLE)
  dspr_U, dspr_L,
#else
  sspr_U, sspr_L,
#endif
};

#ifdef SMP
static int (*spr_thread[])(BLASLONG, FLOAT, FLOAT *, BLASLONG, FLOAT *, FLOAT *, int) = {
#ifdef XDOUBLE
  qspr_thread_U, qspr_thread_L,
#elif defined(DOUBLE)
  dspr_thread_U, dspr_thread_L,
#else
  sspr_thread_U, sspr_thread_L,
#endif
};
#endif

#ifndef CBLAS

void NAME(char *UPLO, blasint *N, FLOAT  *ALPHA,
	 FLOAT  *x, blasint *INCX, FLOAT *a){

  char uplo_arg = *UPLO;
  blasint n		= *N;
  FLOAT alpha	= *ALPHA;
  blasint incx	= *INCX;

  blasint info;
  int uplo;
  FLOAT *buffer;
#ifdef SMP
  int nthreads;
#endif

  PRINT_DEBUG_NAME;

  TOUPPER(uplo_arg);
  uplo  = -1;

  if (uplo_arg  == 'U') uplo  = 0;
  if (uplo_arg  == 'L') uplo  = 1;

  info = 0;

  if (incx == 0)          info =  5;
  if (n < 0)              info =  2;
  if (uplo  < 0)          info =  1;

  if (info != 0) {
    BLASFUNC(xerbla)(ERROR_NAME, &info, sizeof(ERROR_NAME));
    return;
  }

#else

void CNAME(enum CBLAS_ORDER order,
	   enum CBLAS_UPLO Uplo,
	   blasint n,
	   FLOAT alpha,
	   FLOAT  *x, blasint incx,
	   FLOAT  *a) {

  FLOAT *buffer;
  int uplo;
  blasint info;
#ifdef SMP
  int nthreads;
#endif

  PRINT_DEBUG_CNAME;

  uplo = -1;
  info =  0;

  if (order == CblasColMajor) {
    if (Uplo == CblasUpper)         uplo  = 0;
    if (Uplo == CblasLower)         uplo  = 1;

    info = -1;

    if (incx == 0)          info =  5;
    if (n < 0)              info =  2;
    if (uplo  < 0)          info =  1;
  }

  if (order == CblasRowMajor) {
    if (Uplo == CblasUpper)         uplo  = 1;
    if (Uplo == CblasLower)         uplo  = 0;

    info = -1;

    if (incx == 0)          info =  5;
    if (n < 0)              info =  2;
    if (uplo  < 0)          info =  1;
  }

  if (info >= 0) {
    BLASFUNC(xerbla)(ERROR_NAME, &info, sizeof(ERROR_NAME));
    return;
  }

#endif

  if (n == 0) return;

  if (alpha == ZERO) return;

  IDEBUG_START;

  FUNCTION_PROFILE_START();

  if (incx < 0 ) x -= (n - 1) * incx;

  buffer = (FLOAT *)blas_memory_alloc(1);

#ifdef SMP
  nthreads = num_cpu_avail(2);

  if (nthreads == 1) {
#endif

  (spr[uplo])(n, alpha, x, incx, a, buffer);

#ifdef SMP
  } else {

    (spr_thread[uplo])(n, alpha, x, incx, a, buffer, nthreads);

  }
#endif

  blas_memory_free(buffer);

  FUNCTION_PROFILE_END(1, n * n / 2 + n, n * n);

  IDEBUG_END;

  return;
}


text:
<title>Y64 Tests</title>

Y64 Tests


text:
package it.unimi.dsi.fastutil;

import java.util.Iterator;
import java.util.ListIterator;

/** A list iterator over a {@link BigList}.
 *
 *
This kind of iterator is essentially a {@link ListIterator} with long indices.
 *
 * @see Iterator
 * @see ListIterator
 */

public interface BigListIterator<K> extends BidirectionalIterator<K> {

	/** Returns the index of the element that would be returned by a subsequent call to next.
	 * (Returns list size if the list iterator is at the end of the list.)
	 *
	 * @return the index of the element that would be returned by a subsequent call to next, or list
	 * size if list iterator is at end of list.
	 * @see ListIterator#nextIndex()
	 */

	long nextIndex();

	/** Returns the index of the element that would be returned by a subsequent call to previous.
	 * (Returns -1 if the list iterator is at the beginning of the list.)
	 *
	 * @return the index of the element that would be returned by a subsequent call to previous, or
	 * -1 if list iterator is at beginning of list.
	 * @see ListIterator#previousIndex()
	 */

	long previousIndex();

	/**
	 * Replaces the last element returned by {@link #next} or
	 * {@link #previous} with the specified element (optional operation).
	 *
	 *
This default implemention just throws an {@link UnsupportedOperationException}.
	 *
	 * @param e an element.
	 * @see ListIterator#set(Object)
	 */
	default void set(final K e) {
			throw new UnsupportedOperationException();
	}

	/**
	 * Inserts the specified element into the list (optional operation).
	 *
	 *
This default implemention just throws an {@link UnsupportedOperationException}.
	 *
	 * @param e an element.
	 * @see ListIterator#add(Object)
	 */
	default void add(final K e) {
		throw new UnsupportedOperationException();
	}
}


text: <link rel="stylesheet" href="dist/flip.css">


text:
Import Backup Wallet File

If you have a Coinpunk wallet backup, this allows you to re-import it.

It must be a Coinpunk wallet, no other wallet formats are supported yet.

You will need the email and password for the previous wallet when it was exported.

    <form class="form-horizontal" onsubmit="coinpunk.controllers.accounts.performImport(); return false;">

        Email

          <input type="text" class="form-control" id="importId" placeholder="Your wallet email">

        Password

          <input type="password" class="form-control" id="importPassword" placeholder="Your wallet password" autocomplete="off">

        Wallet File

          <input id="importFile" type="file">

        <button class="btn btn-success btn-lg">Import</button>

    </form>


text:
<?php
/**
 * Created by PhpStorm.
 * User: Asen
 * Date: 18.11.2016 г.
 * Time: 21:14
 */

namespace app\components;

use app\models\Proforma;
use app\models\User;
use Yii;

class FileComponent
{
    const TYPE_FACTURA = 'ФАКТУРА';
    const TYPE_PROFORMA = 'ПРОФОРМА ФАКТУРА';
    const TYPE_ORIGINAL = 'О Р И Г И Н А Л';
    const TYPE_DUBLICATE = 'К О П И Е';

    public $filePathProforma;
    public $filePathFactura;
    public $imagesPath;
    public $imagesPathForPictures;
    public $allowedTypes;

    public function __construct($company = null)
    {
        if (!$company) {
            $currentUser = $this->getCurrentUser();
            $this->filePathProforma = getcwd()
                . DIRECTORY_SEPARATOR . 'proforma'
                . DIRECTORY_SEPARATOR . $currentUser->username;
            if (!is_dir($this->filePathProforma))
                mkdir($this->filePathProforma, 0777, true);
            $this->filePathFactura = getcwd()
                . DIRECTORY_SEPARATOR . 'facturi'
                . DIRECTORY_SEPARATOR . $currentUser->username;
            if (!is_dir($this->filePathFactura))
                mkdir($this->filePathFactura, 0777, true);

            $this->imagesPath = getcwd() . DIRECTORY_SEPARATOR . 'place_images'
                . DIRECTORY_SEPARATOR . $currentUser->username . DIRECTORY_SEPARATOR;
            if (!is_dir($this->imagesPath))
                mkdir($this->imagesPath, 0777, true);
            $this->filePathFactura .= DIRECTORY_SEPARATOR;
            $this->filePathProforma .= DIRECTORY_SEPARATOR;
            $this->imagesPathForPictures = Yii::$app->getHomeUrl() . 'place_images'
                . DIRECTORY_SEPARATOR . $currentUser->username . DIRECTORY_SEPARATOR;
        } else {
            $this->filePathProforma = getcwd()
                . DIRECTORY_SEPARATOR . 'proforma'
                . DIRECTORY_SEPARATOR . $company->username;
            if (!is_dir($this->filePathProforma))
                mkdir($this->filePathProforma, 0777, true);
            $this->filePathFactura = getcwd()
                . DIRECTORY_SEPARATOR . 'facturi'
                . DIRECTORY_SEPARATOR . $company->username;
            if (!is_dir($this->filePathFactura))
                mkdir($this->filePathFactura, 0777, true);

            $this->imagesPath = getcwd() . DIRECTORY_SEPARATOR . 'place_images'
                . DIRECTORY_SEPARATOR . $company->username . DIRECTORY_SEPARATOR;
            if (!is_dir($this->imagesPath))
                mkdir($this->imagesPath, 0777, true);
            $this->filePathFactura .= DIRECTORY_SEPARATOR;
            $this->filePathProforma .= DIRECTORY_SEPARATOR;
            $this->imagesPathForPictures = Yii::$app->getHomeUrl() . 'place_images'
                . DIRECTORY_SEPARATOR . $company->username . DIRECTORY_SEPARATOR;
        }
        $this->allowedTypes = [IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_BMP, IMAGETYPE_GIF, IMAGETYPE_PSD];
    }

    /**
     * @return Proforma
     */
    public function getProforma($id)
    {
        return Proforma::findOne($id);
    }

    /**
     * @return \TCPDF
     */
    public function preparePdfData()
    {
        /* @var $pdf \TCPDF */
        $pdf = new \TCPDF('P');
        $pdf->setPrintHeader(false);
        $pdf->SetMargins(10, 10, 10);
        $pdf->setCellHeightRatio(1);
        $pdf->SetFontSize(14);
        $pdf->AddPage();
        $pdf->setPrintFooter(false);
        $pdf->setFooterMargin(1);
        return $pdf;
    }

    public function saveNewImage($targetPath)
    {
        $info = getimagesize($_FILES['Place']['tmp_name']['picture']);
        $fileType = $_FILES['Place']['type']['picture'];
        if ($info && in_array($info[2], $this->allowedTypes)) {
            move_uploaded_file($_FILES['Place']['tmp_name']['picture'],
                $targetPath . $_FILES['Place']['name']['picture']);
        } else {
            unlink($_FILES['Place']['tmp_name']['picture']);
        }
    }

    /**
     * @return bool|User
     */
    private function getCurrentUser()
    {
        $user = User::findOne(Yii::$app->user->id);
        if (!$user) {
            Yii::$app->session->setFlash('error', 'Няма такъв потребител!');
            throw new \Exception('Няма такъв потребител!');
        }
        return $user;
    }
}