text:
import React from "react";
import {
  DefaultFarmwareStep, FarmwareName, TileExecuteScript,
} from "../tile_execute_script";
import { mount, shallow } from "enzyme";
import { ExecuteScript } from "farmbot/dist";
import { StepParams } from "../../interfaces";
import { Actions } from "../../../constants";
import {
  fakeFarmwareData, fakeStepParams,
} from "../../../__test_support__/fake_sequence_step_data";

describe("<TileExecuteScript />", () => {
  const fakeProps = (): StepParams<ExecuteScript> => {
    const farmwareData = fakeFarmwareData();
    farmwareData.farmwareNames = ["one", "two", "three"];
    farmwareData.firstPartyFarmwareNames = ["one"];
    farmwareData.farmwareConfigs = { "farmware-to-execute": [] };
    return {
      ...fakeStepParams({
        kind: "execute_script",
        args: { label: "farmware-to-execute" }
      }),
      farmwareData,
    };
  };

  it("renders inputs", () => {
    const wrapper = mount(<TileExecuteScript {...fakeProps()} />);
    const inputs = wrapper.find("input");
    const labels = wrapper.find("label");
    expect(inputs.length).toEqual(2);
    expect(labels.length).toEqual(2);
    expect(inputs.first().props().placeholder).toEqual("Run Farmware");
    expect(labels.at(0).text()).toEqual("Package Name");
    expect(labels.at(1).text()).toEqual("Manual input");
    expect(inputs.at(1).props().value).toEqual("farmware-to-execute");
  });

  it("renders farmware list", () => {
    const wrapper = shallow(<DefaultFarmwareStep {...fakeProps()} />);
    expect(wrapper.find("FBSelect").props().list).toEqual([
      { label: "two", value: "two" },
      { label: "three", value: "three" },
    ]);
  });

  it("doesn't show 1st party in list", () => {
    const p = fakeProps();
    p.farmwareData && (p.farmwareData.showFirstPartyFarmware = true);
    const wrapper = shallow(<DefaultFarmwareStep {...p} />);
    expect(wrapper.find("FBSelect").props().list).toEqual([
      { label: "two", value: "two" },
      { label: "three", value: "three" },
    ]);
  });

  it("doesn't show manual input if installed farmware is selected", () => {
    const p = fakeProps();
    p.currentStep.args.label = "two";
    const wrapper = mount(<TileExecuteScript {...p} />);
    expect(wrapper.find("label").length).toEqual(1);
  });

  it("shows special 1st-party Farmware name: plant detection", () => {
    const p = fakeProps();
    p.currentStep.args.label = FarmwareName.PlantDetection;
    p.farmwareData?.farmwareNames.push(FarmwareName.PlantDetection);
    const wrapper = mount(<TileExecuteScript {...p} />);
    expect(wrapper.find("label").length).toEqual(0);
    expect(wrapper.text().toLowerCase())
      .toContain("results are viewable from the photos panel.");
    expect(wrapper.text().toLowerCase()).not.toContain("package");
  });

  it("shows special 1st-party Farmware name: measure soil height", () => {
    const p = fakeProps();
    p.currentStep.args.label = FarmwareName.MeasureSoilHeight;
    p.farmwareData?.farmwareNames.push(FarmwareName.MeasureSoilHeight);
    const wrapper = mount(<TileExecuteScript {...p} />);
    expect(wrapper.find("label").length).toEqual(0);
    expect(wrapper.text().toLowerCase())
      .toContain("results are viewable in the points panel.");
    expect(wrapper.text().toLowerCase()).not.toContain("package");
  });

  it("renders manual input", () => {
    const p = fakeProps();
    p.farmwareData = undefined;
    const wrapper = mount(<TileExecuteScript {...p} />);
    expect(wrapper.find("button").text()).toEqual("Manual Input");
    expect(wrapper.find("label").at(1).text()).toEqual("Manual input");
    expect(wrapper.find("input").at(1).props().value)
      .toEqual("farmware-to-execute");
  });

  it("uses drop-down to update step", () => {
    const p = fakeProps();
    const wrapper = shallow(<DefaultFarmwareStep {...p} />);
    wrapper.find("FBSelect").simulate("change", {
      label: "farmware-name",
      value: "farmware-name"
    });
    expect(p.dispatch).toHaveBeenCalledWith({
      payload: expect.objectContaining({
        update: expect.objectContaining({
          body: [{ kind: "execute_script", args: { label: "farmware-name" } }]
        })
      }),
      type: Actions.OVERWRITE_RESOURCE
    });
  });

  it("clears body when switching Farmware", () => {
    const p = fakeProps();
    p.currentStep.body = [
      { kind: "pair", args: { label: "x", value: 1 }, comment: "X" }];
    const wrapper = shallow(<DefaultFarmwareStep {...p} />);
    wrapper.find("FBSelect").simulate("change", {
      label: "farmware-name",
      value: "farmware-name"
    });
    expect(p.dispatch).toHaveBeenCalledWith({
      payload: expect.objectContaining({
        update: expect.objectContaining({
          body: [{ kind: "execute_script", args: { label: "farmware-name" } }]
        })
      }),
      type: Actions.OVERWRITE_RESOURCE
    });
  });

  it("displays warning when camera is disabled", () => {
    const p = fakeProps();
    p.currentStep.args.label = FarmwareName.PlantDetection;
    p.farmwareData && (p.farmwareData.cameraDisabled = true);
    const wrapper = mount(<TileExecuteScript {...p} />);
    expect(wrapper.html()).toContain("fa-exclamation-triangle");
  });

  it("displays warning when camera is uncalibrated", () => {
    const p = fakeProps();
    p.currentStep.args.label = FarmwareName.PlantDetection;
    p.farmwareData && (p.farmwareData.cameraCalibrated = false);
    const wrapper = mount(<TileExecuteScript {...p} />);
    expect(wrapper.html()).toContain("fa-exclamation-triangle");
  });
});


text:
package org.apache.apex.malhar.lib.fs.s3;

import java.io.FileNotFoundException;
import java.io.IOException;

import javax.validation.constraints.NotNull;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.apex.malhar.lib.fs.FSRecordCompactionOperator;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.PutObjectResult;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;

import com.datatorrent.api.Context;
import com.datatorrent.api.DAG;
import com.datatorrent.api.DefaultOutputPort;
import com.datatorrent.lib.io.fs.AbstractReconciler;

/**
 * This operator uploads files to Amazon S3 after files are finalized and
 * frozen by the committed callback.
 *
 * S3TupleOutputModule uses this operator in conjunction with S3CompactionOperator
 *
 * @since 3.7.0
 */
@org.apache.hadoop.classification.InterfaceStability.Evolving
public class S3Reconciler extends AbstractReconciler<FSRecordCompactionOperator.OutputMetaData, FSRecordCompactionOperator.OutputMetaData>
{
  /**
   * Access key id for Amazon S3
   */
  @NotNull
  private String accessKey;

  /**
   * Secret key for Amazon S3
   */
  @NotNull
  private String secretKey;

  /**
   * Bucket name for data upload
   */
  @NotNull
  private String bucketName;

  /**
   * S3 Region
   */
  private String region;

  /**
   * Directory name under S3 bucket
   */
  @NotNull
  private String directoryName;

  /**
   * Client instance for connecting to Amazon S3
   */
  protected transient AmazonS3 s3client;

  /**
   * FileSystem instance for reading intermediate directory
   */
  protected transient FileSystem fs;

  protected transient String filePath;

  private static final String TMP_EXTENSION = ".tmp";

  public final transient DefaultOutputPort<FSRecordCompactionOperator.OutputMetaData> outputPort = new DefaultOutputPort<>();

  @Override
  public void setup(Context.OperatorContext context)
  {
    s3client = new AmazonS3Client(new BasicAWSCredentials(accessKey, secretKey));
    if (region != null) {
      s3client.setRegion(Region.getRegion(Regions.fromName(region)));
    }
    filePath = context.getValue(DAG.APPLICATION_PATH);
    try {
      fs = FileSystem.newInstance(new Path(filePath).toUri(), new Configuration());
    } catch (IOException e) {
      logger.error("Unable to create FileSystem: {}", e.getMessage());
    }
    super.setup(context);
  }

  /**
   * Enques the tuple for processing after committed callback
   */
  @Override
  protected void processTuple(FSRecordCompactionOperator.OutputMetaData outputMetaData)
  {
    logger.debug("enque : {}", outputMetaData);
    enqueueForProcessing(outputMetaData);
  }

  /**
   * Uploads the file on Amazon S3 using putObject API from S3 client
   */
  @Override
  protected void processCommittedData(FSRecordCompactionOperator.OutputMetaData outputMetaData)
  {
    try {
      Path path = new Path(outputMetaData.getPath());
      if (fs.exists(path) == false) {
        logger.debug("Ignoring non-existent path assuming replay : {}", path);
        return;
      }
      FSDataInputStream fsinput = fs.open(path);
      ObjectMetadata omd = new ObjectMetadata();
      omd.setContentLength(outputMetaData.getSize());
      String keyName = directoryName + Path.SEPARATOR + outputMetaData.getFileName();
      PutObjectRequest request = new PutObjectRequest(bucketName, keyName, fsinput, omd);
      if (outputMetaData.getSize() < Integer.MAX_VALUE) {
        request.getRequestClientOptions().setReadLimit((int)outputMetaData.getSize());
      } else {
        throw new RuntimeException("PutRequestSize greater than Integer.MAX_VALUE");
      }
      if (fs.exists(path)) {
        PutObjectResult result = s3client.putObject(request);
        logger.debug("File {} Uploaded at {}", keyName, result.getETag());
      }
    } catch (FileNotFoundException e) {
      logger.debug("Ignoring non-existent path assuming replay : {}", outputMetaData.getPath());
    } catch (IOException e) {
      logger.error("Unable to create Stream: {}", e.getMessage());
    }
  }

  /**
   * Clears intermediate/temporary files if any
   */
  @Override
  public void endWindow()
  {
    while (doneTuples.peek() != null) {
      FSRecordCompactionOperator.OutputMetaData metaData = doneTuples.poll();
      removeIntermediateFiles(metaData);
      if (outputPort.isConnected()) {
        // Emit the meta data with S3 path
        metaData.setPath(getDirectoryName() + Path.SEPARATOR + metaData.getFileName());
        outputPort.emit(metaData);
      }
    }
  }

  /**
   * Remove intermediate files
   */
  protected void removeIntermediateFiles(FSRecordCompactionOperator.OutputMetaData metaData)
  {
    logger.debug("found metaData = {}", metaData);
    committedTuples.remove(metaData);
    try {
      Path dest = new Path(metaData.getPath());
      //Deleting the intermediate files and when writing to tmp files
      // there can be vagrant tmp files which we have to clean
      FileStatus[] statuses = fs.listStatus(dest.getParent());

      for (FileStatus status : statuses) {
        String statusName = status.getPath().getName();
        if (statusName.endsWith(TMP_EXTENSION) && statusName.startsWith(metaData.getFileName())) {
          //a tmp file has tmp extension always preceded by timestamp
          String actualFileName = statusName.substring(0,
              statusName.lastIndexOf('.', statusName.lastIndexOf('.') - 1));
          logger.debug("actualFileName = {}", actualFileName);
          if (metaData.getFileName().equals(actualFileName)) {
            logger.debug("deleting stray file {}", statusName);
            fs.delete(status.getPath(), true);
          }
        } else if (statusName.equals(metaData.getFileName())) {
          logger.info("deleting s3-compaction file {}", statusName);
          fs.delete(status.getPath(), true);
        }
      }
    } catch (IOException e) {
      logger.error("Unable to Delete a file: {}", metaData.getFileName());
    }
  }

  /**
   * Get access key id
   *
   * @return Access key id for Amazon S3
   */
  public String getAccessKey()
  {
    return accessKey;
  }

  /**
   * Set access key id
   *
   * @param accessKey
   *          Access key id for Amazon S3
   */
  public void setAccessKey(@NotNull String accessKey)
  {
    this.accessKey = Preconditions.checkNotNull(accessKey);
  }

  /**
   * Get secret key
   *
   * @return Secret key for Amazon S3
   */
  public String getSecretKey()
  {
    return secretKey;
  }

  /**
   * Set secret key
   *
   * @param secretKey
   *          Secret key for Amazon S3
   */
  public void setSecretKey(@NotNull String secretKey)
  {
    this.secretKey = Preconditions.checkNotNull(secretKey);
  }

  /**
   * Get bucket name
   *
   * @return Bucket name for data upload
   */
  public String getBucketName()
  {
    return bucketName;
  }

  /**
   * Set bucket name
   *
   * @param bucketName
   *          Bucket name for data upload
   */
  public void setBucketName(@NotNull String bucketName)
  {
    this.bucketName = Preconditions.checkNotNull(bucketName);
  }

  /**
   * Get directory name
   *
   * @return Directory name under S3 bucket
   */
  public String getDirectoryName()
  {
    return directoryName;
  }

  /**
   * Set directory name
   *
   * @param directoryName
   *          Directory name under S3 bucket
   */
  public void setDirectoryName(@NotNull String directoryName)
  {
    this.directoryName = Preconditions.checkNotNull(directoryName);
  }

  /**
   * Get the AWS S3 Region
   * @return region
   */
  public String getRegion()
  {
    return region;
  }

  /**
   * Set the AWS S3 Region
   * @param region region
   */
  public void setRegion(String region)
  {
    this.region = region;
  }

  /**
   * Set Amazon S3 client
   *
   * @param s3client
   *          Client for Amazon S3
   */
  @VisibleForTesting
  void setS3client(AmazonS3 s3client)
  {
    this.s3client = s3client;
  }

  private static final Logger logger = LoggerFactory.getLogger(S3Reconciler.class);

}

redpajama_set_name: RedPajamaGithub


text:
MongoMapper Search
============

MongoMapper Search is a simple full text search implementation for MongoMapper ODM based on mongoid_search (https://github.com/mauriciozaffari/mongoid_search).

Installation
--------

In your Gemfile:

    gem 'mongomapper_search'

Then:

    bundle install

Examples
--------

    class Product
      include MongoMapper::Document
      include MongoMapper::Search
      key :brand, String
      key :name, String

      many :tags
      belongs_to :category

      search_in :brand, :name, {:tags => :name} => 1, {:category => :name} => 2
    end

    class Tag
      include MongoMapper::Document
      key :name, String

      belongs_to :product
    end

    class Category
      include MongoMapper::Document
      key :name, String

      many :products
    end

Syntax:

    search_in :brand, :name => 3, {:tags => :name} => 1

The search will be done using fields named as the symbols passed.
You can pass a boost parameter to smooth your search like in:

	:name => 3 #It means that keywords found on name is 3 times more important than keywords found on :brand

The default boost is 1.
For while, complex attributes like {:tags => :name} must be declared with a boost value.

Now you can run search, which will look in the search field and return all matching results:

    Product.search("apple iphone").size
    => 1

Note that the search is case insensitive, and accept partial searching too:

    Product.search("ipho").size
    => 1

You can use search in a chainable way:

    Product.where(:brand => "Apple").search('iphone')

Options
-------

match:
  _:any_ - match any occurrence
  _:all_ - match all ocurrences
  Default is _:any_.

    search_in :brand, :name, { :tags => :name } => 1, { :match => :any }

    Product.search("apple motorola").size
    => 1

    search_in :brand, :name, { :tags => :name } => 1, { :match => :all }

    Product.search("apple motorola").size
    => 0

allow_empty_search:
  _true_ - match any occurrence
  _false_ - match all ocurrences
  Default is _false_.

    search_in :brand, :name, { :tags => :name } => 1, { :allow_empty_search => true }

    Product.search("").size
    => 1

RoadMap
----

- Create a ignore list so the search can ignore some words


text:
package ch.epfl.data.squall.api.scala.SquallType

import java.util.Date
import java.text.SimpleDateFormat
import java.io.{ ObjectOutputStream, ObjectInputStream }
import java.io.{ FileOutputStream, FileInputStream }
import java.io.Serializable
import scala.language.experimental.macros

import ch.epfl.data.squall.api.scala.macros.Macros

/**
 * @author mohamed
 */
trait SquallType[T] extends Serializable {
  def convert(v: T): List[String]
  def convertBack(v: List[String]): T
  def convertIndexesOfTypeToListOfInt(tuple: T): List[Int]
  def convertToIndexesOfTypeT(index: List[Int]): T
  def getLength(): Int
}

object SquallType extends Serializable {

  implicit def IntType = new SquallType[Int] {
    def convert(v: Int): List[String] = List(v.toString)
    def convertBack(v: List[String]): Int = v.head.toInt
    def convertIndexesOfTypeToListOfInt(index: Int): List[Int] = List(index)
    def convertToIndexesOfTypeT(index: List[Int]): Int = index(0)
    def getLength(): Int = 1
  }

  implicit def DoubleType = new SquallType[Double] {
    def convert(v: Double): List[String] = List(v.toString)
    def convertBack(v: List[String]): Double = v.head.toDouble
    def convertIndexesOfTypeToListOfInt(index: Double): List[Int] = List(index.toInt)
    def convertToIndexesOfTypeT(index: List[Int]): Double = index(0).toDouble
    def getLength(): Int = 1
  }

  implicit def StringType = new SquallType[String] {
    def convert(v: String): List[String] = List(v)
    def convertBack(v: List[String]): String = v.head
    def convertIndexesOfTypeToListOfInt(index: String): List[Int] = List(index.toInt)
    def convertToIndexesOfTypeT(index: List[Int]): String = index(0).toString()
    def getLength(): Int = 1
  }

  implicit def DateType = new SquallType[Date] {
    def convert(v: Date): List[String] = List((new SimpleDateFormat("yyyy-MM-dd")).format(v))
    def convertBack(v: List[String]): Date = (new SimpleDateFormat("yyyy-MM-dd")).parse(v.head)
    def convertIndexesOfTypeToListOfInt(index: Date): List[Int] = List(index.getDay)
    def convertToIndexesOfTypeT(index: List[Int]): Date = new Date(7, index(0), 2000) //hacked the index represents the day
    def getLength(): Int = 1
  }

  /* An implicit macro which takes care of handling tuples and records defined using case classes */
  implicit def materializeSquallType[T]: SquallType[T] = macro Macros.materializeSquallTypeImpl[SquallType, T]
}


text:
import java.util.ArrayList;
import java.util.List;

/**
 * Created by SixDays on 2/4/15.
 */
public class Problem3 {
    public static void main(String[] args) {
        long num = 600851475143L;
        long divider = 2;
        List<Long> factors = new ArrayList<>();

        while (num > 1) {
            while ((num % divider) == 0) {
                factors.add(divider);
                num /= divider;
            }
            divider++;
        }
        System.out.println(factors.toString());
    }
}


text:
package fr.unice.spinefm.ProcessModel.impl.test;

import org.junit.Before;
import fr.unice.spinefm.FMModel.FMModelFactory;
import fr.unice.spinefm.FMModel.FeatureModel;
import fr.unice.spinefm.MSPLModel.DomainElement;
import fr.unice.spinefm.MSPLModel.MSPLModelFactory;
import fr.unice.spinefm.ProcessModel.ConfigurationProcessStep;
import fr.unice.spinefm.ProcessModel.ProcessModelFactory;
import fr.unice.spinefm.fmengine.exceptions.FMEngineException;
import fr.unice.spinefm.fmengine.familiar.FMLSpineFMAdapter;
import fr.unice.spinefm.fmengine.familiar.FamiliarInterpreter;

public class TestConfigurationProcessStep {

	private FMLSpineFMAdapter adapter;
	private FeatureModel fm;
	private ConfigurationProcessStep cps;
	private DomainElement de;

	@Before
	public void setUp() throws FMEngineException {
		this.adapter = new FMLSpineFMAdapter(FamiliarInterpreter.getInstance());

		String cmd = "a = FM(Source: TypeInfo Product Criteria; TypeInfo: PictureAlbum; Product: (FlickR|Picasa); Criteria: [Sort]; Sort: (Date|Name)+; Picasa <-> Date;)";
		this.adapter.getSFI().eval(cmd);

		this.fm = FMModelFactory.eINSTANCE.createFeatureModel();
		this.fm.setId("a");
		this.adapter.populateFeatureModel(fm);

		this.de = MSPLModelFactory.eINSTANCE.createDomainElement();
		this.de.setId("a");
		this.de.setRefers_on(this.fm);
		this.cps = ProcessModelFactory.eINSTANCE.createConfigurationProcessStep();
		this.cps.setId("cpsA");
		this.cps.setDomainElement(de);
		//this.cps.setFMA(this.adapter);
	}
	/*
	@Test
	public void testGetStateWithoutActionSelectMandatoryFeatures() throws IllegalCallException, FeatureNotFoundException {
		ConfigurationState state = this.cps.getState();

		ConfigurationState expected = ActionModelFactory.eINSTANCE.createConfigurationState();
		expected.setFm(this.fm);
		expected.getSelectedFeatures().add(this.fm.getFeatureFromName("TypeInfo"));
		expected.getSelectedFeatures().add(this.fm.getFeatureFromName("Source"));
		expected.getSelectedFeatures().add(this.fm.getFeatureFromName("PictureAlbum"));
		expected.getSelectedFeatures().add(this.fm.getFeatureFromName("Criteria"));
		expected.getSelectedFeatures().add(this.fm.getFeatureFromName("Product"));
		expected.getDeselectedFeatures();

		assertEquals(expected, state);
	}

	@Test
	public void testGetStateAfterActionSelectSort() throws IllegalCallException, FeatureNotFoundException {
		Action a = ActionModelFactory.eINSTANCE.createActionSelect();
		a.setFeature(this.fm.getFeatureFromName("Sort"));
		a.setFm(this.fm);

		this.cps.addActionToDo(a);
		ConfigurationState state = this.cps.getState();

		ConfigurationState expected = ActionModelFactory.eINSTANCE.createConfigurationState();
		expected.setFm(this.fm);
		expected.getSelectedFeatures().add(this.fm.getFeatureFromName("TypeInfo"));
		expected.getSelectedFeatures().add(this.fm.getFeatureFromName("Source"));
		expected.getSelectedFeatures().add(this.fm.getFeatureFromName("PictureAlbum"));
		expected.getSelectedFeatures().add(this.fm.getFeatureFromName("Criteria"));
		expected.getSelectedFeatures().add(this.fm.getFeatureFromName("Product"));
		expected.getSelectedFeatures().add(this.fm.getFeatureFromName("Sort"));
		expected.getDeselectedFeatures();

		assertEquals(expected, state);
	}

	@Test
	public void testGetStateAfterActionDeselectSort() throws IllegalCallException, FeatureNotFoundException {
		Action a = ActionModelFactory.eINSTANCE.createActionDeselect();
		a.setFeature(this.fm.getFeatureFromName("Sort"));
		a.setFm(this.fm);

		this.cps.addActionToDo(a);
		ConfigurationState state = this.cps.getState();

		ConfigurationState expected = ActionModelFactory.eINSTANCE.createConfigurationState();
		expected.setFm(this.fm);
		expected.getSelectedFeatures().add(this.fm.getFeatureFromName("TypeInfo"));
		expected.getSelectedFeatures().add(this.fm.getFeatureFromName("Source"));
		expected.getSelectedFeatures().add(this.fm.getFeatureFromName("PictureAlbum"));
		expected.getSelectedFeatures().add(this.fm.getFeatureFromName("Criteria"));
		expected.getSelectedFeatures().add(this.fm.getFeatureFromName("Product"));
		expected.getSelectedFeatures().add(this.fm.getFeatureFromName("FlickR"));

		expected.getDeselectedFeatures().add(this.fm.getFeatureFromName("Sort"));
		expected.getDeselectedFeatures().add(this.fm.getFeatureFromName("Date"));
		expected.getDeselectedFeatures().add(this.fm.getFeatureFromName("Name"));
		expected.getDeselectedFeatures().add(this.fm.getFeatureFromName("Picasa"));

		assertEquals(expected, state);
	}

	@Test
	public void testGetActionsDoneListWithoutDoingNothingReportImplicitActions() throws IllegalCallException, FeatureNotFoundException {
		Action selectTypeInfo = ActionModelFactory.eINSTANCE.createActionSelect();
		selectTypeInfo.setFeature(this.fm.getFeatureFromName("TypeInfo"));
		selectTypeInfo.setFm(this.fm);

		Action selectSource = ActionModelFactory.eINSTANCE.createActionSelect();
		selectSource.setFeature(this.fm.getFeatureFromName("Source"));
		selectSource.setFm(this.fm);

		Action selectPictureAlbum = ActionModelFactory.eINSTANCE.createActionSelect();
		selectPictureAlbum.setFeature(this.fm.getFeatureFromName("PictureAlbum"));
		selectPictureAlbum.setFm(this.fm);

		Action selectCriteria = ActionModelFactory.eINSTANCE.createActionSelect();
		selectCriteria.setFeature(this.fm.getFeatureFromName("Criteria"));
		selectCriteria.setFm(this.fm);

		Action selectProduct = ActionModelFactory.eINSTANCE.createActionSelect();
		selectProduct.setFeature(this.fm.getFeatureFromName("Product"));
		selectProduct.setFm(this.fm);

		ConfigurationProcessStep cps_expected = ProcessModelFactory.eINSTANCE.createConfigurationProcessStep();
		cps_expected.setDomainElement(de);
		cps_expected.setId(this.cps.getId());

		cps_expected.getActionsDone().add(selectTypeInfo);
		cps_expected.getActionsDone().add(selectSource);
		cps_expected.getActionsDone().add(selectPictureAlbum);
		cps_expected.getActionsDone().add(selectCriteria);
		cps_expected.getActionsDone().add(selectProduct);

		cps_expected.getActionsToDo();
		assertEquals(cps_expected, cps);
	}

	@Test
	public void testGetActionsDoneAfterDeselectingSortReportImplicitActions() throws IllegalCallException, FeatureNotFoundException {
		Action a = ActionModelFactory.eINSTANCE.createActionDeselect();
		a.setFeature(this.fm.getFeatureFromName("Sort"));
		a.setFm(this.fm);

		this.cps.addActionToDo(a);
		this.cps.getState();

		Action selectTypeInfo = ActionModelFactory.eINSTANCE.createActionSelect();
		selectTypeInfo.setFeature(this.fm.getFeatureFromName("TypeInfo"));
		selectTypeInfo.setFm(this.fm);

		Action selectSource = ActionModelFactory.eINSTANCE.createActionSelect();
		selectSource.setFeature(this.fm.getFeatureFromName("Source"));
		selectSource.setFm(this.fm);

		Action selectPictureAlbum = ActionModelFactory.eINSTANCE.createActionSelect();
		selectPictureAlbum.setFeature(this.fm.getFeatureFromName("PictureAlbum"));
		selectPictureAlbum.setFm(this.fm);

		Action selectCriteria = ActionModelFactory.eINSTANCE.createActionSelect();
		selectCriteria.setFeature(this.fm.getFeatureFromName("Criteria"));
		selectCriteria.setFm(this.fm);

		Action selectProduct = ActionModelFactory.eINSTANCE.createActionSelect();
		selectProduct.setFeature(this.fm.getFeatureFromName("Product"));
		selectProduct.setFm(this.fm);

		Action selectFlickR = ActionModelFactory.eINSTANCE.createActionSelect();
		selectFlickR.setFeature(this.fm.getFeatureFromName("FlickR"));
		selectFlickR.setFm(this.fm);

		Action deselectPicasa = ActionModelFactory.eINSTANCE.createActionDeselect();
		deselectPicasa.setFeature(this.fm.getFeatureFromName("Picasa"));
		deselectPicasa.setFm(this.fm);

		Action deselectSort = ActionModelFactory.eINSTANCE.createActionDeselect();
		deselectSort.setFeature(this.fm.getFeatureFromName("Sort"));
		deselectSort.setFm(this.fm);

		Action deselectDate = ActionModelFactory.eINSTANCE.createActionDeselect();
		deselectDate.setFeature(this.fm.getFeatureFromName("Date"));
		deselectDate.setFm(this.fm);

		Action deselectName = ActionModelFactory.eINSTANCE.createActionDeselect();
		deselectName.setFeature(this.fm.getFeatureFromName("Name"));
		deselectName.setFm(this.fm);

		ConfigurationProcessStep cps_expected = ProcessModelFactory.eINSTANCE.createConfigurationProcessStep();
		cps_expected.setDomainElement(de);
		cps_expected.setId(this.cps.getId());

		cps_expected.getActionsDone().add(selectTypeInfo);
		cps_expected.getActionsDone().add(selectSource);
		cps_expected.getActionsDone().add(selectPictureAlbum);
		cps_expected.getActionsDone().add(selectCriteria);
		cps_expected.getActionsDone().add(selectProduct);
		cps_expected.getActionsDone().add(selectFlickR);
		cps_expected.getActionsDone().add(deselectPicasa);
		cps_expected.getActionsDone().add(deselectDate);
		cps_expected.getActionsDone().add(deselectName);
		cps_expected.getActionsDone().add(deselectSort);

		cps_expected.getActionsToDo();
		assertEquals(cps_expected, cps);
	}

	@Test
	public void testIsCompleteWhenDoingNothingIsFalse() throws IllegalCallException, FMEngineException {
		System.err.println(this.cps);
		assertFalse(this.cps.isComplete());
	}*/
}


text:
class Simulation
	attr_reader :num_trades, :trade_history

	def initialize(strategy)
		@strategy = strategy
		@shares = {}
		@cash = STARTING_CASH.to_i
		@num_trades = 0
		@trade_history = []
		@diversity = 0

		STOCK_SYMBOLS.each do |stock_symbol|
			@shares[stock_symbol.to_sym] = 0
		end

		run_simulation
	end

	def final_assets
		total = @cash

		@shares.each do |stock_symbol, num_shares|
			current_value = $stock_quotes[stock_symbol.to_s][DAYS_TO_SIMULATE - 1][:close]
			total += num_shares * current_value

			if num_shares > 0
				@diversity += 1
			end
		end

		total -= @num_trades * COST_PER_TRADE

		return total.round(2)
	end

	def score
		return ((final_assets() - STARTING_CASH) + (@diversity * DIVERSITY_BONUS)).round(2)
	end

	private

	def run_simulation

		DAYS_TO_SIMULATE.times do |day|

			$stock_quotes.each do |stock_symbol, quote|
				position = quote[day]

				if position

					velocity = position[:velocity]
					tradeDirection = nil

					if velocity > @strategy.parameters[:buyVelocity]
						tradeDirection = 1
						tradeVerb = 'BUY'
					end

					if velocity < @strategy.parameters[:sellVelocity]
						tradeDirection = -1
						tradeVerb = 'SELL'
					end

					if tradeDirection
						tradeAction = @strategy.parameters[:buyVolume] / position[:close]
						tradeAction = (tradeAction * tradeDirection).round(2)
	      		trade stock_symbol, position, tradeAction
	      		@trade_history.push "#{tradeVerb} #{stock_symbol}. Velocity at: #{velocity}. Action: #{tradeAction}. Date: #{position[:date]}"
					end

				end
			end
		end
	end

	def trade(stock_symbol, position, tradeAction)

		tradeCost = (tradeAction * position[:close]).round(2)
		@num_trades += 1

		shares = @shares[stock_symbol.to_sym]

    # If we don't have enough money to complete the suggested trade.
    if @cash - tradeCost < 0
      tradeAction = @cash / position[:close]
    end

    # If we don't have enough stocks to complete the suggested trade.
    if shares + tradeAction < 0
      tradeAction = shares * -1
    end

    tradeCost = (tradeAction * position[:close]).round(2)

    # Keep track of our shares and cash
    @shares[stock_symbol.to_sym] = (shares + tradeAction).round(2)
    @cash = (@cash - tradeCost).round(2)

    # Make sure we aren't cheating
    if shares < 0
      log shares
      raise 'Shares cannot be negative!'
    end

    if @cash < 0
      if @cash > -0.01
        @cash = 0
      else
        raise 'You can\'t use money you don\'t have... What do you think this is, America?!'
      end
    end
	end
end


text:
package com.intellij.openapi.fileTypes;

/**
 * An IJ plugin related code.
 */
public interface ContentBasedClassFileProcessor {
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

namespace Microsoft.MixedReality.Toolkit.Utilities.Solvers
{
    /// <summary>
    /// Provides a solver that overlaps with the tracked object.
    /// </summary>
    public class Overlap : Solver
    {
        public override void SolverUpdate()
        {
            GoalPosition = SolverHandler.TransformTarget.position;
            GoalRotation = SolverHandler.TransformTarget.rotation;

            UpdateWorkingPositionToGoal();
            UpdateWorkingRotationToGoal();
        }
    }
}


text:
#region Header

#endregion

using System;
using System.Collections;
using System.Collections.Specialized;

namespace PerfAssist.LitJson
{
    public class JsonMockWrapper : IJsonWrapper
    {
        public bool IsArray { get { return false; } }
        public bool IsBoolean { get { return false; } }
        public bool IsDouble { get { return false; } }
        public bool IsInt { get { return false; } }
        public bool IsLong { get { return false; } }
        public bool IsObject { get { return false; } }
        public bool IsString { get { return false; } }

        public bool GetBoolean() { return false; }
        public double GetDouble() { return 0.0; }
        public int GetInt() { return 0; }
        public JsonType GetJsonType() { return JsonType.None; }
        public long GetLong() { return 0L; }
        public string GetString() { return ""; }

        public void SetBoolean(bool val) { }
        public void SetDouble(double val) { }
        public void SetInt(int val) { }
        public void SetJsonType(JsonType type) { }
        public void SetLong(long val) { }
        public void SetString(string val) { }

        public string ToJson() { return ""; }
        public void ToJson(JsonWriter writer) { }

        bool IList.IsFixedSize { get { return true; } }
        bool IList.IsReadOnly { get { return true; } }

        object IList.this[int index]
        {
            get { return null; }
            set { }
        }

        int IList.Add(object value) { return 0; }
        void IList.Clear() { }
        bool IList.Contains(object value) { return false; }
        int IList.IndexOf(object value) { return -1; }
        void IList.Insert(int i, object v) { }
        void IList.Remove(object value) { }
        void IList.RemoveAt(int index) { }

        int ICollection.Count { get { return 0; } }
        bool ICollection.IsSynchronized { get { return false; } }
        object ICollection.SyncRoot { get { return null; } }

        void ICollection.CopyTo(Array array, int index) { }

        IEnumerator IEnumerable.GetEnumerator() { return null; }

        bool IDictionary.IsFixedSize { get { return true; } }
        bool IDictionary.IsReadOnly { get { return true; } }

        ICollection IDictionary.Keys { get { return null; } }
        ICollection IDictionary.Values { get { return null; } }

        object IDictionary.this[object key]
        {
            get { return null; }
            set { }
        }

        void IDictionary.Add(object k, object v) { }
        void IDictionary.Clear() { }
        bool IDictionary.Contains(object key) { return false; }
        void IDictionary.Remove(object key) { }

        IDictionaryEnumerator IDictionary.GetEnumerator() { return null; }

        object IOrderedDictionary.this[int idx]
        {
            get { return null; }
            set { }
        }

        IDictionaryEnumerator IOrderedDictionary.GetEnumerator()
        {
            return null;
        }
        void IOrderedDictionary.Insert(int i, object k, object v) { }
        void IOrderedDictionary.RemoveAt(int i) { }
    }
}


text:
var Controller = function(api, configuration) {
	this.api = api;
	this.options = {};
	this.routes = {};
	this.actions = {};
	this.helpers = {};

	this.responses = api.responses;

	if(typeof(configuration.options) === "object") this.options = configuration.options;
	if(typeof(configuration.routes) === "object") this.routes = configuration.routes;
	if(typeof(configuration.actions) === "object") this.actions = configuration.actions;
	if(typeof(configuration.helpers) === "object") this.helpers = configuration.helpers;

	for(var funcName in this.helpers) {
		this.helpers[funcName] = wrapFunction(this.helpers[funcName], this);
	}
};

Controller.prototype.checkRoute = function(req, urlParts) {
	var selectedRoute = false;
	var curAction = false;
	var params = {};

	for(var action in this.routes) {
		curAction = action;
		var route = this.routes[action];

		if(typeof(route.path) === "string" && route.path.substr(0, 1) === "/") {
			route.path = route.path.substr(1);
		}

		var routePieces = typeof(route.path) === "string" ? route.path.split("/") : route.path;

		//Before we get fancy, check to see if the url and the route have the same number of parts
		if(routePieces.length !== urlParts.length) {
			continue;
		}

		if(route.method.toUpperCase() !== req.method.toUpperCase()) {
			continue;
		}

		//Store any matched params here
		params = {};

		//If we determine that it's not this route somewhere in the inner loop
		//we will set cont = true, and then break the inner loop.  Then we can continue the outer loop
		var cont = false;
		var i, max;

		for(i=0, max=routePieces.length; i<max; i++) {
			var urlPart = urlParts[i];
			var routePart = routePieces[i];

			//Check if the route part is a property flag

			switch(routePart.substr(0, 1)) {

				case "*": //Mixed
					var replaced = urlPart.replace(/[A-Za-z0-9]/g, "");

					if(replaced.length === 0) {
						params[routePart.substr(1)] = urlPart;
					} else {
						cont = true;
					}
					break;

				case "%": //Number
					var replaced = urlPart.replace(/[0-9]/g, "");

					if(replaced.length === 0) {
						params[routePart.substr(1)] = urlPart;
					} else {
						cont = true;
					}

					break;

				case ":": //String
					var replaced = urlPart.replace(/[A-Za-z]/g, "");

					if(replaced.length === 0) {
						params[routePart.substr(1)] = urlPart;
					} else {
						cont = true;
					}

					break;

				case "[": //Probably regexp.  Need to check for outer bracket
						if(routePart.lastIndexOf("]") !== -1) {
							var reg = new RegExp(routePart.substr(routePart.indexOf("[") + 1, routePart.lastIndexOf("]") - 1));

							var exec = reg.exec(urlPart);

							if(exec.length > 0 && exec[0].length === urlPart.length) {
								params[routePart.substr(routePart.lastIndexOf("]") + 1)] = urlPart;
							} else {
								cont = true;
							}
						} else {
							//This doesn't actually look like a regexp, so just match it like a 1-to-1 string
							if(routePart !== urlPart) {
								cont = true;
							}
						}
					break;

				default: //1-to-1 string
					if(routePart !== urlPart) {
						cont = true;
					}

					break;

			}

			//If continue is true, then we break out of this loop, and continue on the next one.  This means
			//that the current route did not match
			if(cont) {
				this.api.private.debug("Route did not match "+curAction, 1);
				break;
			}

		}

		//The only way the code can get to here and cont still be false is if the previous route passed on all measures
		//If that's the case 'Move Along'
		if(cont) {
			continue;
		}

		//So, presumably, if we get to this point then we have the correct route.  Like I said, 'Move Along'
		selectedRoute = curAction;
		this.api.private.debug("Found matching route "+ curAction, 1);
		break;

	}

	if(selectedRoute === false) {
		return false;
	} else {
		return {
			meta: this.routes[selectedRoute],
			handler: function(req, res) {
				if(typeof(this.actions[selectedRoute]) === "function") {
					this.actions[selectedRoute].call(this, req, res, params);
				} else {
					this.api.responses.internalError(res);
					this.api.private.debug("We found a matching route, but there is no action for that route!", 3);
					throw new Error("Simple-API: Selected Route has no matching Action: " + selectedRoute);
				}
			}
		}
	}
}

/** Helper Functions **/
var wrapFunction = function(func, that) {
	return function() {
		return func.apply(that, arguments);
	}
}

module.exports = exports = Controller;


text:
if platform_family?("rhel")
  include_recipe 'pxe::rhel'
elsif platform_family?("debian")
  include_recipe 'pxe::deb'
end


text:
#import "ZXAbstractBlackBoxTestCase.h"

@interface ZXUPCABlackBox6BlurryTestCase : ZXAbstractBlackBoxTestCase

@end


text:
import string

class Template (string.Template):
    delimiter = '@'
    escaped = '@@'


text:
package eu.ehealth.db.storagecomponent;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import eu.ehealth.db.xsd.QuestionnaireAnswers;

/**
 *
Clase Java para anonymous complex type.
 *
 *
El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="data" type="{http://aladdin-project.eu/xsd}QuestionnaireAnswers"/>
 *         <element name="userId" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "data",
    "userId"
})
@XmlRootElement(name = "StoreQuestionnaireAnswers")
public class StoreQuestionnaireAnswers {

    @XmlElement(required = true)
    protected QuestionnaireAnswers data;
    @XmlElement(required = true)
    protected String userId;

    /**
     * Obtiene el valor de la propiedad data.
     *
     * @return
     *     possible object is
     *     {@link QuestionnaireAnswers }
     *
     */
    public QuestionnaireAnswers getData() {
        return data;
    }

    /**
     * Define el valor de la propiedad data.
     *
     * @param value
     *     allowed object is
     *     {@link QuestionnaireAnswers }
     *
     */
    public void setData(QuestionnaireAnswers value) {
        this.data = value;
    }

    /**
     * Obtiene el valor de la propiedad userId.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getUserId() {
        return userId;
    }

    /**
     * Define el valor de la propiedad userId.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setUserId(String value) {
        this.userId = value;
    }

}


text:
namespace Microsoft.Azure.Management.StreamAnalytics
{
    using Microsoft.Azure;
    using Microsoft.Azure.Management;
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Models;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// Extension methods for OutputsOperations.
    /// </summary>
    public static partial class OutputsOperationsExtensions
    {
            /// <summary>
            /// Creates an output or replaces an already existing output under an existing
            /// streaming job.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='output'>
            /// The definition of the output that will be used to create a new output or
            /// replace the existing one under the streaming job.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group that contains the resource. You can obtain
            /// this value from the Azure Resource Manager API or the portal.
            /// </param>
            /// <param name='jobName'>
            /// The name of the streaming job.
            /// </param>
            /// <param name='outputName'>
            /// The name of the output.
            /// </param>
            /// <param name='ifMatch'>
            /// The ETag of the output. Omit this value to always overwrite the current
            /// output. Specify the last-seen ETag value to prevent accidentally
            /// overwritting concurrent changes.
            /// </param>
            /// <param name='ifNoneMatch'>
            /// Set to '*' to allow a new output to be created, but to prevent updating an
            /// existing output. Other values will result in a 412 Pre-condition Failed
            /// response.
            /// </param>
            public static Output CreateOrReplace(this IOutputsOperations operations, Output output, string resourceGroupName, string jobName, string outputName, string ifMatch = default(string), string ifNoneMatch = default(string))
            {
                return operations.CreateOrReplaceAsync(output, resourceGroupName, jobName, outputName, ifMatch, ifNoneMatch).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Creates an output or replaces an already existing output under an existing
            /// streaming job.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='output'>
            /// The definition of the output that will be used to create a new output or
            /// replace the existing one under the streaming job.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group that contains the resource. You can obtain
            /// this value from the Azure Resource Manager API or the portal.
            /// </param>
            /// <param name='jobName'>
            /// The name of the streaming job.
            /// </param>
            /// <param name='outputName'>
            /// The name of the output.
            /// </param>
            /// <param name='ifMatch'>
            /// The ETag of the output. Omit this value to always overwrite the current
            /// output. Specify the last-seen ETag value to prevent accidentally
            /// overwritting concurrent changes.
            /// </param>
            /// <param name='ifNoneMatch'>
            /// Set to '*' to allow a new output to be created, but to prevent updating an
            /// existing output. Other values will result in a 412 Pre-condition Failed
            /// response.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<Output> CreateOrReplaceAsync(this IOutputsOperations operations, Output output, string resourceGroupName, string jobName, string outputName, string ifMatch = default(string), string ifNoneMatch = default(string), CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.CreateOrReplaceWithHttpMessagesAsync(output, resourceGroupName, jobName, outputName, ifMatch, ifNoneMatch, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Updates an existing output under an existing streaming job. This can be
            /// used to partially update (ie. update one or two properties) an output
            /// without affecting the rest the job or output definition.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='output'>
            /// An Output object. The properties specified here will overwrite the
            /// corresponding properties in the existing output (ie. Those properties will
            /// be updated). Any properties that are set to null here will mean that the
            /// corresponding property in the existing output will remain the same and not
            /// change as a result of this PATCH operation.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group that contains the resource. You can obtain
            /// this value from the Azure Resource Manager API or the portal.
            /// </param>
            /// <param name='jobName'>
            /// The name of the streaming job.
            /// </param>
            /// <param name='outputName'>
            /// The name of the output.
            /// </param>
            /// <param name='ifMatch'>
            /// The ETag of the output. Omit this value to always overwrite the current
            /// output. Specify the last-seen ETag value to prevent accidentally
            /// overwritting concurrent changes.
            /// </param>
            public static Output Update(this IOutputsOperations operations, Output output, string resourceGroupName, string jobName, string outputName, string ifMatch = default(string))
            {
                return operations.UpdateAsync(output, resourceGroupName, jobName, outputName, ifMatch).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Updates an existing output under an existing streaming job. This can be
            /// used to partially update (ie. update one or two properties) an output
            /// without affecting the rest the job or output definition.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='output'>
            /// An Output object. The properties specified here will overwrite the
            /// corresponding properties in the existing output (ie. Those properties will
            /// be updated). Any properties that are set to null here will mean that the
            /// corresponding property in the existing output will remain the same and not
            /// change as a result of this PATCH operation.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group that contains the resource. You can obtain
            /// this value from the Azure Resource Manager API or the portal.
            /// </param>
            /// <param name='jobName'>
            /// The name of the streaming job.
            /// </param>
            /// <param name='outputName'>
            /// The name of the output.
            /// </param>
            /// <param name='ifMatch'>
            /// The ETag of the output. Omit this value to always overwrite the current
            /// output. Specify the last-seen ETag value to prevent accidentally
            /// overwritting concurrent changes.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<Output> UpdateAsync(this IOutputsOperations operations, Output output, string resourceGroupName, string jobName, string outputName, string ifMatch = default(string), CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.UpdateWithHttpMessagesAsync(output, resourceGroupName, jobName, outputName, ifMatch, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Deletes an output from the streaming job.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group that contains the resource. You can obtain
            /// this value from the Azure Resource Manager API or the portal.
            /// </param>
            /// <param name='jobName'>
            /// The name of the streaming job.
            /// </param>
            /// <param name='outputName'>
            /// The name of the output.
            /// </param>
            public static void Delete(this IOutputsOperations operations, string resourceGroupName, string jobName, string outputName)
            {
                operations.DeleteAsync(resourceGroupName, jobName, outputName).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Deletes an output from the streaming job.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group that contains the resource. You can obtain
            /// this value from the Azure Resource Manager API or the portal.
            /// </param>
            /// <param name='jobName'>
            /// The name of the streaming job.
            /// </param>
            /// <param name='outputName'>
            /// The name of the output.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task DeleteAsync(this IOutputsOperations operations, string resourceGroupName, string jobName, string outputName, CancellationToken cancellationToken = default(CancellationToken))
            {
                (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, jobName, outputName, null, cancellationToken).ConfigureAwait(false)).Dispose();
            }

            /// <summary>
            /// Gets details about the specified output.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group that contains the resource. You can obtain
            /// this value from the Azure Resource Manager API or the portal.
            /// </param>
            /// <param name='jobName'>
            /// The name of the streaming job.
            /// </param>
            /// <param name='outputName'>
            /// The name of the output.
            /// </param>
            public static Output Get(this IOutputsOperations operations, string resourceGroupName, string jobName, string outputName)
            {
                return operations.GetAsync(resourceGroupName, jobName, outputName).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Gets details about the specified output.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group that contains the resource. You can obtain
            /// this value from the Azure Resource Manager API or the portal.
            /// </param>
            /// <param name='jobName'>
            /// The name of the streaming job.
            /// </param>
            /// <param name='outputName'>
            /// The name of the output.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<Output> GetAsync(this IOutputsOperations operations, string resourceGroupName, string jobName, string outputName, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, jobName, outputName, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Lists all of the outputs under the specified streaming job.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group that contains the resource. You can obtain
            /// this value from the Azure Resource Manager API or the portal.
            /// </param>
            /// <param name='jobName'>
            /// The name of the streaming job.
            /// </param>
            /// <param name='select'>
            /// The $select OData query parameter. This is a comma-separated list of
            /// structural properties to include in the response, or "*" to include all
            /// properties. By default, all properties are returned except diagnostics.
            /// Currently only accepts '*' as a valid value.
            /// </param>
            public static IPage<Output> ListByStreamingJob(this IOutputsOperations operations, string resourceGroupName, string jobName, string select = default(string))
            {
                return operations.ListByStreamingJobAsync(resourceGroupName, jobName, select).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Lists all of the outputs under the specified streaming job.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group that contains the resource. You can obtain
            /// this value from the Azure Resource Manager API or the portal.
            /// </param>
            /// <param name='jobName'>
            /// The name of the streaming job.
            /// </param>
            /// <param name='select'>
            /// The $select OData query parameter. This is a comma-separated list of
            /// structural properties to include in the response, or "*" to include all
            /// properties. By default, all properties are returned except diagnostics.
            /// Currently only accepts '*' as a valid value.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<IPage<Output>> ListByStreamingJobAsync(this IOutputsOperations operations, string resourceGroupName, string jobName, string select = default(string), CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.ListByStreamingJobWithHttpMessagesAsync(resourceGroupName, jobName, select, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Tests whether an output's datasource is reachable and usable by the Azure
            /// Stream Analytics service.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group that contains the resource. You can obtain
            /// this value from the Azure Resource Manager API or the portal.
            /// </param>
            /// <param name='jobName'>
            /// The name of the streaming job.
            /// </param>
            /// <param name='outputName'>
            /// The name of the output.
            /// </param>
            /// <param name='output'>
            /// If the output specified does not already exist, this parameter must contain
            /// the full output definition intended to be tested. If the output specified
            /// already exists, this parameter can be left null to test the existing output
            /// as is or if specified, the properties specified will overwrite the
            /// corresponding properties in the existing output (exactly like a PATCH
            /// operation) and the resulting output will be tested.
            /// </param>
            public static ResourceTestStatus Test(this IOutputsOperations operations, string resourceGroupName, string jobName, string outputName, Output output = default(Output))
            {
                return operations.TestAsync(resourceGroupName, jobName, outputName, output).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Tests whether an output's datasource is reachable and usable by the Azure
            /// Stream Analytics service.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group that contains the resource. You can obtain
            /// this value from the Azure Resource Manager API or the portal.
            /// </param>
            /// <param name='jobName'>
            /// The name of the streaming job.
            /// </param>
            /// <param name='outputName'>
            /// The name of the output.
            /// </param>
            /// <param name='output'>
            /// If the output specified does not already exist, this parameter must contain
            /// the full output definition intended to be tested. If the output specified
            /// already exists, this parameter can be left null to test the existing output
            /// as is or if specified, the properties specified will overwrite the
            /// corresponding properties in the existing output (exactly like a PATCH
            /// operation) and the resulting output will be tested.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<ResourceTestStatus> TestAsync(this IOutputsOperations operations, string resourceGroupName, string jobName, string outputName, Output output = default(Output), CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.TestWithHttpMessagesAsync(resourceGroupName, jobName, outputName, output, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Tests whether an output's datasource is reachable and usable by the Azure
            /// Stream Analytics service.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group that contains the resource. You can obtain
            /// this value from the Azure Resource Manager API or the portal.
            /// </param>
            /// <param name='jobName'>
            /// The name of the streaming job.
            /// </param>
            /// <param name='outputName'>
            /// The name of the output.
            /// </param>
            /// <param name='output'>
            /// If the output specified does not already exist, this parameter must contain
            /// the full output definition intended to be tested. If the output specified
            /// already exists, this parameter can be left null to test the existing output
            /// as is or if specified, the properties specified will overwrite the
            /// corresponding properties in the existing output (exactly like a PATCH
            /// operation) and the resulting output will be tested.
            /// </param>
            public static ResourceTestStatus BeginTest(this IOutputsOperations operations, string resourceGroupName, string jobName, string outputName, Output output = default(Output))
            {
                return operations.BeginTestAsync(resourceGroupName, jobName, outputName, output).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Tests whether an output's datasource is reachable and usable by the Azure
            /// Stream Analytics service.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group that contains the resource. You can obtain
            /// this value from the Azure Resource Manager API or the portal.
            /// </param>
            /// <param name='jobName'>
            /// The name of the streaming job.
            /// </param>
            /// <param name='outputName'>
            /// The name of the output.
            /// </param>
            /// <param name='output'>
            /// If the output specified does not already exist, this parameter must contain
            /// the full output definition intended to be tested. If the output specified
            /// already exists, this parameter can be left null to test the existing output
            /// as is or if specified, the properties specified will overwrite the
            /// corresponding properties in the existing output (exactly like a PATCH
            /// operation) and the resulting output will be tested.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<ResourceTestStatus> BeginTestAsync(this IOutputsOperations operations, string resourceGroupName, string jobName, string outputName, Output output = default(Output), CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.BeginTestWithHttpMessagesAsync(resourceGroupName, jobName, outputName, output, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Lists all of the outputs under the specified streaming job.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='nextPageLink'>
            /// The NextLink from the previous successful call to List operation.
            /// </param>
            public static IPage<Output> ListByStreamingJobNext(this IOutputsOperations operations, string nextPageLink)
            {
                return operations.ListByStreamingJobNextAsync(nextPageLink).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Lists all of the outputs under the specified streaming job.
            /// </summary>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='nextPageLink'>
            /// The NextLink from the previous successful call to List operation.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<IPage<Output>> ListByStreamingJobNextAsync(this IOutputsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.ListByStreamingJobNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

    }
}


text:
metro
=====

This is a [Sinatra](http://www.sinatrarb.com) application prototype that you can use in order to study Sinatra using some actual code. Although it's not polished, I wanted to publish this online
in order to help other newcommers. This application is pure ruby, there's not much JavaScript laying around but you can add your code on top if needed, the application will load
all files sitting in `public/js/` directory automatically.

## What was the Application for?

I have deployed two [Screenly](http://www.screenlyapp.com/) nodes. Screenly uses an [SQLite3](http://www.sqlite.org/index.html) database. This application shows informations about my nodes but can display info
about third party nodes as well. The nodes were connected to an [OpenVPN](http://openvpn.net/) server. I run my Rack applications using [unicorn](http://unicorn.bogomips.org/) HTTP server, but you can choose
whatever you like.

## Technologies involved

Browsing the code you can find the following:

* Multilingual support using [i18n gem](https://github.com/svenfuchs/i18n).
* Full login scheme.
* Session handling using [sinatra-session](https://github.com/mjijackson/sinatra-session).
* Role authentication / permissions via `session['name']`.
* Database passwords are encrypted and salted using [bcrypt](http://bcrypt-ruby.rubyforge.org/).
* Caching support using [sinatra-cache](https://github.com/kematzy/sinatra-cache), some [Nginx](http://www.nginx.org) fine tunning is necessary but improves response time considerably.
* Email support using [pony gem](https://github.com/benprew/pony).
* [RSpec](http://rspec.info/) and [Capybara](https://github.com/jnicklas/capybara) testing.

HTML5/CSS is based on the awesome [workless](http://workless.ikreativ.com/) and the initial skeleton is based on [riblits](https://github.com/Phrogz/riblits).


text:
class XlsxWriter
  class VmlDrawing < Xml
    def relative_path
      "xl/drawings/vmlDrawing1.vml"
    end
  end
end


text:
<?php

/*
    VERY IMPORTANT, PLEASE ADD COMMENTS DESRIBES YOUR QUERIES AND COMMANDS
*/

class Guest extends Human {
    /*
        Guest will sign up for an account, you will use the global add method
    */
    public function Regestration($Email , $Password , $firstname, $lastname,$address , $phonenumber) {
        $DB = Database::getObject();
        $userid = mysqli_fetch_array($DB->get("user_types",array("id"),"type","user"));
        $array = array("first_name" => $firstname, "last_name" => $lastname, "email" => $Email, "phone_number" => $phonenumber, "user_type_id" => $userid[0]);
        if (Validation::checkEmail($Email) != "update") {
            $DB->add("user", $array);
        } else {
            $DB->edit("user", $array, "email", $array["email"]);
        }

        $getuserID = mysqli_fetch_array($DB->get("user", array("id"), "email", $Email));
        //echo $getuserID[0];

        $Password = md5($Password);
        $DB->add("member_details", array("user_id" => $getuserID[0], "password" => $Password, "address" => $address));

        $associativeArray = array("id" => $getuserID[0], "first_name" => $firstname, "last_name" => $lastname, "email" => $Email, "phone_number" => $phonenumber, "user_type_id" => 0, "address" => $address);

        foreach ($associativeArray as $key => $value) {
            $_SESSION["$key"] = $value;
        }
        $_SESSION["password"] = $Password;
    }

    /*
        Guest will make a reservation, you will use the global add method
    */
    public function addReservation(reservation $reservation) {
        //TODO
    }

    /*
        Guest will update a reservation, you will use the global update method
    */
    public function updateReservation(reservation $reservation) {
        //TODO
    }

    /*
        Guest will delete a reservation, you will use the global delete method
    */
    public function deleteReservation(reservation $reservation) {
        //TODO
    }
}


text:
'use strict';

let express       = require('express')
let session       = require('express-session')
let path          = require('path')
let redis         = require('redis')
let favicon       = require('serve-favicon')
let bodyParser    = require('body-parser')
let cookieParser  = require('cookie-parser')

let config = require('./config')
let app    = express()
let router = require('./router')
let Store  = require('connect-redis')(session)
let client = redis.createClient(
  config.redis.url, { no_ready_check: true }
)

client.auth(config.redis.password, (err) => {
  if (err) { console.log(err); return err }
})

app.set('port', process.env.PORT || 7000)
app.set('view engine', 'html')
app.set('cookieSecret', config.cookieSecret)

app.enable('trust proxy', 1)
app.disable('x-powered-by')

app.use(favicon(path.join(__dirname, 'favicon.ico')))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(session({
  genid () { return require('node-uuid').v1() },
  secret: app.get('cookieSecret'),
  resave: false,
  saveUninitialized: false,
  store: new Store({ client: client }),
  cookie: {
    path: '/',
    maxAge: new Date(Date.now() + (60 * 1000 * 60 * 24)),
    expires: new Date(Date.now() + (60 * 1000 * 60 * 24)),
    signed: true,
    httpOnly: true
  }
}))

app.use(router(app, Store, client))
app.use('/assets', express.static(path.join(__dirname, '/../public/assets')))
app.use('/dashboard', express.static(path.join(__dirname, '/../public/dashboard')))

app.listen(app.get('port'), function () {
  console.info(`\n\tExpress running on http://0.0.0.0:${app.get('port')}\n`)
})


text:
package org.teavm.classlib.java.util;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.DuplicateFormatFlagsException;
import java.util.FormatFlagsConversionMismatchException;
import java.util.Formattable;
import java.util.Formatter;
import java.util.IllegalFormatCodePointException;
import java.util.IllegalFormatConversionException;
import java.util.IllegalFormatFlagsException;
import java.util.IllegalFormatPrecisionException;
import java.util.Locale;
import java.util.MissingFormatWidthException;
import java.util.UnknownFormatConversionException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.teavm.junit.TeaVMTestRunner;
import org.teavm.junit.WholeClassCompilation;

@RunWith(TeaVMTestRunner.class)
@WholeClassCompilation
public class FormatterTest {
    @Test(expected = UnknownFormatConversionException.class)
    public void unexpectedEndOfFormatString() {
        new Formatter().format("%1", "foo");
    }

    @Test(expected = DuplicateFormatFlagsException.class)
    public void duplicateFlag() {
        new Formatter().format("%--s", "q");
    }

    @Test(expected = UnknownFormatConversionException.class)
    public void noPrecisionAfterDot() {
        new Formatter().format("%1.s", "q");
    }

    @Test
    public void bothPreviousModifierAndArgumentIndexPresent() {
        String result = new Formatter().format("%s %2$<s", "q", "w").toString();
        assertEquals("q q", result);
    }

    @Test
    public void formatsBoolean() {
        assertEquals("true", new Formatter().format("%b", true).toString());
        assertEquals("false", new Formatter().format("%b", false).toString());

        assertEquals("true", new Formatter().format("%b", new Object()).toString());
        assertEquals("false", new Formatter().format("%b", null).toString());

        assertEquals("  true", new Formatter().format("%6b", true).toString());
        assertEquals("true  ", new Formatter().format("%-6b", true).toString());
        assertEquals("true", new Formatter().format("%2b", true).toString());
        assertEquals("tr", new Formatter().format("%2.2b", true).toString());
        assertEquals("  tr", new Formatter().format("%4.2b", true).toString());
        assertEquals("TRUE", new Formatter().format("%B", true).toString());

        try {
            new Formatter().format("%+b", true);
            fail("Should have thrown exception");
        } catch (FormatFlagsConversionMismatchException e) {
            assertEquals("+", e.getFlags());
            assertEquals('b', e.getConversion());
        }
    }

    @Test
    public void formatsString() {
        assertEquals("23 foo", new Formatter().format("%s %s", 23, "foo").toString());
        assertEquals("0:-1:-1", new Formatter().format("%s", new A()).toString());
        assertEquals("0:2:-1", new Formatter().format("%2s", new A()).toString());
        assertEquals("0:2:3", new Formatter().format("%2.3s", new A()).toString());
        assertEquals("1:3:-1", new Formatter().format("%-3s", new A()).toString());
    }

    static class A implements Formattable {
        @Override
        public void formatTo(Formatter formatter, int flags, int width, int precision) {
            formatter.format("%s", flags + ":" + width + ":" + precision);
        }
    }

    @Test
    public void formatsHashCode() {
        assertEquals("18cc6 17C13", new Formatter().format("%h %H", "foo", "bar").toString());
    }

    @Test
    public void respectsFormatArgumentOrder() {
        String result = new Formatter().format("%s %s %<s %1$s %<s %s %1$s %s %<s", "a", "b", "c", "d").toString();
        assertEquals("a b b a a c a d d", result);
    }

    @Test
    public void formatsChar() {
        assertEquals("x:  Y:\uDBFF\uDFFF ", new Formatter().format("%c:%3C:%-3c", 'x', 'y', 0x10ffff).toString());

        try {
            new Formatter().format("%c", Integer.MAX_VALUE);
            fail("IllegalFormatCodePointException expected");
        } catch (IllegalFormatCodePointException e) {
            assertEquals(Integer.MAX_VALUE, e.getCodePoint());
        }

        assertEquals("null", new Formatter().format("%c", new Object[] { null }).toString());

        try {
            new Formatter().format("%C", new A());
            fail("IllegalFormatConversionException expected");
        } catch (IllegalFormatConversionException e) {
            assertEquals(A.class, e.getArgumentClass());
        }

        try {
            new Formatter().format("%3.1c", 'X');
            fail("IllegalFormatPrecisionException expected");
        } catch (IllegalFormatPrecisionException e) {
            assertEquals(1, e.getPrecision());
        }
    }

    @Test
    public void formatsDecimalInteger() {
        assertEquals("1 2 3 4", new Formatter().format("%d %d %d %d", (byte) 1, (short) 2, 3, 4L).toString());

        assertEquals("00023", new Formatter().format("%05d", 23).toString());
        assertEquals("-0023", new Formatter().format("%05d", -23).toString());
        assertEquals("00001,234", new Formatter(Locale.US).format("%0,9d", 1234).toString());
        assertEquals("(001,234)", new Formatter(Locale.US).format("%0,(9d", -1234).toString());

        assertEquals("1 12 123 1,234 12,345 123,456 1,234,567", new Formatter(Locale.US)
                .format("%,d %,d %,d %,d %,d %,d %,d", 1, 12, 123, 1234, 12345, 123456, 1234567).toString());

        assertEquals("  -123:-234  ", new Formatter().format("%6d:%-6d", -123, -234).toString());

        assertEquals("+123 +0123 +0", new Formatter().format("%+d %+05d %+d", 123, 123, 0).toString());

        assertEquals(": 123:-123:", new Formatter().format(":% d:% d:", 123, -123).toString());

        try {
            new Formatter().format("%#d", 23);
            fail("Should have thrown exception 1");
        } catch (FormatFlagsConversionMismatchException e) {
            assertEquals("#", e.getFlags());
        }

        try {
            new Formatter().format("% +d", 23);
            fail("Should have thrown exception 2");
        } catch (IllegalFormatFlagsException e) {
            assertTrue(e.getFlags().contains("+"));
            assertTrue(e.getFlags().contains(" "));
        }

        try {
            new Formatter().format("%-01d", 23);
            fail("Should have thrown exception 3");
        } catch (IllegalFormatFlagsException e) {
            assertTrue(e.getFlags().contains("-"));
            assertTrue(e.getFlags().contains("0"));
        }

        try {
            new Formatter().format("%-d", 23);
            fail("Should have thrown exception 4");
        } catch (MissingFormatWidthException e) {
            assertTrue(e.getFormatSpecifier().contains("d"));
        }

        try {
            new Formatter().format("%1.2d", 23);
            fail("Should have thrown exception 5");
        } catch (IllegalFormatPrecisionException e) {
            assertEquals(2, e.getPrecision());
        }
    }

    @Test
    public void formatsOctalInteger() {
        assertEquals("1 2 3 4", new Formatter().format("%o %o %o %o", (byte) 1, (short) 2, 3, 4L).toString());

        assertEquals("00027", new Formatter().format("%05o", 23).toString());
        assertEquals("0173", new Formatter().format("%#o", 123).toString());

        try {
            new Formatter().format("%-01o", 23);
            fail("Should have thrown exception 1");
        } catch (IllegalFormatFlagsException e) {
            assertTrue(e.getFlags().contains("-"));
            assertTrue(e.getFlags().contains("0"));
        }

        try {
            new Formatter().format("%-o", 23);
            fail("Should have thrown exception 2");
        } catch (MissingFormatWidthException e) {
            assertTrue(e.getFormatSpecifier().contains("o"));
        }

        try {
            new Formatter().format("%1.2o", 23);
            fail("Should have thrown exception 3");
        } catch (IllegalFormatPrecisionException e) {
            assertEquals(2, e.getPrecision());
        }
    }

    @Test
    public void formatsHexInteger() {
        assertEquals("1 2 3 4", new Formatter().format("%x %x %x %x", (byte) 1, (short) 2, 3, 4L).toString());

        assertEquals("00017", new Formatter().format("%05x", 23).toString());
        assertEquals("0x7b", new Formatter().format("%#x", 123).toString());

        try {
            new Formatter().format("%-01x", 23);
            fail("Should have thrown exception 1");
        } catch (IllegalFormatFlagsException e) {
            assertTrue(e.getFlags().contains("-"));
            assertTrue(e.getFlags().contains("0"));
        }

        try {
            new Formatter().format("%-x", 23);
            fail("Should have thrown exception 2");
        } catch (MissingFormatWidthException e) {
            assertTrue(e.getFormatSpecifier().contains("x"));
        }

        try {
            new Formatter().format("%1.2x", 23);
            fail("Should have thrown exception 3");
        } catch (IllegalFormatPrecisionException e) {
            assertEquals(2, e.getPrecision());
        }
    }
}


text:
<?php

namespace Naldz\Bundle\AuditLogBundle\Tests\Unit\DependencyInjection;

use Naldz\Bundle\AuditLogBundle\DependencyInjection\Configuration;
use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\Yaml\Parser;

class ConfigurationTest extends \PHPUnit_Framework_TestCase
{

    public function testNormalEventConfiguration()
    {
        $yaml = new Parser();
        $rawConfig = $yaml->parse('
audit_log:
    connection:
        host: "localhost"
        username: "root"
        password: "password"
        database: "database"
    user_info_provider_service: "test_user_provider_service"
    event_processor_service: "test_event_processor_service"
    events:
        patient.archive:
            message: "Patient has been archived."
        patient.add:
            message: "Patient has been archived."
');
        $processor = new Processor();
        $configuration = new Configuration();
        $config = $processor->processConfiguration($configuration, $rawConfig);
    }

    public function testInvalidEventProcessor()
    {
        $this->setExpectedException('RuntimeException');

        $yaml = new Parser();
        $rawConfig = $yaml->parse('
audit_log:
    connection:
        host: "localhost"
        username: "root"
        password: "password"
        database: "database"
    user_info_provider_service: "test_user_provider_service"
    event_processor_service: ~
    events:
        patient.archive:
            message: "Patient has been archived."
        patient.add:
            message: "Patient has been archived."
');
        $processor = new Processor();
        $configuration = new Configuration();
        $config = $processor->processConfiguration($configuration, $rawConfig);
    }

    public function testInvalidUserProvider()
    {
        $this->setExpectedException('RuntimeException');

        $yaml = new Parser();
        $rawConfig = $yaml->parse('
audit_log:
    connection:
        host: "localhost"
        username: "root"
        password: "password"
        database: "database"
    user_info_provider_service: ~
    event_processor_service: "test_event_processor"
    events:
        patient.archive:
            message: "Patient has been archived."
        patient.add:
            message: "Patient has been archived."
');
        $processor = new Processor();
        $configuration = new Configuration();
        $config = $processor->processConfiguration($configuration, $rawConfig);
    }

}


text:
/* widgets/buttonToggle/widget.js */

//create an event-handler for when the user clicks the button
$.container.addEventListener("click", function(_event)
	{
		//hide the clicked item, show the unclicked one
		buttonToggleByIdClicked(_event.source.id);
	}
); //book bug: missing semi

//_buttonId name of the id of the UI control clicked
function buttonToggleByIdClicked(_buttonId)
{
	//a refresher/primer on === vs. == in JS
	//http://www.w3schools.com/js/js_comparisons.asp
	if(_buttonId === "on")
	{
		//remember the $ accesses controls in the view
		$.on.hide();
		$.off.show();
	}else if(_buttonId === "off")
	{
		$.on.show();
		$.off.hide();
	}
}


text:
from django.contrib import admin

from .models import Profile, Module

admin.site.register(Profile)
admin.site.register(Module)


text:
set -e

sudo yum -y install cmake bison flex boost-devel boost-python boost-regex

RDKIT_PKG="$1"
PYTHON_PREFIX="$2"

# Determine build locations
RDKIT_VERSION=`basename $RDKIT_PKG .tgz`
RDKIT_VERSION_STORE=$PYTHON_PREFIX/opt/rdkit
RDKIT_SRC=$RDKIT_VERSION_STORE/$RDKIT_VERSION
RDKIT_BUILD=$RDKIT_SRC/build
RDBASE=$PYTHON_PREFIX/local/rdkit
export RDBASE

$PYTHON_PREFIX/bin/python -c 'import numpy' || ( echo "ERROR: Numpy is required but was not found!" && exit 1 )
$PYTHON_PREFIX/bin/python -c 'import pandas' || (echo "WARNING: Pandas not found!" && sleep 5 )

NUM_PROCS=$( grep processor /proc/cpuinfo | wc -l )
#UNCOMMENT THE FOLLOWING LINE FOR SERIAL BUILD
#NUM_PROCS=1

# Setup source tree
mkdir -pv $RDKIT_VERSION_STORE
tar -xzvf $RDKIT_PKG -C $RDKIT_VERSION_STORE
( cd $RDKIT_SRC/External/INCHI-API ; ./download-inchi.sh )

# Link current installation version to python-expected location
ln -sfnv ../opt/rdkit/$RDKIT_VERSION $RDBASE

mkdir -pv $RDKIT_BUILD
cd $RDKIT_BUILD

# Configure to use non-standard python
cmake -DPYTHON_EXECUTABLE=$PYTHON_PREFIX/bin/python \
      -DPYTHON_INCLUDE_PATH=$PYTHON_PREFIX/include/python2.7 \
      -DPYTHON_LIBRARY=$PYTHON_PREFIX/lib/libpython2.7.so \
      -DPYTHON_NUMPY_INCLUDE_PATH=$PYTHON_PREFIX/lib/python2.7/site-packages/numpy/core/include \
      -DRDK_BUILD_INCHI_SUPPORT=ON \
      -DINCHI_LIBRARY=$RDKIT_SRC/External/INCHI-API \
      -DINCHI_INCLUDE_DIR=$RDKIT_SRC/External/INCHI-API/src \
      ..

# Build with NUM_PROCS processes
make -j $NUM_PROCS
make install

# Manually install libraries to "addtional library path"
( cd $PYTHON_PREFIX/local/lib ; ln -sv ../rdkit/lib/lib* . )

# Install python path file
RDKIT_PTH=$( $PYTHON_PREFIX/bin/python -c 'import distutils;print distutils.sysconfig_get_python_lib()' )/rdkit.pth
cat > $RDKIT_PTH <<EOF
../../../local/rdkit
EOF


text:
using System;
using Android.Content;
using Android.Graphics;
using Android.Runtime;
using Android.Util;
using Android.Views;

namespace MonoDroid.ColorPickers
{
    public delegate void PanelClickedEventHandler(object sender, ColorChangedEventArgs e);

    class ColorPickerPanelView: View
    {
        public event PanelClickedEventHandler PanelClicked;

        /**
	     * The width in pixels of the border
	     * surrounding the color panel.
	     */
	    private const float	BorderWidthPx = 1;

	    private float _density = 1f;

	    private Color _borderColor = Color.Argb(255,110,110,110);
	    private Color _color = Color.Argb(255,0,0,0);

	    private Paint _borderPaint;
	    private Paint _colorPaint;

	    private RectF _drawingRect;
	    private RectF _colorRect;

	    private AlphaPatternDrawable _alphaPattern;

        protected ColorPickerPanelView(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
        {
            Init();
        }

        public ColorPickerPanelView(Context context) : this(context, null)
        {
        }

        public ColorPickerPanelView(Context context, IAttributeSet attrs) : this(context, attrs, 0)
        {
        }

        public ColorPickerPanelView(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle)
        {
            Init();
        }

        private void Init()
        {
            _borderPaint = new Paint();
            _colorPaint = new Paint();
            _density = Context.Resources.DisplayMetrics.Density;
        }

        public Color Color
        {
            get { return _color; }
            set {
                _color = value;
                Invalidate();
            }
        }

        public Color BorderColor
        {
            get { return _borderColor; }
            set
            {
                _borderColor = value;
                Invalidate();
            }
        }

        protected override void OnDraw(Canvas canvas)
        {
            var rect = _colorRect;

            if (BorderWidthPx > 0)
            {
                _borderPaint.Color = _borderColor;
                canvas.DrawRect(_drawingRect, _borderPaint);
		    }

            if (_alphaPattern != null)
            {
                _alphaPattern.Draw(canvas);
		    }

            _colorPaint.Color = _color;

            canvas.DrawRect(rect, _colorPaint);
        }

        protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec)
        {
            var width = MeasureSpec.GetSize(widthMeasureSpec);
            var height = MeasureSpec.GetSize(heightMeasureSpec);

            SetMeasuredDimension(width, height);
        }

        protected override void OnSizeChanged(int w, int h, int oldw, int oldh)
        {
            base.OnSizeChanged(w, h, oldw, oldh);

            _drawingRect = new RectF
                               {
                                   Left = PaddingLeft,
                                   Right = w - PaddingRight,
                                   Top = PaddingTop,
                                   Bottom = h - PaddingBottom
                               };

            SetUpColorRect();
        }

        private void SetUpColorRect(){
		    var dRect = _drawingRect;

            var left = dRect.Left + BorderWidthPx;
            var top = dRect.Top + BorderWidthPx;
            var bottom = dRect.Bottom - BorderWidthPx;
            var right = dRect.Right - BorderWidthPx;

		    _colorRect = new RectF(left,top, right, bottom);

		    _alphaPattern = new AlphaPatternDrawable((int)(5 * _density));

            _alphaPattern.SetBounds(
			    (int) Math.Round(_colorRect.Left),
                (int) Math.Round(_colorRect.Top),
                (int) Math.Round(_colorRect.Right),
                (int) Math.Round(_colorRect.Bottom)
		    );
	    }

        public override bool OnTouchEvent(MotionEvent e)
        {
            if (e.Action == MotionEventActions.Up || e.Action == MotionEventActions.Down)
            {
                if (PanelClicked != null)
                    PanelClicked(this, new ColorChangedEventArgs { Color = _color });
            }

            return base.OnTouchEvent(e);
        }
    }
}


text:
import itertools

from pyspark.sql import functions as sqlfunctions

from graphframes import GraphFrame

__all__ = ['Graphs']

class Graphs(object):
    """Example GraphFrames for testing the API

    :param sqlContext: SQLContext
    """

    def __init__(self, sqlContext):
        self._sql = sqlContext
        self._sc = sqlContext._sc

    def friends(self):
        """A GraphFrame of friends in a (fake) social network."""
        sqlContext = self._sql
        # Vertex DataFrame
        v = sqlContext.createDataFrame([
            ("a", "Alice", 34),
            ("b", "Bob", 36),
            ("c", "Charlie", 30),
            ("d", "David", 29),
            ("e", "Esther", 32),
            ("f", "Fanny", 36)
        ], ["id", "name", "age"])
        # Edge DataFrame
        e = sqlContext.createDataFrame([
            ("a", "b", "friend"),
            ("b", "c", "follow"),
            ("c", "b", "follow"),
            ("f", "c", "follow"),
            ("e", "f", "follow"),
            ("e", "d", "friend"),
            ("d", "a", "friend")
        ], ["src", "dst", "relationship"])
        # Create a GraphFrame
        return GraphFrame(v, e)

    def gridIsingModel(self, n, vStd=1.0, eStd=1.0):
        """Grid Ising model with random parameters.

        Ising models are probabilistic graphical models over binary variables x\ :sub:`i`.
        Each binary variable x\ :sub:`i` corresponds to one vertex, and it may take values -1 or +1.
        The probability distribution P(X) (over all x\ :sub:`i`) is parameterized by vertex factors
        a\ :sub:`i` and edge factors b\ :sub:`ij`:

           P(X) = (1/Z) * exp[ \sum_i a_i x_i + \sum_{ij} b_{ij} x_i x_j ]

        where Z is the normalization constant (partition function). See `Wikipedia
        <https://en.wikipedia.org/wiki/Ising_model>`__ for more information on Ising models.

        Each vertex is parameterized by a single scalar a\ :sub:`i`.
        Each edge is parameterized by a single scalar b\ :sub:`ij`.

        :param n: Length of one side of the grid.  The grid will be of size n x n.
        :param vStd: Standard deviation of normal distribution used to generate vertex factors "a".
                     Default of 1.0.
        :param eStd: Standard deviation of normal distribution used to generate edge factors "b".
                     Default of 1.0.
        :return: GraphFrame. Vertices have columns "id" and "a". Edges have columns "src", "dst",
            and "b".  Edges are directed, but they should be treated as undirected in any algorithms
            run on this model. Vertex IDs are of the form "i,j".  E.g., vertex "1,3" is in the
            second row and fourth column of the grid.
        """
        # check param n
        if n < 1:
            raise ValueError(
                "Grid graph must have size >= 1, but was given invalid value n = {}"
                .format(n))

        # create coodinates grid
        coordinates = self._sql.createDataFrame(
            itertools.product(range(n), range(n)),
            schema=('i', 'j'))

        # create SQL expression for converting coordinates (i,j) to a string ID "i,j"
        # avoid Cartesian join due to SPARK-15425: use generator since n should be small
        toIDudf = sqlfunctions.udf(lambda i, j: '{},{}'.format(i,j))

        # create the vertex DataFrame
        # create SQL expression for converting coordinates (i,j) to a string ID "i,j"
        vIDcol = toIDudf(sqlfunctions.col('i'), sqlfunctions.col('j'))
        # add random parameters generated from a normal distribution
        seed = 12345
        vertices = (coordinates.withColumn('id', vIDcol)
            .withColumn('a', sqlfunctions.randn(seed) * vStd))

        # create the edge DataFrame
        # create SQL expression for converting coordinates (i,j+1) and (i+1,j) to string IDs
        rightIDcol = toIDudf(sqlfunctions.col('i'), sqlfunctions.col('j') + 1)
        downIDcol = toIDudf(sqlfunctions.col('i') + 1, sqlfunctions.col('j'))
        horizontalEdges = (coordinates.filter(sqlfunctions.col('j') != n - 1)
            .select(vIDcol.alias('src'), rightIDcol.alias('dst')))
        verticalEdges = (coordinates.filter(sqlfunctions.col('i') != n - 1)
            .select(vIDcol.alias('src'), downIDcol.alias('dst')))
        allEdges = horizontalEdges.unionAll(verticalEdges)
        # add random parameters from a normal distribution
        edges = allEdges.withColumn('b', sqlfunctions.randn(seed + 1) * eStd)

        # create the GraphFrame
        g = GraphFrame(vertices, edges)

        # materialize graph as workaround for SPARK-13333
        g.vertices.cache().count()
        g.edges.cache().count()

        return g


text:
<?xml version='1.0' encoding='utf-8'?>
<root>
    <metric id='2001000' type='quality-rule' originalName='Avoid redefining paragraph'                           filter='-4' filterLabel='Cobol' />
    <metric id='2001002' type='quality-rule' originalName='Avoid occurs dependending on non binary data'         filter='-4' filterLabel='Cobol' />
    <metric id='2001004' type='quality-rule' originalName='Section should be terminated by an empty paragraph'         filter='-4' filterLabel='Cobol' />
</root>


text:
/* eslint-disable import/prefer-default-export */
import { useState, useLayoutEffect } from 'react';

/**
 * custom hoook to detect the window size of a broswer
 * @return {Array} [height, width ].
 */
export const useWindowSize = () => {
  const [size, setSize] = useState([0, 0]);
  useLayoutEffect(() => {
    function updateSize() {
      setSize([window.innerWidth, window.innerHeight]);
    }
    window.addEventListener('resize', updateSize);
    updateSize();
    return () => window.removeEventListener('resize', updateSize);
  }, []);
  return size;
};