text:
MeshResourceLoader::MeshResourceLoader()
{
}

MeshResourceLoader::~MeshResourceLoader()
{
}

Model* MeshResourceLoader::Load(const aiScene* scene)
{
    // From the scene, load up the Meshs in the hierarchy
    int meshIndex = 0;
    Model* model = new Model();
    model->Initialize(scene->mNumMeshes);

    while (meshIndex < scene->mNumMeshes)
    {
        aiMesh* currentMesh = scene->mMeshes[meshIndex];

        unsigned int vertexCount = currentMesh->mNumVertices;
        unsigned int indexCount = currentMesh->mNumFaces * 3;

        PositionNormalUVLayout* vertexData = new PositionNormalUVLayout[vertexCount];

        for (int vertexIndex = 0; vertexIndex < vertexCount; vertexIndex++)
        {
            vertexData[vertexIndex].Position.x = currentMesh->mVertices[vertexIndex].x;
            vertexData[vertexIndex].Position.y = currentMesh->mVertices[vertexIndex].y;
            vertexData[vertexIndex].Position.z = currentMesh->mVertices[vertexIndex].z;
            vertexData[vertexIndex].Normal.x = currentMesh->mNormals[vertexIndex].x;
            vertexData[vertexIndex].Normal.y = currentMesh->mNormals[vertexIndex].y;
            vertexData[vertexIndex].Normal.z = currentMesh->mNormals[vertexIndex].z;
            vertexData[vertexIndex].UV.x = currentMesh->mTextureCoords[0][vertexIndex].x;
            vertexData[vertexIndex].UV.y = currentMesh->mTextureCoords[0][vertexIndex].y;
        }

        unsigned int* indexData = new unsigned int[indexCount+1];
        unsigned int faceCount = currentMesh->mNumFaces;
        unsigned int indexOffset = 0;
        for (int faceIndex = 0; faceIndex < faceCount; faceIndex++)
        {
            indexData[++indexOffset] = currentMesh->mFaces[faceIndex].mIndices[0];
            indexData[++indexOffset] = currentMesh->mFaces[faceIndex].mIndices[1];
            indexData[++indexOffset] = currentMesh->mFaces[faceIndex].mIndices[2];
        }

        Mesh* drawable = new Mesh();
        drawable->Load(vertexData, vertexCount, indexData, indexCount);

        model->AddMesh(drawable);

        meshIndex++;
    }

    return model;
}


text:
package com.laytonsmith.core.taskmanager;

/**
 * Fired when a task's state is changed
 */
public interface TaskStateChangeListener {

	/**
	 * Fired when a task's state has changed.
	 *
	 * @param from The old state
	 * @param task The TaskHandler for this task. The new state can be determined from this object.
	 */
	void taskStateChanged(TaskState from, TaskHandler task);

}

redpajama_set_name: RedPajamaGithub


text:
/**
 * Adds logging functionality to the client.
 */
package com.dmdirc.addons.logging;


text:
package com.zaradai.kunzite.optimizer.model;

import org.junit.Test;

import java.util.List;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;

public class InputRowGeneratorTest {
    private static final String COL_NAME_1 = "col1";
    private static final String COL_NAME_2 = "col2";
    private static final String COL_NAME_3 = "col3";

    @Test
    public void shouldGetFirst() throws Exception {
        InputRow row = createInputRow();
        InputRow uut = InputRowGenerator.getFirst(row.getSchema());

        assertThat(uut.getValue(0), is(0));
        assertThat(uut.getValue(1), is(0));
        assertThat(uut.getValue(2), is(0));
    }

    @Test
    public void shouldGetRandom() throws Exception {
        InputRow row = createInputRow();
        InputRow uut = InputRowGenerator.getRandom(row.getSchema());

        assertThat(uut, not(nullValue()));
    }

    @Test
    public void shouldGetNext() throws Exception {
        InputRow row = createInputRow();
        InputRow uut = InputRowGenerator.getNext(row);

        assertThat(uut.getValue(0), is(1));
        assertThat(uut.getValue(1), is(0));
        assertThat(uut.getValue(2), is(0));
    }

    @Test
    public void shouldWrapGetNext() throws Exception {
        InputRow row = createInputRow();
        setRowValues(row, 18, 18, 18);

        InputRow uut = InputRowGenerator.getNext(row);

        assertThat(uut.getValue(0), is(0));
        assertThat(uut.getValue(1), is(0));
        assertThat(uut.getValue(2), is(0));
    }

    @Test
    public void shouldGetPrev() throws Exception {
        InputRow row = createInputRow();
        setRowValues(row, 0, 5, 5);

        InputRow uut = InputRowGenerator.getPrev(row);

        assertThat(uut.getValue(0), is(18));
        assertThat(uut.getValue(1), is(4));
        assertThat(uut.getValue(2), is(5));
    }

    @Test
    public void shouldWrapGetPrev() throws Exception {
        InputRow row = createInputRow();
        setRowValues(row, 0, 0, 0);

        InputRow uut = InputRowGenerator.getPrev(row);

        assertThat(uut.getValue(0), is(18));
        assertThat(uut.getValue(1), is(18));
        assertThat(uut.getValue(2), is(18));
    }

    @Test
    public void shouldGetNeighbours() throws Exception {
        InputRow row = createInputRow();
        setRowValues(row, 5, 5, 5);

        List<InputRow> res = InputRowGenerator.getNeighbours(row);
        assertThat(res.size(), is(27));
        // no need to test values as the NeighboursInputRowBuilder will be tested by its unit tests
    }

    private InputRow createInputRow() {
        return InputRow.fromSchema(InputRowSchema.newBuilder()
                .withName(COL_NAME_1).from(1.0).until(10.0).withStep(0.5)
                .withName(COL_NAME_2).from(1.0).until(10.0).withStep(0.5)
                .withName(COL_NAME_3).from(1.0).until(10.0).withStep(0.5)
                .build());
    }

    private void setRowValues(InputRow row, int one, int two, int three) {
        row.setValue(0, one);
        row.setValue(1, two);
        row.setValue(2, three);
    }
}


text:
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { useIntl } from 'react-intl';
import { CarouselInput, CarouselSlide } from '@strapi/design-system/CarouselInput';
import getTrad from '../../../utils/getTrad';
import { AssetDefinition } from '../../../constants';
import { CarouselAssetActions } from './CarouselAssetActions';
import { CarouselAsset } from './CarouselAsset';
import { EmptyStateAsset } from './EmptyStateAsset';
import { EditAssetDialog } from '../../EditAssetDialog';

export const CarouselAssets = ({
  assets,
  disabled,
  error,
  hint,
  label,
  onAddAsset,
  onDeleteAsset,
  onDeleteAssetFromMediaLibrary,
  onDropAsset,
  onEditAsset,
  onNext,
  onPrevious,
  required,
  selectedAssetIndex,
  trackedLocation,
}) => {
  const { formatMessage } = useIntl();
  const [isEditingAsset, setIsEditingAsset] = useState(false);

  const currentAsset = assets[selectedAssetIndex];

  return (
    <>
      <CarouselInput
        label={label}
        secondaryLabel={currentAsset?.name}
        selectedSlide={selectedAssetIndex}
        previousLabel={formatMessage({
          id: getTrad('mediaLibraryInput.actions.previousSlide'),
          defaultMessage: 'Previous slide',
        })}
        nextLabel={formatMessage({
          id: getTrad('mediaLibraryInput.actions.nextSlide'),
          defaultMessage: 'Next slide',
        })}
        onNext={onNext}
        onPrevious={onPrevious}
        hint={hint}
        error={error}
        required={required}
        actions={
          currentAsset ? (
            <CarouselAssetActions
              asset={currentAsset}
              onDeleteAsset={disabled ? undefined : onDeleteAsset}
              onDeleteAssetFromMediaLibrary={onDeleteAssetFromMediaLibrary}
              onAddAsset={disabled ? undefined : onAddAsset}
              onEditAsset={onEditAsset ? () => setIsEditingAsset(true) : undefined}
            />
          ) : (
            undefined
          )
        }
      >
        {assets.length === 0 ? (
          <CarouselSlide
            label={formatMessage(
              { id: getTrad('mediaLibraryInput.slideCount'), defaultMessage: '{n} of {m} slides' },
              { n: 1, m: 1 }
            )}
          >
            <EmptyStateAsset disabled={disabled} onClick={onAddAsset} onDropAsset={onDropAsset} />
          </CarouselSlide>
        ) : (
          assets.map((asset, index) => (
            <CarouselSlide
              key={asset.id}
              label={formatMessage(
                {
                  id: getTrad('mediaLibraryInput.slideCount'),
                  defaultMessage: '{n} of {m} slides',
                },
                { n: index + 1, m: assets.length }
              )}
            >
              <CarouselAsset asset={asset} />
            </CarouselSlide>
          ))
        )}
      </CarouselInput>

      {isEditingAsset && (
        <EditAssetDialog
          onClose={editedAsset => {
            setIsEditingAsset(false);

            // The asset has been deleted
            if (editedAsset === null) {
              onDeleteAssetFromMediaLibrary();
            }

            if (editedAsset) {
              onEditAsset(editedAsset);
            }
          }}
          asset={currentAsset}
          canUpdate
          canCopyLink
          canDownload
          trackedLocation={trackedLocation}
        />
      )}
    </>
  );
};

CarouselAssets.defaultProps = {
  disabled: false,
  error: undefined,
  hint: undefined,
  onDropAsset: undefined,
  required: false,
  trackedLocation: undefined,
};

CarouselAssets.propTypes = {
  assets: PropTypes.arrayOf(AssetDefinition).isRequired,
  disabled: PropTypes.bool,
  error: PropTypes.string,
  hint: PropTypes.string,
  label: PropTypes.string.isRequired,
  onAddAsset: PropTypes.func.isRequired,
  onDeleteAsset: PropTypes.func.isRequired,
  onDeleteAssetFromMediaLibrary: PropTypes.func.isRequired,
  onDropAsset: PropTypes.func,
  onEditAsset: PropTypes.func.isRequired,
  onNext: PropTypes.func.isRequired,
  onPrevious: PropTypes.func.isRequired,
  required: PropTypes.bool,
  selectedAssetIndex: PropTypes.number.isRequired,
  trackedLocation: PropTypes.string,
};


text:
#ifndef MOLCULETRANSFER_H
#define MOLCULETRANSFER_H

#if ENSEMBLE==GCMC || ENSEMBLE==GEMC

#include "MoveBase.h"
#include "TrialMol.h"

//#define DEBUG_MOVES

class MoleculeTransfer : public MoveBase
{
public:

  MoleculeTransfer(System &sys, StaticVals const& statV) :
    MoveBase(sys, statV), molLookRef(sys.molLookupRef),
    ffRef(statV.forcefield) {}

  virtual uint Prep(const double subDraw, const double movPerc);
  // To relax the system in NE_MTMC move
  virtual uint PrepNEMTMC(const uint box, const uint midx = 0, const uint kidx = 0) {
    return mv::fail_state::NO_FAIL;
  }
  virtual uint Transform();
  virtual void CalcEn();
  virtual void Accept(const uint earlyReject, const ulong step);
  virtual void PrintAcceptKind();

private:

  double GetCoeff() const;
  uint GetBoxPairAndMol(const double subDraw, const double movPerc);
  MolPick molPick;
  uint sourceBox, destBox;
  uint pStart, pLen;
  uint molIndex, kindIndex;

  double W_tc, W_recip;
  double correct_old, correct_new, self_old, self_new;
  cbmc::TrialMol oldMol, newMol;
  Intermolecular tcLose, tcGain, recipLose, recipGain;
  MoleculeLookup & molLookRef;
  Forcefield const& ffRef;
};

void MoleculeTransfer::PrintAcceptKind()
{
  for(uint k = 0; k < molRef.GetKindsCount(); k++) {
    printf("%-30s %-5s ", "% Accepted Mol-Transfer ", molRef.kinds[k].name.c_str());
    for(uint b = 0; b < BOX_TOTAL; b++) {
      if(moveSetRef.GetTrial(b, mv::MOL_TRANSFER, k) > 0)
        printf("%10.5f ", (100.0 * moveSetRef.GetAccept(b, mv::MOL_TRANSFER, k)));
      else
        printf("%10.5f ", 0.0);
    }
    std::cout << std::endl;
  }
}

inline uint MoleculeTransfer::GetBoxPairAndMol(const double subDraw, const double movPerc)
{
  // Need to call a function to pick a molecule that is not fixed but cannot be
  // swap between boxes. (beta != 1, beta !=2)
  uint state = prng.PickMolAndBoxPair2(molIndex, kindIndex, sourceBox, destBox,
                                       subDraw, movPerc);
#if ENSEMBLE == GCMC
  if(state == mv::fail_state::NO_MOL_OF_KIND_IN_BOX && sourceBox == mv::BOX1) {
    std::cout << "Error: There are no molecules of kind " <<
              molRef.kinds[kindIndex].name << " left in reservoir.\n";
    exit(EXIT_FAILURE);
  }
#endif

  if (state == mv::fail_state::NO_FAIL) {
    pStart = pLen = 0;
    molRef.GetRangeStartLength(pStart, pLen, molIndex);
  }
  return state;
}

inline uint MoleculeTransfer::Prep(const double subDraw, const double movPerc)
{
  GOMC_EVENT_START(1, GomcProfileEvent::PREP_SWAP);
  overlap = false;
  uint state = GetBoxPairAndMol(subDraw, movPerc);
  if (state == mv::fail_state::NO_FAIL) {
    newMol = cbmc::TrialMol(molRef.kinds[kindIndex], boxDimRef, destBox);
    oldMol = cbmc::TrialMol(molRef.kinds[kindIndex], boxDimRef, sourceBox);
    oldMol.SetCoords(coordCurrRef, pStart);
  }
  GOMC_EVENT_STOP(1, GomcProfileEvent::PREP_SWAP);
  return state;
}

inline uint MoleculeTransfer::Transform()
{
  GOMC_EVENT_START(1, GomcProfileEvent::TRANS_SWAP);
  cellList.RemoveMol(molIndex, sourceBox, coordCurrRef);
  molRef.kinds[kindIndex].Build(oldMol, newMol, molIndex);
  overlap = newMol.HasOverlap();
  GOMC_EVENT_STOP(1, GomcProfileEvent::TRANS_SWAP);
  return mv::fail_state::NO_FAIL;
}

inline void MoleculeTransfer::CalcEn()
{
  GOMC_EVENT_START(1, GomcProfileEvent::CALC_EN_SWAP);
  W_tc = 1.0;
  W_recip = 1.0;
  correct_old = 0.0;
  correct_new = 0.0;
  self_old = 0.0;
  self_new = 0.0;

  if (ffRef.useLRC) {
    tcLose = calcEnRef.MoleculeTailChange(sourceBox, kindIndex, false);
    tcGain = calcEnRef.MoleculeTailChange(destBox, kindIndex, true);
    W_tc = exp(-1.0 * ffRef.beta * (tcGain.energy + tcLose.energy));
  }

  if (newMol.GetWeight() > SMALL_WEIGHT && !overlap) {
    correct_new = calcEwald->SwapCorrection(newMol);
    correct_old = calcEwald->SwapCorrection(oldMol);
    self_new = calcEwald->SwapSelf(newMol);
    self_old = calcEwald->SwapSelf(oldMol);
    //SwapDestRecip must be called first to backup the cosMol and sinMol
    recipGain.energy =
      calcEwald->SwapDestRecip(newMol, destBox, molIndex);
    recipLose.energy =
      calcEwald->SwapSourceRecip(oldMol, sourceBox, molIndex);
    //need to contribute the self and correction energy
    W_recip = exp(-1.0 * ffRef.beta * (recipGain.energy + recipLose.energy +
                                       correct_new - correct_old +
                                       self_new - self_old));
  }
  GOMC_EVENT_STOP(1, GomcProfileEvent::CALC_EN_SWAP);
}

inline double MoleculeTransfer::GetCoeff() const
{
#if ENSEMBLE == GEMC
  return (double)(molLookRef.NumKindInBoxSwappable(kindIndex, sourceBox)) /
         (double)(molLookRef.NumKindInBoxSwappable(kindIndex, destBox) + 1) *
         boxDimRef.volume[destBox] * boxDimRef.volInv[sourceBox];
#elif ENSEMBLE == GCMC
  if (sourceBox == mv::BOX0) { //Delete case
    if(ffRef.isFugacity) {
      return (double)(molLookRef.NumKindInBoxSwappable(kindIndex, sourceBox)) *
             boxDimRef.volInv[sourceBox] /
             (BETA * molRef.kinds[kindIndex].chemPot);
    } else {
      return (double)(molLookRef.NumKindInBoxSwappable(kindIndex, sourceBox)) *
             boxDimRef.volInv[sourceBox] *
             exp(-BETA * molRef.kinds[kindIndex].chemPot);
    }
  } else { //Insertion case
    if(ffRef.isFugacity) {
      return boxDimRef.volume[destBox] /
             (double)(molLookRef.NumKindInBoxSwappable(kindIndex, destBox) + 1) *
             (BETA * molRef.kinds[kindIndex].chemPot);
    } else {
      return boxDimRef.volume[destBox] /
             (double)(molLookRef.NumKindInBoxSwappable(kindIndex, destBox) + 1) *
             exp(BETA * molRef.kinds[kindIndex].chemPot);
    }
  }
#endif
}

inline void MoleculeTransfer::Accept(const uint rejectState, const ulong step)
{
  GOMC_EVENT_START(1, GomcProfileEvent::ACC_SWAP);
  bool result;
  //If we didn't skip the move calculation
  if(rejectState == mv::fail_state::NO_FAIL) {
    double molTransCoeff = GetCoeff();
    double Wo = oldMol.GetWeight();
    double Wn = newMol.GetWeight();
    double Wrat = Wn / Wo * W_tc * W_recip;

    //safety to make sure move will be rejected in overlap case
    if(newMol.GetWeight() > SMALL_WEIGHT && !overlap) {
      result = prng() < molTransCoeff * Wrat;
    } else
      result = false;

    if(result) {
      //Add tail corrections
      sysPotRef.boxEnergy[sourceBox].tailCorrection += tcLose.energy;
      sysPotRef.boxEnergy[destBox].tailCorrection += tcGain.energy;
      //Add rest of energy.
      sysPotRef.boxEnergy[sourceBox] -= oldMol.GetEnergy();
      sysPotRef.boxEnergy[destBox] += newMol.GetEnergy();
      //Add Reciprocal energy
      sysPotRef.boxEnergy[sourceBox].recip += recipLose.energy;
      sysPotRef.boxEnergy[destBox].recip += recipGain.energy;
      //Add correction energy
      sysPotRef.boxEnergy[sourceBox].correction -= correct_old;
      sysPotRef.boxEnergy[destBox].correction += correct_new;
      //Add self energy
      sysPotRef.boxEnergy[sourceBox].self -= self_old;
      sysPotRef.boxEnergy[destBox].self += self_new;

      //Set coordinates, new COM; shift index to new box's list
      newMol.GetCoords().CopyRange(coordCurrRef, 0, pStart, pLen);
      comCurrRef.SetNew(molIndex, destBox);
      molLookRef.ShiftMolBox(molIndex, sourceBox, destBox,
                             kindIndex);
      cellList.AddMol(molIndex, destBox, coordCurrRef);

      //Zero out box energies to prevent small number
      //errors in double.
      if (molLookRef.NumInBox(sourceBox) == 0) {
        sysPotRef.boxEnergy[sourceBox].Zero();
        sysPotRef.boxVirial[sourceBox].Zero();
      } else if (molLookRef.NumInBox(sourceBox) == 1) {
        sysPotRef.boxEnergy[sourceBox].inter = 0;
        sysPotRef.boxVirial[sourceBox].inter = 0;
        sysPotRef.boxEnergy[sourceBox].real = 0;
        sysPotRef.boxVirial[sourceBox].real = 0;
      }

      calcEwald->UpdateRecip(sourceBox);
      calcEwald->UpdateRecip(destBox);

      //Retotal
      sysPotRef.Total();
      // Update the velocity
      velocity.UpdateMolVelocity(molIndex, destBox);
    } else {
      cellList.AddMol(molIndex, sourceBox, coordCurrRef);
      //when weight is 0, MolDestSwap() will not be executed, thus cos/sin
      //molRef will not be changed. Also since no memcpy, doing restore
      //results in memory overwrite
      if (newMol.GetWeight() > SMALL_WEIGHT && !overlap) {
        calcEwald->RestoreMol(molIndex);
      }
    }

  } else //we didn't even try because we knew it would fail
    result = false;

  moveSetRef.Update(mv::MOL_TRANSFER, result, destBox, kindIndex);
  GOMC_EVENT_STOP(1, GomcProfileEvent::ACC_SWAP);
}

#endif

#endif


text:
package com.gpudb.filesystem.download;

import java.nio.ByteBuffer;
import java.util.List;
import java.util.Map;

/**
 * This is an internal class and not meant to be used by the end users of the
 * filesystem API. The consequences of using this class directly in client code
 * is not guaranteed and maybe undesirable.

 * This class packages and mimics certain important attributes of a multi-part
 * download operation. The attributes of this class are in one-one correspondence
 * to those specified in the {@link com.gpudb.GPUdb#downloadFiles(List, List, List, Map)}
 * endpoint.
 */
public class MultiPartDownloadInfo {

    /**
     * Default constructor
     */
    public MultiPartDownloadInfo() {
    }

    /**
     * The position to start reading the file from.
     */
    private long readOffset;

    /**
     * The number of bytes to read starting from {@link #readOffset}
     */
    private long readLength;

    /**
     * The part number out of {@link #totalParts}
     */
    private long downloadPartNumber;

    private ByteBuffer data;

    /**
     * The total number of parts
     */
    private long totalParts;

    public long getReadOffset() {
        return readOffset;
    }

    public void setReadOffset(long readOffset) {
        this.readOffset = readOffset;
    }

    public long getReadLength() {
        return readLength;
    }

    public void setReadLength(long readLength) {
        this.readLength = readLength;
    }

    public long getDownloadPartNumber() {
        return downloadPartNumber;
    }

    public void setDownloadPartNumber(long downloadPartNumber) {
        this.downloadPartNumber = downloadPartNumber;
    }

    public long getTotalParts() {
        return totalParts;
    }

    public void setTotalParts(long totalParts) {
        this.totalParts = totalParts;
    }

    public ByteBuffer getData() {
        return data;
    }

    public void setData(ByteBuffer data) {
        this.data = data;
    }
}


text:
require "origen"
class OrigenDocHelpersApplication < Origen::Application

  config.name     = "Origen Documentation Helpers"
  config.initials = "OrigenDocHelpers"
  config.rc_url   = "git@github.com:Origen-SDK/origen_doc_helpers"
  config.release_externally = true
  # To enable deployment of your documentation to a web server (via the 'origen web'
  # command) fill in these attributes.
  config.web_directory = "git@github.com:Origen-SDK/Origen-SDK.github.io.git/doc_helpers"
  config.web_domain = "https://origen-sdk.org/doc_helpers"
  config.disqus_shortname = "origen-sdk"

  config.semantically_version = true

  config.lint_test = {
    # Require the lint tests to pass before allowing a release to proceed
    :run_on_tag => true,
    # Auto correct violations where possible whenever 'origen lint' is run
    :auto_correct => true,
    # Limit the testing for large legacy applications
    #:level => :easy,
    # Run on these directories/files by default
    #:files => ["lib", "config/application.rb"],
  }

  # To automatically deploy your documentation after every tag use this code
  def after_release_email(tag, note, type, selector, options)
    command = "origen web compile --remote"
    Dir.chdir Origen.root do
      system command
    end
  end

  def after_web_site_compile(options)
    Origen.app.runner.launch action: :program, files: "program"
    # Then the documentation
    OrigenDocHelpers.generate_flow_docs layout: "#{Origen.root}/templates/web/layouts/_basic.html.erb", tab: :flows  do |d|
      d.page flow: :probe1,
             name: "Probe 1 Flow",
             target: "default.rb"
    end
  end
end


text:
import importlib

from migrate import exceptions as versioning_exceptions
from migrate import UniqueConstraint
from migrate.versioning import api as versioning_api
import mock
from oslo_db.sqlalchemy import utils as db_utils
import sqlalchemy

from nova import context
from nova.db.sqlalchemy import api as db_api
from nova.db.sqlalchemy import migration
from nova import exception
from nova import objects
from nova import test
from nova.tests import fixtures as nova_fixtures
from nova.tests import uuidsentinel

class TestNullInstanceUuidScanDB(test.TestCase):

    # NOTE(mriedem): Copied from the 267 database migration.
    def downgrade(self, migrate_engine):
        UniqueConstraint('uuid',
                         table=db_utils.get_table(migrate_engine, 'instances'),
                         name='uniq_instances0uuid').drop()
        for table_name in ('instances', 'shadow_instances'):
            table = db_utils.get_table(migrate_engine, table_name)
            table.columns.uuid.alter(nullable=True)

    def setUp(self):
        super(TestNullInstanceUuidScanDB, self).setUp()

        self.engine = db_api.get_engine()
        # When this test runs, we've already run the schema migration to make
        # instances.uuid non-nullable, so we have to alter the table here
        # so we can test against a real database.
        self.downgrade(self.engine)
        # Now create fake entries in the fixed_ips, consoles and
        # instances table where (instance_)uuid is None for testing.
        for table_name in ('fixed_ips', 'instances', 'consoles'):
            table = db_utils.get_table(self.engine, table_name)
            fake_record = {'id': 1}
            table.insert().execute(fake_record)

    def test_db_null_instance_uuid_scan_readonly(self):
        results = migration.db_null_instance_uuid_scan(delete=False)
        self.assertEqual(1, results.get('instances'))
        self.assertEqual(1, results.get('consoles'))
        # The fixed_ips table should be ignored.
        self.assertNotIn('fixed_ips', results)
        # Now pick a random table with an instance_uuid column and show it's
        # in the results but with 0 hits.
        self.assertEqual(0, results.get('instance_info_caches'))
        # Make sure nothing was deleted.
        for table_name in ('fixed_ips', 'instances', 'consoles'):
            table = db_utils.get_table(self.engine, table_name)
            record = table.select(table.c.id == 1).execute().first()
            self.assertIsNotNone(record)

    def test_db_null_instance_uuid_scan_delete(self):
        results = migration.db_null_instance_uuid_scan(delete=True)
        self.assertEqual(1, results.get('instances'))
        self.assertEqual(1, results.get('consoles'))
        # The fixed_ips table should be ignored.
        self.assertNotIn('fixed_ips', results)
        # Now pick a random table with an instance_uuid column and show it's
        # in the results but with 0 hits.
        self.assertEqual(0, results.get('instance_info_caches'))
        # Make sure fixed_ips wasn't touched, but instances and instance_faults
        # records were deleted.
        fixed_ips = db_utils.get_table(self.engine, 'fixed_ips')
        record = fixed_ips.select(fixed_ips.c.id == 1).execute().first()
        self.assertIsNotNone(record)

        consoles = db_utils.get_table(self.engine, 'consoles')
        record = consoles.select(consoles.c.id == 1).execute().first()
        self.assertIsNone(record)

        instances = db_utils.get_table(self.engine, 'instances')
        record = instances.select(instances.c.id == 1).execute().first()
        self.assertIsNone(record)

@mock.patch.object(migration, 'db_version', return_value=2)
@mock.patch.object(migration, '_find_migrate_repo', return_value='repo')
@mock.patch.object(versioning_api, 'upgrade')
@mock.patch.object(versioning_api, 'downgrade')
@mock.patch.object(migration, 'get_engine', return_value='engine')
class TestDbSync(test.NoDBTestCase):

    def test_version_none(self, mock_get_engine, mock_downgrade, mock_upgrade,
            mock_find_repo, mock_version):
        database = 'fake'
        migration.db_sync(database=database)
        mock_version.assert_called_once_with(database, context=None)
        mock_find_repo.assert_called_once_with(database)
        mock_get_engine.assert_called_once_with(database, context=None)
        mock_upgrade.assert_called_once_with('engine', 'repo', None)
        self.assertFalse(mock_downgrade.called)

    def test_downgrade(self, mock_get_engine, mock_downgrade, mock_upgrade,
            mock_find_repo, mock_version):
        database = 'fake'
        migration.db_sync(1, database=database)
        mock_version.assert_called_once_with(database, context=None)
        mock_find_repo.assert_called_once_with(database)
        mock_get_engine.assert_called_once_with(database, context=None)
        mock_downgrade.assert_called_once_with('engine', 'repo', 1)
        self.assertFalse(mock_upgrade.called)

@mock.patch.object(migration, '_find_migrate_repo', return_value='repo')
@mock.patch.object(versioning_api, 'db_version')
@mock.patch.object(migration, 'get_engine')
class TestDbVersion(test.NoDBTestCase):

    def test_db_version(self, mock_get_engine, mock_db_version,
            mock_find_repo):
        database = 'fake'
        mock_get_engine.return_value = 'engine'
        migration.db_version(database)
        mock_find_repo.assert_called_once_with(database)
        mock_db_version.assert_called_once_with('engine', 'repo')

    def test_not_controlled(self, mock_get_engine, mock_db_version,
            mock_find_repo):
        database = 'api'
        mock_get_engine.side_effect = ['engine', 'engine', 'engine']
        exc = versioning_exceptions.DatabaseNotControlledError()
        mock_db_version.side_effect = [exc, '']
        metadata = mock.MagicMock()
        metadata.tables.return_value = []
        with mock.patch.object(sqlalchemy, 'MetaData',
                metadata), mock.patch.object(migration,
                        'db_version_control') as mock_version_control:
            migration.db_version(database)
            mock_version_control.assert_called_once_with(0,
                                                         database,
                                                         context=None)
            db_version_calls = [mock.call('engine', 'repo')] * 2
            self.assertEqual(db_version_calls, mock_db_version.call_args_list)
        engine_calls = [mock.call(database, context=None)] * 3
        self.assertEqual(engine_calls, mock_get_engine.call_args_list)

@mock.patch.object(migration, '_find_migrate_repo', return_value='repo')
@mock.patch.object(migration, 'get_engine', return_value='engine')
@mock.patch.object(versioning_api, 'version_control')
class TestDbVersionControl(test.NoDBTestCase):

    def test_version_control(self, mock_version_control, mock_get_engine,
            mock_find_repo):
        database = 'fake'
        migration.db_version_control(database=database)
        mock_find_repo.assert_called_once_with(database)
        mock_version_control.assert_called_once_with('engine', 'repo', None)

class TestGetEngine(test.NoDBTestCase):

    def test_get_main_engine(self):
        with mock.patch.object(db_api, 'get_engine',
                return_value='engine') as mock_get_engine:
            engine = migration.get_engine()
            self.assertEqual('engine', engine)
            mock_get_engine.assert_called_once_with(context=None)

    def test_get_api_engine(self):
        with mock.patch.object(db_api, 'get_api_engine',
                return_value='api_engine') as mock_get_engine:
            engine = migration.get_engine('api')
            self.assertEqual('api_engine', engine)
            mock_get_engine.assert_called_once_with()

class TestFlavorCheck(test.TestCase):
    def setUp(self):
        super(TestFlavorCheck, self).setUp()
        self.context = context.get_admin_context()
        self.migration = importlib.import_module(
            'nova.db.sqlalchemy.migrate_repo.versions.'
            '291_enforce_flavors_migrated')
        self.engine = db_api.get_engine()

    def test_upgrade_clean(self):
        inst = objects.Instance(context=self.context,
                                uuid=uuidsentinel.fake,
                                user_id=self.context.user_id,
                                project_id=self.context.project_id,
                                system_metadata={'foo': 'bar'})
        inst.create()
        self.migration.upgrade(self.engine)

    def test_upgrade_dirty(self):
        inst = objects.Instance(context=self.context,
                                uuid=uuidsentinel.fake,
                                user_id=self.context.user_id,
                                project_id=self.context.project_id,
                                system_metadata={'foo': 'bar',
                                                 'instance_type_id': 'foo'})
        inst.create()
        self.assertRaises(exception.ValidationError,
                          self.migration.upgrade, self.engine)

    def test_upgrade_flavor_deleted_instances(self):
        inst = objects.Instance(context=self.context,
                                uuid=uuidsentinel.fake,
                                user_id=self.context.user_id,
                                project_id=self.context.project_id,
                                system_metadata={'foo': 'bar',
                                                 'instance_type_id': 'foo'})
        inst.create()
        inst.destroy()
        self.migration.upgrade(self.engine)

class TestNewtonCheck(test.TestCase):
    def setUp(self):
        super(TestNewtonCheck, self).setUp()
        self.useFixture(nova_fixtures.DatabaseAtVersion(329))
        self.context = context.get_admin_context()
        self.migration = importlib.import_module(
            'nova.db.sqlalchemy.migrate_repo.versions.'
            '330_enforce_mitaka_online_migrations')
        self.engine = db_api.get_engine()

    def test_aggregate_not_migrated(self):
        agg = db_api.aggregate_create(self.context, {"name": "foobar"})
        db_api.aggregate_update(self.context, agg.id, {'uuid': None})
        self.assertRaises(exception.ValidationError,
                          self.migration.upgrade, self.engine)

    def test_pci_device_type_vf_not_migrated(self):
        db_api.pci_device_update(self.context, 1, 'foo:bar',
                                 {'parent_addr': None,
                                  'compute_node_id': 1,
                                  'address': 'foo:bar',
                                  'vendor_id': '123',
                                  'product_id': '456',
                                  'dev_type': 'type-VF',
                                  'label': 'foobar',
                                  'status': 'whatisthis?'})
        # type-VF devices should have a parent_addr
        self.assertRaises(exception.ValidationError,
                          self.migration.upgrade, self.engine)

    def test_pci_device_type_pf_not_migrated(self):
        db_api.pci_device_update(self.context, 1, 'foo:bar',
                                 {'parent_addr': None,
                                  'compute_node_id': 1,
                                  'address': 'foo:bar',
                                  'vendor_id': '123',
                                  'product_id': '456',
                                  'dev_type': 'type-PF',
                                  'label': 'foobar',
                                  'status': 'whatisthis?'})
        # blocker should not block on type-PF devices
        self.migration.upgrade(self.engine)

    def test_pci_device_type_pci_not_migrated(self):
        db_api.pci_device_update(self.context, 1, 'foo:bar',
                                 {'parent_addr': None,
                                  'compute_node_id': 1,
                                  'address': 'foo:bar',
                                  'vendor_id': '123',
                                  'product_id': '456',
                                  'dev_type': 'type-PCI',
                                  'label': 'foobar',
                                  'status': 'whatisthis?'})
        # blocker should not block on type-PCI devices
        self.migration.upgrade(self.engine)

class TestOcataCheck(test.TestCase):
    def setUp(self):
        super(TestOcataCheck, self).setUp()
        self.context = context.get_admin_context()
        self.migration = importlib.import_module(
            'nova.db.sqlalchemy.migrate_repo.versions.'
            '345_require_online_migration_completion')
        self.engine = db_api.get_engine()
        self.flavor_values = {
            'name': 'foo',
            'memory_mb': 256,
            'vcpus': 1,
            'root_gb': 10,
            'ephemeral_gb': 100,
            'flavorid': 'bar',
            'swap': 1,
            'rxtx_factor': 1.0,
            'vcpu_weight': 1,
            'disabled': False,
            'is_public': True,
        }
        self.keypair_values = {
            'name': 'foo',
            'user_ud': 'bar',
            'fingerprint': 'baz',
            'public_key': 'bat',
            'type': 'ssh',
        }
        self.aggregate_values = {
            'uuid': uuidsentinel.agg,
            'name': 'foo',
        }
        self.ig_values = {
            'user_id': 'foo',
            'project_id': 'bar',
            'uuid': uuidsentinel.ig,
            'name': 'baz',
        }

    def test_upgrade_clean(self):
        self.migration.upgrade(self.engine)

    def test_upgrade_dirty_flavors(self):
        db_api.flavor_create(self.context, self.flavor_values)
        self.assertRaises(exception.ValidationError,
                          self.migration.upgrade, self.engine)

    def test_upgrade_with_deleted_flavors(self):
        flavor = db_api.flavor_create(self.context, self.flavor_values)
        db_api.flavor_destroy(self.context, flavor['flavorid'])
        self.migration.upgrade(self.engine)

    def test_upgrade_dirty_keypairs(self):
        db_api.key_pair_create(self.context, self.keypair_values)
        self.assertRaises(exception.ValidationError,
                          self.migration.upgrade, self.engine)

    def test_upgrade_with_deleted_keypairs(self):
        keypair = db_api.key_pair_create(self.context, self.keypair_values)
        db_api.key_pair_destroy(self.context,
                                keypair['user_id'], keypair['name'])
        self.migration.upgrade(self.engine)

    def test_upgrade_dirty_aggregates(self):
        db_api.aggregate_create(self.context, self.aggregate_values)
        self.assertRaises(exception.ValidationError,
                          self.migration.upgrade, self.engine)

    def test_upgrade_with_deleted_aggregates(self):
        agg = db_api.aggregate_create(self.context, self.aggregate_values)
        db_api.aggregate_delete(self.context, agg['id'])
        self.migration.upgrade(self.engine)

    def test_upgrade_dirty_instance_groups(self):
        db_api.instance_group_create(self.context, self.ig_values)
        self.assertRaises(exception.ValidationError,
                          self.migration.upgrade, self.engine)

    def test_upgrade_with_deleted_instance_groups(self):
        group = db_api.instance_group_create(self.context, self.ig_values)
        db_api.instance_group_delete(self.context, group['uuid'])
        self.migration.upgrade(self.engine)

class TestNewtonCellsCheck(test.NoDBTestCase):
    USES_DB_SELF = True

    def setUp(self):
        super(TestNewtonCellsCheck, self).setUp()
        self.useFixture(nova_fixtures.DatabaseAtVersion(28, 'api'))
        self.context = context.get_admin_context()
        self.migration = importlib.import_module(
            'nova.db.sqlalchemy.api_migrations.migrate_repo.versions.'
            '030_require_cell_setup')
        self.engine = db_api.get_api_engine()

    @mock.patch('nova.objects.Flavor._ensure_migrated')
    def _flavor_me(self, _):
        flavor = objects.Flavor(context=self.context,
                                name='foo', memory_mb=123,
                                vcpus=1, root_gb=1,
                                flavorid='m1.foo')
        flavor.create()

    def test_upgrade_with_no_cell_mappings(self):
        self._flavor_me()
        self.assertRaisesRegex(exception.ValidationError,
                               'Cell mappings',
                               self.migration.upgrade, self.engine)

    def test_upgrade_with_only_cell0(self):
        self._flavor_me()
        cell0 = objects.CellMapping(context=self.context,
                                    uuid=objects.CellMapping.CELL0_UUID,
                                    name='cell0',
                                    transport_url='fake',
                                    database_connection='fake')
        cell0.create()
        self.assertRaisesRegex(exception.ValidationError,
                               'Cell mappings',
                               self.migration.upgrade, self.engine)

    def test_upgrade_without_cell0(self):
        self._flavor_me()
        cell1 = objects.CellMapping(context=self.context,
                                    uuid=uuidsentinel.cell1,
                                    name='cell1',
                                    transport_url='fake',
                                    database_connection='fake')
        cell1.create()
        cell2 = objects.CellMapping(context=self.context,
                                    uuid=uuidsentinel.cell2,
                                    name='cell2',
                                    transport_url='fake',
                                    database_connection='fake')
        cell2.create()
        self.assertRaisesRegex(exception.ValidationError,
                               'Cell0',
                               self.migration.upgrade, self.engine)

    def test_upgrade_with_no_host_mappings(self):
        self._flavor_me()
        cell0 = objects.CellMapping(context=self.context,
                                    uuid=objects.CellMapping.CELL0_UUID,
                                    name='cell0',
                                    transport_url='fake',
                                    database_connection='fake')
        cell0.create()
        cell1 = objects.CellMapping(context=self.context,
                                    uuid=uuidsentinel.cell1,
                                    name='cell1',
                                    transport_url='fake',
                                    database_connection='fake')
        cell1.create()

        with mock.patch.object(self.migration, 'LOG') as log:
            self.migration.upgrade(self.engine)
            self.assertTrue(log.warning.called)

    def test_upgrade_with_required_mappings(self):
        self._flavor_me()
        cell0 = objects.CellMapping(context=self.context,
                                    uuid=objects.CellMapping.CELL0_UUID,
                                    name='cell0',
                                    transport_url='fake',
                                    database_connection='fake')
        cell0.create()
        cell1 = objects.CellMapping(context=self.context,
                                    uuid=uuidsentinel.cell1,
                                    name='cell1',
                                    transport_url='fake',
                                    database_connection='fake')
        cell1.create()
        hostmapping = objects.HostMapping(context=self.context,
                                          cell_mapping=cell1,
                                          host='foo')
        hostmapping.create()

        self.migration.upgrade(self.engine)

    def test_upgrade_new_deploy(self):
        self.migration.upgrade(self.engine)


text:
//
//  CNPostalAddress.h
//  Contacts
//
//  Copyright (c) 2015 Apple Inc. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <Contacts/ContactsDefines.h>

NS_ASSUME_NONNULL_BEGIN

/*!
 * @abstract An immutable value object representing a postal address.
 *
 * @discussion CNPostalAddress is thread safe.
 */
NS_CLASS_AVAILABLE(10_11, 9_0)
@interface CNPostalAddress : NSObject <NSCopying, NSMutableCopying, NSSecureCoding>

/*! multi-street address is delimited with carriage returns "\n" */
@property (readonly, copy, NS_NONATOMIC_IOSONLY) NSString *street;
@property (readonly, copy, NS_NONATOMIC_IOSONLY) NSString *city;
@property (readonly, copy, NS_NONATOMIC_IOSONLY) NSString *state;
@property (readonly, copy, NS_NONATOMIC_IOSONLY) NSString *postalCode;
@property (readonly, copy, NS_NONATOMIC_IOSONLY) NSString *country;
@property (readonly, copy, NS_NONATOMIC_IOSONLY) NSString *ISOCountryCode;

/*! Returns a user displayable property name. */
+ (NSString*)localizedStringForKey:(NSString *)key;

@end

// Properties that are always fetched. Can be used with key value coding and observing.
CONTACTS_EXTERN NSString * const CNPostalAddressStreetKey                            NS_AVAILABLE(10_11, 9_0);
CONTACTS_EXTERN NSString * const CNPostalAddressCityKey                              NS_AVAILABLE(10_11, 9_0);
CONTACTS_EXTERN NSString * const CNPostalAddressStateKey                             NS_AVAILABLE(10_11, 9_0);
CONTACTS_EXTERN NSString * const CNPostalAddressPostalCodeKey                        NS_AVAILABLE(10_11, 9_0);
CONTACTS_EXTERN NSString * const CNPostalAddressCountryKey                           NS_AVAILABLE(10_11, 9_0);
CONTACTS_EXTERN NSString * const CNPostalAddressISOCountryCodeKey                    NS_AVAILABLE(10_11, 9_0);

NS_ASSUME_NONNULL_END


text:
package org.epnoi.model.modules;

import org.epnoi.model.Annotation;

import java.util.List;

public interface AnnotationHandler {

	public Annotation annotate(String URI, String topicURI);

	public Annotation annotate(String URI, String predicateURI, String topicURI);

	public Annotation label(String URI, String label);

	public void removeAnnotation(String URI, String topicURI);

	public void removeLabel(String URI, String label);

	public List<String> getAnnotatedAs(String topicURI);

	public List<String> getLabeledAs(String label);

	public List<String> getAnnotatedAs(String topicURI, String type);

	public List<String> getLabeledAs(String label, String type);

	public List<String> getAnnotations(String topicURI);

	public List<String> getLabels(String URI);

	public List<String> getAnnotations();

}


text:
package com.daohen.personaltoolboxlibrary;

import android.app.Application;
import android.content.Intent;

import com.daohen.personal.toolbox.library.CrashHandler;
import com.daohen.personal.toolbox.library.util.Booleans;
import com.daohen.personal.toolbox.library.util.Contexts;

/**
 * CREATE BY DAOHEN
 * EMAIL: alunfeixue2011@gmail.com
 * DATE : 2017/08/17 00:21
 */

public class App extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        Contexts.get().setContext(this);
        Booleans.setRelease(false);
        CrashHandler.get().init(getApplicationContext(), new Intent(this, MainActivity.class));
    }

}


text:
#ifndef _MMC_H
#define _MMC_H
/* core-internal functions */
void mmc_init_card(struct mmc_card *card, struct mmc_host *host);
int mmc_register_card(struct mmc_card *card);
void mmc_remove_card(struct mmc_card *card);

struct mmc_host *mmc_alloc_host_sysfs(int extra, struct device *dev);
int mmc_add_host_sysfs(struct mmc_host *host);
void mmc_remove_host_sysfs(struct mmc_host *host);
void mmc_free_host_sysfs(struct mmc_host *host);

int mmc_schedule_work(struct work_struct *work);
int mmc_schedule_delayed_work(struct delayed_work *work, unsigned long delay);
void mmc_flush_scheduled_work(void);
#endif


text:
using Plugin.Share;
using Plugin.Share.Abstractions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Xamarin.Forms;

namespace ShareTest
{
    public class App : Application
    {
        public App()
        {
            var button = new Button
            {
                Text = "Share some text"
            };

            var button1 = new Button
            {
                Text = "Share a link"
            };

            var button2 = new Button
            {
                Text = "Open browser"
            };

            var buttonShare = new Button
            {
                Text = "Share"
            };

            var switchTitle = new Switch { IsToggled = true };
            var switchText = new Switch { IsToggled = true };
            var switchUrl = new Switch { IsToggled = true };
            var switchChooserTitle = new Switch { IsToggled = true };

            button.Clicked += (sender, args) =>
            {
                CrossShare.Current.Share("Follow @JamesMontemagno on Twitter", "Share");
            };

            button1.Clicked += (sender, args) =>
            {
                CrossShare.Current.ShareLink("http://motzcod.es", "Checkout my blog", "MotzCod.es");
            };

            button2.Clicked += (sender, args) =>
            {
                CrossShare.Current.OpenBrowser("http://motzcod.es", new BrowserOptions() { SafariBarTintColor = new ShareColor(200, 0, 0), SafariControlTintColor = new ShareColor(255, 255, 255), ChromeToolbarColor = new ShareColor(200, 0, 0) });
            };

            buttonShare.Clicked += (sender, args) =>
            {
                var shareMessage = new ShareMessage();
                var shareOptions = new ShareOptions();

                if (switchTitle.IsToggled)
                    shareMessage.Title = "MotzCod.es";
                if (switchText.IsToggled)
                    shareMessage.Text = "Checkout my blog";
                if (switchUrl.IsToggled)
                    shareMessage.Url = "http://motzcod.es";

                if (switchChooserTitle.IsToggled)
                    shareOptions.ChooserTitle = "Share this!";

                CrossShare.Current.Share(shareMessage, shareOptions);
            };

            // The root page of your application
            MainPage = new ContentPage
            {
                Content = new StackLayout
                {
                    VerticalOptions = LayoutOptions.Center,
                    Children =
                    {
                        new Label
                        {
                            XAlign = TextAlignment.Center,
                            Text = "Welcome to Share Plugin Sample!"
                        },
                        button,
                        button1,
                        button2,
                        new Label
                        {
                            XAlign = TextAlignment.Center,
                            Text = "New sharing options:"
                        },
                        new StackLayout
                        {
                            Orientation = StackOrientation.Horizontal,
                            Children = { switchTitle, new Label { Text = "Include title" } }
                        },
                        new StackLayout
                        {
                            Orientation = StackOrientation.Horizontal,
                            Children = { switchText, new Label { Text = "Include text" } }
                        },
                        new StackLayout
                        {
                            Orientation = StackOrientation.Horizontal,
                            Children = { switchUrl, new Label { Text = "Include url" } }
                        },
                        new StackLayout
                        {
                            Orientation = StackOrientation.Horizontal,
                            Children = { switchChooserTitle, new Label { Text = "Include chooser title (Android only)" } }
                        },
                        buttonShare
                    }
                }
            };
        }

        protected override void OnStart()
        {
            // Handle when your app starts
        }

        protected override void OnSleep()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume()
        {
            // Handle when your app resumes
        }
    }
}


text:
<!DOCTYPE html>

<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
<title>gr-popup-interface</title>

<link rel="import" href="../../../test/common-test-setup.html"/>
<link rel="import" href="gr-popup-interface.html"/>

<test-fixture id="container">
  <template>

  </template>
</test-fixture>

<dom-module id="gr-user-test-popup">
  <template>

some test module

  </template>

</dom-module>


text:
Template.postItem.helpers({
  ownPost: function() {
    return this.userId === Meteor.userId();
  },

  openPost: function() {
    post = Posts.findOne({_id: this._id});
    return post.open === true;
  }
});


text:
class AddCommonNameToRelics < ActiveRecord::Migration
  def change
    add_column :relics, :common_name, :string, :default => ""
  end
end


text:
<?php

namespace spec\Sylius\Component\Shipping\Model;

use PhpSpec\ObjectBehavior;
use Sylius\Component\Shipping\Model\ShipmentInterface;
use Sylius\Component\Shipping\Model\ShippableInterface;

/**
 * @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl>
 */
class ShipmentItemSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType('Sylius\Component\Shipping\Model\ShipmentItem');
    }

    function it_implements_Sylius_shipment_item_interface()
    {
        $this->shouldImplement('Sylius\Component\Shipping\Model\ShipmentItemInterface');
    }

    function it_has_no_id_by_default()
    {
        $this->getId()->shouldReturn(null);
    }

    function it_does_not_belong_to_shipment_by_default()
    {
        $this->getShipment()->shouldReturn(null);
    }

    function it_allows_assigning_itself_to_shipment(ShipmentInterface $shipment)
    {
        $this->setShipment($shipment);
        $this->getShipment()->shouldReturn($shipment);
    }

    function it_allows_detaching_itself_from_shipment(ShipmentInterface $shipment)
    {
        $this->setShipment($shipment);
        $this->getShipment()->shouldReturn($shipment);

        $this->setShipment(null);
        $this->getShipment()->shouldReturn(null);
    }

    function it_has_no_shippable_defined_by_default()
    {
        $this->getShippable()->shouldReturn(null);
    }

    function it_allows_defining_shippable(ShippableInterface $shippable)
    {
        $this->setShippable($shippable);
        $this->getShippable()->shouldReturn($shippable);
    }

    function it_has_ready_state_by_default()
    {
        $this->getShippingState()->shouldReturn(ShipmentInterface::STATE_READY);
    }

    function its_state_is_mutable()
    {
        $this->setShippingState(ShipmentInterface::STATE_SHIPPED);
        $this->getShippingState()->shouldReturn(ShipmentInterface::STATE_SHIPPED);
    }

    function it_initializes_creation_date_by_default()
    {
        $this->getCreatedAt()->shouldHaveType('DateTime');
    }

    function its_creation_date_is_mutable()
    {
        $date = new \DateTime();

        $this->setCreatedAt($date);
        $this->getCreatedAt()->shouldReturn($date);
    }

    function it_has_no_last_update_date_by_default()
    {
        $this->getUpdatedAt()->shouldReturn(null);
    }

    function its_last_update_date_is_mutable()
    {
        $date = new \DateTime();

        $this->setUpdatedAt($date);
        $this->getUpdatedAt()->shouldReturn($date);
    }
}


text:
using namespace std;

namespace openlr
{
namespace
{
class EdgeContainer
{
public:
  explicit EdgeContainer(Graph const & graph) : m_graph(graph) {}

  void ProcessEdge(Graph::Edge const & edge)
  {
    CHECK(!edge.IsFake(), ());

    feature::TypesHolder types;
    m_graph.GetFeatureTypes(edge.GetFeatureId(), types);

    ftypes::HighwayClass const hwClass = ftypes::GetHighwayClass(types);
    if (m_minHwClass == ftypes::HighwayClass::Undefined)
    {
      m_minHwClass = hwClass;
      m_maxHwClass = m_minHwClass;
      m_oneWay.m_field = ftypes::IsOneWayChecker::Instance()(types);
      m_roundabout.m_field = ftypes::IsRoundAboutChecker::Instance()(types);
      m_link.m_field = ftypes::IsLinkChecker::Instance()(types);
    }
    else
    {
      m_minHwClass = static_cast<ftypes::HighwayClass>(
          min(base::Underlying(m_minHwClass), base::Underlying(hwClass)));
      m_maxHwClass = static_cast<ftypes::HighwayClass>(
          max(base::Underlying(m_maxHwClass), base::Underlying(hwClass)));

      if (m_oneWay.m_allEqual && m_oneWay.m_field != ftypes::IsOneWayChecker::Instance()(types))
        m_oneWay.m_allEqual = false;

      if (m_roundabout.m_allEqual && m_roundabout.m_field != ftypes::IsRoundAboutChecker::Instance()(types))
        m_roundabout.m_allEqual = false;

      if (m_link.m_allEqual && m_link.m_field != ftypes::IsLinkChecker::Instance()(types))
        m_link.m_allEqual = false;
    }
  }

  uint8_t GetHighwayClassDiff() const
  {
    CHECK_NOT_EQUAL(m_minHwClass, ftypes::HighwayClass::Undefined, ());
    CHECK_GREATER_OR_EQUAL(m_maxHwClass, m_minHwClass, ());

    uint8_t const hwClassDiff = static_cast<uint8_t>(m_maxHwClass) - static_cast<uint8_t>(m_minHwClass);
    return hwClassDiff;
  }

  bool AreAllOneWaysEqual() const { return m_oneWay.m_allEqual; }
  bool AreAllRoundaboutEqual() const { return m_roundabout.m_allEqual; }
  bool AreAllLinksEqual() const { return m_link.m_allEqual; }

private:
  struct Field
  {
    bool m_field = false;
    bool m_allEqual = true;
  };

  Graph const & m_graph;

  ftypes::HighwayClass m_minHwClass = ftypes::HighwayClass::Undefined;
  ftypes::HighwayClass m_maxHwClass = ftypes::HighwayClass::Undefined;
  Field m_oneWay;
  Field m_roundabout;
  Field m_link;
};

/// \returns true if |path| may be used as a candidate. In that case |lenScore| is filled
/// with score of this candidate based on length. The closer length of the |path| to
/// |distanceToNextPoint| the more score.
bool ValidatePathByLength(Graph::EdgeVector const & path, double distanceToNextPoint,
                          LinearSegmentSource source, Score & lenScore)
{
  CHECK(!path.empty(), ());
  CHECK_NOT_EQUAL(source, LinearSegmentSource::NotValid, ());

  Score const kMaxScoreForRouteLen = 110;

  double pathLen = 0.0;
  for (auto const & e : path)
    pathLen += EdgeLength(e);

  // 0 <= |pathDiffRatio| <= 1. The more pathDiffRatio the closer |distanceToNextPoint| and |pathLen|.
  double const pathDiffRatio =
      1.0 - abs(distanceToNextPoint - pathLen) / max(distanceToNextPoint, pathLen);

  bool const shortPath = path.size() <= 2;
  double const kMinValidPathDiffRation =
      source == LinearSegmentSource::FromLocationReferenceTag ? 0.6 : 0.25;
  if (pathDiffRatio <= kMinValidPathDiffRation && !shortPath)
    return false;

  lenScore = static_cast<Score>(kMaxScoreForRouteLen * (pathDiffRatio - kMinValidPathDiffRation) /
                                (1.0 - kMinValidPathDiffRation));

  return true;
}
}  // namespace

ScorePathsConnector::ScorePathsConnector(Graph & graph, RoadInfoGetter & infoGetter, v2::Stats & stat)
  : m_graph(graph), m_infoGetter(infoGetter), m_stat(stat)
{
}

bool ScorePathsConnector::FindBestPath(vector<LocationReferencePoint> const & points,
                                       vector<vector<ScorePath>> const & lineCandidates,
                                       LinearSegmentSource source,
                                       vector<Graph::EdgeVector> & resultPath)
{
  CHECK_NOT_EQUAL(source, LinearSegmentSource::NotValid, ());
  CHECK_GREATER_OR_EQUAL(points.size(), 2, ());

  resultPath.resize(points.size() - 1);

  for (size_t i = 1; i < points.size(); ++i)
  {
    // @TODO It's possible that size of |points| is more then two. In that case two or more edges
    // should be approximated with routes. If so only |toCandidates| which may be reached from
    // |fromCandidates| should be used for the next edge.

    auto const & point = points[i - 1];
    auto const distanceToNextPoint = static_cast<double>(point.m_distanceToNextPoint);
    auto const & fromCandidates = lineCandidates[i - 1];
    auto const & toCandidates = lineCandidates[i];
    auto & resultPathPart = resultPath[i - 1];

    vector<ScorePath> result;
    for (size_t fromInd = 0; fromInd < fromCandidates.size(); ++fromInd)
    {
      for (size_t toInd = 0; toInd < toCandidates.size(); ++toInd)
      {
        Graph::EdgeVector path;
        if (!ConnectAdjacentCandidateLines(fromCandidates[fromInd].m_path,
                                           toCandidates[toInd].m_path, source, point.m_lfrcnp,
                                           distanceToNextPoint, path))
        {
          continue;
        }

        Score pathLenScore = 0;
        if (!ValidatePathByLength(path, distanceToNextPoint, source, pathLenScore))
          continue;

        auto const score = pathLenScore + GetScoreForUniformity(path) +
                           fromCandidates[fromInd].m_score + toCandidates[toInd].m_score;
        result.emplace_back(score, move(path));
      }
    }

    for (auto const & p : result)
      CHECK(!p.m_path.empty(), ());

    if (result.empty())
    {
      LOG(LINFO, ("No shortest path found"));
      ++m_stat.m_noShortestPathFound;
      resultPathPart.clear();
      return false;
    }

    auto const it = max_element(
        result.cbegin(), result.cend(),
        [](ScorePath const & o1, ScorePath const & o2) { return o1.m_score < o2.m_score; });

    // Note. In case of source == LinearSegmentSource::FromCoordinatesTag there is less
    // information about a openlr segment so less score is collected.
    Score const kMinValidScore = source == LinearSegmentSource::FromLocationReferenceTag ? 240 : 165;
    if (it->m_score < kMinValidScore)
    {
      LOG(LINFO, ("The shortest path found but it is not good. The best score:", it->m_score));
      ++m_stat.m_notEnoughScore;
      return false;
    }

    resultPathPart = it->m_path;
    LOG(LDEBUG, ("Best score:", it->m_score, "resultPathPart.size():", resultPathPart.size()));
  }

  CHECK_EQUAL(resultPath.size(), points.size() - 1, ());

  return true;
}

bool ScorePathsConnector::FindShortestPath(Graph::Edge const & from, Graph::Edge const & to,
                                           LinearSegmentSource source,
                                           FunctionalRoadClass lowestFrcToNextPoint,
                                           uint32_t maxPathLength, Graph::EdgeVector & path)
{
  double constexpr kLengthToleranceFactor = 1.1;
  uint32_t constexpr kMinLengthTolerance = 20;
  uint32_t const lengthToleranceM =
      max(static_cast<uint32_t>(kLengthToleranceFactor * maxPathLength), kMinLengthTolerance);

  struct State
  {
    State(Graph::Edge const & e, uint32_t const s) : m_edge(e), m_score(s) {}

    bool operator>(State const & o) const
    {
      return tie(m_score, m_edge) > tie(o.m_score, o.m_edge);
    }

    Graph::Edge m_edge;
    uint32_t m_score;
  };

  CHECK(from.HasRealPart() && to.HasRealPart(), ());

  priority_queue<State, vector<State>, greater<>> q;
  map<Graph::Edge, double> scores;
  map<Graph::Edge, Graph::Edge> links;

  q.emplace(from, 0);
  scores[from] = 0;

  while (!q.empty())
  {
    auto const state = q.top();
    q.pop();

    auto const & stateEdge = state.m_edge;
    // TODO(mgsergio): Unify names: use either score or distance.
    auto const stateScore = state.m_score;

    if (stateScore > maxPathLength + lengthToleranceM)
      continue;

    if (stateScore > scores[stateEdge])
      continue;

    if (stateEdge == to)
    {
      for (auto edge = stateEdge; edge != from; edge = links[edge])
        path.emplace_back(edge);
      path.emplace_back(from);
      reverse(begin(path), end(path));
      return true;
    }

    Graph::EdgeVector edges;
    m_graph.GetOutgoingEdges(stateEdge.GetEndJunction(), edges);
    for (auto const & edge : edges)
    {
      if (source == LinearSegmentSource::FromLocationReferenceTag &&
          !ConformLfrcnpV3(edge, lowestFrcToNextPoint, m_infoGetter))
      {
        continue;
      }

      CHECK(!stateEdge.IsFake(), ());
      CHECK(!edge.IsFake(), ());

      auto const it = scores.find(edge);
      auto const eScore = stateScore + EdgeLength(edge);
      if (it == end(scores) || it->second > eScore)
      {
        scores[edge] = eScore;
        links[edge] = stateEdge;
        q.emplace(edge, eScore);
      }
    }
  }

  return false;
}

bool ScorePathsConnector::ConnectAdjacentCandidateLines(Graph::EdgeVector const & from,
                                                        Graph::EdgeVector const & to,
                                                        LinearSegmentSource source,
                                                        FunctionalRoadClass lowestFrcToNextPoint,
                                                        double distanceToNextPoint,
                                                        Graph::EdgeVector & resultPath)
{
  CHECK(!to.empty(), ());

  if (auto const skip = PathOverlappingLen(from, to))
  {
    if (skip == -1)
      return false;

    resultPath.insert(resultPath.end(), from.cbegin(), from.cend());
    resultPath.insert(resultPath.end(), to.cbegin() + skip, to.cend());
    return true;
  }

  CHECK_NOT_EQUAL(from, to, ());

  Graph::EdgeVector shortestPath;
  auto const found =
      FindShortestPath(from.back(), to.front(), source, lowestFrcToNextPoint,
                       static_cast<uint32_t>(ceil(distanceToNextPoint)), shortestPath);
  if (!found)
    return false;

  CHECK_EQUAL(from.back(), shortestPath.front(), ());
  resultPath.insert(resultPath.end(), from.cbegin(), prev(from.cend()));
  resultPath.insert(resultPath.end(), shortestPath.cbegin(), shortestPath.cend());

  CHECK_EQUAL(to.front(), shortestPath.back(), ());
  resultPath.insert(resultPath.end(), next(to.begin()), to.end());

  return !resultPath.empty();
}

Score ScorePathsConnector::GetScoreForUniformity(Graph::EdgeVector const & path)
{
  EdgeContainer edgeContainer(m_graph);
  for (auto const & edge : path)
    edgeContainer.ProcessEdge(edge);

  auto const hwClassDiff = edgeContainer.GetHighwayClassDiff();
  Score constexpr kScoreForTheSameHwClass = 40;
  Score constexpr kScoreForNeighboringHwClasses = 15;
  Score const hwClassScore = hwClassDiff == 0
                             ? kScoreForTheSameHwClass
                             : hwClassDiff == 1 ? kScoreForNeighboringHwClasses : 0;

  Score constexpr kScoreForOneWayOnly = 17;
  Score constexpr kScoreForRoundaboutOnly = 18;
  Score constexpr kScoreForLinkOnly = 10;
  Score const allEqualScore =
      (edgeContainer.AreAllOneWaysEqual() ? kScoreForOneWayOnly : 0) +
      (edgeContainer.AreAllRoundaboutEqual() ? kScoreForRoundaboutOnly : 0) +
      (edgeContainer.AreAllLinksEqual() ? kScoreForLinkOnly : 0);

  return hwClassScore + allEqualScore;
}
}  // namespace openlr


text:
package com.stefansavev.randomprojections.implementation

import java.util.Random

import com.stefansavev.randomprojections.buffers.{DoubleArrayBuffer, IntArrayBuffer}
import com.stefansavev.randomprojections.datarepr.dense.DataFrameView
import com.stefansavev.randomprojections.datarepr.sparse.SparseVector
import com.stefansavev.randomprojections.implementation.query.NearestNeigbhorQueryScratchBuffer

trait AbstractProjectionVector{
  def getProjectionTypeName: String
}

case class HadamardProjectionVector(signs: SparseVector) extends AbstractProjectionVector{
  def getProjectionTypeName: String  = "hadamardProjectionVector"
}

trait ProjectionStrategy{
  def nextRandomProjection(depth: Int, view: DataFrameView, prevProjection: AbstractProjectionVector): AbstractProjectionVector
}

trait ProjectionStrategyBuilder{
  type T <: ProjectionStrategy
  def build(settings: IndexSettings, rnd: Random, dataFrameView: DataFrameView): T
  def datasetSplitStrategy: DatasetSplitStrategy
}

class SearchBucketsResult(numFeatures: Int, scratch: NearestNeigbhorQueryScratchBuffer){
  var depth: Int = 1
  def tmpInput: Array[Double] = scratch.tmpInput
  def tmpOutput: Array[Double] = scratch.tmpOutput
  val bucketIndexBuffer: IntArrayBuffer = new IntArrayBuffer()
  val bucketScoreBuffer: DoubleArrayBuffer = new DoubleArrayBuffer()
}


text:
require "spec_helper"

describe Geotab::Concerns::Conditionable do
  let(:dummy) { Class.new { extend Geotab::Concerns::Conditionable } }
  let(:conditions) { {"c1" => "v1", "c2" => {"c3" => "v3"}} }

  before :each do
    dummy.conditions.merge!(conditions)
  end

  describe ".conditions" do
    it "should be a simple getter" do
      expect(dummy.conditions).to eq(conditions)
    end
  end

  describe ".clear_conditions" do
    it "should set @conditions to an empty hash" do
      expect{ dummy.clear_conditions }.to change{ dummy.conditions  }.to({})
    end
  end
end


text:
namespace content {
namespace {

std::string GetMandatoryStreamConstraint(
    const WebKit::WebMediaConstraints& constraints, const std::string& key) {
  if (constraints.isNull())
    return std::string();

  WebKit::WebString value;
  constraints.getMandatoryConstraintValue(UTF8ToUTF16(key), value);
  return UTF16ToUTF8(value);
}

void UpdateOptionsIfTabMediaRequest(
    const WebKit::WebUserMediaRequest& user_media_request,
    StreamOptions* options) {
  if (options->audio_type != content::MEDIA_NO_SERVICE &&
      GetMandatoryStreamConstraint(user_media_request.audioConstraints(),
                                   kMediaStreamSource) ==
          kMediaStreamSourceTab) {
    options->audio_type = content::MEDIA_TAB_AUDIO_CAPTURE;
    options->audio_device_id = GetMandatoryStreamConstraint(
        user_media_request.audioConstraints(),
        kMediaStreamSourceId);
  }

  if (options->video_type != content::MEDIA_NO_SERVICE &&
      GetMandatoryStreamConstraint(user_media_request.videoConstraints(),
                                   kMediaStreamSource) ==
          kMediaStreamSourceTab) {
    options->video_type = content::MEDIA_TAB_VIDEO_CAPTURE;
    options->video_device_id = GetMandatoryStreamConstraint(
        user_media_request.videoConstraints(),
        kMediaStreamSourceId);
  }
}

static int g_next_request_id  = 0;

// Creates a WebKit representation of a stream sources based on
// |devices| from the MediaStreamDispatcher.
void CreateWebKitSourceVector(
    const std::string& label,
    const StreamDeviceInfoArray& devices,
    WebKit::WebMediaStreamSource::Type type,
    WebKit::WebVector<WebKit::WebMediaStreamSource>& webkit_sources) {
  CHECK_EQ(devices.size(), webkit_sources.size());
  for (size_t i = 0; i < devices.size(); ++i) {
    const char* track_type =
        (type == WebKit::WebMediaStreamSource::TypeAudio) ? "a" : "v";
    std::string source_id = StringPrintf("%s%s%u", label.c_str(),
                                         track_type,
                                         static_cast<unsigned int>(i));
    webkit_sources[i].initialize(
          UTF8ToUTF16(source_id),
          type,
          UTF8ToUTF16(devices[i].device.name));
    webkit_sources[i].setExtraData(
        new content::MediaStreamSourceExtraData(devices[i]));
  }
}

webrtc::MediaStreamInterface* GetNativeMediaStream(
    const WebKit::WebMediaStreamDescriptor& descriptor) {
  content::MediaStreamExtraData* extra_data =
      static_cast<content::MediaStreamExtraData*>(descriptor.extraData());
  if (!extra_data)
    return NULL;
  webrtc::MediaStreamInterface* stream = extra_data->local_stream();
  if (!stream)
    stream = extra_data->remote_stream();
  return stream;
}

}  // namespace

MediaStreamImpl::MediaStreamImpl(
    RenderView* render_view,
    MediaStreamDispatcher* media_stream_dispatcher,
    VideoCaptureImplManager* vc_manager,
    MediaStreamDependencyFactory* dependency_factory)
    : RenderViewObserver(render_view),
      dependency_factory_(dependency_factory),
      media_stream_dispatcher_(media_stream_dispatcher),
      vc_manager_(vc_manager) {
}

MediaStreamImpl::~MediaStreamImpl() {
}

void MediaStreamImpl::OnLocalMediaStreamStop(
    const std::string& label) {
  DVLOG(1) << "MediaStreamImpl::OnLocalMediaStreamStop(" << label << ")";

  UserMediaRequestInfo* user_media_request = FindUserMediaRequestInfo(label);
  if (user_media_request) {
    media_stream_dispatcher_->StopStream(label);
    DeleteUserMediaRequestInfo(user_media_request);
  } else {
    DVLOG(1) << "MediaStreamImpl::OnLocalMediaStreamStop: the stream has "
             << "already been stopped.";
  }
}

void MediaStreamImpl::requestUserMedia(
    const WebKit::WebUserMediaRequest& user_media_request,
    const WebKit::WebVector<WebKit::WebMediaStreamSource>& audio_sources,
    const WebKit::WebVector<WebKit::WebMediaStreamSource>& video_sources) {
  // Save histogram data so we can see how much GetUserMedia is used.
  // The histogram counts the number of calls to the JS API
  // webGetUserMedia.
  UpdateWebRTCMethodCount(WEBKIT_GET_USER_MEDIA);
  DCHECK(CalledOnValidThread());
  int request_id = g_next_request_id++;
  StreamOptions options(MEDIA_NO_SERVICE, MEDIA_NO_SERVICE);
  WebKit::WebFrame* frame = NULL;
  GURL security_origin;

  // |user_media_request| can't be mocked. So in order to test at all we check
  // if it isNull.
  if (user_media_request.isNull()) {
    // We are in a test.
    if (audio_sources.size() > 0)
      options.audio_type = MEDIA_DEVICE_AUDIO_CAPTURE;
    if (video_sources.size() > 0)
      options.video_type = MEDIA_DEVICE_VIDEO_CAPTURE;
  } else {
    if (user_media_request.audio())
      options.audio_type = MEDIA_DEVICE_AUDIO_CAPTURE;
    if (user_media_request.video())
      options.video_type = MEDIA_DEVICE_VIDEO_CAPTURE;

    security_origin = GURL(user_media_request.securityOrigin().toString());
    // Get the WebFrame that requested a MediaStream.
    // The frame is needed to tell the MediaStreamDispatcher when a stream goes
    // out of scope.
    frame = user_media_request.ownerDocument().frame();
    DCHECK(frame);

    UpdateOptionsIfTabMediaRequest(user_media_request, &options);
  }

  DVLOG(1) << "MediaStreamImpl::requestUserMedia(" << request_id << ", [ "
           << "audio=" << (options.audio_type)
           << ", video=" << (options.video_type) << " ], "
           << security_origin.spec() << ")";

  user_media_requests_.push_back(
      new UserMediaRequestInfo(request_id, frame, user_media_request));

  media_stream_dispatcher_->GenerateStream(
      request_id,
      AsWeakPtr(),
      options,
      security_origin);
}

void MediaStreamImpl::cancelUserMediaRequest(
    const WebKit::WebUserMediaRequest& user_media_request) {
  DCHECK(CalledOnValidThread());
  UserMediaRequestInfo* request = FindUserMediaRequestInfo(user_media_request);
  if (request) {
    // We can't abort the stream generation process.
    // Instead, erase the request. Once the stream is generated we will stop the
    // stream if the request does not exist.
    DeleteUserMediaRequestInfo(request);
  }
}

WebKit::WebMediaStreamDescriptor MediaStreamImpl::GetMediaStream(
    const GURL& url) {
  return WebKit::WebMediaStreamRegistry::lookupMediaStreamDescriptor(url);
}

bool MediaStreamImpl::IsMediaStream(const GURL& url) {
  return CheckMediaStream(url);
}

// static
bool MediaStreamImpl::CheckMediaStream(const GURL& url) {
  WebKit::WebMediaStreamDescriptor descriptor(
      WebKit::WebMediaStreamRegistry::lookupMediaStreamDescriptor(url));

  if (descriptor.isNull() || !descriptor.extraData())
    return false;  // This is not a valid stream.

  webrtc::MediaStreamInterface* stream = GetNativeMediaStream(descriptor);
  return stream &&
         ((stream->video_tracks() && stream->video_tracks()->count() > 0) ||
          (stream->audio_tracks() && stream->audio_tracks()->count() > 0));
}

scoped_refptr<webkit_media::VideoFrameProvider>
MediaStreamImpl::GetVideoFrameProvider(
    const GURL& url,
    const base::Closure& error_cb,
    const webkit_media::VideoFrameProvider::RepaintCB& repaint_cb) {
  DCHECK(CalledOnValidThread());
  WebKit::WebMediaStreamDescriptor descriptor(GetMediaStream(url));

  if (descriptor.isNull() || !descriptor.extraData())
    return NULL;  // This is not a valid stream.

  DVLOG(1) << "MediaStreamImpl::GetVideoFrameProvider stream:"
           << UTF16ToUTF8(descriptor.label());

  webrtc::MediaStreamInterface* stream = GetNativeMediaStream(descriptor);
  if (stream)
    return CreateVideoFrameProvider(stream, error_cb, repaint_cb);
  NOTREACHED();
  return NULL;
}

scoped_refptr<media::VideoDecoder> MediaStreamImpl::GetVideoDecoder(
    const GURL& url,
    const scoped_refptr<base::MessageLoopProxy>& message_loop) {
  DCHECK(CalledOnValidThread());
  WebKit::WebMediaStreamDescriptor descriptor(GetMediaStream(url));

  if (descriptor.isNull() || !descriptor.extraData())
    return NULL;  // This is not a valid stream.

  DVLOG(1) << "MediaStreamImpl::GetVideoDecoder stream:"
           << UTF16ToUTF8(descriptor.label());

  webrtc::MediaStreamInterface* stream = GetNativeMediaStream(descriptor);
  if (stream)
    return CreateVideoDecoder(stream, message_loop);
  NOTREACHED();
  return NULL;
}

scoped_refptr<webkit_media::MediaStreamAudioRenderer>
MediaStreamImpl::GetAudioRenderer(const GURL& url) {
  DCHECK(CalledOnValidThread());
  WebKit::WebMediaStreamDescriptor descriptor(GetMediaStream(url));

  if (descriptor.isNull() || !descriptor.extraData())
    return NULL;  // This is not a valid stream.

  DVLOG(1) << "MediaStreamImpl::GetAudioRenderer stream:"
           << UTF16ToUTF8(descriptor.label());

  MediaStreamExtraData* extra_data =
      static_cast<MediaStreamExtraData*>(descriptor.extraData());

  if (extra_data->remote_stream()) {
    WebRtcAudioDeviceImpl* audio_device =
        dependency_factory_->GetWebRtcAudioDevice();

    // Share the existing renderer if any, otherwise create a new one.
    scoped_refptr<WebRtcAudioRenderer> renderer(audio_device->renderer());
    if (!renderer) {
      renderer = CreateRemoteAudioRenderer(extra_data->remote_stream());

      if (renderer && !audio_device->SetRenderer(renderer))
        renderer = NULL;
    }

    return renderer;
  } else if (extra_data->local_stream()) {
    // Create the local audio renderer if the stream contains audio tracks.
    return CreateLocalAudioRenderer(extra_data->local_stream());
  }

  NOTREACHED();
  return NULL;
}

// Callback from MediaStreamDispatcher.
// The requested stream have been generated by the MediaStreamDispatcher.
void MediaStreamImpl::OnStreamGenerated(
    int request_id,
    const std::string& label,
    const StreamDeviceInfoArray& audio_array,
    const StreamDeviceInfoArray& video_array) {
  DCHECK(CalledOnValidThread());
  DVLOG(1) << "MediaStreamImpl::OnStreamGenerated stream:" << label;

  UserMediaRequestInfo* request_info = FindUserMediaRequestInfo(request_id);
  if (!request_info) {
    // This can happen if the request is canceled or the frame reloads while
    // MediaStreamDispatcher is processing the request.
    // We need to tell the dispatcher to stop the stream.
    media_stream_dispatcher_->StopStream(label);
    DVLOG(1) << "Request ID not found";
    return;
  }
  request_info->generated = true;

  WebKit::WebVector<WebKit::WebMediaStreamSource> audio_source_vector(
      audio_array.size());
  CreateWebKitSourceVector(label, audio_array,
                           WebKit::WebMediaStreamSource::TypeAudio,
                           audio_source_vector);
  WebKit::WebVector<WebKit::WebMediaStreamSource> video_source_vector(
      video_array.size());
  CreateWebKitSourceVector(label, video_array,
                           WebKit::WebMediaStreamSource::TypeVideo,
                           video_source_vector);

  WebKit::WebUserMediaRequest* request = &(request_info->request);
  WebKit::WebString webkit_label = UTF8ToUTF16(label);
  WebKit::WebMediaStreamDescriptor* description = &(request_info->descriptor);

  description->initialize(webkit_label, audio_source_vector,
                          video_source_vector);

  // WebUserMediaRequest don't have an implementation in unit tests.
  // Therefore we need to check for isNull here.
  WebKit::WebMediaConstraints audio_constraints = request->isNull() ?
      WebKit::WebMediaConstraints() : request->audioConstraints();
  WebKit::WebMediaConstraints video_constraints = request->isNull() ?
      WebKit::WebMediaConstraints() : request->videoConstraints();

  dependency_factory_->CreateNativeMediaSources(
      audio_constraints, video_constraints, description,
      base::Bind(&MediaStreamImpl::OnCreateNativeSourcesComplete, AsWeakPtr()));
}

// Callback from MediaStreamDispatcher.
// The requested stream failed to be generated.
void MediaStreamImpl::OnStreamGenerationFailed(int request_id) {
  DCHECK(CalledOnValidThread());
  DVLOG(1) << "MediaStreamImpl::OnStreamGenerationFailed("
           << request_id << ")";
  UserMediaRequestInfo* request_info = FindUserMediaRequestInfo(request_id);
  if (!request_info) {
    // This can happen if the request is canceled or the frame reloads while
    // MediaStreamDispatcher is processing the request.
    DVLOG(1) << "Request ID not found";
    return;
  }
  CompleteGetUserMediaRequest(request_info->descriptor,
                              &request_info->request,
                              false);
  DeleteUserMediaRequestInfo(request_info);
}

// Callback from MediaStreamDependencyFactory when the sources in |description|
// have been generated.
void MediaStreamImpl::OnCreateNativeSourcesComplete(
    WebKit::WebMediaStreamDescriptor* description,
    bool request_succeeded) {
  DVLOG(1) << "MediaStreamImpl::OnCreateNativeSourcesComplete stream:"
           << UTF16ToUTF8(description->label());
  UserMediaRequestInfo* request_info = FindUserMediaRequestInfo(description);
  if (!request_info) {
    // This can happen if the request is canceled or the frame reloads while
    // MediaStreamDependencyFactory is creating the sources.
    DVLOG(1) << "Request ID not found";
    return;
  }

  // Create a native representation of the stream.
  if (request_succeeded) {
    dependency_factory_->CreateNativeLocalMediaStream(
        description,
        base::Bind(&MediaStreamImpl::OnLocalMediaStreamStop, AsWeakPtr()));
  }
  CompleteGetUserMediaRequest(request_info->descriptor, &request_info->request,
                              request_succeeded);
  if (!request_succeeded) {
    OnLocalMediaStreamStop(UTF16ToUTF8(description->label()));
  }
}

void MediaStreamImpl::OnDevicesEnumerated(
    int request_id,
    const StreamDeviceInfoArray& device_array) {
  DVLOG(1) << "MediaStreamImpl::OnDevicesEnumerated("
           << request_id << ")";
  NOTIMPLEMENTED();
}

void MediaStreamImpl::OnDevicesEnumerationFailed(int request_id) {
  DVLOG(1) << "MediaStreamImpl::OnDevicesEnumerationFailed("
           << request_id << ")";
  NOTIMPLEMENTED();
}

void MediaStreamImpl::OnDeviceOpened(
    int request_id,
    const std::string& label,
    const StreamDeviceInfo& video_device) {
  DVLOG(1) << "MediaStreamImpl::OnDeviceOpened("
           << request_id << ", " << label << ")";
  NOTIMPLEMENTED();
}

void MediaStreamImpl::OnDeviceOpenFailed(int request_id) {
  DVLOG(1) << "MediaStreamImpl::VideoDeviceOpenFailed("
           << request_id << ")";
  NOTIMPLEMENTED();
}

void MediaStreamImpl::CompleteGetUserMediaRequest(
    const WebKit::WebMediaStreamDescriptor& stream,
    WebKit::WebUserMediaRequest* request_info,
    bool request_succeeded) {
  if (request_succeeded) {
    request_info->requestSucceeded(stream);
  } else {
    request_info->requestFailed();
  }
}

MediaStreamImpl::UserMediaRequestInfo*
MediaStreamImpl::FindUserMediaRequestInfo(int request_id) {
  UserMediaRequests::iterator it = user_media_requests_.begin();
  for (; it != user_media_requests_.end(); ++it) {
    if ((*it)->request_id == request_id)
      return (*it);
  }
  return NULL;
}

MediaStreamImpl::UserMediaRequestInfo*
MediaStreamImpl::FindUserMediaRequestInfo(
    const WebKit::WebUserMediaRequest& request) {
  UserMediaRequests::iterator it = user_media_requests_.begin();
  for (; it != user_media_requests_.end(); ++it) {
    if ((*it)->request == request)
      return (*it);
  }
  return NULL;
}

MediaStreamImpl::UserMediaRequestInfo*
MediaStreamImpl::FindUserMediaRequestInfo(const std::string& label) {
  UserMediaRequests::iterator it = user_media_requests_.begin();
  for (; it != user_media_requests_.end(); ++it) {
    if ((*it)->generated && (*it)->descriptor.label() == UTF8ToUTF16(label))
      return (*it);
  }
  return NULL;
}

MediaStreamImpl::UserMediaRequestInfo*
MediaStreamImpl::FindUserMediaRequestInfo(
    WebKit::WebMediaStreamDescriptor* descriptor) {
  UserMediaRequests::iterator it = user_media_requests_.begin();
  for (; it != user_media_requests_.end(); ++it) {
    if (&((*it)->descriptor) == descriptor)
      return  (*it);
  }
  return NULL;
}

void MediaStreamImpl::DeleteUserMediaRequestInfo(
    UserMediaRequestInfo* request) {
  UserMediaRequests::iterator it = user_media_requests_.begin();
  for (; it != user_media_requests_.end(); ++it) {
    if ((*it) == request) {
      user_media_requests_.erase(it);
      return;
    }
  }
  NOTREACHED();
}

void MediaStreamImpl::FrameWillClose(WebKit::WebFrame* frame) {
  // Loop through all UserMediaRequests and find the requests that belong to the
  // frame that is being closed.
  UserMediaRequests::iterator request_it = user_media_requests_.begin();

  while (request_it != user_media_requests_.end()) {
    if ((*request_it)->frame == frame) {
      DVLOG(1) << "MediaStreamImpl::FrameWillClose: "
               << "Cancel user media request " << (*request_it)->request_id;
      // If the request is generated, it means that the MediaStreamDispatcher
      // has generated a stream for us and we need to let the
      // MediaStreamDispatcher know that the stream is no longer wanted.
      // If not, we cancel the request and delete the request object.
      if ((*request_it)->generated) {
        media_stream_dispatcher_->StopStream(
            UTF16ToUTF8((*request_it)->descriptor.label()));
      } else {
        media_stream_dispatcher_->CancelGenerateStream(
            (*request_it)->request_id);
      }
      request_it = user_media_requests_.erase(request_it);
    } else {
      ++request_it;
    }
  }
}

scoped_refptr<webkit_media::VideoFrameProvider>
MediaStreamImpl::CreateVideoFrameProvider(
    webrtc::MediaStreamInterface* stream,
    const base::Closure& error_cb,
    const webkit_media::VideoFrameProvider::RepaintCB& repaint_cb) {
  if (!stream->video_tracks() || stream->video_tracks()->count() == 0)
    return NULL;

  DVLOG(1) << "MediaStreamImpl::CreateRemoteVideoFrameProvider label:"
           << stream->label();

  return new RTCVideoRenderer(
      stream->video_tracks()->at(0),
      error_cb,
      repaint_cb);
}

scoped_refptr<media::VideoDecoder> MediaStreamImpl::CreateVideoDecoder(
    webrtc::MediaStreamInterface* stream,
    const scoped_refptr<base::MessageLoopProxy>& message_loop) {
  if (!stream->video_tracks() || stream->video_tracks()->count() == 0)
    return NULL;

  DVLOG(1) << "MediaStreamImpl::CreateRemoteVideoDecoder label:"
           << stream->label();

  return new RTCVideoDecoder(
      message_loop,
      base::MessageLoopProxy::current(),
      stream->video_tracks()->at(0));
}

scoped_refptr<WebRtcAudioRenderer> MediaStreamImpl::CreateRemoteAudioRenderer(
    webrtc::MediaStreamInterface* stream) {
  if (!stream->audio_tracks() || stream->audio_tracks()->count() == 0)
    return NULL;

  DVLOG(1) << "MediaStreamImpl::CreateRemoteAudioRenderer label:"
           << stream->label();

  return new WebRtcAudioRenderer(RenderViewObserver::routing_id());
}

scoped_refptr<WebRtcLocalAudioRenderer>
MediaStreamImpl::CreateLocalAudioRenderer(
    webrtc::MediaStreamInterface* stream) {
  if (!stream->audio_tracks() || stream->audio_tracks()->count() == 0)
    return NULL;

  DVLOG(1) << "MediaStreamImpl::CreateLocalAudioRenderer label:"
           << stream->label();

  scoped_refptr<WebRtcAudioCapturer> source =
      dependency_factory_->GetWebRtcAudioDevice()->capturer();
  if (!source) {
    return NULL;
  }

  // Create a new WebRtcLocalAudioRenderer instance and connect it to the
  // existing WebRtcAudioCapturer so that the renderer can use it as source.
  return new WebRtcLocalAudioRenderer(source, RenderViewObserver::routing_id());
}

MediaStreamSourceExtraData::MediaStreamSourceExtraData(
    const StreamDeviceInfo& device_info)
    : device_info_(device_info) {
}

MediaStreamSourceExtraData::MediaStreamSourceExtraData(
    media::AudioCapturerSource* source)
    : audio_source_(source)  {
}

MediaStreamSourceExtraData::~MediaStreamSourceExtraData() {}

MediaStreamExtraData::MediaStreamExtraData(
    webrtc::MediaStreamInterface* remote_stream)
    : remote_stream_(remote_stream) {
}

MediaStreamExtraData::MediaStreamExtraData(
    webrtc::LocalMediaStreamInterface* local_stream)
    : local_stream_(local_stream) {
}

MediaStreamExtraData::~MediaStreamExtraData() {
}

void MediaStreamExtraData::SetLocalStreamStopCallback(
    const StreamStopCallback& stop_callback) {
  stream_stop_callback_ = stop_callback;
}

void MediaStreamExtraData::OnLocalStreamStop() {
  if (!stream_stop_callback_.is_null())
    stream_stop_callback_.Run(local_stream_->label());
}

}  // namespace content


text:
package com.example.javaee.SampleProjectJAXRS.model;

public class A {

    private int id;

    private String name;

    private B b;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public B getB() {
        return b;
    }

    public void setB(B b) {
        this.b = b;
    }

}


text:
My Arduino Sketches.

If anyone is interested enough to read a blog article about how I did any
of these, please contact me and I'll write one.

## test-128x64ZW

Simple test of driving a 128x64 LCD display using U8Glib. Set up for a ST7920
via SPI, but any of the other U8Glibsupported types would work, of course.

## Distance1

Sinmple read of an ultrasonic distance sensor, giving a time of flight in
microseconds and distance in centimetres over the serial interface.

## MCP23017-first

Drive an I2C connected MCP23017. Set up for 8 LEDs attached to GPA0-7, a button
attached to GPB0 and another LED to GPB1, controlled by the button.

### MCP library

A simple library to drive the MCP23017, which allows for setting pin direction
individually and in bulk, and reading and writing of the pins indivdually and in bulk.

## Keypad1

Simple read of a 4x4 keypad, using the Keypad library, outputting the pressed
keys over the serial link.

## ReadJoysticks

Read 2 analog joysticks and output the raw values over the serial link.

## Stepper1

Drive a 28BYJ-48 stepper motor via its interface board continually one
revolution clockwise, then counter-clockwise. The time for a revolution and
hence the RPM are output on the serial link.

## LCD-first

Very minimal check of a connected LCD display.

## WS1812B

Use the Adafruit NeoPixel library to drive my 8-LCD pixel bar with a rainbow pattern.
Updated to 24 LCDs.

## stepper-driver

## Badge1

First version of the sketch for my proximity badge. This one just displays the
distance from an ultrasonic distance sensor in different colours of the NeoPixel strip.

## Badge2

Second version of the proximity badge, which has the added 4x20 LCD. The LCD is cleared
when there is no one around. Now that I know how to turn the backlight on and off
under program control, I will do that next time.

## Joysticks-128x64

## Joysticks-128x64-Graphic

## Keypad-MC17-4x4

Read a 4x4 keypad connected to a MCP23017 i2c interface and output the pressed
keys to the serial link.

## Keypad-MC17-4x3-128x64

Read a 4x3 keypad connected to a MCP23017 i2c interface and output the pressed
keys to the LCD screen.

## Keypad-MC17-4x4-Multi

Read a 4x4 keypad connected to a MCP23017 i2c interface and output the key press,
release, and hold information to the serial link.

## LCD-Joysticks

## LDR-Reader-128x64

## Stepper-MCP

## Sweep

Sweep a servo from one end to the other, using the Servo library.

## conway-life-128x64

[John Conway's game of life](http://www.conwaylife.com/) implemented on the
128x64 LCD. Updated to use the newly discovered
[Copperhead](http://conwaylife.com/wiki/Copperhead)
spaceship which goes across the screen in a little over 500 generations.

## keypad-MC17-stepper

## keypad-stepper

## meArm

## Oscilloscope1

Simple oscilloscope which outputs to a 128x64 display. Initially set to 1V per
division vertically and 100ms per division horizontally. Updates twice a second.

Tested with the output from a 2 transistor oscillator at about 4Hz.


text:
/**
@module ember
@submodule ember-runtime
*/

import Ember from 'ember';
import replace from './utils/replace';
import SortableMixin from './utils/sortable-mixin';

const {
  ArrayProxy,
  ControllerMixin,
  Error: EmberError,
  Array: EmberArray,
  computed,
  get,
} = Ember;

/**
  `Ember.ArrayController` provides a way for you to publish a collection of
  objects so that you can easily bind to the collection from a Handlebars
  `#each` helper, an `Ember.CollectionView`, or other controllers.

  The advantage of using an `ArrayController` is that you only have to set up
  your view bindings once; to change what's displayed, simply swap out the
  `model` property on the controller.

  For example, imagine you wanted to display a list of items fetched via an XHR
  request. Create an `Ember.ArrayController` and set its `model` property:

  ```javascript
  MyApp.listController = Ember.ArrayController.create();

  $.get('people.json', function(data) {
    MyApp.listController.set('model', data);
  });
  ```

  Then, create a view that binds to your new controller:

  ```handlebars
  {{#each MyApp.listController as |person|}}
    {{person.firstName}} {{person.lastName}}
  {{/each}}
  ```

  Although you are binding to the controller, the behavior of this controller
  is to pass through any methods or properties to the underlying array. This
  capability comes from `Ember.ArrayProxy`, which this class inherits from.

  Sometimes you want to display computed properties within the body of an
  `#each` helper that depend on the underlying items in `model`, but are not
  present on those items.   To do this, set `itemController` to the name of a
  controller (probably an `ObjectController`) that will wrap each individual item.

  For example:

  ```handlebars
  {{#each controller as |post|}}
    <li>{{post.title}} ({{post.titleLength}} characters)</li>
  {{/each}}
  ```

  ```javascript
  App.PostsController = Ember.ArrayController.extend({
    itemController: 'post'
  });

  App.PostController = Ember.ObjectController.extend({
    // the `title` property will be proxied to the underlying post.
    titleLength: function() {
      return this.get('title').length;
    }.property('title')
  });
  ```

  In some cases it is helpful to return a different `itemController` depending
  on the particular item.  Subclasses can do this by overriding
  `lookupItemController`.

  For example:

  ```javascript
  App.MyArrayController = Ember.ArrayController.extend({
    lookupItemController: function( object ) {
      if (object.get('isSpecial')) {
        return "special"; // use App.SpecialController
      } else {
        return "regular"; // use App.RegularController
      }
    }
  });
  ```

  The itemController instances will have a `parentController` property set to
  the `ArrayController` instance.

  @class ArrayController
  @namespace Ember
  @extends Ember.ArrayProxy
  @uses Ember.SortableMixin
  @uses Ember.ControllerMixin
  @deprecated
  @public
*/

export default ArrayProxy.extend(ControllerMixin, SortableMixin, {
  /*
    Duck typing to support this legacy controllers from the each helper in Ember's view layer
  */
  _isArrayController: true,

  /**
    A string containing the controller name used to wrap items.

    For example:

    ```javascript
    App.MyArrayController = Ember.ArrayController.extend({
      itemController: 'myItem' // use App.MyItemController
    });
    ```

    @property itemController
    @type String
    @default null
    @private
  */
  itemController: null,

  /**
    Return the name of the controller to wrap items, or `null` if items should
    be returned directly.  The default implementation simply returns the
    `itemController` property, but subclasses can override this method to return
    different controllers for different objects.

    For example:

    ```javascript
    App.MyArrayController = Ember.ArrayController.extend({
      lookupItemController: function( object ) {
        if (object.get('isSpecial')) {
          return "special"; // use App.SpecialController
        } else {
          return "regular"; // use App.RegularController
        }
      }
    });
    ```

    @method lookupItemController
    @param {Object} object
    @return {String}
    @private
  */
  lookupItemController() {
    return get(this, 'itemController');
  },

  objectAtContent(idx) {
    var length = get(this, 'length');
    var arrangedContent = get(this, 'arrangedContent');
    var object = arrangedContent && arrangedContent.objectAt(idx);
    var controllerClass;

    if (idx >= 0 && idx < length) {
      controllerClass = this.lookupItemController(object);

      if (controllerClass) {
        return this.controllerAt(idx, object, controllerClass);
      }
    }

    // When `controllerClass` is falsy, we have not opted in to using item
    // controllers, so return the object directly.

    // When the index is out of range, we want to return the "out of range"
    // value, whatever that might be.  Rather than make assumptions
    // (e.g. guessing `null` or `undefined`) we defer this to `arrangedContent`.
    return object;
  },

  arrangedContentDidChange() {
    this._super(...arguments);
    this._resetSubControllers();
  },

  arrayContentDidChange(idx, removedCnt, addedCnt) {
    var subControllers = this._subControllers;

    if (subControllers.length) {
      var subControllersToRemove = subControllers.slice(idx, idx + removedCnt);

      subControllersToRemove.forEach(function(subController) {
        if (subController) {
          subController.destroy();
        }
      });

      replace(subControllers, idx, removedCnt, new Array(addedCnt));
    }

    // The shadow array of subcontrollers must be updated before we trigger
    // observers, otherwise observers will get the wrong subcontainer when
    // calling `objectAt`
    this._super(idx, removedCnt, addedCnt);
  },

  init() {
    this._super(...arguments);
    this._subControllers = [];
  },

  model: computed({
    get() {
      return Ember.A();
    },
    set(key, value) {
      Ember.assert(
        'ArrayController expects `model` to implement the Ember.Array mixin. ' +
        'This can often be fixed by wrapping your model with `Ember.A()`.',
        EmberArray.detect(value) || !value
      );

      return value;
    }
  }),

  /**
    Flag to mark as being "virtual". Used to keep this instance
    from participating in the parentController hierarchy.

    @private
    @property _isVirtual
    @type Boolean
  */
  _isVirtual: false,

  controllerAt(idx, object, controllerClass) {
    var container = get(this, 'container');
    var subControllers = this._subControllers;
    var fullName, subController, parentController;

    if (subControllers.length > idx) {
      subController = subControllers[idx];

      if (subController) {
        return subController;
      }
    }

    if (this._isVirtual) {
      parentController = get(this, 'parentController');
    } else {
      parentController = this;
    }

    fullName = 'controller:' + controllerClass;

    if (!container._registry.has(fullName)) {
      throw new EmberError('Could not resolve itemController: "' + controllerClass + '"');
    }

    subController = container.lookupFactory(fullName).create({
      target: parentController,
      parentController: parentController,
      model: object
    });

    subControllers[idx] = subController;

    return subController;
  },

  _subControllers: null,

  _resetSubControllers() {
    var controller;
    var subControllers = this._subControllers;

    if (subControllers.length) {
      for (var i = 0, length = subControllers.length; length > i; i++) {
        controller = subControllers[i];

        if (controller) {
          controller.destroy();
        }
      }

      subControllers.length = 0;
    }
  },

  willDestroy() {
    this._resetSubControllers();
    this._super(...arguments);
  }
});