text:
import React from "react";
import {useQuery} from "@apollo/client";
import gql from "graphql-tag.macro";
import {
  Button,
  UncontrolledDropdown as Dropdown,
  DropdownItem,
  DropdownMenu,
  DropdownToggle,
} from "helpers/reactstrap";
import {Link} from "react-router-dom";

const QueryResult = ({loading, data}) =>
  !loading && data?.thorium?.spaceEdventuresCenter?.flightTypes?.length > 0 ? (
    <Dropdown>
      <DropdownToggle caret size="lg" block color="success">
        New Flight
      </DropdownToggle>
      <DropdownMenu>
        <DropdownItem tag={Link} to="/flight">
          Unspecified Flight Type
        </DropdownItem>
        <DropdownItem divider />
        {data.thorium.spaceEdventuresCenter.flightTypes.map(f => (
          <DropdownItem
            tag={Link}
            to={`/flight?flightType=${f.id}`}
            key={f.id}
            value={f.id}
          >
            {f.name}
          </DropdownItem>
        ))}
      </DropdownMenu>
    </Dropdown>
  ) : (
    <Button tag={Link} to="/flight" color="success" block size="lg">
      New Flight
    </Button>
  );

const QUERY = gql`
  query Thorium {
    thorium {
      spaceEdventuresCenter {
        id
        name
        flightTypes {
          id
          name
          classHours
          flightHours
        }
      }
    }
  }
`;
const NewFlight = () => {
  const {loading, data} = useQuery(QUERY);
  return (

Start a new Flight

      <QueryResult loading={loading} data={data} />

  );
};
export default NewFlight;


text:
[CmdletBinding()]
param(
  [Parameter(Mandatory=$true, HelpMessage="Enter the specified node-version (e.g. 6.10.2) from https://nodejs.org/en/download/releases/.")]
  [String]$node_version,

  [Switch]$silent,

  [Switch]$publish
)

# ===== CONSTANTS =====
$REPOSITORYNAME = "softaware/webdev"
$IMAGEPATH = "./images/"
$DOCKERFILEROOTPATH = "$($IMAGEPATH)Dockerfile"
$DISTRIBUTIONS = @("alpine","debian")

function Generate-Image {
  param(
    [String]$node_version,
    [String]$distribution,
    [Boolean]$silent,
    [Boolean]$publish
  )

  $generatedfile = $IMAGEPATH + "Dockerfile.gen"

  $dockerfile = $DOCKERFILEROOTPATH + "." + $distribution
  $tag = $distribution + "-" + $node_version
  $imagename = $REPOSITORYNAME + ":" + $tag

  $template = Get-Content $dockerfile -Raw
  $generated = $template.Replace("{{ node_version }}", $node_version)
  $generated | Out-File -Encoding UTF8 $generatedfile

  $command = {docker image build (&{If($silent) {"--quiet"}}) --force-rm -f $generatedfile -t $imagename $IMAGEPATH}
  if (!$silent) {& $command} else {& $command | Out-Null}
  Remove-Item $generatedfile

  "$($imagename) created successfully"

  if ($publish) {
    Publish-Image $imagename
  }
}

function Publish-Image {
  param(
    [String]$imagename
  )
  $command = {docker push $imagename}
  if (!$silent) {& $command} else {& $command | Out-Null}

  "$($imagename) published successfully"
}

function Generate-Images {
  param(
    [String]$node_version,
    [String[]]$distributions,
    [Boolean]$silent,
    [Boolean]$publish
  )
  foreach ($distribution in $distributions) {
    Generate-Image $node_version $distribution $silent $publish
  }
}

Generate-Images $node_version $DISTRIBUTIONS $silent.IsPresent $publish.IsPresent

redpajama_set_name: RedPajamaGithub


text:
import { connect } from 'react-redux';

import { historyPush } from '../actions/routeActions';
import Header from '../components/general/Header';

const mapStateToProps = ({ userStore }) => ({
  isLoggedIn: !!userStore.user.id,
  isUserAdmin: userStore.user.isAdmin,
});

const mapDispatchToProps = dispatch => ({
  onShortcutClick: path => dispatch(historyPush(path)),
});

export default connect(mapStateToProps, mapDispatchToProps)(Header);


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TestItemCreator;

namespace QuizControl
{
    public class TestRenderer
    {
        public void RenderTest(Test test)
        {
        }

        public void RenderQuestion(Question question)
        {
        }

        public void RenderTests(List<Test> tests)
        {
        }

        public void RenderScoreBoard()
        {
        }
        public void RenderFinishButton()
        {
        }
        public TestRenderer OnCalculateResultBtnClick()
        {
            return new TestRenderer();
        }
        public void SetDialogWinProperties()
        {}
        public void SetDialogButtons()
        {}

    }
}


text:
use std::collections::hash_map::DefaultHasher;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};

use itertools::Itertools;
use pyo3::basic::CompareOp;
use pyo3::exceptions::{PyException, PyTypeError, PyValueError};
use pyo3::prelude::*;
use pyo3::types::{PyIterator, PyString, PyTuple, PyType};

use fs::{
  DirectoryDigest, FilespecMatcher, GlobExpansionConjunction, PathGlobs, StrictGlobMatching,
  EMPTY_DIRECTORY_DIGEST,
};
use hashing::{Digest, Fingerprint, EMPTY_DIGEST};
use store::Snapshot;

use crate::Failure;

pub(crate) fn register(m: &PyModule) -> PyResult<()> {
  m.add_class::<PyDigest>()?;
  m.add_class::<PyFileDigest>()?;
  m.add_class::<PySnapshot>()?;
  m.add_class::<PyMergeDigests>()?;
  m.add_class::<PyAddPrefix>()?;
  m.add_class::<PyRemovePrefix>()?;
  m.add_class::<PyFilespecMatcher>()?;

  m.add("EMPTY_DIGEST", PyDigest(EMPTY_DIRECTORY_DIGEST.clone()))?;
  m.add("EMPTY_FILE_DIGEST", PyFileDigest(EMPTY_DIGEST))?;
  m.add("EMPTY_SNAPSHOT", PySnapshot(Snapshot::empty()))?;

  m.add_function(wrap_pyfunction!(default_cache_path, m)?)?;
  Ok(())
}

///
/// A marker indicating that a `StoreError` is being converted into a python exception, since retry
/// via #11331 needs to preserve `Failure` information across Python boundaries.
///
/// TODO: Any use of `PyErr::from(Failure::from(StoreError))` would trigger this same conversion,
/// so this method can eventually be replaced with direct conversion via `?`.
///
pub fn possible_store_missing_digest(e: store::StoreError) -> PyErr {
  let failure: Failure = e.into();
  failure.into()
}

#[pyclass(name = "Digest")]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PyDigest(pub DirectoryDigest);

impl fmt::Display for PyDigest {
  fn fmt(&self, f: &mut fmt::Formatter) -> std::fmt::Result {
    let digest = self.0.as_digest();
    write!(
      f,
      "Digest('{}', {})",
      digest.hash.to_hex(),
      digest.size_bytes,
    )
  }
}

#[pymethods]
impl PyDigest {
  /// NB: This constructor is only safe for use in testing, or when there is some other guarantee
  /// that the Digest has been persisted.
  #[new]
  fn __new__(fingerprint: &str, serialized_bytes_length: usize) -> PyResult<Self> {
    let fingerprint = Fingerprint::from_hex_string(fingerprint)
      .map_err(|e| PyValueError::new_err(format!("Invalid digest hex: {}", e)))?;
    Ok(Self(DirectoryDigest::from_persisted_digest(Digest::new(
      fingerprint,
      serialized_bytes_length,
    ))))
  }

  fn __hash__(&self) -> u64 {
    self.0.as_digest().hash.prefix_hash()
  }

  fn __repr__(&self) -> String {
    format!("{}", self)
  }

  fn __richcmp__(&self, other: &PyDigest, op: CompareOp, py: Python) -> PyObject {
    match op {
      CompareOp::Eq => (self == other).into_py(py),
      CompareOp::Ne => (self != other).into_py(py),
      _ => py.NotImplemented(),
    }
  }

  #[getter]
  fn fingerprint(&self) -> String {
    self.0.as_digest().hash.to_hex()
  }

  #[getter]
  fn serialized_bytes_length(&self) -> usize {
    self.0.as_digest().size_bytes
  }
}

#[pyclass(name = "FileDigest")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PyFileDigest(pub Digest);

#[pymethods]
impl PyFileDigest {
  #[new]
  fn __new__(fingerprint: &str, serialized_bytes_length: usize) -> PyResult<Self> {
    let fingerprint = Fingerprint::from_hex_string(fingerprint)
      .map_err(|e| PyValueError::new_err(format!("Invalid file digest hex: {}", e)))?;
    Ok(Self(Digest::new(fingerprint, serialized_bytes_length)))
  }

  fn __hash__(&self) -> u64 {
    self.0.hash.prefix_hash()
  }

  fn __repr__(&self) -> String {
    format!(
      "FileDigest('{}', {})",
      self.0.hash.to_hex(),
      self.0.size_bytes
    )
  }

  fn __richcmp__(&self, other: &PyFileDigest, op: CompareOp, py: Python) -> PyObject {
    match op {
      CompareOp::Eq => (self == other).into_py(py),
      CompareOp::Ne => (self != other).into_py(py),
      _ => py.NotImplemented(),
    }
  }

  #[getter]
  fn fingerprint(&self) -> String {
    self.0.hash.to_hex()
  }

  #[getter]
  fn serialized_bytes_length(&self) -> usize {
    self.0.size_bytes
  }
}

#[pyclass(name = "Snapshot")]
pub struct PySnapshot(pub Snapshot);

#[pymethods]
impl PySnapshot {
  #[classmethod]
  fn _unsafe_create(
    _cls: &PyType,
    py_digest: PyDigest,
    files: Vec<String>,
    dirs: Vec<String>,
  ) -> PyResult<Self> {
    let snapshot =
      unsafe { Snapshot::create_for_testing_ffi(py_digest.0.as_digest(), files, dirs) };
    Ok(Self(snapshot.map_err(PyException::new_err)?))
  }

  fn __hash__(&self) -> u64 {
    self.0.digest.hash.prefix_hash()
  }

  fn __repr__(&self) -> PyResult<String> {
    Ok(format!(
      "Snapshot(digest=({}, {}), dirs=({}), files=({}))",
      self.0.digest.hash.to_hex(),
      self.0.digest.size_bytes,
      self
        .0
        .tree
        .directories()
        .into_iter()
        .map(|d| d.display().to_string())
        .collect::<Vec<_>>()
        .join(","),
      self
        .0
        .tree
        .files()
        .into_iter()
        .map(|d| d.display().to_string())
        .collect::<Vec<_>>()
        .join(","),
    ))
  }

  fn __richcmp__(&self, other: &PySnapshot, op: CompareOp, py: Python) -> PyObject {
    match op {
      CompareOp::Eq => (self.0.digest == other.0.digest).into_py(py),
      CompareOp::Ne => (self.0.digest != other.0.digest).into_py(py),
      _ => py.NotImplemented(),
    }
  }

  #[getter]
  fn digest(&self) -> PyDigest {
    PyDigest(self.0.clone().into())
  }

  #[getter]
  fn files<'py>(&self, py: Python<'py>) -> &'py PyTuple {
    let files = self.0.tree.files();
    PyTuple::new(
      py,
      files
        .into_iter()
        .map(|path| PyString::new(py, &path.to_string_lossy()))
        .collect::<Vec<_>>(),
    )
  }

  #[getter]
  fn dirs<'py>(&self, py: Python<'py>) -> &'py PyTuple {
    let dirs = self.0.tree.directories();
    PyTuple::new(
      py,
      dirs
        .into_iter()
        .map(|path| PyString::new(py, &path.to_string_lossy()))
        .collect::<Vec<_>>(),
    )
  }

  // NB: Prefix with underscore. The Python call will be hidden behind a helper which returns a much
  // richer type.
  fn _diff<'py>(&self, other: &PySnapshot, py: Python<'py>) -> &'py PyTuple {
    let result = self.0.tree.diff(&other.0.tree);

    let into_tuple = |x: &Vec<PathBuf>| -> &'py PyTuple {
      PyTuple::new(
        py,
        x.iter()
          .map(|path| PyString::new(py, &path.to_string_lossy()))
          .collect::<Vec<_>>(),
      )
    };

    PyTuple::new(
      py,
      vec![
        into_tuple(&result.our_unique_files),
        into_tuple(&result.our_unique_dirs),
        into_tuple(&result.their_unique_files),
        into_tuple(&result.their_unique_dirs),
        into_tuple(&result.changed_files),
      ],
    )
  }
}

#[pyclass(name = "MergeDigests")]
#[derive(Debug, PartialEq, Eq)]
pub struct PyMergeDigests(pub Vec<DirectoryDigest>);

#[pymethods]
impl PyMergeDigests {
  #[new]
  fn __new__(digests: &PyAny, py: Python) -> PyResult<Self> {
    let digests: PyResult<Vec<DirectoryDigest>> = PyIterator::from_object(py, digests)?
      .map(|v| {
        let py_digest = v?.extract::<PyDigest>()?;
        Ok(py_digest.0)
      })
      .collect();
    Ok(Self(digests?))
  }

  fn __hash__(&self) -> u64 {
    let mut s = DefaultHasher::new();
    self.0.hash(&mut s);
    s.finish()
  }

  fn __repr__(&self) -> String {
    let digests = self
      .0
      .iter()
      .map(|d| format!("{}", PyDigest(d.clone())))
      .join(", ");
    format!("MergeDigests([{}])", digests)
  }

  fn __richcmp__(&self, other: &PyMergeDigests, op: CompareOp, py: Python) -> PyObject {
    match op {
      CompareOp::Eq => (self == other).into_py(py),
      CompareOp::Ne => (self != other).into_py(py),
      _ => py.NotImplemented(),
    }
  }
}

#[pyclass(name = "AddPrefix")]
#[derive(Debug, PartialEq, Eq)]
pub struct PyAddPrefix {
  pub digest: DirectoryDigest,
  pub prefix: PathBuf,
}

#[pymethods]
impl PyAddPrefix {
  #[new]
  fn __new__(digest: PyDigest, prefix: PathBuf) -> Self {
    Self {
      digest: digest.0,
      prefix,
    }
  }

  fn __hash__(&self) -> u64 {
    let mut s = DefaultHasher::new();
    self.digest.as_digest().hash.prefix_hash().hash(&mut s);
    self.prefix.hash(&mut s);
    s.finish()
  }

  fn __repr__(&self) -> String {
    format!(
      "AddPrefix('{}', {})",
      PyDigest(self.digest.clone()),
      self.prefix.display()
    )
  }

  fn __richcmp__(&self, other: &PyAddPrefix, op: CompareOp, py: Python) -> PyObject {
    match op {
      CompareOp::Eq => (self == other).into_py(py),
      CompareOp::Ne => (self != other).into_py(py),
      _ => py.NotImplemented(),
    }
  }
}

#[pyclass(name = "RemovePrefix")]
#[derive(Debug, PartialEq, Eq)]
pub struct PyRemovePrefix {
  pub digest: DirectoryDigest,
  pub prefix: PathBuf,
}

#[pymethods]
impl PyRemovePrefix {
  #[new]
  fn __new__(digest: PyDigest, prefix: PathBuf) -> Self {
    Self {
      digest: digest.0,
      prefix,
    }
  }

  fn __hash__(&self) -> u64 {
    let mut s = DefaultHasher::new();
    self.digest.as_digest().hash.prefix_hash().hash(&mut s);
    self.prefix.hash(&mut s);
    s.finish()
  }

  fn __repr__(&self) -> String {
    format!(
      "RemovePrefix('{}', {})",
      PyDigest(self.digest.clone()),
      self.prefix.display()
    )
  }

  fn __richcmp__(&self, other: &PyRemovePrefix, op: CompareOp, py: Python) -> PyObject {
    match op {
      CompareOp::Eq => (self == other).into_py(py),
      CompareOp::Ne => (self != other).into_py(py),
      _ => py.NotImplemented(),
    }
  }
}

// -----------------------------------------------------------------------------
// PathGlobs
// -----------------------------------------------------------------------------

struct PyPathGlobs(PathGlobs);

impl<'source> FromPyObject<'source> for PyPathGlobs {
  fn extract(obj: &'source PyAny) -> PyResult<Self> {
    let globs: Vec<String> = obj.getattr("globs")?.extract()?;

    let description_of_origin_field = obj.getattr("description_of_origin")?;
    let description_of_origin = if description_of_origin_field.is_none() {
      None
    } else {
      Some(description_of_origin_field.extract()?)
    };

    let match_behavior_str: &str = obj
      .getattr("glob_match_error_behavior")?
      .getattr("value")?
      .extract()?;
    let match_behavior = StrictGlobMatching::create(match_behavior_str, description_of_origin)
      .map_err(PyValueError::new_err)?;

    let conjunction_str: &str = obj.getattr("conjunction")?.getattr("value")?.extract()?;
    let conjunction =
      GlobExpansionConjunction::create(conjunction_str).map_err(PyValueError::new_err)?;

    Ok(PyPathGlobs(PathGlobs::new(
      globs,
      match_behavior,
      conjunction,
    )))
  }
}

// -----------------------------------------------------------------------------
// FilespecMatcher
// -----------------------------------------------------------------------------

#[pyclass(name = "FilespecMatcher")]
#[derive(Debug)]
pub struct PyFilespecMatcher(FilespecMatcher);

#[pymethods]
impl PyFilespecMatcher {
  #[new]
  fn __new__(includes: Vec<String>, excludes: Vec<String>, py: Python) -> PyResult<Self> {
    // Parsing the globs has shown up in benchmarks
    // (https://github.com/pantsbuild/pants/issues/16122), so we use py.allow_threads().
    let matcher =
      py.allow_threads(|| FilespecMatcher::new(includes, excludes).map_err(PyValueError::new_err))?;
    Ok(Self(matcher))
  }

  fn __hash__(&self) -> u64 {
    let mut s = DefaultHasher::new();
    self.0.include_globs().hash(&mut s);
    self.0.exclude_globs().hash(&mut s);
    s.finish()
  }

  fn __repr__(&self) -> String {
    let includes = self
      .0
      .include_globs()
      .iter()
      .map(|pattern| pattern.to_string())
      .join(", ");
    let excludes = self.0.exclude_globs().join(", ");
    format!("FilespecMatcher(includes=['{includes}'], excludes=[{excludes}])",)
  }

  fn __richcmp__(&self, other: &PyFilespecMatcher, op: CompareOp, py: Python) -> PyObject {
    match op {
      CompareOp::Eq => (self.0.include_globs() == other.0.include_globs()
        && self.0.exclude_globs() == other.0.exclude_globs())
      .into_py(py),
      CompareOp::Ne => (self.0.include_globs() != other.0.include_globs()
        || self.0.exclude_globs() != other.0.exclude_globs())
      .into_py(py),
      _ => py.NotImplemented(),
    }
  }

  fn matches(&self, paths: Vec<String>, py: Python) -> PyResult<Vec<String>> {
    py.allow_threads(|| {
      Ok(
        paths
          .into_iter()
          .filter(|p| self.0.matches(Path::new(p)))
          .collect(),
      )
    })
  }
}

// -----------------------------------------------------------------------------
// Utils
// -----------------------------------------------------------------------------

#[pyfunction]
fn default_cache_path() -> PyResult<String> {
  fs::default_cache_path()
    .into_os_string()
    .into_string()
    .map_err(|s| {
      PyTypeError::new_err(format!(
        "Default cache path {:?} could not be converted to a string.",
        s
      ))
    })
}


text:
package org.jenkinsci.plugins.gitchangelog.perform;

import java.io.Serializable;

public class RemoteResult implements Serializable {

 private static final long serialVersionUID = 8363216067945804103L;
 private String leftSideTitle;
 private String leftSideUrl;
 private String log;
 private String summary;

 public String getLeftSideTitle() {
  return this.leftSideTitle;
 }

 public String getLeftSideUrl() {
  return this.leftSideUrl;
 }

 public String getLog() {
  return this.log;
 }

 public String getSummary() {
  return this.summary;
 }

 public void setLeftSide(String leftSideTitle, String leftSideUrl) {
  this.leftSideTitle = leftSideTitle;
  this.leftSideUrl = leftSideUrl;
 }

 public void setLog(String log) {
  this.log = log;
 }

 public void setSummary(String summary) {
  this.summary = summary;
 }
}


text:
using System;
using NUnit.Framework;
using ProtoSharp.Core;

namespace ProtoSharp.Core
{
    /*
     * Theese are taken from the documentation page at:
     * http://code.google.com/apis/protocolbuffers/docs/encoding.html
     */
    [TestFixture]
    public class EncodingTests
    {
        /*
         * message Test1 {
         *    required int32 a = 1;
         * }
         */
        //Test1 with a = 150
        public static readonly byte[] SimpleMessage = { 0x08, 0x96, 0x01 };
        [Test]
        public void SimpleMessageWireTypeIsVarint()
        {
            MessageReader reader = new MessageReader(SimpleMessage);
            Assert.AreEqual(WireType.Varint, reader.ReadMessageTag().WireType);
        }
        [Test]
        public void SimpleMessageTagIsOne()
        {
            MessageReader reader = new MessageReader(SimpleMessage);
            Assert.AreEqual(1, new MessageTag(reader.ReadInt32()).Number);
        }
        [Test]
        public void SimpleMessageValueIs150()
        {
            MessageReader reader = new MessageReader(SimpleMessage);
            reader.ReadMessageTag();
            Assert.AreEqual(150, reader.ReadInt32());
        }

        /*
         * message Test2 {
         *   required string b = 2;
         * }
         */
        public static readonly byte[] Test2Testing = { 0x12, 0x07, 0x74, 0x65, 0x73, 0x74, 0x69, 0x6e, 0x67 };
        [Test]
        public void Test2TestingWireTypeIsString()
        {
            MessageReader reader = new MessageReader(Test2Testing);
            Assert.AreEqual(WireType.String, reader.ReadMessageTag().WireType);
        }
        [Test]
        public void Test2TestingTagIsTwo()
        {
            MessageReader reader= new MessageReader(Test2Testing);
            Assert.AreEqual(2, reader.ReadMessageTag().Number);
        }
        [Test]
        public void Test2TestingValueIs_testing()
        {
            MessageReader reader = new MessageReader(Test2Testing);
            reader.ReadMessageTag();
            reader.ReadInt32();
            Assert.AreEqual("testing", reader.ReadString());
        }
        /*
         * message Test3 {
         *   required Test1 c = 3
         * }
         */
        public static readonly byte[] Test3EmbeddedMessage = { 0x1a, 0x03, 0x08, 0x96, 0x01 };
        public void EmbeddedMessage_ShouldHaveWireTypeString()
        {
            MessageReader reader = new MessageReader(Test3EmbeddedMessage);
            Assert.AreEqual(WireType.String, reader.ReadMessageTag().WireType);
        }
        public void Test3EmbeddedMessageHasTagThree()
        {
            MessageReader reader = new MessageReader(Test3EmbeddedMessage);
            Assert.AreEqual(3, reader.ReadMessageTag().Number);
        }
    }
}


text:
TextureWorker is a (very) easy to use GUI for the texture packer that comes with LibGDX.

## Are there any system requirements?

You only need to have installed at least Java 8. TextureWorker should work pretty well on Windows, OS X and Linux distributions.
There isn't any installer because TextureWorker works as a portable software, that means that you just need to run the .jar file. Please take a look at "How to compile"!

## Does this represent the final version of TextureWorker in any way?

No. The currently TextureWorker is in Alpha stage, but it should work pretty well anyway. Whatever a few features are missing at this time, but should be added in future versions.

## How to compile

At this time I don't offer precompiled JAR files by myself, but it's very easy to compile the source of TextureWorker to an executable JAR file. Overall we compile TextureWorker like every other LibGDX software.

### Easy going

> *NOTE: You need to use the Terminal (OS X, Linux, ...) or CMD (Windows)*

* Navigate to the downloaded TextureWorker folder

```
cd 'Path/To/Downloaded/Folder'
```

* Create a JAR

```
./gradlew desktop:dist
```

### Execute

> Now you can use the file explorer as an alternative

* Your new JAR is now located at ".../desktop/build/libs/<NameOfJar>.jar".
* Double-click on the created JAR

**_OR_**

```
java -jar <NameOfJar>.jar
```

## Any last words?

Not really, just have fun while develop and while use this software when you need to pack textures for your LibGDX application/game.


text:
[![Build Status](https://travis-ci.org/cmheisel/agile-analytics.svg?branch=master)](https://travis-ci.org/cmheisel/agile-analytics)
[![Coverage Status](https://coveralls.io/repos/github/cmheisel/agile-analytics/badge.svg?branch=master)](https://coveralls.io/github/cmheisel/agile-analytics?branch=master)
[![Stories in Ready](https://badge.waffle.io/cmheisel/agile-analytics.svg?label=ready&title=Ready)](http://waffle.io/cmheisel/agile-analytics)

Extract data about items from JIRA, output raw data and interesting reports

## Architecture

The agile extractor is composed of several different components. Fetchers gather data, which is fed to one or more analyzer/reporters/writer combos.

### Components

#### Fetchers

Fetchers are responsible for getting raw data about tickets from agile data sources (JIRA, Trello, etc.)

They depend on fetcher specific configuration including things like API end points, credentials and search criteria.

They produce a set of AgileTicket objects with a known interface.

#### Analyzers

Analyzers take in a set of AgileTicket objects and an analysis configuration and return a set of AnalyzedTicket objects that contain the original AgileTicket as well as additional data calculated in light of the analysis context.

For example, a CycleTime analyzer would look for a start_state and an end_state in the configuration, and calculate the days between those and store it as cycle_time on the AnalyzedTicket object.

#### Reporters

Reporters take in a set of AnalyzedTicket objects and a report configuration and return a Report object. It has two standard attributes:
* Table - A representation of the report as a 2 dimensional table, provides column headers, row labels, and values for each row/column combo
* Summary - A key/value store of report specific data

#### Writers

Writers take in a Report and a WriterConfig can write it out a particular source. Examples:
* CSV to standout
* CSV to a file
* Google spreadsheet
* Plotly

### Diagram

```
                                                            +----------->  Reporter: Distribution
                                                            |                title=Cycle Time Distribution
                                                            |                start_date=1/1/2015
                                                            |                end_date=3/31/2015
                                                            |                field=cycle_time
                                                            |
                                                            +----------->  Reporter: Throughput
                                                            |                title=Weekly Throughput
                                                            |                start_date=1/1/2015
                                                            |                end_date=3/31/2015
                                                            |                period=weekly
                                                            |
                                                            |
                                                            |
                 +----------------->  Analyzer: Cycle Time  +
                 |                      start_state=Backlog
                 |                      end_state=Deployed
                 |                      issue_types=Story
                 |
Fetcher          |                                          +-----------> Reporter: Throughput
  source=JIRA    +---------------->  Analyzer: Defect       +               title=Escaped Defects
  filter=1111    |                     defect_types=Bug,Incident            start_date=1/1/2015
  auth=user,pass |                                                          end_date=3/31/2015
                 |
                 |
                 +---------------->  Analyzer: Cycle Time   +-----------> Reporter: Throughput
                                       start_state=Analysis                 title=Weekly Analysis Throughput
                                       end_state=Dev                        start_date=1/1/2015
                                                                            end_date=3/31/2015
                                                                            period=weekly
```


text:
'use strict';

var Message = require('../message');
var inherits = require('util').inherits;
var bitcore = require('bitcore-lib');
var BufferUtil = bitcore.util.buffer;

/**
 * Request information about active peers
 * @extends Message
 * @param {Object} options
 * @constructor
 */
function GetaddrMessage(arg, options) {
  Message.call(this, options);
  this.command = 'getaddr';
}
inherits(GetaddrMessage, Message);

GetaddrMessage._name = 'GetAddr';

GetaddrMessage.prototype.setPayload = function() {};

GetaddrMessage.prototype.getPayload = function() {
  return BufferUtil.EMPTY_BUFFER;
};

module.exports = GetaddrMessage;


text:
<?php
namespace Core\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Eva\Mvc\Controller\RestfulModuleController;
use Eva\Api;
use Core\Auth;

class NewsletterController extends RestfulModuleController
{
    protected $renders = array(
        'restPostNewsletter' => 'blank',
        'restDeleteNewsletter' => 'blank',
    );

    public function restPostNewsletter()
    {
        $postData = $this->params()->fromPost();

        $callback = $this->params()->fromPost('callback');
        $callback = $callback ? $callback : '/home/';

        $user = Auth::getLoginUser();
        $userModel = Api::_()->getModel('User\Model\User');
        $mine = $userModel->getUser($user['id']);

        if (!$mine) {
            exit;
        }

        $postTable = Api::_()->getDbTable('Core\DbTable\Newsletters');

        $postTable->where(array(
            'user_id' => $mine['id'],
        ))->remove();
        $postTable->create(array(
            'user_id' => $mine['id'],
            'email' => $mine['email'],
        ));

        $this->redirect()->toUrl($callback);
    }

    public function restDeleteNewsletter()
    {
        $postData = $this->params()->fromPost();

        $callback = $this->params()->fromPost('callback');
        $callback = $callback ? $callback : '/home/';

        $user = Auth::getLoginUser();
        $userModel = Api::_()->getModel('User\Model\User');
        $mine = $userModel->getUser($user['id']);

        if (!$mine) {
            exit;
        }

        $postTable = Api::_()->getDbTable('Core\DbTable\Newsletters');

        $postTable->where(array(
            'user_id' => $mine['id'],
        ))->remove();

        $this->redirect()->toUrl($callback);
    }
}


text:
package com.github.chen0040.leetcode.day17.medium;

/**
 * Created by xschen on 12/8/2017.
 *
 * link: https://leetcode.com/problems/odd-even-linked-list/description/
 */
public class OddEvenLinkedList {
    public class ListNode {
      int val;
      ListNode next;
      ListNode(int x) { val = x; }
  }

   public class Solution {
      public ListNode oddEvenList(ListNode head) {
         if(head == null || head.next == null) return head;
         ListNode odd_head = null;
         ListNode even_head = null;
         ListNode odd = null;
         ListNode even = null;

         ListNode node = head;
         boolean is_odd = true;
         while(node != null) {
            ListNode node_next = node.next;

            if(is_odd) {
               ListNode old = odd;
               odd = node;
               odd.next = null;
               if(old != null) old.next = odd;
               if(odd_head == null) odd_head = odd;

               is_odd = false;
            } else {
               ListNode old = even;
               even = node;
               even.next = null;
               if(old != null) old.next = even;
               if(even_head == null) even_head = even;

               is_odd = true;
            }

            node = node_next;
         }

         if(odd != null) {
            odd.next = even_head;
            return odd_head;
         } else {
            return even_head;
         }
      }
   }
}


text:
package io.getquill.util

import io.getquill.base.Spec

import java.io.Closeable
import scala.concurrent.duration.DurationInt

class CacheSpec extends Spec {

  class Value extends Closeable {
    var closes = 0
    override def close = closes += 1
  }

  "caches hits" in {
    val cache = new Cache[Int, Value]

    val value = new Value
    var calls = 0
    def _value = {
      calls += 1
      Some(value)
    }

    cache.getOrElseUpdate(1, _value, 1.second) mustEqual Some(value)
    cache.getOrElseUpdate(1, _value, 1.second) mustEqual Some(value)

    calls mustEqual 1
  }

  "caches misses" in {
    val cache = new Cache[Int, Value]

    var calls = 0
    def _value = {
      calls += 1
      None
    }

    cache.getOrElseUpdate(1, _value, 1.second) mustEqual None
    cache.getOrElseUpdate(1, _value, 1.second) mustEqual None

    calls mustEqual 1
  }

  "expires keys" in {
    val cache = new Cache[Int, Value]

    val value = new Value
    var calls = 0
    def _value = {
      calls += 1
      Some(value)
    }

    cache.getOrElseUpdate(1, _value, -1.milliseconds)
    cache.getOrElseUpdate(2, None, -1.milliseconds)

    calls mustEqual 1
    value.closes mustEqual 1

    cache.getOrElseUpdate(1, _value, 1.second)

    calls mustEqual 2
    value.closes mustEqual 1
  }
}


text:
package com.explodingground.firge;

import net.minecraft.item.ItemAxe;

/**
 * Created by S0709277 on 21/02/2017.
 */
public class ItemTheFirge extends ItemAxe {

    public ItemTheFirge() {
        super(ToolMaterial.GOLD);
        setCreativeTab(Firge.fTab);
        setRegistryName(Firge.MODID, "the_firge");
        setUnlocalizedName("the_firge");
    }
}


text:
package tdem.TDEM_TOPICS;
/**
 * Automatically generated from IDL const definition
 * @author JacORB IDL compiler
 */

public interface modalSpaceLength
{
	int value = 2952;
}


text:
class PinsController < ApplicationController
  before_action :find_pin, only: [:show, :edit, :update, :destroy, :upvote]
  before_action :authenticate_user!, except: [:index, :show]

	def index
    if params[:category].blank?
      @pins = Pin.all.order("created_at DESC")
    else
      @category_id = Category.find_by(name: params[:category]).id
      @pins = Pin.where(category_id: @category_id).order("created_at DESC")
    end
	end

  def show
    @comments = Comment.where(pin_id: @pin)
  end

	def new
		@pin = current_user.pins.build
	end

	def create
		@pin = current_user.pins.build(pin_params)
    if @pin.save
      redirect_to @pin, notice: "Succesfully created Post"
    else
      render 'new'
    end
	end

  def edit
  end

  def update
    if @pin.update(pin_params)
      redirect_to @pin, notice: "Post was Succesfully updated!"
    else
      render 'edit'
    end
  end

  def destroy
    @pin.destroy
    redirect_to root_path
  end

  def upvote
    @pin.upvote_by current_user
    redirect_to :back
  end

	private

	def pin_params
		params.require(:pin).permit(:title, :description, :image, :category_id)
	end

  def find_pin
    @pin = Pin.find(params[:id])
  end
end


text:
using System;
using System.Runtime.Serialization;
using Gigya.Common.Contracts.Exceptions;
using Newtonsoft.Json;

namespace Gigya.ServiceContract.Exceptions
{
    ///
    /// This excpetion is thrown if a parameter contains an invalid value
    ///
    [Serializable]
    public class InvalidParameterValueException: RequestException
    {
        ///ErrorCode of Invalid_parameter_value
        public override int? ErrorCode => 400006;

        ///
        /// Name of the parameter which has an invalid value
        ///
        [JsonProperty]
        public string parameterName { get; set; }

        ///
        /// For parameters that contain data structures, the path inside the data structure pointing to the field/property that
        /// caused the deserialization or validation error.
        ///
        public string[] ErrorPath { get; set; }

        ///
        /// Initializes a new instance of the <see cref="InvalidParameterValueException"/> class with a specified error message and a reference to the inner exception that is the cause of this exception.
        ///
        /// <param name="paramName">Name of the parameter which has an invalid value</param>
        /// <param name="errorPath">For parameters that contain data structures, the path inside the data structure pointing to the field/property that
        /// caused the deserialization or validation error.</param>
        /// <param name="message">The error message that explains the reason for the exception.</param>
        /// <param name="encrypted">Optional. A collection of type <see cref="Tags"/> that contains additional data about the exception, which must be encrypted when stored.</param>
        /// <param name="unencrypted">Optional. A collection of type <see cref="Tags"/> that contains additional data about the exception, which needn't be encrypted when stored.</param>
        /// <param name="innerException">Optional. The exception that is the cause of the current exception.</param>
        public InvalidParameterValueException(string paramName, string[] errorPath, string message, Exception innerException = null, Tags encrypted = null, Tags unencrypted = null) : base(message, innerException, encrypted, unencrypted)
        {
            parameterName = paramName;
            ErrorPath = errorPath;
        }

        /// Initializes a new instance of the <see cref="InvalidParameterValueException"/> class with serialized data.
        /// <param name="info"> The <see cref="SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
        /// <param name="context">The <see cref="StreamingContext"/> that contains  contextual information about the source or destination.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="info"/> parameter is null.</exception>
        /// <exception cref="SerializationException">The class name is null or <see cref="Exception.HResult"/> is zero (0). </exception>
        public InvalidParameterValueException(SerializationInfo info, StreamingContext context) : base(info, context)
        {
        }
    }
}


text:
var x = 1;

if (this.x !== 1) {
  throw("#1: variable x is a property of global object");
}

try {
  if(delete this.x !== false){
    throw("#2: variable x has property attribute DontDelete");
  }
} catch(e) {
  if(x === 1 && e instanceof TypeError) {
    console.log('passed');
  }
}


text:
import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'

import * as actions from './actions'
import * as getters from './getters'
import createLogger from 'vuex/dist/logger'

import api from './modules/api'
import user from './modules/user'
import video from './modules/video'
import alert from './modules/alert'
import category from './modules/category'

Vue.use(Vuex)

const debug = process.env.NODE_ENV !== 'production'
Vue.config.debug = debug

const plugins = [
  createPersistedState()
]

export default new Vuex.Store({
  modules: {
    api,
    user,
    video,
    alert,
    category
  },
  actions,
  getters,
  strict: debug,
  plugins: debug ? [createLogger(), ...plugins] : plugins
})


text:
<?php

namespace PayPal\Api;

/**
 * Class Address
 *
 * Base Address object used as billing address in a payment or extended for Shipping Address.
 *
 * @package PayPal\Api
 *
 * @property string phone
 */
class Address extends BaseAddress
{
    /**
     * Phone number in E.123 format.
     *
     * @param string $phone
     *
     * @return $this
     */
    public function setPhone($phone)
    {
        $this->phone = $phone;
        return $this;
    }

    /**
     * Phone number in E.123 format.
     *
     * @return string
     */
    public function getPhone()
    {
        return $this->phone;
    }

}


text:
package networking

import (
	"fmt"
	"net"
	"reflect"
	"regexp"
	"strings"
	"time"

	testexutil "github.com/openshift/origin/test/extended/util"
	testutil "github.com/openshift/origin/test/util"

	kapi "k8s.io/kubernetes/pkg/api"
	kapiunversioned "k8s.io/kubernetes/pkg/api/unversioned"
	utilwait "k8s.io/kubernetes/pkg/util/wait"
	e2e "k8s.io/kubernetes/test/e2e/framework"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

const (
	hostSubnetTimeout = 30 * time.Second
)

var _ = Describe("[networking] OVS", func() {
	Context("generic", func() {
		f1 := e2e.NewDefaultFramework("net-ovs1")
		oc := testexutil.NewCLI("get-flows", testexutil.KubeConfigPath())

		It("should add and remove flows when pods are added and removed", func() {
			nodes := e2e.GetReadySchedulableNodesOrDie(f1.ClientSet)
			origFlows := getFlowsForAllNodes(oc, nodes.Items)
			Expect(len(origFlows)).To(Equal(len(nodes.Items)))
			for _, flows := range origFlows {
				Expect(len(flows)).ToNot(Equal(0))
			}

			podName := "ovs-test-webserver"
			deployNodeName := nodes.Items[0].Name
			ipPort := e2e.LaunchWebserverPod(f1, podName, deployNodeName)
			ip := strings.Split(ipPort, ":")[0]

			checkFlowsForAllNodes(oc, nodes.Items, func(nodeName string, newFlows []string) error {
				if nodeName == deployNodeName {
					return findFlowOrError("Should have flows referring to pod IP address", newFlows, ip)
				} else {
					return matchFlowsOrError("Flows on non-deployed-to nodes should be unchanged", newFlows, origFlows[nodeName])
				}
			})

			err := f1.ClientSet.Core().Pods(f1.Namespace.Name).Delete(podName, &kapi.DeleteOptions{})
			Expect(err).NotTo(HaveOccurred())

			checkFlowsForNode(oc, deployNodeName, func(nodeName string, flows []string) error {
				return matchFlowsOrError("Flows after deleting pod should be same as before creating it", flows, origFlows[nodeName])
			})
		})

		It("should add and remove flows when nodes are added and removed", func() {
			var err error
			nodes := e2e.GetReadySchedulableNodesOrDie(f1.ClientSet)
			origFlows := getFlowsForAllNodes(oc, nodes.Items)

			// The SDN/OVS code doesn't care that the node doesn't actually exist,
			// but we try to pick an IP on our local subnet to avoid sending
			// traffic into the real world.
			highNodeIP := ""
			for _, node := range nodes.Items {
				if node.Status.Addresses[0].Address > highNodeIP {
					highNodeIP = node.Status.Addresses[0].Address
				}
			}
			Expect(highNodeIP).NotTo(Equal(""))
			ip := net.ParseIP(highNodeIP)
			Expect(ip).NotTo(BeNil())
			ip = ip.To4()
			Expect(ip).NotTo(BeNil())
			Expect(ip[3]).NotTo(Equal(255))
			ip[3] += 1
			newNodeIP := ip.String()

			nodeName := "ovs-test-node"
			node := &kapi.Node{
				TypeMeta: kapiunversioned.TypeMeta{
					Kind: "Node",
				},
				ObjectMeta: kapi.ObjectMeta{
					Name: nodeName,
				},
				Spec: kapi.NodeSpec{
					Unschedulable: true,
				},
				Status: kapi.NodeStatus{
					Addresses: []kapi.NodeAddress{
						{
							Type:    kapi.NodeInternalIP,
							Address: newNodeIP,
						},
					},
				},
			}
			node, err = f1.ClientSet.Core().Nodes().Create(node)
			Expect(err).NotTo(HaveOccurred())
			defer f1.ClientSet.Core().Nodes().Delete(node.Name, &kapi.DeleteOptions{})

			osClient, err := testutil.GetClusterAdminClient(testexutil.KubeConfigPath())
			Expect(err).NotTo(HaveOccurred())

			e2e.Logf("Waiting up to %v for HostSubnet to be created", hostSubnetTimeout)
			for start := time.Now(); time.Since(start) < hostSubnetTimeout; time.Sleep(time.Second) {
				_, err = osClient.HostSubnets().Get(node.Name)
				if err == nil {
					break
				}
			}
			Expect(err).NotTo(HaveOccurred())

			checkFlowsForAllNodes(oc, nodes.Items, func(nodeName string, newFlows []string) error {
				return findFlowOrError("Should have flows referring to node IP address", newFlows, newNodeIP)
			})

			err = f1.ClientSet.Core().Nodes().Delete(node.Name, &kapi.DeleteOptions{})
			Expect(err).NotTo(HaveOccurred())
			e2e.Logf("Waiting up to %v for HostSubnet to be deleted", hostSubnetTimeout)
			for start := time.Now(); time.Since(start) < hostSubnetTimeout; time.Sleep(time.Second) {
				_, err = osClient.HostSubnets().Get(node.Name)
				if err != nil {
					break
				}
			}
			Expect(err).NotTo(BeNil())

			checkFlowsForAllNodes(oc, nodes.Items, func(nodeName string, flows []string) error {
				return matchFlowsOrError("Flows after deleting node should be same as before creating it", flows, origFlows[nodeName])
			})
		})
	})

	InMultiTenantContext(func() {
		f1 := e2e.NewDefaultFramework("net-ovs1")
		oc := testexutil.NewCLI("get-flows", testexutil.KubeConfigPath())

		It("should add and remove flows when services are added and removed", func() {
			nodes := e2e.GetReadySchedulableNodesOrDie(f1.ClientSet)
			origFlows := getFlowsForAllNodes(oc, nodes.Items)

			serviceName := "ovs-test-service"
			deployNodeName := nodes.Items[0].Name
			ipPort := launchWebserverService(f1, serviceName, deployNodeName)
			ip := strings.Split(ipPort, ":")[0]

			checkFlowsForAllNodes(oc, nodes.Items, func(nodeName string, newFlows []string) error {
				return findFlowOrError("Should have flows referring to service IP address", newFlows, ip)
			})

			err := f1.ClientSet.Core().Pods(f1.Namespace.Name).Delete(serviceName, &kapi.DeleteOptions{})
			Expect(err).NotTo(HaveOccurred())
			err = f1.ClientSet.Core().Services(f1.Namespace.Name).Delete(serviceName, &kapi.DeleteOptions{})
			Expect(err).NotTo(HaveOccurred())

			checkFlowsForAllNodes(oc, nodes.Items, func(nodeName string, flows []string) error {
				return matchFlowsOrError("Flows after deleting service should be same as before creating it", flows, origFlows[nodeName])
			})
		})
	})
})

type FlowError struct {
	msg      string
	flows    []string
	expected []string
}

func (err FlowError) Error() string {
	return err.msg
}

func matchFlowsOrError(msg string, flows, expected []string) error {
	if reflect.DeepEqual(flows, expected) {
		return nil
	} else {
		return FlowError{msg, flows, expected}
	}
}

func findFlowOrError(msg string, flows []string, ip string) error {
	for _, flow := range flows {
		if strings.Contains(flow, "="+ip+",") || strings.Contains(flow, "="+ip+" ") {
			return nil
		}
	}
	return FlowError{fmt.Sprintf("%s (%s)", msg, ip), flows, nil}
}

func doGetFlowsForNode(oc *testexutil.CLI, nodeName string) ([]string, error) {
	pod := &kapi.Pod{
		TypeMeta: kapiunversioned.TypeMeta{
			Kind: "Pod",
		},
		ObjectMeta: kapi.ObjectMeta{
			GenerateName: "flow-check",
		},
		Spec: kapi.PodSpec{
			Containers: []kapi.Container{
				{
					Name:  "flow-check",
					Image: "openshift/openvswitch",
					// kubernetes seems to get confused sometimes if the pod exits too quickly
					Command: []string{"sh", "-c", "ovs-ofctl -O OpenFlow13 dump-flows br0 && sleep 1"},
					VolumeMounts: []kapi.VolumeMount{
						{
							Name:      "ovs-socket",
							MountPath: "/var/run/openvswitch/br0.mgmt",
						},
					},
				},
			},
			Volumes: []kapi.Volume{
				{
					Name: "ovs-socket",
					VolumeSource: kapi.VolumeSource{
						HostPath: &kapi.HostPathVolumeSource{
							Path: "/var/run/openvswitch/br0.mgmt",
						},
					},
				},
			},
			NodeName:      nodeName,
			RestartPolicy: kapi.RestartPolicyNever,
			// We don't actually need HostNetwork, we just set it so that deploying this pod won't cause any OVS flows to be added
			SecurityContext: &kapi.PodSecurityContext{
				HostNetwork: true,
			},
		},
	}
	f := oc.KubeFramework()
	podClient := f.ClientSet.Core().Pods(f.Namespace.Name)
	pod, err := podClient.Create(pod)
	if err != nil {
		return nil, err
	}
	defer podClient.Delete(pod.Name, &kapi.DeleteOptions{})
	err = waitForPodSuccessInNamespace(f.ClientSet, pod.Name, "flow-check", f.Namespace.Name)
	if err != nil {
		return nil, err
	}
	logs, err := oc.Run("logs").Args(pod.Name).Output()
	if err != nil {
		return nil, err
	}

	// For ease of comparison, strip out the parts of the rules that change
	flows := strings.Split(logs, "\n")
	strip_re := regexp.MustCompile(`(duration|n_packets|n_bytes)=[^,]*, `)
	for i := range flows {
		flows[i] = strip_re.ReplaceAllLiteralString(flows[i], "")
	}
	return flows, nil
}

func getFlowsForAllNodes(oc *testexutil.CLI, nodes []kapi.Node) map[string][]string {
	var err error
	flows := make(map[string][]string, len(nodes))
	for _, node := range nodes {
		flows[node.Name], err = doGetFlowsForNode(oc, node.Name)
		expectNoError(err)
	}
	return flows
}

type CheckFlowFunc func(nodeName string, flows []string) error

var checkFlowBackoff = utilwait.Backoff{
	Duration: time.Second,
	Factor:   2,
	Steps:    5,
}

func checkFlowsForNode(oc *testexutil.CLI, nodeName string, checkFlow CheckFlowFunc) {
	var lastCheckErr error
	e2e.Logf("Checking OVS flows for node %q up to %d times", nodeName, checkFlowBackoff.Steps)
	err := utilwait.ExponentialBackoff(checkFlowBackoff, func() (bool, error) {
		flows, err := doGetFlowsForNode(oc, nodeName)
		if err != nil {
			return false, err
		}
		if lastCheckErr = checkFlow(nodeName, flows); lastCheckErr != nil {
			e2e.Logf("Check failed (%v)", lastCheckErr)
			return false, nil
		}
		return true, nil
	})
	if err != nil && lastCheckErr != nil {
		err = lastCheckErr
	}
	expectNoError(err)
}

func checkFlowsForAllNodes(oc *testexutil.CLI, nodes []kapi.Node, checkFlow CheckFlowFunc) {
	var lastCheckErr error
	e2e.Logf("Checking OVS flows for all nodes up to %d times", checkFlowBackoff.Steps)
	err := utilwait.ExponentialBackoff(checkFlowBackoff, func() (bool, error) {
		lastCheckErr = nil
		for _, node := range nodes {
			flows, err := doGetFlowsForNode(oc, node.Name)
			if err != nil {
				return false, err
			}
			if lastCheckErr = checkFlow(node.Name, flows); lastCheckErr != nil {
				e2e.Logf("Check failed for node %q (%v)", node.Name, lastCheckErr)
				return false, nil
			}
		}
		return true, nil
	})
	if err != nil && lastCheckErr != nil {
		err = lastCheckErr
	}
	expectNoError(err)
}


text:
require 'sinatra/router'

module Pliny
  class Router < Sinatra::Router

    # yield to a builder block in which all defined apps will only respond for
    # the given version
    def version(*versions, &block)
      condition = lambda { |env|
        versions.include?(env["HTTP_X_API_VERSION"])
      }
      with_conditions(condition, &block)
    end
  end
end


text:
<?
	require_once($_SERVER['DOCUMENT_ROOT'] . '/cp/_includes/config.php');

	try {

		$_SESSION['forms']['edit-location'] = array();

		$objLocation = new Location($_POST['locationId']);

		$objLocation->setIsActive($_POST['isActive']);
		$objLocation->setName($_POST['name']);
		$objLocation->setDescription($_POST['description']);
		$objLocation->setAddress1($_POST['address1']);
		$objLocation->setAddress2($_POST['address2'] ? $_POST['address2'] : '');
		$objLocation->setCity($_POST['city']);
		$objLocation->setState($_POST['state']);
		$objLocation->setZipCode($_POST['zipCode']);
		$objLocation->setDateCreated(time());

		if (!$objLocation->updateDatabase())
			throw new RecordUpdateInsertion();

		$_SESSION['forms']['location']['success'] = '<strong>' . $objLocation->getName() . '</strong> was saved successfully!';

		header('Location: index.php');
		exit;

	} catch (Exception $objException) {

		foreach ($_POST as $strKey => $mxdValue)
			$_SESSION['forms']['edit-location'][$strKey] = $mxdValue;

		$_SESSION['forms']['edit-location']['error'] = true;

		header('Location: edit.php');
		exit;

	}


text:
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Anemone.Foreign.Mempool (
    Mempool(..)
  , create
  , alloc
  , allocBytes
  , calloc
  , callocBytes
  , free
  , totalAllocSize
  , isPointerAligned
  ) where

import           Anemone.Foreign.Data ( CBool(..) )

import           Data.Void (Void)

import           Foreign.C.Types ( CInt (..), CSize(..) )
import           Foreign.Ptr ( Ptr )
import           Foreign.Storable ( Storable(..) )

import           GHC.Generics (Generic)

import           P

import           System.IO (IO)

import qualified Prelude as Savage

-- | The Mempool constructor must be exposed to work in FFI calls.
--   However, it must not be used in any other places.
--   The only way to construct a Mempool is by calling @create@.
--
newtype Mempool =
  Mempool (Ptr Void)
  deriving (Eq, Ord, Show, Storable, Generic)

foreign import ccall unsafe "anemone_mempool_create"
  create :: IO Mempool

foreign import ccall unsafe "hs_anemone_mempool_alloc"
  allocBytes :: Mempool -> CSize -> IO (Ptr a)

foreign import ccall unsafe "hs_anemone_mempool_calloc"
  callocBytes :: Mempool -> CSize -> CSize -> IO (Ptr a)

foreign import ccall unsafe "anemone_mempool_free"
  free :: Mempool -> IO ()

foreign import ccall unsafe "anemone_mempool_total_alloc_size"
  totalAllocSize :: Mempool -> IO Int64

foreign import ccall unsafe "anemone_is_pointer_aligned"
  isPointerAligned :: Ptr Void -> IO CBool

alloc :: forall a. Storable a => Mempool -> IO (Ptr a)
alloc mp =
  allocBytes mp (fromIntegral $ sizeOf (Savage.undefined :: a))

calloc :: forall a. Storable a => Mempool -> CSize -> IO (Ptr a)
calloc mp i =
  callocBytes mp i (fromIntegral $ sizeOf (Savage.undefined :: a))


text:
#include "config.h"
#include "DFGFixupPhase.h"

#if ENABLE(DFG_JIT)

#include "DFGGraph.h"
#include "DFGInsertionSet.h"
#include "DFGPhase.h"

namespace JSC { namespace DFG {

class FixupPhase : public Phase {
public:
    FixupPhase(Graph& graph)
        : Phase(graph, "fixup")
    {
    }

    bool run()
    {
        for (BlockIndex blockIndex = 0; blockIndex < m_graph.m_blocks.size(); ++blockIndex)
            fixupBlock(m_graph.m_blocks[blockIndex].get());
        return true;
    }

private:
    void fixupBlock(BasicBlock* block)
    {
        if (!block)
            return;
        ASSERT(block->isReachable);
        for (m_indexInBlock = 0; m_indexInBlock < block->size(); ++m_indexInBlock) {
            m_compileIndex = block->at(m_indexInBlock);
            fixupNode(m_graph[m_compileIndex]);
        }
        m_insertionSet.execute(*block);
    }

    void fixupNode(Node& node)
    {
        if (!node.shouldGenerate())
            return;

        NodeType op = node.op();

#if DFG_ENABLE(DEBUG_PROPAGATION_VERBOSE)
        dataLogF("   %s @%u: ", Graph::opName(op), m_compileIndex);
#endif

        switch (op) {
        case GetById: {
            if (m_graph.m_fixpointState > BeforeFixpoint)
                break;

            Node* nodePtr = &node;

            if (!isInt32Speculation(m_graph[m_compileIndex].prediction()))
                break;
            if (codeBlock()->identifier(nodePtr->identifierNumber()) != globalData().propertyNames->length)
                break;
            ArrayProfile* arrayProfile =
                m_graph.baselineCodeBlockFor(nodePtr->codeOrigin)->getArrayProfile(
                    nodePtr->codeOrigin.bytecodeIndex);
            ArrayMode arrayMode = ArrayMode(Array::SelectUsingPredictions);
            if (arrayProfile) {
                arrayProfile->computeUpdatedPrediction(m_graph.baselineCodeBlockFor(node.codeOrigin));
                arrayMode = ArrayMode::fromObserved(arrayProfile, Array::Read, false);
                arrayMode = arrayMode.refine(
                    m_graph[node.child1()].prediction(),
                    m_graph[m_compileIndex].prediction());
                if (arrayMode.supportsLength() && arrayProfile->hasDefiniteStructure()) {
                    m_graph.ref(nodePtr->child1());
                    Node checkStructure(CheckStructure, nodePtr->codeOrigin, OpInfo(m_graph.addStructureSet(arrayProfile->expectedStructure())), nodePtr->child1().index());
                    checkStructure.ref();
                    NodeIndex checkStructureIndex = m_graph.size();
                    m_graph.append(checkStructure);
                    m_insertionSet.append(m_indexInBlock, checkStructureIndex);
                    nodePtr = &m_graph[m_compileIndex];
                }
            } else {
                arrayMode = arrayMode.refine(
                    m_graph[node.child1()].prediction(),
                    m_graph[m_compileIndex].prediction());
            }
            if (!arrayMode.supportsLength())
                break;
            nodePtr->setOp(GetArrayLength);
            ASSERT(nodePtr->flags() & NodeMustGenerate);
            nodePtr->clearFlags(NodeMustGenerate | NodeClobbersWorld);
            m_graph.deref(m_compileIndex);
            nodePtr->setArrayMode(arrayMode);

            NodeIndex storage = checkArray(arrayMode, nodePtr->codeOrigin, nodePtr->child1().index(), NoNode, lengthNeedsStorage, nodePtr->shouldGenerate());
            if (storage == NoNode)
                break;

            nodePtr = &m_graph[m_compileIndex];
            nodePtr->children.child2() = Edge(storage);
            break;
        }
        case GetIndexedPropertyStorage: {
            ASSERT(node.arrayMode().canCSEStorage());
            break;
        }
        case GetByVal: {
            node.setArrayMode(
                node.arrayMode().refine(
                    m_graph[node.child1()].prediction(),
                    m_graph[node.child2()].prediction()));

            blessArrayOperation(node.child1(), node.child2(), 2);

            Node* nodePtr = &m_graph[m_compileIndex];
            ArrayMode arrayMode = nodePtr->arrayMode();
            if (arrayMode.type() == Array::Double
                && arrayMode.arrayClass() == Array::OriginalArray
                && arrayMode.speculation() == Array::InBounds
                && arrayMode.conversion() == Array::AsIs
                && m_graph.globalObjectFor(nodePtr->codeOrigin)->arrayPrototypeChainIsSane()
                && !(nodePtr->flags() & NodeUsedAsOther))
                nodePtr->setArrayMode(arrayMode.withSpeculation(Array::SaneChain));

            break;
        }
        case StringCharAt:
        case StringCharCodeAt: {
            // Currently we have no good way of refining these.
            ASSERT(node.arrayMode() == ArrayMode(Array::String));
            blessArrayOperation(node.child1(), node.child2(), 2);
            break;
        }

        case ArrayPush: {
            // May need to refine the array mode in case the value prediction contravenes
            // the array prediction. For example, we may have evidence showing that the
            // array is in Int32 mode, but the value we're storing is likely to be a double.
            // Then we should turn this into a conversion to Double array followed by the
            // push. On the other hand, we absolutely don't want to refine based on the
            // base prediction. If it has non-cell garbage in it, then we want that to be
            // ignored. That's because ArrayPush can't handle any array modes that aren't
            // array-related - so if refine() turned this into a "Generic" ArrayPush then
            // that would break things.
            node.setArrayMode(
                node.arrayMode().refine(
                    m_graph[node.child1()].prediction() & SpecCell,
                    SpecInt32,
                    m_graph[node.child2()].prediction()));
            blessArrayOperation(node.child1(), node.child2(), 2);

            Node* nodePtr = &m_graph[m_compileIndex];
            switch (nodePtr->arrayMode().type()) {
            case Array::Double:
                fixDoubleEdge(1);
                break;
            default:
                break;
            }
            break;
        }

        case ArrayPop: {
            blessArrayOperation(node.child1(), node.child2(), 1);
            break;
        }

        case ValueToInt32: {
            if (m_graph[node.child1()].shouldSpeculateNumber()
                && node.mustGenerate()) {
                node.clearFlags(NodeMustGenerate);
                m_graph.deref(m_compileIndex);
            }
            break;
        }

        case BitAnd:
        case BitOr:
        case BitXor:
        case BitRShift:
        case BitLShift:
        case BitURShift: {
            fixIntEdge(node.children.child1());
            fixIntEdge(node.children.child2());
            break;
        }

        case CompareEq:
        case CompareLess:
        case CompareLessEq:
        case CompareGreater:
        case CompareGreaterEq:
        case CompareStrictEq: {
            if (Node::shouldSpeculateInteger(m_graph[node.child1()], m_graph[node.child2()]))
                break;
            if (!Node::shouldSpeculateNumber(m_graph[node.child1()], m_graph[node.child2()]))
                break;
            fixDoubleEdge(0);
            fixDoubleEdge(1);
            break;
        }

        case LogicalNot: {
            if (m_graph[node.child1()].shouldSpeculateInteger())
                break;
            if (!m_graph[node.child1()].shouldSpeculateNumber())
                break;
            fixDoubleEdge(0);
            break;
        }

        case Branch: {
            if (!m_graph[node.child1()].shouldSpeculateInteger()
                && m_graph[node.child1()].shouldSpeculateNumber())
                fixDoubleEdge(0);

            Node& myNode = m_graph[m_compileIndex]; // reload because the graph may have changed
            Edge logicalNotEdge = myNode.child1();
            Node& logicalNot = m_graph[logicalNotEdge];
            if (logicalNot.op() == LogicalNot
                && logicalNot.adjustedRefCount() == 1) {
                Edge newChildEdge = logicalNot.child1();
                if (m_graph[newChildEdge].hasBooleanResult()) {
                    m_graph.ref(newChildEdge);
                    m_graph.deref(logicalNotEdge);
                    myNode.children.setChild1(newChildEdge);

                    BlockIndex toBeTaken = myNode.notTakenBlockIndex();
                    BlockIndex toBeNotTaken = myNode.takenBlockIndex();
                    myNode.setTakenBlockIndex(toBeTaken);
                    myNode.setNotTakenBlockIndex(toBeNotTaken);
                }
            }
            break;
        }

        case SetLocal: {
            if (node.variableAccessData()->isCaptured())
                break;
            if (!node.variableAccessData()->shouldUseDoubleFormat())
                break;
            fixDoubleEdge(0);
            break;
        }

        case ArithAdd:
        case ValueAdd: {
            if (m_graph.addShouldSpeculateInteger(node))
                break;
            if (!Node::shouldSpeculateNumberExpectingDefined(m_graph[node.child1()], m_graph[node.child2()]))
                break;
            fixDoubleEdge(0);
            fixDoubleEdge(1);
            break;
        }

        case ArithSub: {
            if (m_graph.addShouldSpeculateInteger(node)
                && node.canSpeculateInteger())
                break;
            fixDoubleEdge(0);
            fixDoubleEdge(1);
            break;
        }

        case ArithNegate: {
            if (m_graph.negateShouldSpeculateInteger(node))
                break;
            fixDoubleEdge(0);
            break;
        }

        case ArithMin:
        case ArithMax:
        case ArithMod: {
            if (Node::shouldSpeculateIntegerForArithmetic(m_graph[node.child1()], m_graph[node.child2()])
                && node.canSpeculateInteger())
                break;
            fixDoubleEdge(0);
            fixDoubleEdge(1);
            break;
        }

        case ArithMul: {
            if (m_graph.mulShouldSpeculateInteger(node))
                break;
            fixDoubleEdge(0);
            fixDoubleEdge(1);
            break;
        }

        case ArithDiv: {
            if (Node::shouldSpeculateIntegerForArithmetic(m_graph[node.child1()], m_graph[node.child2()])
                && node.canSpeculateInteger()) {
                if (isX86())
                    break;
                fixDoubleEdge(0);
                fixDoubleEdge(1);

                Node& oldDivision = m_graph[m_compileIndex];

                Node newDivision = oldDivision;
                newDivision.setRefCount(2);
                newDivision.predict(SpecDouble);
                NodeIndex newDivisionIndex = m_graph.size();

                oldDivision.setOp(DoubleAsInt32);
                oldDivision.children.initialize(Edge(newDivisionIndex, DoubleUse), Edge(), Edge());

                m_graph.append(newDivision);
                m_insertionSet.append(m_indexInBlock, newDivisionIndex);

                break;
            }
            fixDoubleEdge(0);
            fixDoubleEdge(1);
            break;
        }

        case ArithAbs: {
            if (m_graph[node.child1()].shouldSpeculateIntegerForArithmetic()
                && node.canSpeculateInteger())
                break;
            fixDoubleEdge(0);
            break;
        }

        case ArithSqrt: {
            fixDoubleEdge(0);
            break;
        }

        case PutByVal:
        case PutByValAlias: {
            Edge child1 = m_graph.varArgChild(node, 0);
            Edge child2 = m_graph.varArgChild(node, 1);
            Edge child3 = m_graph.varArgChild(node, 2);

            node.setArrayMode(
                node.arrayMode().refine(
                    m_graph[child1].prediction(),
                    m_graph[child2].prediction(),
                    m_graph[child3].prediction()));

            blessArrayOperation(child1, child2, 3);

            Node* nodePtr = &m_graph[m_compileIndex];

            switch (nodePtr->arrayMode().modeForPut().type()) {
            case Array::Double:
                fixDoubleEdge(2);
                break;
            case Array::Int8Array:
            case Array::Int16Array:
            case Array::Int32Array:
            case Array::Uint8Array:
            case Array::Uint8ClampedArray:
            case Array::Uint16Array:
            case Array::Uint32Array:
                if (!m_graph[child3].shouldSpeculateInteger())
                    fixDoubleEdge(2);
                break;
            case Array::Float32Array:
            case Array::Float64Array:
                fixDoubleEdge(2);
                break;
            default:
                break;
            }
            break;
        }

        case NewArray: {
            for (unsigned i = m_graph.varArgNumChildren(node); i--;) {
                node.setIndexingType(
                    leastUpperBoundOfIndexingTypeAndType(
                        node.indexingType(), m_graph[m_graph.varArgChild(node, i)].prediction()));
            }
            if (node.indexingType() == ArrayWithDouble) {
                for (unsigned i = m_graph.varArgNumChildren(node); i--;)
                    fixDoubleEdge(i);
            }
            break;
        }

        default:
            break;
        }

#if DFG_ENABLE(DEBUG_PROPAGATION_VERBOSE)
        if (!(node.flags() & NodeHasVarArgs)) {
            dataLogF("new children: ");
            node.dumpChildren(WTF::dataFile());
        }
        dataLogF("\n");
#endif
    }

    NodeIndex addNode(const Node& node, bool shouldGenerate)
    {
        NodeIndex nodeIndex = m_graph.size();
        m_graph.append(node);
        m_insertionSet.append(m_indexInBlock, nodeIndex);
        if (shouldGenerate)
            m_graph[nodeIndex].ref();
        return nodeIndex;
    }

    NodeIndex checkArray(ArrayMode arrayMode, CodeOrigin codeOrigin, NodeIndex array, NodeIndex index, bool (*storageCheck)(const ArrayMode&) = canCSEStorage, bool shouldGenerate = true)
    {
        ASSERT(arrayMode.isSpecific());

        m_graph.ref(array);

        Structure* structure = arrayMode.originalArrayStructure(m_graph, codeOrigin);

        if (arrayMode.doesConversion()) {
            if (index != NoNode)
                m_graph.ref(index);

            if (structure) {
                Node arrayify(ArrayifyToStructure, codeOrigin, OpInfo(structure), OpInfo(arrayMode.asWord()), array, index);
                arrayify.ref();
                NodeIndex arrayifyIndex = m_graph.size();
                m_graph.append(arrayify);
                m_insertionSet.append(m_indexInBlock, arrayifyIndex);
            } else {
                Node arrayify(Arrayify, codeOrigin, OpInfo(arrayMode.asWord()), array, index);
                arrayify.ref();
                NodeIndex arrayifyIndex = m_graph.size();
                m_graph.append(arrayify);
                m_insertionSet.append(m_indexInBlock, arrayifyIndex);
            }
        } else {
            if (structure) {
                Node checkStructure(CheckStructure, codeOrigin, OpInfo(m_graph.addStructureSet(structure)), array);
                checkStructure.ref();
                NodeIndex checkStructureIndex = m_graph.size();
                m_graph.append(checkStructure);
                m_insertionSet.append(m_indexInBlock, checkStructureIndex);
            } else {
                Node checkArray(CheckArray, codeOrigin, OpInfo(arrayMode.asWord()), array);
                checkArray.ref();
                NodeIndex checkArrayIndex = m_graph.size();
                m_graph.append(checkArray);
                m_insertionSet.append(m_indexInBlock, checkArrayIndex);
            }
        }

        if (!storageCheck(arrayMode))
            return NoNode;

        if (shouldGenerate)
            m_graph.ref(array);

        if (arrayMode.usesButterfly())
            return addNode(Node(GetButterfly, codeOrigin, array), shouldGenerate);

        return addNode(Node(GetIndexedPropertyStorage, codeOrigin, OpInfo(arrayMode.asWord()), array), shouldGenerate);
    }

    void blessArrayOperation(Edge base, Edge index, unsigned storageChildIdx)
    {
        if (m_graph.m_fixpointState > BeforeFixpoint)
            return;

        Node* nodePtr = &m_graph[m_compileIndex];

        switch (nodePtr->arrayMode().type()) {
        case Array::ForceExit: {
            Node forceExit(ForceOSRExit, nodePtr->codeOrigin);
            forceExit.ref();
            NodeIndex forceExitIndex = m_graph.size();
            m_graph.append(forceExit);
            m_insertionSet.append(m_indexInBlock, forceExitIndex);
            return;
        }

        case Array::SelectUsingPredictions:
        case Array::Unprofiled:
            ASSERT_NOT_REACHED();
            return;

        case Array::Generic:
            return;

        default: {
            NodeIndex storage = checkArray(nodePtr->arrayMode(), nodePtr->codeOrigin, base.index(), index.indexUnchecked());
            if (storage == NoNode)
                return;

            m_graph.child(m_graph[m_compileIndex], storageChildIdx) = Edge(storage);
            return;
        } }
    }

    void fixIntEdge(Edge& edge)
    {
        Node& node = m_graph[edge];
        if (node.op() != ValueToInt32)
            return;

        if (!m_graph[node.child1()].shouldSpeculateInteger())
            return;

        Edge oldEdge = edge;
        Edge newEdge = node.child1();

        m_graph.ref(newEdge);
        m_graph.deref(oldEdge);

        edge = newEdge;
    }

    void fixDoubleEdge(unsigned childIndex)
    {
        Node& source = m_graph[m_compileIndex];
        Edge& edge = m_graph.child(source, childIndex);

        if (!m_graph[edge].shouldSpeculateInteger()) {
            edge.setUseKind(DoubleUse);
            return;
        }

        NodeIndex resultIndex = (NodeIndex)m_graph.size();

#if DFG_ENABLE(DEBUG_PROPAGATION_VERBOSE)
        dataLogF("(replacing @%u->@%u with @%u->@%u) ",
                m_compileIndex, edge.index(), m_compileIndex, resultIndex);
#endif

        // Fix the edge up here because it's a reference that will be clobbered by
        // the append() below.
        NodeIndex oldIndex = edge.index();
        edge = Edge(resultIndex, DoubleUse);

        m_graph.append(Node(Int32ToDouble, source.codeOrigin, oldIndex));
        m_insertionSet.append(m_indexInBlock, resultIndex);

        Node& int32ToDouble = m_graph[resultIndex];
        int32ToDouble.predict(SpecDouble);
        int32ToDouble.ref();
    }

    unsigned m_indexInBlock;
    NodeIndex m_compileIndex;
    InsertionSet<NodeIndex> m_insertionSet;
};

bool performFixup(Graph& graph)
{
    SamplingRegion samplingRegion("DFG Fixup Phase");
    return runPhase<FixupPhase>(graph);
}

} } // namespace JSC::DFG

#endif // ENABLE(DFG_JIT)


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'httparty'
require 'mock_web_service'


text:
<?php
/* @var $this PostController */
/* @var $model Post */

$this->breadcrumbs=array(
	'Posts'=>array('index'),
	$model->title=>array('view','id'=>$model->id),
	'Update',
);

$this->menu=array(
	array('label'=>'List Post', 'url'=>array('index')),
	array('label'=>'Create Post', 'url'=>array('create')),
	array('label'=>'View Post', 'url'=>array('view', 'id'=>$model->id)),
	array('label'=>'Manage Post', 'url'=>array('admin')),
);
?>

Update Post <?php echo $model->id; ?>

<?php $this->renderPartial('_form', array('model'=>$model)); ?>


text:
Cordova Plugin Camera Preview
====================

Cordova plugin that allows camera interaction from Javascript and HTML

**We are continually improving the plugin for an eventual v1.0.0 release, in the meantime the API may change. Please use master until a new version is released.**

**PR's are greatly appreciated**

# Features

Start a camera preview from HTML code.

Drag the preview box.

Set camera color effect.

Send the preview box to back of the HTML content.

Set a custom position for the camera preview box.

Set a custom size for the preview box.

Set a custom alpha for the preview box.

Set the focus mode, zoom, color effects, exposure mode, white balance mode and exposure compensation

Maintain HTML interactivity.

### iOS only features

These are some features that are currently iOS only, however we would love to see PR's for this functionality in Android.

Tap to focus

# Installation

Use any one of the installation methods listed below depending on which framework you use.

```
cordova plugin add https://github.com/cordova-plugin-camera-preview/cordova-plugin-camera-preview.git

ionic plugin add https://github.com/cordova-plugin-camera-preview/cordova-plugin-camera-preview.git

meteor add cordova:cordova-plugin-camera-preview@https://github.com/cordova-plugin-camera-preview/cordova-plugin-camera-preview.git#[latest_commit_id]

<plugin spec="https://github.com/cordova-plugin-camera-preview/cordova-plugin-camera-preview.git" source="git" />
```

# Methods

### startCamera(options, [successCallback, errorCallback])

Starts the camera preview instance.

Options:
All options stated are optional and will default to values here

* `x` - Defaults to 0
* `y` - Defaults to 0
* `width` - Defaults to window.screen.width
* `height` - Defaults to window.screen.height
* `camera` - See [CAMERA_DIRECTION](#camera_Settings.CameraDirection) - Defaults to front camera/code>
* `toBack` - Defaults to false - Set to true if you want your html in front of your preview
* `tapPhoto` - Defaults to true - Does not work if toBack is set to false in which case you use the takePicture method
* `previewDrag` - Defaults to false - Does not work if toBack is set to false

```javascript
let options = {
  x: 0,
  y: 0,
  width: window.screen.width,
  height: window.screen.height,
  camera: CameraPreview.CAMERA_DIRECTION.BACK,
  toBack: false,
  tapPhoto: true,
  previewDrag: false
};

CameraPreview.startCamera(options);
```

When setting the toBack to true, remember to add the style below on your app's HTML or body element:

```css
html, body, .ion-app, .ion-content {
  background-color: transparent;
}
```

### stopCamera([successCallback, errorCallback])

<info>Stops the camera preview instance.</info>

```javascript
CameraPreview.stopCamera();
```

### switchCamera([successCallback, errorCallback])

<info>Switch between the rear camera and front camera, if available.</info>

```javascript
CameraPreview.switchCamera();
```

### show([successCallback, errorCallback])

<info>Show the camera preview box.</info>

```javascript
CameraPreview.show();
```

### hide([successCallback, errorCallback])

<info>Hide the camera preview box.</info>

```javascript
CameraPreview.hide();
```

### takePicture(options, successCallback, [errorCallback])

<info>Take the picture. If width and height are not specified or are 0 it will use the defaults. If width and height are specified, it will choose a supported photo size that is closest to width and height specified and has closest aspect ratio to the preview. The argument `quality` defaults to `85` and specifies the quality/compression value: `0=max compression`, `100=max quality`.</info>

```javascript
CameraPreview.takePicture({width:640, height:640, quality: 85}, function(base64PictureData){
  /*
    base64PictureData is base64 encoded jpeg image. Use this data to store to a file or upload.
    Its up to the you to figure out the best way to save it to disk or whatever for your application.
  */

  // One simple example is if you are going to use it inside an HTML img src attribute then you would do the following:
  imageSrcData = 'data:image/jpeg;base64,' +base64PictureData;
  $('img#my-img').attr('src', imageSrcData);
});

// OR if you want to use the default options.

CameraPreview.takePicture(function(base64PictureData){
  /* code here */
});
```
### getSupportedFocusModes(cb, [errorCallback])

<info>Get focus modes supported by the camera device currently started. Returns an array containing supported focus modes. See [FOCUS_MODE](#camera_Settings.FocusMode) for possible values that can be returned.</info>

```javascript
CameraPreview.getSupportedFocusModes(function(focusModes){
  focusModes.forEach(function(focusMode) {
    console.log(focusMode + ', ');
  });
});
```

### setFocusMode(focusMode, [successCallback, errorCallback])

<info>Set the focus mode for the camera device currently started.</info>

* `focusMode` - [FOCUS_MODE](#camera_Settings.FocusMode)

```javascript
CameraPreview.setFocusMode(CameraPreview.FOCUS_MODE.CONTINUOUS_PICTURE);
```

### getFocusMode(cb, [errorCallback])

<info>Get the focus mode for the camera device currently started. Returns a string representing the current focus mode.</info>See [FOCUS_MODE](#camera_Settings.FocusMode) for possible values that can be returned.</info>

```javascript
CameraPreview.getFocusMode(function(currentFocusMode){
  console.log(currentFocusMode);
});
```

### getSupportedFlashModes(cb, [errorCallback])

<info>Get the flash modes supported by the camera device currently started. Returns an array containing supported flash modes. See [FLASH_MODE](#camera_Settings.FlashMode) for possible values that can be returned</info>

```javascript
CameraPreview.getSupportedFlashModes(function(flashModes){
  flashModes.forEach(function(flashMode) {
    console.log(flashMode + ', ');
  });
});
```

### setFlashMode(flashMode, [successCallback, errorCallback])

<info>Set the flash mode. See [FLASH_MODE](#camera_Settings.FlashMode) for details about the possible values for flashMode.</info>

```javascript
CameraPreview.setFlashMode(CameraPreview.FLASH_MODE.ON);
```

### getFlashMode(cb, [errorCallback])

<info>Get the flash mode for the camera device currently started. Returns a string representing the current flash mode.</info>See [FLASH_MODE](#camera_Settings.FlashMode) for possible values that can be returned</info>

```javascript
CameraPreview.getFlashMode(function(currentFlashMode){
  console.log(currentFlashMode);
});
```
### setColorEffect(colorEffect, [successCallback, errorCallback])

<info>Set the color effect. See [COLOR_EFFECT](#camera_Settings.ColorEffect) for details about the possible values for colorEffect.</info>

```javascript
CameraPreview.setColorEffect(CameraPreview.COLOR_EFFECT.NEGATIVE);
```

### setZoom(zoomMultiplier, [successCallback, errorCallback])

<info>Set the zoom level for the camera device currently started. zoomMultipler option accepts an integer. Zoom level is initially at 1</info>

```javascript
CameraPreview.setZoom(2);
```

### getZoom(cb, [errorCallback])

<info>Get the current zoom level for the camera device currently started. Returns an integer representing the current zoom level.</info>

```javascript
CameraPreview.getZoom(function(currentZoom){
  console.log(currentZoom);
});
```

### getMaxZoom(cb, [errorCallback])

<info>Get the maximum zoom level for the camera device currently started. Returns an integer representing the manimum zoom level.</info>

```javascript
CameraPreview.getMaxZoom(function(maxZoom){
  console.log(maxZoom);
});
```

### getSupportedWhiteBalanceModes(cb, [errorCallback])

<info>Returns an array with supported white balance modes for the camera device currently started. See [WHITE_BALANCE_MODE](#camera_Settings.WhiteBalanceMode) for details about the possible values returned.</info>

```javascript
CameraPreview.getSupportedWhiteBalanceModes(function(whiteBalanceModes){
  console.log(whiteBalanceModes);
});
```

### getWhiteBalanceMode(cb, [errorCallback])

<info>Get the curent white balance mode of the camera device currently started. See [WHITE_BALANCE_MODE](#camera_Settings.WhiteBalanceMode) for details about the possible values returned.</info>

```javascript
CameraPreview.getWhiteBalanceMode(function(whiteBalanceMode){
  console.log(whiteBalanceMode);
});
```
### setWhiteBalanceMode(whiteBalanceMode, [successCallback, errorCallback])

<info>Set the white balance mode for the camera device currently started. See [WHITE_BALANCE_MODE](#camera_Settings.WhiteBalanceMode) for details about the possible values for whiteBalanceMode.</info>

```javascript
CameraPreview.setWhiteBalanceMode(CameraPreview.WHITE_BALANCE_MODE.CLOUDY_DAYLIGHT);
```

### getExposureModes(cb, [errorCallback])

<info>Returns an array with supported exposure modes for the camera device currently started. See [EXPOSURE_MODE](#camera_Settings.ExposureMode) for details about the possible values returned.</info>

```javascript
CameraPreview.getExposureModes(function(exposureModes){
  console.log(exposureModes);
});
```

### getExposureMode(cb, [errorCallback])

<info>Get the curent exposure mode of the camera device currently started. See [EXPOSURE_MODE](#camera_Settings.ExposureMode) for details about the possible values returned.</info>

```javascript
CameraPreview.getExposureMode(function(exposureMode){
  console.log(exposureMode);
});
```
### setExposureMode(exposureMode, [successCallback, errorCallback])

<info>Set the exposure mode for the camera device currently started. See [EXPOSURE_MODE](#camera_Settings.ExposureMode) for details about the possible values for exposureMode.</info>

```javascript
CameraPreview.setExposureMode(CameraPreview.EXPOSURE_MODE.CONTINUOUS);
```
### getExposureCompensationRange(cb, [errorCallback])

<info>Get the minimum and maximum exposure compensation for the camera device currently started. Returns an object containing min and max integers.</info>

```javascript
CameraPreview.getExposureCompensationRange(function(expoxureRange){
  console.log("min: " + exposureRange.min);
  console.log("max: " + exposureRange.max);
});
```
### getExposureCompensation(cb, [errorCallback])

<info>Get the current exposure compensation for the camera device currently started. Returns an integer representing the current exposure compensation.</info>

```javascript
CameraPreview.getExposureCompensation(function(expoxureCompensation){
  console.log(exposureCompensation);
});
```
### setExposureCompensation(exposureCompensation, [successCallback, errorCallback])

<info>Set the exposure compensation for the camera device currently started. exposureCompensation accepts an integer. if exposureCompensation is lesser than the minimum exposure compensation, it is set to the minimum. if exposureCompensation is greater than the maximum exposure compensation, it is set to the maximum. (see getExposureCompensationRange() to get the minumum an maximum exposure compensation).</info>

```javascript
CameraPreview.setExposureCompensation(-2);
CameraPreview.setExposureCompensation(3);
```

### setPreviewSize([dimensions, successCallback, errorCallback])

<info>Change the size of the preview window.</info>

```javascript
CameraPreview.setPreviewSize({width: window.screen.width, height: window.screen.height});
```

### getSupportedPictureSizes(cb, [errorCallback])

```javascript
CameraPreview.getSupportedPictureSizes(function(dimensions){
  // note that the portrait version, width and height swapped, of these dimensions are also supported
  dimensions.forEach(function(dimension) {
    console.log(dimension.width + 'x' + dimension.height);
  });
});
```

### tapToFocus(xPoint, yPoint, [successCallback, errorCallback])

<info>Set specific focus point. Note, this assumes the camera is full-screen.</info>

```javascript
let xPoint = event.x;
let yPoint = event.y
CameraPreview.tapToFocus(xPoint, yPoint);
```

# Settings

### FOCUS_MODE

<info>Focus mode settings:</info>

| Name | Type | Default | Note |
| --- | --- | --- | --- |
| FIXED | string | fixed |  |
| AUTO | string | auto |  |
| CONTINUOUS | string | continuous | IOS Only |
| CONTINUOUS_PICTURE | string | continuous-picture | Android Only |
| CONTINUOUS_VIDEO | string | continuous-video | Android Only |
| EDOF | string | edof | Android Only |
| INFINITY | string | infinity | Android Only |
| MACRO | string | macro | Android Only |

### FLASH_MODE

<info>Flash mode settings:</info>

| Name | Type | Default | Note |
| --- | --- | --- | --- |
| OFF | string | off |  |
| ON | string | on |  |
| AUTO | string | auto |  |
| RED_EYE | string | red-eye | Android Only |
| TORCH | string | torch |  |

### CAMERA_DIRECTION

<info>Camera direction settings:</info>

| Name | Type | Default |
| --- | --- | --- |
| BACK | string | back |
| FRONT | string | front |

### COLOR_EFFECT

<info>Color effect settings:</info>

| Name | Type | Default | Note |
| --- | --- | --- | --- |
| AQUA | string | aqua | Android Only |
| BLACKBOARD | string | blackboard | Android Only |
| MONO | string | mono | |
| NEGATIVE | string | negative | |
| NONE | string | none | |
| POSTERIZE | string | posterize | |
| SEPIA | string | sepia | |
| SOLARIZE | string | solarize | Android Only |
| WHITEBOARD | string | whiteboard | Android Only |

### EXPOSURE_MODE

<info>Exposure mode settings:</info>

| Name | Type | Default | Note |
| --- | --- | --- | --- |
| AUTO | string | auto | IOS Only |
| CONTINUOUS | string | continuous | |
| CUSTOM | string | custom | |
| LOCK | string | lock | IOS Only |

Note: Use AUTO to allow the device automatically adjusts the exposure once and then changes the exposure mode to LOCK.

### WHITE_BALANCE_MODE

<info>White balance mode settings:</info>

| Name | Type | Default | Note |
| --- | --- | --- | --- |
| LOCK | string | lock | |
| AUTO | string | auto | |
| CONTINUOUS | string | continuous | IOS Only |
| INCANDESCENT | string | incandescent | |
| CLOUDY_DAYLIGHT | string | cloudy-daylight | |
| DAYLIGHT | string | daylight | |
| FLUORESCENT | string | fluorescent | |
| SHADE | string | shade | |
| TWILIGHT | string | twilight | |
| WARM_FLUORESCENT | string | warm-fluorescent | |

# IOS Quirks
It is not possible to use your computers webcam during testing in the simulator, you must device test.

# Sample App

cordova-plugin-camera-preview-sample-app for a complete working Cordova example for Android and iOS platforms.

# Screenshots

# Credits

Maintained by Weston Ganger - [@westonganger](https://github.com/westonganger)

Created by Marcel Barbosa Pinto [@mbppower](https://github.com/mbppower)


text:
extern t_config config;
extern int edslineno;
extern YYSTYPE edslval;
extern char *edstext;

int find_control(const char *ctrl_name, t_ctrl_type *ctrl);
int parse_config(const char *fname);
void clean_up_config(void);

int find_free_button(int btn_array[]);
bool mark_available_button(int btn_array[], int button);
int add_used_ctrl(int ctrl_array[], size_t len, unsigned int button, t_ctrl_type ctrl_type);
bool mark_ctrl(int ctrl_array[], size_t len, int ctrl, int min, int max, int val);

bool sort_out_buttons(void);

#endif