text:
package de.lessvoid.nifty.renderer.lwjgl.render.io;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.ComponentColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Hashtable;

import javax.imageio.ImageIO;

/**
 * An image data provider that uses ImageIO to retrieve image data in a format
 * suitable for creating OpenGL textures. This implementation is used when
 * formats not natively supported by the library are required.
 *
 * @author kevin
 */
public class ImageIOImageData implements ImageData {
  private static final ColorModel glAlphaColorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), new int[] { 8, 8, 8, 8 }, true, false, ComponentColorModel.TRANSLUCENT, DataBuffer.TYPE_BYTE);
  private static final ColorModel glColorModel = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB), new int[] { 8, 8, 8, 0 }, false, false, ComponentColorModel.OPAQUE, DataBuffer.TYPE_BYTE);
  private int depth;
  private int height;
  private int width;
  private int texWidth;
  private int texHeight;
  private boolean edging = true;

  /* (non-Javadoc)
   * @see de.lessvoid.nifty.renderer.lwjgl.render.io.ImageData#getDepth()
   */
  public int getDepth() {
    return depth;
  }

  /* (non-Javadoc)
   * @see de.lessvoid.nifty.renderer.lwjgl.render.io.ImageData#getHeight()
   */
  public int getHeight() {
    return height;
  }

  /* (non-Javadoc)
   * @see de.lessvoid.nifty.renderer.lwjgl.render.io.ImageData#getTexHeight()
   */
  public int getTexHeight() {
    return texHeight;
  }

  /* (non-Javadoc)
   * @see de.lessvoid.nifty.renderer.lwjgl.render.io.ImageData#getTexWidth()
   */
  public int getTexWidth() {
    return texWidth;
  }

  /* (non-Javadoc)
   * @see de.lessvoid.nifty.renderer.lwjgl.render.io.ImageData#getWidth()
   */
  public int getWidth() {
    return width;
  }

  public ByteBuffer loadImage(InputStream fis) throws IOException {
    return loadImage(fis, false, null);
  }

  public ByteBuffer loadImage(InputStream fis, boolean flipped, int[] transparent) throws IOException {
    return loadImage(fis, flipped, false, transparent);
  }

  public ByteBuffer loadImage(InputStream fis, boolean flipped, boolean forceAlpha, int[] transparent) throws IOException {
    if (transparent != null) {
      forceAlpha = true;
    }

    try {
      BufferedImage bufferedImage = ImageIO.read(fis);
      return imageToByteBuffer(bufferedImage, flipped, forceAlpha, transparent, true, false);
    } finally {
      fis.close();
    }
  }

  public ByteBuffer loadMouseCursorImage(InputStream fis) throws IOException {
    BufferedImage bufferedImage = ImageIO.read(fis);
    return imageToByteBuffer(bufferedImage, true, true, null, false, true);
  }

  public ByteBuffer loadImageDirect(InputStream fis) throws IOException {
    BufferedImage bufferedImage = ImageIO.read(fis);
    return imageToByteBuffer(bufferedImage, false, true, null, false, false);
  }

  public ByteBuffer imageToByteBuffer(BufferedImage image, boolean flipped, boolean forceAlpha, int[] transparent, boolean powerOfTwoSupport, boolean modeARGB) {
    ByteBuffer imageBuffer = null;
    WritableRaster raster;
    BufferedImage texImage;

    int texWidth = image.getWidth();
    int texHeight = image.getHeight();

    if (powerOfTwoSupport) {
      // find the closest power of 2 for the width and height
      // of the produced texture
      texWidth = 2;
      texHeight = 2;

      while (texWidth < image.getWidth()) {
        texWidth *= 2;
      }
      while (texHeight < image.getHeight()) {
        texHeight *= 2;
      }
    }

    this.width = image.getWidth();
    this.height = image.getHeight();
    this.texHeight = texHeight;
    this.texWidth = texWidth;

    // create a raster that can be used by OpenGL as a source
    // for a texture
    boolean useAlpha = image.getColorModel().hasAlpha() || forceAlpha;

    if (useAlpha) {
      depth = 32;
      raster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, texWidth, texHeight, 4, null);
      texImage = new BufferedImage(glAlphaColorModel, raster, false, new Hashtable<Object, Object>());
    } else {
      depth = 24;
      raster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, texWidth, texHeight, 3, null);
      texImage = new BufferedImage(glColorModel, raster, false, new Hashtable<Object, Object>());
    }

    // copy the source image into the produced image
    Graphics2D g = (Graphics2D) texImage.getGraphics();

    // only need to blank the image for mac compatibility if we're using alpha
    if (useAlpha) {
      g.setColor(new Color(0f, 0f, 0f, 0f));
      g.fillRect(0, 0, texWidth, texHeight);
    }

    if (flipped) {
      g.scale(1, -1);
      g.drawImage(image, 0, -height, null);
    } else {
      g.drawImage(image, 0, 0, null);
    }

    if (edging) {
      if (height < texHeight - 1) {
        copyArea(texImage, 0, 0, width, 1, 0, texHeight - 1);
        copyArea(texImage, 0, height - 1, width, 1, 0, 1);
      }
      if (width < texWidth - 1) {
        copyArea(texImage, 0, 0, 1, height, texWidth - 1, 0);
        copyArea(texImage, width - 1, 0, 1, height, 1, 0);
      }
    }

    // build a byte buffer from the temporary image
    // that be used by OpenGL to produce a texture.
    byte[] data = ((DataBufferByte) texImage.getRaster().getDataBuffer()).getData();
    if (transparent != null) {
      for (int i = 0; i < data.length; i += 4) {
        boolean match = true;
        for (int c = 0; c < 3; c++) {
          int value = data[i + c] < 0 ? 256 + data[i + c] : data[i + c];
          if (value != transparent[c]) {
            match = false;
          }
        }

        if (match) {
          data[i + 3] = 0;
        }
      }
    }
    if (modeARGB) {
      for (int i = 0; i < data.length; i += 4) {
        byte rr = data[i + 0];
        byte gg = data[i + 1];
        byte bb = data[i + 2];
        byte aa = data[i + 3];
        data[i + 0] = bb;
        data[i + 1] = gg;
        data[i + 2] = rr;
        data[i + 3] = aa;
      }
    }

    imageBuffer = ByteBuffer.allocateDirect(data.length);
    imageBuffer.order(ByteOrder.nativeOrder());
    imageBuffer.put(data, 0, data.length);
    imageBuffer.flip();
    g.dispose();

    return imageBuffer;
  }

  /* (non-Javadoc)
   * @see de.lessvoid.nifty.renderer.lwjgl.render.io.ImageData#getImageBufferData()
   */
  public ByteBuffer getImageBufferData() {
    throw new RuntimeException("ImageIOImageData doesn't store it's image.");
  }

  private void copyArea(BufferedImage image, int x, int y, int width, int height, int dx, int dy) {
    Graphics2D g = (Graphics2D) image.getGraphics();
   g.drawImage(image.getSubimage(x, y, width, height), x + dx, y + dy, null);
  }
}


text:
//==============================================================================
//         Copyright 2003 - 2011   LASMEA UMR 6602 CNRS/Univ. Clermont II
//         Copyright 2009 - 2011   LRI    UMR 8623 CNRS/Univ Paris Sud XI
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_BITWISE_FUNCTIONS_BITWISE_ORNOT_HPP_INCLUDED
#define NT2_BITWISE_FUNCTIONS_BITWISE_ORNOT_HPP_INCLUDED

#include <boost/simd/bitwise/include/functions/bitwise_ornot.hpp>
#include <nt2/include/functor.hpp>

/* Automatically generated for module core.base */

namespace nt2
{
  namespace tag
  {
    #ifdef DOXYGEN_ONLY
    /*! \brief Same as \classref{boost::simd::tag::bitwise_ornot_} **/
    struct bitwise_ornot_ {};
    #endif
    using boost::simd::tag::bitwise_ornot_;
  }

  #ifdef DOXYGEN_ONLY
  /*! \brief Same as \funcref{boost::simd::bitwise_ornot} **/
  template<class... Args>
  details::unspecified bitwise_ornot(Args&&... args);
  #endif
  using boost::simd::bitwise_ornot;
}

#endif

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace Genkgo\Camt\Camt053;

use DateTimeImmutable;
use DOMDocument;
use Genkgo\Camt\DecoderInterface;
use Genkgo\Camt\Exception\InvalidMessageException;
use Genkgo\Camt\Iban;
use Money\Currency;
use Money\Money;
use SimpleXMLElement;

class Decoder implements DecoderInterface
{
    /**
     * @var SimpleXMLElement[]
     */
    private $document;

    /**
     * @param DOMDocument $document
     * @throws InvalidMessageException
     */
    private function validate(DOMDocument $document)
    {
        libxml_use_internal_errors(true);
        $valid = $document->schemaValidate(dirname(dirname(__DIR__)).'/assets/camt.053.001.02.xsd');
        $errors = libxml_get_errors();
        libxml_clear_errors();

        if (!$valid) {
            $messages = [];
            foreach ($errors as $error) {
                $messages[] = $error->message;
            }

            $errorMessage = implode("\n", $messages);
            throw new InvalidMessageException("Provided XML is not valid according to the XSD:\n{$errorMessage}");
        }
    }

    /**
     * @param DOMDocument $document
     * @return Message
     * @throws InvalidMessageException
     */
    public function decode(DOMDocument $document)
    {
        $this->validate($document);
        $this->document = simplexml_import_dom($document);

        $message = new Message();
        $this->addGroupHeaderToMessage($message);
        $this->addStatementsToMessage($message);

        return $message;
    }

    /**
     * @param SimpleXMLElement $statementXml
     * @param Statement $statement
     */
    private function addBalancesToStatement(SimpleXMLElement $statementXml, Statement $statement)
    {
        $balancesXml = $statementXml->Bal;
        foreach ($balancesXml as $balanceXml) {
            $amount = Money::stringToUnits((string)$balanceXml->Amt);
            $currency = (string)$balanceXml->Amt['Ccy'];
            $date = (string)$balanceXml->Dt->Dt;

            if ((string) $balanceXml->CdtDbtInd === 'DBIT') {
                $amount = $amount * -1;
            }

            if ((string) $balanceXml->Tp->CdOrPrtry->Cd === 'OPBD') {
                $balance = Balance::opening(
                    new Money(
                        $amount,
                        new Currency($currency)
                    ),
                    new DateTimeImmutable($date)
                );
            } else {
                $balance = Balance::closing(
                    new Money(
                        $amount,
                        new Currency($currency)
                    ),
                    new DateTimeImmutable($date)
                );
            }

            $statement->addBalance($balance);
        }
    }

    /**
     * @param SimpleXMLElement $statementXml
     * @param Statement $statement
     */
    private function addEntriesToStatement(SimpleXMLElement $statementXml, Statement $statement)
    {
        $index = 0;
        $entriesXml = $statementXml->Ntry;
        foreach ($entriesXml as $entryXml) {
            $amount = Money::stringToUnits((string) $entryXml->Amt);
            $currency = (string)$entryXml->Amt['Ccy'];
            $bookingDate = (string)$entryXml->BookgDt->Dt;
            $valueDate = (string)$entryXml->ValDt->Dt;

            if ((string) $entryXml->CdtDbtInd === 'DBIT') {
                $amount = $amount * -1;
            }

            $entry = new Entry(
                $statement,
                $index,
                new Money($amount, new Currency($currency)),
                new DateTimeImmutable($bookingDate),
                new DateTimeImmutable($valueDate)
            );

            if (isset($entryXml->RvslInd) && (string) $entryXml->RvslInd === 'true') {
                $entry->setReversalIndicator(true);
            }

            if (isset($entryXml->NtryRef) && (string) $entryXml->NtryRef) {
                $entry->setReference((string) $entryXml->NtryRef);
            }

            if (isset($entryXml->NtryDtls->Btch->PmtInfId) && (string) $entryXml->NtryDtls->Btch->PmtInfId) {
                $entry->setBatchPaymentId((string) $entryXml->NtryDtls->Btch->PmtInfId);
            }

            $this->addTransactionDetailsToEntry($entryXml, $entry);

            $statement->addEntry($entry);
            $index++;
        }
    }

    /**
     * @param SimpleXMLElement $entryXml
     * @param Entry $entry
     */
    private function addTransactionDetailsToEntry(SimpleXMLElement $entryXml, Entry $entry)
    {
        $detailsXml = $entryXml->NtryDtls->TxDtls;
        if ($detailsXml) {
            foreach ($detailsXml as $detailXml) {
                $detail = new EntryTransactionDetail();
                $this->addReferencesToTransactionDetails($detailXml, $detail);
                $this->addRelatedPartiesToTransactionDetails($detailXml, $detail);
                $this->addRemittanceInformationToTransactionDetails($detailXml, $detail);
                $entry->addTransactionDetail($detail);
            }
        }
    }

    /**
     * @param SimpleXMLElement $detailXml
     * @param EntryTransactionDetail $detail
     */
    private function addRelatedPartiesToTransactionDetails(SimpleXMLElement $detailXml, EntryTransactionDetail $detail)
    {
        if (isset($detailXml->RltdPties)) {
            foreach ($detailXml->RltdPties as $relatedPartyXml) {

                if (isset($relatedPartyXml->Cdtr)) {
                    $relatedPartyTypeXml = $relatedPartyXml->Cdtr;
                    $relatedPartyTypeAccountXml = $relatedPartyXml->CdtrAcct;
                    $relatedPartyType = $creditor = new Creditor((string) $relatedPartyTypeXml->Nm);
                } elseif (isset($relatedPartyXml->Dbtr)) {
                    $relatedPartyTypeXml = $relatedPartyXml->Dbtr;
                    $relatedPartyTypeAccountXml = $relatedPartyXml->DbtrAcct;
                    $relatedPartyType = $creditor = new Debtor((string) $relatedPartyTypeXml->Nm);
                } else {
                    continue;
                }

                if (isset($relatedPartyTypeXml->PstlAdr)) {
                    $address = new Address();
                    if (isset($relatedPartyTypeXml->PstlAdr->Ctry)) {
                        $address = $address->setCountry($relatedPartyTypeXml->PstlAdr->Ctry);
                    }
                    if (isset($relatedPartyTypeXml->PstlAdr->AdrLine)) {
                        foreach ($relatedPartyTypeXml->PstlAdr->AdrLine as $line) {
                            $address = $address->addAddressLine((string)$line);
                        }
                    }

                    $relatedPartyType->setAddress($address);
                }

                if (isset($relatedPartyTypeAccountXml->Id->IBAN) && $ibanCode = (string) $relatedPartyTypeAccountXml->Id->IBAN) {
                    $account = new Account(new Iban($ibanCode));
                } else {
                    $account = null;
                }

                $relatedParty = new RelatedParty($relatedPartyType, $account);
                $detail->addRelatedParty($relatedParty);
            }
        }
    }

    /**
     * @param SimpleXMLElement $detailXml
     * @param EntryTransactionDetail $detail
     */
    private function addReferencesToTransactionDetails(SimpleXMLElement $detailXml, EntryTransactionDetail $detail)
    {
        if (isset($detailXml->Refs->EndToEndId)) {
            $endToEndId = (string)$detailXml->Refs->EndToEndId;
            if (isset($detailXml->Refs->MndtId)) {
                $mandateId = (string)$detailXml->Refs->MndtId;
            } else {
                $mandateId = null;
            }
            $detail->addReference(new Reference($endToEndId, $mandateId));
        }
    }

    /**
     * @param SimpleXMLElement $detailXml
     * @param EntryTransactionDetail $detail
     */
    private function addRemittanceInformationToTransactionDetails(SimpleXMLElement $detailXml, EntryTransactionDetail $detail)
    {
        if (isset($detailXml->RmtInf)) {
            if (isset($detailXml->RmtInf->Ustrd)) {
                $remittanceInformation = RemittanceInformation::fromUnstructured(
                    (string)$detailXml->RmtInf->Ustrd
                );
                $detail->setRemittanceInformation($remittanceInformation);
            }
        }
    }

    /**
     * @param Message $message
     */
    private function addGroupHeaderToMessage(Message $message)
    {
        $groupHeaderXml = $this->document->BkToCstmrStmt->GrpHdr;
        $groupHeader = new GroupHeader(
            (string)$groupHeaderXml->MsgId,
            new DateTimeImmutable((string)$groupHeaderXml->CreDtTm)
        );

        $message->setGroupHeader($groupHeader);
    }

    /**
     * @param Message $message
     */
    private function addStatementsToMessage($message)
    {
        $statements = [];

        $statementsXml = $this->document->BkToCstmrStmt->Stmt;
        foreach ($statementsXml as $statementXml) {
            $statement = new Statement(
                $statementXml->Id,
                new DateTimeImmutable((string)$statementXml->CreDtTm),
                new Account(new Iban((string)$statementXml->Acct->Id->IBAN))
            );

            $this->addBalancesToStatement($statementXml, $statement);
            $this->addEntriesToStatement($statementXml, $statement);

            $statements[] = $statement;
        }

        $message->setStatements($statements);
    }

}


text:
pledge.github.io
================


text:
using Laurus.UiTest.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Laurus.UiTest.Selenium.IntegrationTest.Pages
{
	public interface IInstrumentedPage : IPage
	{
		IEditable Name { get; }
		IEditable Age { get; }
		IClickable Submit { get; }
		IStatic StaticSpan { get; }
		IStatic Result { get; }
	}

    public class InstrumentedPageMap : PageMap<IInstrumentedPage>
	{
        public InstrumentedPageMap() : base("data-qa")
		{
			AddToMap(x => x.StaticSpan, LocatorKey.Name, "uninstrumented");
			AddToMap(x => x.Result, LocatorKey.Id, "result");
		}
	}
}


text:
using System;
using System.Linq;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Psi;
using TestFx.ReSharper.UnitTesting.Explorers.Metadata;
using TestFx.ReSharper.UnitTesting.Explorers.Tree;
using TestFx.Utilities;

namespace TestFx.ReSharper.Extensions.SpecK
{
  [PsiComponent]
  public class TestProviderFactory : ITestDeclarationProviderFactory, ITestMetadataProviderFactory
  {
    private readonly ITreePresenter _treePresenter;
    private readonly IMetadataPresenter _metadataPresenter;

    public TestProviderFactory (ITreePresenter treePresenter, IMetadataPresenter metadataPresenter)
    {
      _treePresenter = treePresenter;
      _metadataPresenter = metadataPresenter;
    }

    #region ITestDeclarationProviderFactory

    public ITestDeclarationProvider CreateTestDeclarationProvider (IIdentity assemblyIdentity, IProject project, Func<bool> notInterrupted)
    {
      return new TestDeclarationProvider(_treePresenter, project, assemblyIdentity, notInterrupted);
    }

    #endregion

    #region ITestMetadataProviderFactory

    public ITestMetadataProvider CreateTestMetadataProvider (IIdentity assemblyIdentity, IProject project, Func<bool> notInterrupted)
    {
      return new TestMetadataProvider(_metadataPresenter, project, assemblyIdentity, notInterrupted);
    }

    #endregion
  }
}


text:
package nl.han.ica.ap.purify.module.java.duplicatecode;

import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.junit.Assert.assertEquals;

import nl.han.ica.ap.purify.language.java.JavaParser.MemberDeclContext;
import nl.han.ica.ap.purify.language.java.JavaParser.VariableDeclaratorIdContext;

import org.antlr.v4.runtime.tree.ParseTree;
import org.junit.Before;
import org.junit.Test;

/**
 * The the similarity of trees.
 *
 * @author Arjan
 */
public class ParseTreeSimilarityTest {
	private ParseTree left;
	private ParseTree right;

	@Before
	public void setUp() {
		left = createMock(ParseTree.class);
		right = createMock(ParseTree.class);
	}

	/**
	 * Test the similarity of a similar parse tree.
	 */
	@Test
	public void similarTest() {
		ParseTreeSimilarity similarity;

		// Build left parse tree.
		MemberDeclContext leftChild = createMock(MemberDeclContext.class);

		expect(left.getChildCount()).andReturn(1).anyTimes();
		expect(left.getChild(0)).andReturn(leftChild);

		expect(leftChild.getChildCount()).andReturn(0).anyTimes();

		replay(left);
		replay(leftChild);

		// Build right parse tree.
		MemberDeclContext rightChild = createMock(MemberDeclContext.class);

		expect(right.getChildCount()).andReturn(1).anyTimes();
		expect(right.getChild(0)).andReturn(rightChild);

		expect(rightChild.getChildCount()).andReturn(0).anyTimes();

		replay(right);
		replay(rightChild);

		similarity = new ParseTreeSimilarity(left, right);

		assertEquals(0,0f, similarity.getSimilarity());

		verify(left);
		verify(leftChild);
		verify(right);
		verify(rightChild);
	}

	/**
	 * Left tree has no children. Right tree has one child.
	 *
	 * 0.66 		= 2 x 1 / (2 x 1 + 0 + 1)
	 */
	@Test
	public void different1Test() {
		ParseTreeSimilarity similarity;

		// Build left parse tree.
		expect(left.getChildCount()).andReturn(0).anyTimes();

		replay(left);

		// Build right parse tree.
		MemberDeclContext rightChild = createMock(MemberDeclContext.class);

		expect(right.getChildCount()).andReturn(1).anyTimes();
		expect(right.getChild(0)).andReturn(rightChild);

		expect(rightChild.getChildCount()).andReturn(0).anyTimes();

		replay(right);
		replay(rightChild);

		similarity = new ParseTreeSimilarity(left, right);

		assertEquals(0.66f, similarity.getSimilarity(), 0.01);

		verify(left);
		verify(right);
		verify(rightChild);
	}

	/**
	 * Left tree has no children. Right tree has two children.
	 *
	 * 0.5 			= 2 x 1 / (2 x 1 + 0 + 2)
	 */
	@Test
	public void different2Test() {
		ParseTreeSimilarity similarity;

		// Build left parse tree.
		expect(left.getChildCount()).andReturn(0).anyTimes();

		replay(left);

		// Build right parse tree.
		MemberDeclContext right1Child =
				createMock(MemberDeclContext.class);
		VariableDeclaratorIdContext right2Child =
				createMock(VariableDeclaratorIdContext.class);

		expect(right.getChildCount()).andReturn(2).anyTimes();
		expect(right.getChild(0)).andReturn(right1Child);
		expect(right.getChild(1)).andReturn(right2Child);

		expect(right1Child.getChildCount()).andReturn(0).anyTimes();
		expect(right2Child.getChildCount()).andReturn(0).anyTimes();

		replay(right);
		replay(right1Child);
		replay(right2Child);

		similarity = new ParseTreeSimilarity(left, right);

		assertEquals(0.5f, similarity.getSimilarity(), 0.01);

		verify(left);
		verify(right);
		verify(right1Child);
		verify(right2Child);
	}

	/**
	 * Left tree has 1 child. Right tree has two children.
	 *
	 * 0.4 			= 2 x 1 / (2 x 1 + 1 + 2)
	 */
	@Test
	public void different3Test() {
		ParseTreeSimilarity similarity;

		// Build left parse tree.
		VariableDeclaratorIdContext left1Child =
				createMock(VariableDeclaratorIdContext.class);

		expect(left.getChildCount()).andReturn(1).anyTimes();
		expect(left.getChild(0)).andReturn(left1Child);

		expect(left1Child.getChildCount()).andReturn(0).anyTimes();

		replay(left);
		replay(left1Child);

		// Build right parse tree.
		MemberDeclContext right1Child =
				createMock(MemberDeclContext.class);
		VariableDeclaratorIdContext right2Child =
				createMock(VariableDeclaratorIdContext.class);

		expect(right.getChildCount()).andReturn(2).anyTimes();
		expect(right.getChild(0)).andReturn(right1Child);
		expect(right.getChild(1)).andReturn(right2Child);

		expect(right1Child.getChildCount()).andReturn(0).anyTimes();
		expect(right2Child.getChildCount()).andReturn(0).anyTimes();

		replay(right);
		replay(right1Child);
		replay(right2Child);

		similarity = new ParseTreeSimilarity(left, right);

		assertEquals(0.4f, similarity.getSimilarity(), 0.01);

		verify(left);
		verify(left1Child);
		verify(right);
		verify(right1Child);
		verify(right2Child);
	}
}


text:
#include <zephyr/kernel.h>
#include <zephyr/sys/printk.h>

#include <zephyr/bluetooth/bluetooth.h>
#include <zephyr/bluetooth/conn.h>
#include <zephyr/bluetooth/gatt.h>

extern int mtu_exchange(struct bt_conn *conn);
extern int write_cmd(struct bt_conn *conn);
extern struct bt_conn *conn_connected;
extern uint32_t last_write_rate;
extern void (*start_scan_func)(void);

static void device_found(const bt_addr_le_t *addr, int8_t rssi, uint8_t type,
			 struct net_buf_simple *ad)
{
	char dev[BT_ADDR_LE_STR_LEN];
	struct bt_conn *conn;
	int err;

	bt_addr_le_to_str(addr, dev, sizeof(dev));
	printk("[DEVICE]: %s, AD evt type %u, AD data len %u, RSSI %i\n",
	       dev, type, ad->len, rssi);

	/* We're only interested in connectable events */
	if (type != BT_GAP_ADV_TYPE_ADV_IND &&
	    type != BT_GAP_ADV_TYPE_ADV_DIRECT_IND) {
		return;
	}

	/* connect only to devices in close proximity */
	if (rssi < -70) {
		return;
	}

	err = bt_le_scan_stop();
	if (err) {
		printk("%s: Stop LE scan failed (err %d)\n", __func__, err);
		return;
	}

	err = bt_conn_le_create(addr, BT_CONN_LE_CREATE_CONN,
				BT_LE_CONN_PARAM_DEFAULT, &conn);
	if (err) {
		printk("%s: Create conn failed (err %d)\n", __func__, err);
		start_scan_func();
	} else {
		bt_conn_unref(conn);
	}
}

static void start_scan(void)
{
	int err;

	err = bt_le_scan_start(BT_LE_SCAN_ACTIVE, device_found);
	if (err) {
		printk("%s: Scanning failed to start (err %d)\n", __func__,
		       err);
		return;
	}

	printk("%s: Scanning successfully started\n", __func__);
}

void mtu_updated(struct bt_conn *conn, uint16_t tx, uint16_t rx)
{
	printk("Updated MTU: TX: %d RX: %d bytes\n", tx, rx);
}

static struct bt_gatt_cb gatt_callbacks = {
	.att_mtu_updated = mtu_updated
};

uint32_t central_gatt_write(uint32_t count)
{
	int err;

	err = bt_enable(NULL);
	if (err) {
		printk("Bluetooth init failed (err %d)\n", err);
		return 0U;
	}
	printk("Bluetooth initialized\n");

	bt_gatt_cb_register(&gatt_callbacks);

	conn_connected = NULL;
	last_write_rate = 0U;

	start_scan_func = start_scan;
	start_scan_func();

	while (true) {
		struct bt_conn *conn = NULL;

		if (conn_connected) {
			/* Get a connection reference to ensure that a
			 * reference is maintained in case disconnected
			 * callback is called while we perform GATT Write
			 * command.
			 */
			conn = bt_conn_ref(conn_connected);
		}

		if (conn) {
			(void)write_cmd(conn);
			bt_conn_unref(conn);

			if (count) {
				count--;
				if (!count) {
					break;
				}
			}

			k_yield();
		} else {
			k_sleep(K_SECONDS(1));
		}
	}

	return last_write_rate;
}


text:
set -eux

# CONTAINER 1 is controller and monolith
container_name="ctrl"
source "$m_meza_host/tests/docker/init-controller.sh"
container_id_1="$container_id"
docker_ip_1="$docker_ip"
docker_exec_1=( "${docker_exec[@]}" )

# CONTAINER 2 is a backup server
container_name="bkup"
source "$m_meza_host/tests/docker/init-minion.sh"
docker_ip_2="$docker_ip"
docker_exec_2=( "${docker_exec[@]}" )

# CONTAINER 1
# (1) Get local secret config from repo
# (2) Change backup server IP address to docker#2 in hosts file
# (3) Change all other servers to docker#1 IP address in hosts file
# (4) Change FQDN to docker#1 IP address in secret.yml
${docker_exec_1[@]} git clone \
	https://github.com/enterprisemediawiki/meza-test-config-secret.git \
	"/opt/conf-meza/secret/$env_name"
${docker_exec_1[@]} sed -r -i "s/localhost #backup/$docker_ip_2/g;" \
	"/opt/conf-meza/secret/$env_name/hosts"
${docker_exec_1[@]} sed -r -i "s/localhost/$docker_ip_1/g;" \
	"/opt/conf-meza/secret/$env_name/hosts"
${docker_exec_1[@]} sed -r -i "s/INSERT_FQDN/$docker_ip_1/g;" \
	"/opt/conf-meza/secret/$env_name/secret.yml"

# Test allow_image_tags (which requires patching Parsoid, plus an item in
# LocalSettings.php)
${docker_exec_1[@]} bash -c "echo -e 'allow_image_tags: True\n' >> '/opt/conf-meza/secret/$env_name/secret.yml'"

# CONTAINER 2: get backup files
${docker_exec_2[@]} git clone \
	https://github.com/jamesmontalvo3/meza-test-backups.git \
	"/opt/data-meza/backups/$env_name"

# Run script on controller to `meza deploy`, `meza create wiki` and
# `meza backup`
${docker_exec_1[@]} bash /opt/meza/tests/deploys/import-from-remote.controller.sh "$env_name"

# Delete Top Wiki (wiki_id = top)
${docker_exec_1[@]} meza delete wiki-promptless "$env_name" "top"

# FIXME: Perform checks that "Top Wiki" is gone, but system is still functional


text:
/*
 * GstreamerExtensions.h
 *
 *  Created on: May 10, 2014
 *      Author: loganek
 */

#ifndef GSTREAMEREXTENSIONS_H_
#define GSTREAMEREXTENSIONS_H_

#include "GstreamerExtensions/Link.h"
#include "GstreamerExtensions/SometimesPad.h"

#endif /* GSTREAMEREXTENSIONS_H_ */


text:
package org.apache.lucene.search.highlight;

import java.util.HashMap;
import java.util.HashSet;

import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.Query;

/**
 * {@link Scorer} implementation which scores text fragments by the number of
 * unique query terms found. This class uses the {@link QueryTermExtractor}
 * class to process determine the query terms and their boosts to be used.
 */
// TODO: provide option to boost score of fragments near beginning of document
// based on fragment.getFragNum()
public class QueryTermScorer implements Scorer {

  TextFragment currentTextFragment = null;
  HashSet<String> uniqueTermsInFragment;

  float totalScore = 0;
  float maxTermWeight = 0;
  private HashMap<String,WeightedTerm> termsToFind;

  private CharTermAttribute termAtt;

  /**
   *
   * @param query a Lucene query (ideally rewritten using query.rewrite before
   *        being passed to this class and the searcher)
   */
  public QueryTermScorer(Query query) {
    this(QueryTermExtractor.getTerms(query));
  }

  /**
   *
   * @param query a Lucene query (ideally rewritten using query.rewrite before
   *        being passed to this class and the searcher)
   * @param fieldName the Field name which is used to match Query terms
   */
  public QueryTermScorer(Query query, String fieldName) {
    this(QueryTermExtractor.getTerms(query, false, fieldName));
  }

  /**
   *
   * @param query a Lucene query (ideally rewritten using query.rewrite before
   *        being passed to this class and the searcher)
   * @param reader used to compute IDF which can be used to a) score selected
   *        fragments better b) use graded highlights eg set font color
   *        intensity
   * @param fieldName the field on which Inverse Document Frequency (IDF)
   *        calculations are based
   */
  public QueryTermScorer(Query query, IndexReader reader, String fieldName) {
    this(QueryTermExtractor.getIdfWeightedTerms(query, reader, fieldName));
  }

  public QueryTermScorer(WeightedTerm[] weightedTerms) {
    termsToFind = new HashMap<>();
    for (int i = 0; i < weightedTerms.length; i++) {
      WeightedTerm existingTerm = termsToFind
          .get(weightedTerms[i].term);
      if ((existingTerm == null)
          || (existingTerm.weight < weightedTerms[i].weight)) {
        // if a term is defined more than once, always use the highest scoring
        // weight
        termsToFind.put(weightedTerms[i].term, weightedTerms[i]);
        maxTermWeight = Math.max(maxTermWeight, weightedTerms[i].getWeight());
      }
    }
  }

  /* (non-Javadoc)
   * @see org.apache.lucene.search.highlight.Scorer#init(org.apache.lucene.analysis.TokenStream)
   */
  @Override
  public TokenStream init(TokenStream tokenStream) {
    termAtt = tokenStream.addAttribute(CharTermAttribute.class);
    return null;
  }

  /*
   * (non-Javadoc)
   *
   * @see
   * org.apache.lucene.search.highlight.FragmentScorer#startFragment(org.apache
   * .lucene.search.highlight.TextFragment)
   */
  @Override
  public void startFragment(TextFragment newFragment) {
    uniqueTermsInFragment = new HashSet<>();
    currentTextFragment = newFragment;
    totalScore = 0;

  }

  /* (non-Javadoc)
   * @see org.apache.lucene.search.highlight.Scorer#getTokenScore()
   */
  @Override
  public float getTokenScore() {
    String termText = termAtt.toString();

    WeightedTerm queryTerm = termsToFind.get(termText);
    if (queryTerm == null) {
      // not a query term - return
      return 0;
    }
    // found a query term - is it unique in this doc?
    if (!uniqueTermsInFragment.contains(termText)) {
      totalScore += queryTerm.getWeight();
      uniqueTermsInFragment.add(termText);
    }
    return queryTerm.getWeight();
  }

  /* (non-Javadoc)
   * @see org.apache.lucene.search.highlight.Scorer#getFragmentScore()
   */
  @Override
  public float getFragmentScore() {
    return totalScore;
  }

  /*
   * (non-Javadoc)
   *
   * @see
   * org.apache.lucene.search.highlight.FragmentScorer#allFragmentsProcessed()
   */
  public void allFragmentsProcessed() {
    // this class has no special operations to perform at end of processing
  }

  /**
   *
   * @return The highest weighted term (useful for passing to GradientFormatter
   *         to set top end of coloring scale.
   */
  public float getMaxTermWeight() {
    return maxTermWeight;
  }
}


text:
package com.piketec.tpt.api.steplist;

/**
 * A simple step to close a step-block.
 */
public interface EndStep extends Step {

}


text:
namespace te
{
	namespace internal
	{
		GameObjectMetaDataStorage::GameObjectMetaDataStorage(size_t amountOfGameObjects) :
			m_metaDataEntries(amountOfGameObjects)
		{
		}

		GameObjectMetaDataStorage::GameObjectMetaData& GameObjectMetaDataStorage::getMetaData(const GameObject& go)
		{
			return m_metaDataEntries[go.getId().index];
		}

		void GameObjectMetaDataStorage::setName(const GameObject& go, const string& name)
		{
			auto index = go.getId().index;
			auto& metaData = m_metaDataEntries[index];

			metaData.name = name;
		}

		const string& GameObjectMetaDataStorage::getName(const GameObject& go)
		{
			return m_metaDataEntries[go.getId().index].name;
		}

		void GameObjectMetaDataStorage::setTag(const GameObject& go, const string& tag)
		{
			auto index = go.getId().index;
			auto& metaData = m_metaDataEntries[index];

			metaData.tag = tag;
		}

		const string& GameObjectMetaDataStorage::getTag(const GameObject& go)
		{
			return m_metaDataEntries[go.getId().index].tag;
		}

		void GameObjectMetaDataStorage::clear()
		{
			m_metaDataEntries.clear();
		}

		void GameObjectMetaDataStorage::resize(size_t amountOfGameObjects)
		{
			m_metaDataEntries.resize(amountOfGameObjects);
		}
	}
}


text:
    <title>Move items</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <meta http-equiv="imagetoolbar" content="no"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
    <meta name="apple-mobile-web-app-capable" content="yes"/>
    <link rel="apple-touch-icon" href="data/apple-touch-icon.png" />
    <link rel="apple-touch-startup-image" href="data/startup-iphone.png" media="screen and (max-device-width: 320px)"/>
    <link href="resources/css/jquery-ui-themes.css" type="text/css" rel="stylesheet">
    <link href="resources/css/axure_rp_page.css" type="text/css" rel="stylesheet">
    <link href="Move_items_files/axurerp_pagespecificstyles.css" type="text/css" rel="stylesheet">

Done

Replace with your iPhone App Design


text:
sringMVC code this Mall

java商城

使用springMVC、mysql


text:
select *
from employees
where age = 32
;


text:
project_path: /web/tools/chrome-devtools/_project.yaml
book_path: /web/tools/chrome-devtools/_book.yaml
description: How to debug Background Fetch, Background Sync, Notifications, and Push Messages with Chrome DevTools.

{# wf_updated_on: 2020-07-10 #}
{# wf_published_on: 2019-09-15 #}
{# wf_blink_components: Platform>DevTools #}

[serviceworker]: https://web.dev/service-workers-cache-storage/
[push]: https://developer.mozilla.org/en-US/docs/Web/API/Push_API
[notifications]: https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API

# Debug Background Services With Chrome DevTools {: .page-title }

{% include "web/_shared/contributors/kaycebasques.html" %}

The **Background Services** section of Chrome DevTools is a collection of tools for the JavaScript APIs
that enables your website to send and receive updates even when a user does not have your website open.
A background service is functionally similar to a [background process](https://en.wikipedia.org/wiki/Background_process).
Chrome DevTools considers each of the following APIs to be a background service:

* [Background Fetch](#fetch)
* [Background Sync](#sync)
* [Notifications](#notifications)
* [Push Messages](#push)

Chrome DevTools can log background service events for 3 days, even when DevTools is not open.
This can help you make sure that events are being sent and received as expected. You can also
inspect the details of each event.

    Figure 1. Viewing the details of an event in the Push Messaging pane.

## Background Fetch {: #fetch }

The [Background Fetch](/web/updates/2018/12/background-fetch) API enables a [service worker][serviceworker] to
reliably download large resources, like movies or podcasts, as a background service. To log Background Fetch
event for 3 days, even when DevTools is not open:

1. [Open DevTools](/web/tools/chrome-devtools/open).
1. Open the **Application** panel.
1. Open the **Background Fetch** pane.

         Figure 2. The Background Fetch pane.

1. Click **Record** ![Record](/web/tools/chrome-devtools/images/shared/record.png){: .inline-icon }.
   After triggering some Background Fetch activity, DevTools logs the events to the table.

         Figure 3. A log of events in the Background Fetch pane.

1. Click an event to view its details in the space below the table.

         Figure 4. Viewing the details of an event in the Background Fetch pane.

## Background Sync {: #sync }

The [Background Sync](/web/updates/2015/12/background-sync) API enables an offline [service worker][serviceworker]
to send data to a server once it has re-established a reliable internet connection. To log Background Sync events for 3 days, even
when DevTools is not open:

1. [Open DevTools](/web/tools/chrome-devtools/open).
1. Open the **Application** panel.
1. Open the **Background Sync** pane.

         Figure 5. The Background Sync pane.

1. Click **Record** ![Record](/web/tools/chrome-devtools/images/shared/record.png){: .inline-icon }.
   After triggering some Background Sync activity, DevTools logs the events to the table.

         Figure 6. A log of events in the Background Sync pane.

1. Click an event to view its details in the space below the table.

         Figure 7. Viewing the details of an event in the Background Sync pane.

## Notifications {: #notifications }

After a [service worker][serviceworker] has received a [Push Message][push] from a server, the service worker
uses the [Notifications][notifications] API to display the data to a user. To log Notifications for 3 days, even
when DevTools is not open:

1. [Open DevTools](/web/tools/chrome-devtools/open).
1. Open the **Application** panel.
1. Open the **Notifications** pane.

         Figure 8. The Notifications pane.

1. Click **Record** ![Record](/web/tools/chrome-devtools/images/shared/record.png){: .inline-icon }.
   After triggering some Notifications activity, DevTools logs the events to the table.

         Figure 9. A log of events in the Notifications pane.

1. Click an event to view its details in the space below the table.

         Figure 10. Viewing the details of an event in the Notifications pane.

## Push Messages {: #push }

To display a push notification to a user, a [service worker][serviceworker] must first use the
[Push Message][push] API to receive data from a server. When the service worker is ready to display
the notification, it uses the [Notifications][notifications] API. To log Push Messages for 3 days, even
when DevTools is not open:

1. [Open DevTools](/web/tools/chrome-devtools/open).
1. Open the **Application** panel.
1. Open the **Push Messaging** pane.

         Figure 11. The Push Messaging pane.

1. Click **Record** ![Record](/web/tools/chrome-devtools/images/shared/record.png){: .inline-icon }.
   After triggering some Push Message activity, DevTools logs the events to the table.

         Figure 12. A log of events in the Push Messaging pane.

1. Click an event to view its details in the space below the table.

         Figure 13. Viewing the details of an event in the Push Messaging pane.

## Feedback {: #feedback }

{% include "web/_shared/helpful.html" %}


text:
type DisplayMessage = (message: string, duration?: number) => void
type DisplayError = (errorMessage: string, duration?: number) => void


text:
require 'csv'

# This implements:
#   the Transformer interface {transform}
#   our ad-hoc CSV data interface {each_with_index}
class StreamingCsvTransformer
  NIL_CODE = 'NULL'

  # Sugar for the common "just give me parsed rows" use case
  # Note that this uses different options that the default.
  def self.from_text(log, file_text, options = {})
    StreamingCsvTransformer.new(log, {
      csv_options: { header_converters: nil }
    }.merge(options)).transform(file_text)
  end

  def initialize(log, options = {})
    @log = log
    @headers = options.fetch(:headers, true)
    @csv_options = options.fetch(:csv_options, {})
    reset_counters!
  end

  # Performs whole-file transformations first
  # This method returns itself, satisfying the {each_with_index} interface for
  # iterating over CSV rows.
  def transform(csv_string)
    @csv_string = ParseableCsvString.new(@log).from_string(csv_string)
    self
  end

  # Stream each line of the CSV and parse it.
  # This includes three different types of transformations to replicate
  # the behavior of CsvTransformer for now.  These could be pushed out to
  # callers in the future.  These are: nil_converter for each field, discarding rows with
  # dirty_data? and parsing particular field names into Ruby dates.
  def each_with_index(&block)
    reset_counters!

    csv_options = {
      headers: @headers,
      header_converters: :symbol,
      converters: lambda { |h| nil_converter(h) }
    }.merge(@csv_options)
    CSV.new(@csv_string, csv_options).each.with_index do |row, index|
      cleaner = CsvRowCleaner.new(row)
      if cleaner.dirty_data?
        @skipped_dirty_rows_count = @skipped_dirty_rows_count + 1
        next
      end

      cleaner.transform_row
      block.call(row, index)
      @processed_rows_count = @processed_rows_count + 1
    end

    @log.puts("StreamingCsvTransformer#stats: #{stats}")
    nil
  end

  private
  def stats
    {
      skipped_dirty_rows_count: @skipped_dirty_rows_count,
      processed_rows_count: @processed_rows_count
    }
  end

  def reset_counters!
    @skipped_dirty_rows_count = 0
    @processed_rows_count = 0
    nil
  end

  def nil_converter(value)
    value == NIL_CODE ? nil : value
  end
end


text: Set the URL of ViewVC installation, such as <tt>http://www.mysvnserver.domain.com/svn-bin/viewvc.cgi</tt>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>About</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/sb-admin.css" rel="stylesheet">

    <link href="css/plugins/morris.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
                        Toggle navigation

                    </button>
                    Home

                            Graphs

                            About

                                Time Unit Selection

                                <button type="button" class="btn btn-lg btn-primary btn-block">By Day</button>

                                <button type="button" class="btn btn-lg btn-primary btn-block">By Week</button>


text:
Pack which allows integration with [Twilio](https://www.twilio.com/) service.

## Configuration

Copy the example configuration in [twilio.yaml.example](./twilio.yaml.example)
to `/opt/stackstorm/configs/twilio.yaml` and edit as required.

It must contain:

* ``account_sid`` - Your account sid (a 34 character string, starting with the
  letters AC).
* ``auth_token`` - Your authentication token.

Account sid and authentication token can be retrieved on the [Account
Dashboard][https://www.twilio.com/user/account/] page.

You can also use dynamic values from the datastore. See the
[docs](https://docs.stackstorm.com/reference/pack_configs.html) for more info.

## Actions

* ``send_sms`` - Action which sends an SMS using Twilio API.


text:
class ChangeSamlProviderOuterForksDefault < ActiveRecord::Migration[6.0]
  DOWNTIME = false

  def up
    change_column_null :saml_providers, :prohibited_outer_forks, false
    change_column_default :saml_providers, :prohibited_outer_forks, true
  end

  def down
    change_column_default :saml_providers, :prohibited_outer_forks, false
    change_column_null :saml_providers, :prohibited_outer_forks, true
  end
end


text:
#include <linux/can.h>
#include <linux/can/raw.h>

#include <endian.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>

#include <chrono>
#include <iomanip>
#include <iostream>
#include <thread>

#include <cerrno>
#include <csignal>
#include <cstdint>
#include <cstdio>
#include <cstring>

#define PROGNAME  "socketcan-raw-demo"
#define VERSION  "2.0.0"

namespace {

struct EngineFrame {
    std::uint16_t rpm;
    // TODO: Some more hypothetical data
};

struct VehicleFrame {
    // TODO: Some hypothetical vehicle status measurements
};

struct BodyControllerFrame {
    // TODO: Some hypothetical vehicle settings flags
};

std::sig_atomic_t signalValue;

void onSignal(int value) {
    signalValue = static_cast<decltype(signalValue)>(value);
}

void usage() {
    std::cout << "Usage: " PROGNAME " [-h] [-V] [-f] interface" << std::endl
              << "Options:" << std::endl
              << "  -h  Display this information" << std::endl
              << "  -V  Display version information" << std::endl
              << "  -f  Run in the foreground" << std::endl
              << std::endl;
}

void version() {
    std::cout << PROGNAME " version " VERSION << std::endl
              << "Compiled on " __DATE__ ", " __TIME__ << std::endl
              << std::endl;
}

void processFrame(const struct canfd_frame& frame) {
    switch (frame.can_id) {
    case 0x0A0:
    {
        EngineFrame engine;
        engine.rpm = be16toh(*(std::uint16_t *)(frame.data + 0));
        std::cout << "RPM: " << engine.rpm << std::endl;
    }
        break;
    case 0x110:
    {
        // TODO: Work!
        // VehicleFrame vehicle;
        std::cout << "Got 0x110" << std::endl; // XXX
    }
        break;
    case 0x320:
    {
        // TODO: Work!
        // BodyControllerFrame bodyController;
        std::cout << "Got 0x320" << std::endl; // XXX
    }
        break;
    default:
        // Should never get here if the receive filters were set up correctly
        std::cerr << "Unexpected CAN ID: 0x"
                  << std::hex << std::uppercase
                  << std::setw(3) << std::setfill('0')
                  << frame.can_id << std::endl;
        std::cerr.copyfmt(std::ios(nullptr));
        break;
    }
}

} // namespace

int main(int argc, char** argv) {
    using namespace std::chrono_literals;

    // Options
    const char* interface;
    bool foreground = false;

    // Service variables
    struct sigaction sa;
    int rc;

    // CAN connection variables
    struct sockaddr_can addr;
    struct ifreq ifr;
    int sockfd;

    // Parse command line arguments
    {
        int opt;

        // Parse option flags
        while ((opt = ::getopt(argc, argv, "Vfh")) != -1) {
            switch (opt) {
            case 'V':
                version();
                return EXIT_SUCCESS;
            case 'f':
                foreground = true;
                break;
            case 'h':
                usage();
                return EXIT_SUCCESS;
            default:
                usage();
                return EXIT_FAILURE;
            }
        }

        // Check for the one positional argument
        if (optind != (argc - 1)) {
            std::cerr << "Missing network interface option!" << std::endl;
            usage();
            return EXIT_FAILURE;
        }

        // Set the network interface to use
        interface = argv[optind];
    }

    // Check if the service should be run as a daemon
    if (!foreground) {
        if (::daemon(0, 1) == -1) {
            std::perror("daemon");
            return EXIT_FAILURE;
        }
    }

    // Register signal handlers
    sa.sa_handler = onSignal;
    ::sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    ::sigaction(SIGINT, &sa, nullptr);
    ::sigaction(SIGTERM, &sa, nullptr);
    ::sigaction(SIGQUIT, &sa, nullptr);
    ::sigaction(SIGHUP, &sa, nullptr);

    // Initialize the signal value to zero
    signalValue = 0;

    // Open the CAN network interface
    sockfd = ::socket(PF_CAN, SOCK_RAW, CAN_RAW);
    if (-1 == sockfd) {
        std::perror("socket");
        goto errSocket;
    }

    // Set a receive filter so we only receive select CAN IDs
    {
        struct can_filter filter[3];
        filter[0].can_id   = 0x0A0;
        filter[0].can_mask = CAN_SFF_MASK;
        filter[1].can_id   = 0x110;
        filter[1].can_mask = CAN_SFF_MASK;
        filter[2].can_id   = 0x320;
        filter[2].can_mask = CAN_SFF_MASK;

        rc = ::setsockopt(
            sockfd,
            SOL_CAN_RAW,
            CAN_RAW_FILTER,
            &filter,
            sizeof(filter)
        );
        if (-1 == rc) {
            std::perror("setsockopt filter");
            goto errSetup;
        }
    }

    // Enable reception of CAN FD frames
    {
        int enable = 1;

        rc = ::setsockopt(
            sockfd,
            SOL_CAN_RAW,
            CAN_RAW_FD_FRAMES,
            &enable,
            sizeof(enable)
        );
        if (-1 == rc) {
            std::perror("setsockopt CAN FD");
            goto errSetup;
        }
    }

    // Get the index of the network interface
    std::strncpy(ifr.ifr_name, interface, IFNAMSIZ);
    if (::ioctl(sockfd, SIOCGIFINDEX, &ifr) == -1) {
        std::perror("ioctl");
        goto errSetup;
    }

    // Bind the socket to the network interface
    addr.can_family = AF_CAN;
    addr.can_ifindex = ifr.ifr_ifindex;
    rc = ::bind(
        sockfd,
        reinterpret_cast<struct sockaddr*>(&addr),
        sizeof(addr)
    );
    if (-1 == rc) {
        std::perror("bind");
        goto errSetup;
    }

    // Log that the service is up and running
    std::cout << "Started" << std::endl;

    // Main loop
    while (0 == signalValue) {
        struct canfd_frame frame;

        // Read in a CAN frame
        auto numBytes = ::read(sockfd, &frame, CANFD_MTU);
        switch (numBytes) {
        case CAN_MTU:
            processFrame(frame);
            break;
        case CANFD_MTU:
            // TODO: Should make an example for CAN FD
            break;
        case -1:
            // Check the signal value on interrupt
            if (EINTR == errno)
                continue;

            // Delay before continuing
            std::perror("read");
            std::this_thread::sleep_for(100ms);
        default:
            continue;
        }
    }

    // Cleanup
    if (::close(sockfd) == -1) {
        std::perror("close");
        return errno;
    }

    std::cout << std::endl << "Bye!" << std::endl;
    return EXIT_SUCCESS;

    // Error handling (reverse order cleanup)
errSetup:
    ::close(sockfd);
errSocket:
    return errno;
}


text:
package com.bluecats.scratchingpost;

import android.content.pm.PackageManager;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;

import com.bluecats.scratchingpost.adapters.SitesAdapter;
import com.bluecats.scratchingpost.databinding.ActivitySitesBinding;
import com.bluecats.sdk.BCBeacon;
import com.bluecats.sdk.BCBeaconManager;
import com.bluecats.sdk.BCBeaconManagerCallback;
import com.bluecats.sdk.BCSite;
import com.bluecats.sdk.BlueCatsSDK;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SitesActivity extends BaseActivity
{
	private static final String TAG = "SitesActivity";
	private static final int LOCATION_PERMISSION_REQUEST_CODE = 0;

	private final List<BCSite> mSitesInside = Collections.synchronizedList( new ArrayList<BCSite>() );
	private final List<BCSite> mSitesNearby = Collections.synchronizedList( new ArrayList<BCSite>() );
	private final SitesAdapter mAdapterSitesInside = new SitesAdapter( mSitesInside );
	private final SitesAdapter mAdapterSitesNearby = new SitesAdapter( mSitesNearby );
	private final BCBeaconManager mBeaconManager = new BCBeaconManager();

	private ActivitySitesBinding mBinding;

	@Override
	protected void onCreate( final Bundle savedInstanceState )
	{
		super.onCreate( savedInstanceState );
		mBinding = DataBindingUtil.setContentView( this, R.layout.activity_sites );

		setSupportActionBar( mBinding.toolbar );

		mBinding.rcySitesInside.setAdapter( mAdapterSitesInside );
		mBinding.rcySitesInside.setLayoutManager( new LinearLayoutManager( this ) );

		mBinding.rcySitesNearby.setAdapter( mAdapterSitesNearby );
		mBinding.rcySitesNearby.setLayoutManager( new LinearLayoutManager( this ) );

		BlueCatsSDK.startPurringWithAppToken( getApplicationContext(), Constants.BLUECATS_APP_TOKEN );
	}

	@Override
	protected void onResume()
	{
		super.onResume();

		BlueCatsSDK.didEnterForeground();

		mBeaconManager.registerCallback( mBeaconManagerCallback );
	}

	@Override
	protected void onPause()
	{
		super.onPause();

		BlueCatsSDK.didEnterBackground();

		mBeaconManager.unregisterCallback( mBeaconManagerCallback );
	}

	private final BCBeaconManagerCallback mBeaconManagerCallback = new BCBeaconManagerCallback()
	{

		@Override
		public void didRangeBeacons(List<BCBeacon> beacons) {
			Log.d(TAG, ""+beacons.size());
		}
		@Override
		public void didEnterSite( final BCSite site )
		{
			runOnUiThread( new Runnable()
			{
				@Override
				public void run()
				{
					if( mSitesInside.add( site ) )
					{
						mAdapterSitesInside.notifyDataSetChanged();
					}

					if( mSitesNearby.remove( site ) )
					{
						mAdapterSitesNearby.notifyDataSetChanged();
					}
				}
			} );
		}

		@Override
		public void didExitSite( final BCSite site )
		{
			runOnUiThread( new Runnable()
			{
				@Override
				public void run()
				{
					if( mSitesInside.remove( site ) )
					{
						mAdapterSitesInside.notifyDataSetChanged();
					}

					if( mSitesNearby.add( site ) )
					{
						mAdapterSitesNearby.notifyDataSetChanged();
					}
				}
			} );
		}
	};
}


text:
I've made Daily Fuzzy open-source!

Here is the source code for the Android app, which is available here: https://play.google.com/store/apps/details?id=com.regosen.dailyfuzzy

## Description

It's a simple gallery app that fetches images, gifs and videos from Reddit's r/aww subreddit, with some additional filtering by title (to weed out non-animal pictures and captions inappropriate for children).

This is my first Android project from scratch, and it contains some template code (as noted in some code comments).

## Features

- save images to your device
- track favorites and past images
- share on Facebook
- daily notifications

## Screenshots


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Atriplex minuticarpa Stutz & G.L. Chu

### Remarks
null


text:
<atlassian-plugin key="${project.groupId}.${project.artifactId}" name="${project.name}" plugins-version="2">
    <plugin-info>
        <description>${project.description}</description>
        <version>${project.version}</version>
        <vendor name="${project.organization.name}" url="${project.organization.url}" />
        <param name="plugin-icon">images/pluginIcon.png</param>
        <param name="plugin-logo">images/pluginLogo.png</param>
    </plugin-info>

    <preStageAction key="gitHubStatusPreStage" class="com.mhackner.bamboo.GitHubStatusPreStage" />
    <postStageAction key="gitHubStatusPostStage" class="com.mhackner.bamboo.GitHubStatusPostStage" />

    <additionalBuildConfigurationPlugin key="configuration" class="com.mhackner.bamboo.Configuration">
        <resource type="freemarker" name="edit" location="com/mhackner/bamboo-github-status/edit.ftl" />
    </additionalBuildConfigurationPlugin>

    <resource type="i18n" name="strings" location="com.mhackner.bamboo-github-status.strings" />

    <component-import key="encryptionService" interface="com.atlassian.bamboo.security.EncryptionService" />
</atlassian-plugin>


text:
This example requires the [serverless framework](http://serverless.com) (tested with v1.6.1).

To get started, run:
* `git clone https://github.com/lambdacult/spark-examples.git` (this repository)
* `cd dotnetcore1.0`
* `./build.sh`
* `serverless deploy`
* assign alias `spark-1` to the newly created version 1
* `rm -R bin` (.zip file needs to change, otherwise AWS won't accept a new version)
* `./build.sh`
* `serverless deploy`
* assign alias `spark-2` and `spark-current` to the newly created version 2

To configure the newly created lambda function with [Spark](https://lambdacult.com/spark), use the following warmup input:
```
{
  "action": "warmup",
  "minimumDurationMilliseconds": ${minimumDurationMilliseconds}
}
```


text:
[![PyPI version](https://badge.fury.io/py/django-supermigrate.svg)](https://badge.fury.io/py/django-supermigrate)

django-supermigrate is a package to manage migrations on production and development environment with no hassle.

## Installation

* Install it through pip

```
pip install django-supermigrate
```

* Download and install manually

```
git clone https://github.com/paytm/django-supermigrate.git
cd django-supermigrate
python setup.py install
```

## Use

1. Add "supermigrate" to your INSTALLED_APPS like this::

    ```
    INSTALLED_APPS = (
        ...
        'supermigrate',
    )
    ```

2. Modify your DATABASE_ROUTERS to include 'default' router like this::

    ```
    DATABASE_ROUTERS  = [ 'supermigrate.database_routers.default.DefaultRouter', ]
    ```

3. Add DATABASE_ROUTER_MAPPING in settings like this::

    ```
        DATABASE_ROUTER_MAPPING = {

            # default db
            "admin" : {
                "DB_FOR_READ": "default_slave",
                "DB_FOR_WRITE": "default",
                "DB_FOR_MIGRATE": ["default", "default_slave"]
            },
            "auth" : {
                "DB_FOR_READ": "default",
                "DB_FOR_WRITE": "default",
                "DB_FOR_MIGRATE": ["default", "default_slave"]
            },

            # other db here

        }
    ```

`DB_FOR_READ` signifies the db that will be used for read queries. `DB_FOR_WRITE` signifies the database that will be used for write queries. `DB_FOR_MIGRATE` is a list and can contain any databasea(master and slave, for development generally)

4. Update settings for live with ::

    ```
    ALLOW_MIGRATE_FALSE = False

    ALLOW_DB_MIGRATE = {
        'default': True
    }
    ```

##Idea

The main idea behind this project is to manage migration __simultaneously__ on development and production environment. The convention is, on __development__ environment, Django should be able to __run__ the migrations and hence the changes should be reflected in the database, whereas on production, the migrations should __not__ be allowed to run, hence they should not create any table on production. They should just create the __associated content types__ and the __permission__ and all the changes on the production, be it any create table or any alter, should go through the DBA.

##Problem

There was no generic way to control the migrations. Django provides a `managed` flag in the `Meta` class of the model, which decides whether the table should be created or not. This flag could have been helpful, if its value was picked from settings at run time. Settings can be split into `live` and `dev` settings. If the managed flag could pick the value from settings, then there was no problem.

So,

```
class Book(models.Model):
    name = models.CharField(max_length=100)

    class Meta:
        managed = True if settings.MANAGED_FLAG else False
```

in settings,

```
# settings_dev.py
MANAGED_FLAG = True

# settings_live.py
MANAGED_FLAG = False
```

This worked for a while, but soon we realized that it was helpful in no way.
For each change in model, a migration file is created which remains same across the development and production environment. Now the above `if` in the managed flag works, but this is resolved only once when the `makemigrations` command is run. So if we create the migration on the development environment, then managed will be True in the generated migration file, but this will be True for production environment also. It can be dangerous if anyone runs by mistake migrations on the production.

One solution can be to run __makemigrations__ on production, using __settings_live__, and hence `managed` flag will be __False__. But that is highly __discouraged__.
Another solution for this can be to keep separate value on `master` and `production` branch. But that becomes very messy to manage.

So how did we solve this problem?

##Solution

On looking deeper into the code, we first found out that there is a database router, which specifies database that will be used for reading, writing, allowing relation and __migrations__ corresponding to an app or model. The interesting function here is `allow_migrate` which takes db, app_label and model_name as argument. This allow_migrate is called for each model in each app. It checks whether on the given database, for a particular model in an app, are the migrations allowed to run? The more interesting thing is that it is not resolved once, infact it is resolved for each and every model in `INSTALLED_APPS`. So If somehow we can hook some checks in the `allow_migrate` which takes its value from settings, then our problem will be solved.

So we decided that for each model, we will keep its managed flag as __True__. There will be a flag in dev and live settings, which will specify whether the migrations should be allowed to run or not. On development, tables will be created by Django and on production, no migrations will be run as `allow_migrate` will return __False__ over there.

The first step in solving this problem was writing a __generic database router__ which takes a required mapping from settings, __DATABASE_ROUTER_MAPPING__. This is a mapping of app is to database, and it is necessary to specify database for every app, else it will not allow  migrations to run. To make it more generic and honour `master-slave` configuration, it takes three keys namely `DB_FOR_READ`, `DB_FOR_WRITE` and `DB_FOR_MIGRATE`. It looks like,

```
DATABASE_ROUTER_MAPPING = {

    # default db
    "admin" : {
        "DB_FOR_READ": "default",
        "DB_FOR_WRITE": "default_slave",
        "DB_FOR_MIGRATE": ["default", "default_slave"]
    }

    # book_store db
    "book": {
        "DB_FOR_READ": "book_store",
        "DB_FOR_WRITE": "book_store_slave",
        "DB_FOR_MIGRATE": ["book_store", "book_store_slave"]
    }
}
```

Important thing that we observed here is that it is mandatory to specify the apps which uses __default__ db. This is because if apps corresponding to a default database are not specified, then when database argument is passed to migrate command like

```
python manage.py migrate --database=book_store
```

then it will create all auth and content types table in `book_store` database, which is not required at all.

To make it even more correct, we also wrote a utility function which checks its value from the settings. It throws an error if no database is specified for a app

```
def is_database_connection_in_settings(appname):

    if not hasattr(settings, 'DATABASE_ROUTER_MAPPING'):
        raise CommandError("DATABASE_ROUTER_MAPPING mapping missing from"
                           " settings")

    if appname.lower() in settings.DATABASE_ROUTER_MAPPING:
        return True
    else:
        raise CommandError("Database not specified for app {}. Please make"
                           " an entry in DATABASE_ROUTER_MAPPING in "
                           "settings".format(appname.lower()))n "
                           "settings".format(appname.lower()))
```

After this we wrote a utility function which check the value of managed_flag from the settings and it is like

```
def is_migrate_allowed():

    '''
    If settings is having ALLOW_MIGRATE_FALSE flag and its value is false,
    then return false, else return none.
    dev settings has no such flag, hence will return None in that case
    live setting has this flag as `False` hence will return False
    '''

    if hasattr(settings, 'ALLOW_MIGRATE_FALSE') and settings.ALLOW_MIGRATE_FALSE == False:
        return False
    return None
```

Our final ```allow_migrate``` looks something like this

```
def allow_migrate(self, db, app_label, model=None, **hints):
    '''
        gets managed flag value,
        if it is false, return false
        if it is None, means it is dev environment
    '''
    managed_flag = is_migrate_allowed()
    if managed_flag == False:
        return False

    if is_database_connection_in_settings(app_label):
        return db in settings.DATABASE_ROUTER_MAPPING[app_label]

    return None

```

This solved our problem to some extent. The only glitch that it brought is each database other than the default database will have a `django_migration` table. and we will run migrate command for each database, like

```
python manage.py migrate --database=book_store
python manage.py migrate --database=default
```

This brought us the need for supermigrate, which runs the migrate command for each key in `DATABASES` defined in `settings`.

Things were running fine uptill now, but we soon realized that there is no need for `django_migration` table in each database other than the default database. On production, we only need to run

```
python manage.py migrate --database=default
```

and all the changes will be reflected, but no such changes were there. Changes like creation of content_type and permission which are very useful. So what we were missing??

On closely observing that we realized that we have disabled migrations for each and every app, which also includes the `auth` and `contenttypes` app. These app are responsible for creating permission and content type and since the managed flag was False for each app on the production, no content type and permission was created.

So to deal with this problem, we followed a convention that,

```
By default no app will be allowed to migrate on production except some
```

To tackle this problem, we defined a `ALLOW_DB_MIGRATE` mapping in settings, which contains all those databases, where migrations are allowed to run, like

```
ALLOW_DB_MIGRATE = {
    'default': True
}
```

and then updated is_migrate_allowed to

```
def is_migrate_allowed(db):

    '''
    If settings is having ALLOW_MIGRATE_FALSE flag and its value is false,
    then return false, else return none.
    dev settings has no such flag, hence will return None in that case
    live setting has this flag as `False` hence will return False
    '''

    if hasattr(settings, 'ALLOW_DB_MIGRATE') and db in settings.ALLOW_DB_MIGRATE:
        return settings.ALLOW_DB_MIGRATE[db]

    if hasattr(settings, 'ALLOW_MIGRATE_FALSE') and settings.ALLOW_MIGRATE_FALSE == False:
        return False
    return None

```

Now the final version of allow_migrate looks like

```
def allow_migrate(self, db, app_label, model=None, **hints):
    '''
        gets managed flag value,
        if it is false, return false
        if it is None, means it is dev environment
    '''
    managed_flag = is_migrate_allowed(db)
    if managed_flag == False:
        return False

    if is_database_connection_in_settings(app_label):
        return db in settings.DATABASE_ROUTER_MAPPING[app_label]

    return None

```

Considering our settings are split across base, dev and live, the following should be there in settings

__base.py__
```
DATABASE_ROUTER_MAPPING = {
    # default db
    "admin" : {
        "DB_FOR_READ": "default",
        "DB_FOR_WRITE": "default_slave",
        "DB_FOR_MIGRATE": ["default", "default_slave"]
    },

    # book_store db
    "book": {
        "DB_FOR_READ": "book_store",
        "DB_FOR_WRITE": "book_store_slave",
        "DB_FOR_MIGRATE": ["book_store", "book_store_slave"]
    }

    # etc
}

DATABASE_ROUTERS  = [ 'supermigrate.database_routers.default.DefaultRouter', ]

```

__settings_dev.py__
```
# nothing here as we want migrations to run
```

__settings_live.py__
```
ALLOW_MIGRATE_FALSE = False

ALLOW_DB_MIGRATE = {
    'default': True
}

```


text:
using System.ServiceProcess;
using Microsoft.Owin;
using SignalR.Core;

[assembly: OwinStartup(typeof(Startup))]
namespace SignalR.Core
{
    public partial class SignalRService : ServiceBase
    {
        public SignalRService()
        {
            InitializeComponent();

            this.ServiceName = this.GetType().Name;
        }

        protected override void OnStart(string[] args)
        {
            WindowsEventLog.WriteInfoLog(string.Format("{0} Starting...", this.ServiceName));

            StartServer();
        }

        protected override void OnStop()
        {
            WindowsEventLog.WriteErrorLog(string.Format("{0} Stopped.", this.ServiceName));
        }

        protected override void OnContinue()
        {
            WindowsEventLog.WriteWarningLog(string.Format("{0} Continued.", this.ServiceName));
        }

        protected override void OnPause()
        {
            WindowsEventLog.WriteWarningLog(string.Format("{0} Paused.", this.ServiceName));
        }

    }
}


text:
using System;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;

namespace Microsoft.Its.Domain.Sql
{
    public class ReservationServiceDbContext : DbContext
    {
        private static string nameOrConnectionString;

        static ReservationServiceDbContext()
        {
            Database.SetInitializer(new ReservationServiceDatabaseInitializer());
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ReservationServiceDbContext"/> class.
        /// </summary>
        public ReservationServiceDbContext() : this(NameOrConnectionString)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ReservationServiceDbContext"/> class.
        /// </summary>
        /// <param name="nameOrConnectionString">Either the database name or a connection string.</param>
        public ReservationServiceDbContext(string nameOrConnectionString) : base(nameOrConnectionString)
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new ReservedValuesEntityTypeConfiguration());
        }

        public static string NameOrConnectionString
        {
            get
            {
                return nameOrConnectionString;
            }
            set
            {
                if (string.IsNullOrWhiteSpace(value))
                {
                    throw new ArgumentException("The value cannot be null, empty or contain only whitespace.");
                }
                nameOrConnectionString = value;
            }
        }

        public DbSet<ReservedValue> ReservedValues { get; set; }

        private class ReservedValuesEntityTypeConfiguration : EntityTypeConfiguration<ReservedValue>
        {
            public ReservedValuesEntityTypeConfiguration()
            {
                ToTable("ReservedValues", "Reservations");

                HasKey(r => new { r.Value, r.Scope });

                Property(r => r.OwnerToken)
                    .IsRequired();
                Property(r => r.Expiration)
                    .IsConcurrencyToken();
                Property(r => r.ConfirmationToken)
                    .HasMaxLength(256);
            }
        }
    }
}


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

/**
 * @fileoverview Utilities for exploration creation, publication ect. when
 * carrrying out end-to-end testing with protractor.
 */

var forms = require('./forms.js');
var waitFor = require('./waitFor.js');
var CreatorDashboardPage = require('./CreatorDashboardPage.js');
var ExplorationEditorPage = require('./ExplorationEditorPage.js');
var LibraryPage = require('./LibraryPage.js');

// Creates an exploration, opens its editor and skips the tutorial.
var createExploration = function() {
  createExplorationAndStartTutorial();
  var explorationEditorPage = new ExplorationEditorPage.ExplorationEditorPage();
  var explorationEditorMainTab = explorationEditorPage.getMainTab();
  explorationEditorMainTab.exitTutorial();
};

// Creates a new exploration and wait for the exploration tutorial to start.
var createExplorationAndStartTutorial = function() {
  creatorDashboardPage = new CreatorDashboardPage.CreatorDashboardPage;
  creatorDashboardPage.get();
  // Wait for the dashboard to transition the creator into the editor page.
  creatorDashboardPage.clickCreateActivityButton();
};

/**
 * Only Admin users can create collections.
 */
var createCollectionAsAdmin = function() {
  creatorDashboardPage = new CreatorDashboardPage.CreatorDashboardPage;
  creatorDashboardPage.get();
  creatorDashboardPage.clickCreateActivityButton();
  var activityCreationModal = element(
    by.css('.protractor-test-creation-modal'));
  waitFor.visibilityOf(
    activityCreationModal, 'Activity Creation modal takes too long to appear');
  creatorDashboardPage.clickCreateCollectionButton();
};

/**
 * Creating exploration for Admin users.
 */
var createExplorationAsAdmin = function() {
  creatorDashboardPage = new CreatorDashboardPage.CreatorDashboardPage;
  creatorDashboardPage.get();
  creatorDashboardPage.clickCreateActivityButton();
  var activityCreationModal = element(
    by.css('.protractor-test-creation-modal'));
  waitFor.visibilityOf(
    activityCreationModal, 'Activity Creation modal takes too long to appear');
  creatorDashboardPage.clickCreateExplorationButton();
};

// This will only work if all changes have been saved and there are no
// outstanding warnings; run from the editor.
var publishExploration = function() {
  element(by.css('.protractor-test-publish-exploration')).isDisplayed().then(
    function() {
      element(by.css('.protractor-test-publish-exploration')).click();
    });
  var prePublicationButtonElem = element(by.css(
    '.protractor-test-confirm-pre-publication'));
  prePublicationButtonElem.isPresent().then(function() {
    prePublicationButtonElem.click();
  });

  waitFor.invisibilityOf(
    prePublicationButtonElem,
    'prePublicationButtonElem taking too long to disappear while publishing');
  element(by.css('.protractor-test-confirm-publish')).click();

  var sharePublishModal = element(
    by.css('.protractor-test-share-publish-modal'));
  var closePublishModalButton = element(
    by.css('.protractor-test-share-publish-close'));
  waitFor.visibilityOf(
    sharePublishModal, 'Share Publish Modal takes too long to appear');
  waitFor.elementToBeClickable(
    closePublishModalButton, 'Close Publish Modal button is not clickable');
  closePublishModalButton.click();
};

// Creates and publishes a minimal exploration
var createAndPublishExploration = function(
    title, category, objective, language) {
  createExploration();
  var explorationEditorPage = new ExplorationEditorPage.ExplorationEditorPage();
  var explorationEditorMainTab = explorationEditorPage.getMainTab();
  explorationEditorMainTab.setContent(forms.toRichText('new exploration'));
  explorationEditorMainTab.setInteraction('EndExploration');

  var explorationEditorSettingsTab = explorationEditorPage.getSettingsTab();
  explorationEditorPage.navigateToSettingsTab();
  explorationEditorSettingsTab.setTitle(title);
  explorationEditorSettingsTab.setCategory(category);
  explorationEditorSettingsTab.setObjective(objective);
  if (language) {
    explorationEditorSettingsTab.setLanguage(language);
  }
  explorationEditorPage.saveChanges();
  publishExploration();
};

// Role management (state editor settings tab)

// Here, 'roleName' is the user-visible form of the role name (e.g. 'Manager').
var _addExplorationRole = function(roleName, username) {
  element(by.css('.protractor-test-edit-roles')).click();
  element(by.css('.protractor-test-role-username')).sendKeys(username);
  element(by.css('.protractor-test-role-select')).
    element(by.cssContainingText('option', roleName)).click();
  element(by.css('.protractor-test-save-role')).click();
};

var addExplorationManager = function(username) {
  _addExplorationRole('Manager', username);
};

var addExplorationCollaborator = function(username) {
  _addExplorationRole('Collaborator', username);
};

var addExplorationTranslator = function(username) {
  _addExplorationRole('Translator', username);
};

var addExplorationPlaytester = function(username) {
  _addExplorationRole('Playtester', username);
};

// Here, roleName is the server-side form of the name (e.g. 'owner').
var _getExplorationRoles = function(roleName) {
  var itemName = roleName + 'Name';
  var listName = roleName + 'Names';
  return element.all(by.repeater(
    itemName + ' in ExplorationRightsService.' + listName + ' track by $index'
  )).map(function(elem) {
    return elem.getText();
  });
};

var getExplorationManagers = function() {
  return _getExplorationRoles('owner');
};

var getExplorationCollaborators = function() {
  return _getExplorationRoles('editor');
};

var getExplorationTranslators = function() {
  return _getExplorationRoles('translator');
};

var getExplorationPlaytesters = function() {
  return _getExplorationRoles('viewer');
};

exports.createExploration = createExploration;
exports.createExplorationAndStartTutorial = createExplorationAndStartTutorial;
exports.publishExploration = publishExploration;
exports.createAndPublishExploration = createAndPublishExploration;
exports.createCollectionAsAdmin = createCollectionAsAdmin;
exports.createExplorationAsAdmin = createExplorationAsAdmin;

exports.addExplorationManager = addExplorationManager;
exports.addExplorationCollaborator = addExplorationCollaborator;
exports.addExplorationTranslator = addExplorationTranslator;
exports.addExplorationPlaytester = addExplorationPlaytester;
exports.getExplorationManagers = getExplorationManagers;
exports.getExplorationCollaborators = getExplorationCollaborators;
exports.getExplorationTranslators = getExplorationTranslators;
exports.getExplorationPlaytesters = getExplorationPlaytesters;


text:
namespace fst {

static const int32 kSTTableMagicNumber = 2125656924;
static const int32 kSTTableFileVersion = 1;

// String-to-type table writing class for object of type 'T' using functor 'W'
// to write an object of type 'T' from a stream. 'W' must conform to the
// following interface:
//
//   struct Writer {
//     void operator()(ostream &, const T &) const;
//   };
//
template <class T, class W>
class STTableWriter {
 public:
  typedef T EntryType;
  typedef W EntryWriter;

  explicit STTableWriter(const string &filename)
      : stream_(filename.c_str(), ofstream::out | ofstream::binary),
        error_(false) {
    WriteType(stream_, kSTTableMagicNumber);
    WriteType(stream_, kSTTableFileVersion);
    if (stream_.fail()) {
      FSTERROR() << "STTableWriter::STTableWriter: error writing to file: "
                 << filename;
      error_=true;
    }
  }

  static STTableWriter<T, W> *Create(const string &filename) {
    if (filename.empty()) {
      LOG(ERROR) << "STTableWriter: writing to standard out unsupported.";
      return 0;
    }
    return new STTableWriter<T, W>(filename);
  }

  void Add(const string &key, const T &t) {
    if (key == "") {
      FSTERROR() << "STTableWriter::Add: key empty: " << key;
      error_ = true;
    } else if (key < last_key_) {
      FSTERROR() << "STTableWriter::Add: key disorder: " << key;
      error_ = true;
    }
    if (error_) return;
    last_key_ = key;
    positions_.push_back(stream_.tellp());
    WriteType(stream_, key);
    entry_writer_(stream_, t);
  }

  bool Error() const { return error_; }

  ~STTableWriter() {
    WriteType(stream_, positions_);
    WriteType(stream_, static_cast<int64>(positions_.size()));
  }

 private:
  EntryWriter entry_writer_;  // Write functor for 'EntryType'
  ofstream stream_;           // Output stream
  vector<int64> positions_;   // Position in file of each key-entry pair
  string last_key_;           // Last key
  bool error_;

  DISALLOW_COPY_AND_ASSIGN(STTableWriter);
};

// String-to-type table reading class for object of type 'T' using functor 'R'
// to read an object of type 'T' form a stream. 'R' must conform to the
// following interface:
//
//   struct Reader {
//     T *operator()(istream &) const;
//   };
//
template <class T, class R>
class STTableReader {
 public:
  typedef T EntryType;
  typedef R EntryReader;

  explicit STTableReader(const vector<string> &filenames)
      : sources_(filenames), entry_(0), error_(false) {
    compare_ = new Compare(&keys_);
    keys_.resize(filenames.size());
    streams_.resize(filenames.size(), 0);
    positions_.resize(filenames.size());
    for (size_t i = 0; i < filenames.size(); ++i) {
      streams_[i] = new ifstream(
          filenames[i].c_str(), ifstream::in | ifstream::binary);
      int32 magic_number = 0, file_version = 0;
      ReadType(*streams_[i], &magic_number);
      ReadType(*streams_[i], &file_version);
      if (magic_number != kSTTableMagicNumber) {
        FSTERROR() << "STTableReader::STTableReader: wrong file type: "
                   << filenames[i];
        error_ = true;
        return;
      }
      if (file_version != kSTTableFileVersion) {
        FSTERROR() << "STTableReader::STTableReader: wrong file version: "
                   << filenames[i];
        error_ = true;
        return;
      }
      int64 num_entries;
      streams_[i]->seekg(-static_cast<int>(sizeof(int64)), ios_base::end);
      ReadType(*streams_[i], &num_entries);
      streams_[i]->seekg(-static_cast<int>(sizeof(int64)) *
                         (num_entries + 1), ios_base::end);
      positions_[i].resize(num_entries);
      for (size_t j = 0; (j < num_entries) && (!streams_[i]->fail()); ++j)
        ReadType(*streams_[i], &(positions_[i][j]));
      streams_[i]->seekg(positions_[i][0]);
      if (streams_[i]->fail()) {
        FSTERROR() << "STTableReader::STTableReader: error reading file: "
                   << filenames[i];
        error_ = true;
        return;
      }

    }
    MakeHeap();
  }

  ~STTableReader() {
    for (size_t i = 0; i < streams_.size(); ++i)
      delete streams_[i];
    delete compare_;
    if (entry_)
      delete entry_;
  }

  static STTableReader<T, R> *Open(const string &filename) {
    if (filename.empty()) {
      LOG(ERROR) << "STTableReader: reading from standard in not supported";
      return 0;
    }
    vector<string> filenames;
    filenames.push_back(filename);
    return new STTableReader<T, R>(filenames);
  }

  static STTableReader<T, R> *Open(const vector<string> &filenames) {
    return new STTableReader<T, R>(filenames);
  }

  void Reset() {
    if (error_) return;
    for (size_t i = 0; i < streams_.size(); ++i)
      streams_[i]->seekg(positions_[i].front());
    MakeHeap();
  }

  bool Find(const string &key) {
    if (error_) return false;
    for (size_t i = 0; i < streams_.size(); ++i)
      LowerBound(i, key);
    MakeHeap();
    return keys_[current_] == key;
  }

  bool Done() const { return error_ || heap_.empty(); }

  void Next() {
    if (error_) return;
    if (streams_[current_]->tellg() <= positions_[current_].back()) {
      ReadType(*(streams_[current_]), &(keys_[current_]));
      if (streams_[current_]->fail()) {
        FSTERROR() << "STTableReader: error reading file: "
                   << sources_[current_];
        error_ = true;
        return;
      }
      push_heap(heap_.begin(), heap_.end(), *compare_);
    } else {
      heap_.pop_back();
    }
    if (!heap_.empty())
      PopHeap();
  }

  const string &GetKey() const {
    return keys_[current_];
  }

  const EntryType &GetEntry() const {
    return *entry_;
  }

  bool Error() const { return error_; }

 private:
  // Comparison functor used to compare stream IDs in the heap
  struct Compare {
    Compare(const vector<string> *keys) : keys_(keys) {}

    bool operator()(size_t i, size_t j) const {
      return (*keys_)[i] > (*keys_)[j];
    };

   private:
    const vector<string> *keys_;
  };

  // Position the stream with ID 'id' at the position corresponding
  // to the lower bound for key 'find_key'
  void LowerBound(size_t id, const string &find_key) {
    ifstream *strm = streams_[id];
    const vector<int64> &positions = positions_[id];
    size_t low = 0, high = positions.size() - 1;

    while (low < high) {
      size_t mid = (low + high)/2;
      strm->seekg(positions[mid]);
      string key;
      ReadType(*strm, &key);
      if (key > find_key) {
        high = mid;
      } else if (key < find_key) {
        low = mid + 1;
      } else {
        for (size_t i = mid; i > low; --i) {
          strm->seekg(positions[i - 1]);
          ReadType(*strm, &key);
          if (key != find_key) {
            strm->seekg(positions[i]);
            return;
          }
        }
        strm->seekg(positions[low]);
        return;
      }
    }
    strm->seekg(positions[low]);
  }

  // Add all streams to the heap
  void MakeHeap() {
    heap_.clear();
    for (size_t i = 0; i < streams_.size(); ++i) {
      ReadType(*streams_[i], &(keys_[i]));
      if (streams_[i]->fail()) {
        FSTERROR() << "STTableReader: error reading file: " << sources_[i];
        error_ = true;
        return;
      }
      heap_.push_back(i);
    }
    make_heap(heap_.begin(), heap_.end(), *compare_);
    PopHeap();
  }

  // Position the stream with the lowest key at the top
  // of the heap, set 'current_' to the ID of that stream
  // and read the current entry from that stream
  void PopHeap() {
    pop_heap(heap_.begin(), heap_.end(), *compare_);
    current_ = heap_.back();
    if (entry_)
      delete entry_;
    entry_ = entry_reader_(*streams_[current_]);
    if (!entry_)
      error_ = true;
    if (streams_[current_]->fail()) {
      FSTERROR() << "STTableReader: error reading entry for key: "
                 << keys_[current_] << ", file: " << sources_[current_];
      error_ = true;
    }
  }

  EntryReader entry_reader_;   // Read functor for 'EntryType'
  vector<ifstream*> streams_;  // Input streams
  vector<string> sources_;     // and corresponding file names
  vector<vector<int64> > positions_;  // Index of positions for each stream
  vector<string> keys_;  // Lowest unread key for each stream
  vector<int64> heap_;   // Heap containing ID of streams with unread keys
  int64 current_;        // Id of current stream to be read
  Compare *compare_;     // Functor comparing stream IDs for the heap
  mutable EntryType *entry_;  // Pointer to the currently read entry
  bool error_;

  DISALLOW_COPY_AND_ASSIGN(STTableReader);
};

// String-to-type table header reading function template on the entry header
// type 'H' having a member function:
//   Read(istream &strm, const string &filename);
// Checks that 'filename' is an STTable and call the H::Read() on the last
// entry in the STTable.
template <class H>
bool ReadSTTableHeader(const string &filename, H *header) {
  ifstream strm(filename.c_str(), ifstream::in | ifstream::binary);
  int32 magic_number = 0, file_version = 0;
  ReadType(strm, &magic_number);
  ReadType(strm, &file_version);
  if (magic_number != kSTTableMagicNumber) {
    LOG(ERROR) << "ReadSTTableHeader: wrong file type: " << filename;
    return false;
  }
  if (file_version != kSTTableFileVersion) {
    LOG(ERROR) << "ReadSTTableHeader: wrong file version: " << filename;
    return false;
  }
  int64 i = -1;
  strm.seekg(-static_cast<int>(sizeof(int64)), ios_base::end);
  ReadType(strm, &i);  // Read number of entries
  if (strm.fail()) {
    LOG(ERROR) << "ReadSTTableHeader: error reading file: " << filename;
    return false;
  }
  if (i == 0) return true;  // No entry header to read
  strm.seekg(-2 * static_cast<int>(sizeof(int64)), ios_base::end);
  ReadType(strm, &i);  // Read position for last entry in file
  strm.seekg(i);
  string key;
  ReadType(strm, &key);
  header->Read(strm, filename + ":" + key);
  if (strm.fail()) {
    LOG(ERROR) << "ReadSTTableHeader: error reading file: " << filename;
    return false;
  }
  return true;
}

bool IsSTTable(const string &filename);

}  // namespace fst

#endif  // FST_EXTENSIONS_FAR_STTABLE_H_


text:
#include "src/cpu/kernels/CpuGemmInterleave4x4Kernel.h"

#include "arm_compute/core/ITensor.h"
#include "arm_compute/core/Validate.h"
#include "arm_compute/core/Window.h"
#include "arm_compute/core/utils/misc/ShapeCalculator.h"
#include "src/core/helpers/AutoConfiguration.h"
#include "src/core/helpers/WindowHelpers.h"

#include <arm_neon.h>

namespace arm_compute
{
namespace cpu
{
namespace kernels
{
using namespace arm_compute::misc::shape_calculator;

void CpuGemmInterleave4x4Kernel::configure(const ITensorInfo *src, ITensorInfo *dst)
{
    ARM_COMPUTE_ERROR_ON_NULLPTR(src, dst);

    // dst auto inizialitation if not yet initialized
    auto_init_if_empty(*dst, src->clone()->set_tensor_shape(compute_interleaved_shape(*src)));

    // Perform validate step
    ARM_COMPUTE_ERROR_THROW_ON(CpuGemmInterleave4x4Kernel::validate(src, dst));

    Window win = calculate_max_window(*src, Steps(1, 4));
    ICPPKernel::configure(win);
}

Status CpuGemmInterleave4x4Kernel::validate(const ITensorInfo *src, const ITensorInfo *dst)
{
    ARM_COMPUTE_RETURN_ERROR_ON_NULLPTR(src, dst);
    //Note: ARM_COMPUTE_RETURN_ERROR_ON_CPU_F16_UNSUPPORTED(src) is not needed here as this kernel doesn't use CPU FP16 instructions.
    ARM_COMPUTE_RETURN_ERROR_ON(src->data_type() == DataType::UNKNOWN);

    if(dst->total_size() != 0)
    {
        const TensorShape dst_shape = compute_interleaved_shape(*src);
        ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DIMENSIONS(dst->tensor_shape(), dst_shape);
        ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(src, dst);
        ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_QUANTIZATION_INFO(src, dst);
    }

    return Status{};
}

void CpuGemmInterleave4x4Kernel::run_op(ITensorPack &tensors, const Window &window, const ThreadInfo &info)
{
    ARM_COMPUTE_UNUSED(info);
    ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(this);
    ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(IKernel::window(), window);
    ARM_COMPUTE_ERROR_ON(tensors.empty());
    /*
    *  This kernel puts the values in a 4x4 block of Matrix A on the same row (Interleaved values)
    *         |a00 a01 a02 a03|
    *         |a10 a11 a12 a13|
    *         |a20 a21 a22 a23| = | a00 a10 a20 a30 || a01 a11 a21 a31 || a02 a12 a22 a32 || a03 a13 a23 a33 |
    *         |a30 a31 a32 a33|
    *
    *         After this operation, the dst matrix will have the following shape: [ height * 4, ceil(width / 4.0f) ]
    */
    const ITensor *src = tensors.get_const_tensor(TensorType::ACL_SRC);
    ITensor       *dst = tensors.get_tensor(TensorType::ACL_DST);

    const size_t window_start_x = window.x().start();
    const size_t window_end_x   = window.x().end();

    const size_t in_height = src->info()->dimension(1);
    const size_t in_stride = src->info()->strides_in_bytes()[1];

    const size_t partial_y = in_height % 4;

    const size_t element_size = src->info()->element_size();

    // Set window for the src tensor
    Window win = window;
    win.set(Window::DimX, Window::Dimension(0, 1, 1));

    // Set window for the dst tensor
    Window win_out(window);
    win_out.set(Window::DimX, Window::Dimension(0, 1, 1));
    win_out.scale(Window::DimY, 0.25f);

    Iterator in(src, win);
    Iterator out(dst, win_out);

    execute_window_loop(win, [&](const Coordinates & id)
    {
        if(id.y() + 4 <= static_cast<int>(in_height))
        {
            for(size_t x = window_start_x; x < window_end_x; ++x)
            {
                std::memcpy(out.ptr() + (x * 4 + 0) * element_size, (in.ptr() + 0 * in_stride) + x * element_size, element_size);
                std::memcpy(out.ptr() + (x * 4 + 1) * element_size, (in.ptr() + 1 * in_stride) + x * element_size, element_size);
                std::memcpy(out.ptr() + (x * 4 + 2) * element_size, (in.ptr() + 2 * in_stride) + x * element_size, element_size);
                std::memcpy(out.ptr() + (x * 4 + 3) * element_size, (in.ptr() + 3 * in_stride) + x * element_size, element_size);
            }
        }
        else
        {
            for(size_t x = window_start_x; x < window_end_x; ++x)
            {
                size_t y = 0;
                for(; y < partial_y; ++y)
                {
                    std::memcpy(out.ptr() + (x * 4 + y) * element_size, (in.ptr() + y * in_stride) + x * element_size, element_size);
                }
                for(; y < 4; ++y)
                {
                    std::memset(out.ptr() + (x * 4 + y) * element_size, 0, element_size);
                }
            }
        }
    },
    in, out);
}

const char *CpuGemmInterleave4x4Kernel::name() const
{
    return "CpuGemmInterleave4x4Kernel";
}
} // namespace kernels
} // namespace cpu
} // namespace arm_compute


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in de Candolle & Lamarck, Fl. franç. (Paris), Edn 3 6: 105 (1815)

#### Original name
Erysiphe euonymi DC., 1815

### Remarks
null