text:
using Cake.Common.Tests.Fixtures.Tools;
using Cake.Common.Tools.XUnit;
using Cake.Core;
using Cake.Core.IO;
using Cake.Testing;
using Cake.Testing.Xunit;
using Xunit;

namespace Cake.Common.Tests.Unit.Tools.XUnit
{
    public sealed class XUnit2RunnerTests
    {
        public sealed class TheRunMethod
        {
            [Fact]
            public void Should_Throw_If_Assembly_Path_Is_Null()
            {
                // Given
                var fixture = new XUnit2RunnerFixture();
                fixture.AssemblyPaths = null;

                // When
                var result = Record.Exception(() => fixture.Run());

                // Then
                Assert.IsArgumentNullException(result, "assemblyPaths");
            }

            [Fact]
            public void Should_Throw_If_XUnit_Runner_Was_Not_Found()
            {
                // Given
                var fixture = new XUnit2RunnerFixture();
                fixture.GivenDefaultToolDoNotExist();

                // When
                var result = Record.Exception(() => fixture.Run());

                // Then
                Assert.IsType<CakeException>(result);
                Assert.Equal("xUnit.net (v2): Could not locate executable.", result.Message);
            }

            [Theory]
            [InlineData("/bin/tools/xUnit/xunit.exe", "/bin/tools/xUnit/xunit.exe")]
            [InlineData("./tools/xUnit/xunit.exe", "/Working/tools/xUnit/xunit.exe")]
            public void Should_Use_XUnit_Runner_From_Tool_Path_If_Provided(string toolPath, string expected)
            {
                // Given
                var fixture = new XUnit2RunnerFixture();
                fixture.Settings.ToolPath = toolPath;
                fixture.GivenSettingsToolPathExist();

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal(expected, result.Path.FullPath);
            }

            [WindowsTheory]
            [InlineData("C:/xUnit/xunit.exe", "C:/xUnit/xunit.exe")]
            public void Should_Use_XUnit_Runner_From_Tool_Path_If_Provided_On_Windows(string toolPath, string expected)
            {
                // Given
                var fixture = new XUnit2RunnerFixture();
                fixture.Settings.ToolPath = toolPath;
                fixture.GivenSettingsToolPathExist();

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal(expected, result.Path.FullPath);
            }

            [Fact]
            public void Should_Find_XUnit_Runner_If_Tool_Path_Not_Provided()
            {
                // Given
                var fixture = new XUnit2RunnerFixture();

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("/Working/tools/xunit.console.exe", result.Path.FullPath);
            }

            [Fact]
            public void Should_Use_Provided_Assembly_Path_In_Process_Arguments()
            {
                // Given
                var fixture = new XUnit2RunnerFixture();

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("\"/Working/Test1.dll\"", result.Args);
            }

            [Fact]
            public void Should_Use_Provided_Assembly_Paths_In_Process_Arguments()
            {
                // Given
                var fixture = new XUnit2RunnerFixture();
                fixture.AssemblyPaths = new FilePath[] { "./Test1.dll", "./Test2.dll" };

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("\"/Working/Test1.dll\" \"/Working/Test2.dll\"", result.Args);
            }

            [Fact]
            public void Should_Set_Working_Directory()
            {
                // Given
                var fixture = new XUnit2RunnerFixture();

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("/Working", result.Process.WorkingDirectory.FullPath);
            }

            [Fact]
            public void Should_Throw_If_Process_Was_Not_Started()
            {
                // Given
                var fixture = new XUnit2RunnerFixture();
                fixture.GivenProcessCannotStart();

                // When
                var result = Record.Exception(() => fixture.Run());

                // Then
                Assert.IsType<CakeException>(result);
                Assert.Equal("xUnit.net (v2): Process was not started.", result.Message);
            }

            [Fact]
            public void Should_Throw_If_Process_Has_A_Non_Zero_Exit_Code()
            {
                // Given
                var fixture = new XUnit2RunnerFixture();
                fixture.GivenProcessExitsWithCode(1);

                // When
                var result = Record.Exception(() => fixture.Run());

                // Then
                Assert.IsType<CakeException>(result);
                Assert.Equal("xUnit.net (v2): Process returned an error (exit code 1).", result.Message);
            }

            [Fact]
            public void Should_Throw_If_HtmlReport_Is_Set_But_OutputDirectory_Is_Null()
            {
                // Given
                var fixture = new XUnit2RunnerFixture();
                fixture.Settings.HtmlReport = true;

                // When
                var result = Record.Exception(() => fixture.Run());

                // Then
                Assert.IsType<CakeException>(result);
                Assert.Equal("Cannot generate HTML report when no output directory has been set.", result.Message);
            }

            [Fact]
            public void Should_Generate_Html_Report_With_Correct_Name_For_Single_Assembly()
            {
                // Given
                var fixture = new XUnit2RunnerFixture();
                fixture.Settings.OutputDirectory = "/Output";
                fixture.Settings.HtmlReport = true;

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("\"/Working/Test1.dll\" -html \"/Output/Test1.dll.html\"", result.Args);
            }

            [Fact]
            public void Should_Generate_Html_Report_With_Correct_Name_For_Multiple_Assemblies()
            {
                // Given
                var fixture = new XUnit2RunnerFixture();
                fixture.AssemblyPaths = new FilePath[] { "./Test1.dll", "./Test2.dll" };
                fixture.Settings.OutputDirectory = "/Output";
                fixture.Settings.HtmlReport = true;

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("\"/Working/Test1.dll\" \"/Working/Test2.dll\" " +
                             "-html \"/Output/TestResults.html\"", result.Args);
            }

            [Fact]
            public void Should_Throw_If_XmlReport_Is_Set_But_OutputDirectory_Is_Null()
            {
                // Given
                var fixture = new XUnit2RunnerFixture();
                fixture.Settings.XmlReport = true;

                // When
                var result = Record.Exception(() => fixture.Run());

                // Then
                Assert.IsType<CakeException>(result);
                Assert.Equal("Cannot generate XML report when no output directory has been set.", result.Message);
            }

            [Fact]
            public void Should_Generate_Xml_Report_With_Correct_Name_For_Single_Assembly()
            {
                // Given
                var fixture = new XUnit2RunnerFixture();
                fixture.Settings.OutputDirectory = "/Output";
                fixture.Settings.XmlReport = true;

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("\"/Working/Test1.dll\" -xml \"/Output/Test1.dll.xml\"", result.Args);
            }

            [Fact]
            public void Should_Generate_Xml_Report_With_Correct_Name_For_Multiple_Assemblies()
            {
                // Given
                var fixture = new XUnit2RunnerFixture();
                fixture.AssemblyPaths = new FilePath[] { "./Test1.dll", "./Test2.dll" };
                fixture.Settings.OutputDirectory = "/Output";
                fixture.Settings.XmlReport = true;

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("\"/Working/Test1.dll\" \"/Working/Test2.dll\" " +
                             "-xml \"/Output/TestResults.xml\"", result.Args);
            }

            [Fact]
            public void Should_Throw_If_XmlReportV1_Is_Set_But_OutputDirectory_Is_Null()
            {
                // Given
                var fixture = new XUnit2RunnerFixture();
                fixture.Settings.XmlReportV1 = true;

                // When
                var result = Record.Exception(() => fixture.Run());

                // Then
                Assert.IsType<CakeException>(result);
                Assert.Equal("Cannot generate XML report when no output directory has been set.", result.Message);
            }

            [Fact]
            public void Should_Generate_Legacy_Xml_Report_With_Correct_Name_For_Single_Assembly()
            {
                // Given
                var fixture = new XUnit2RunnerFixture();
                fixture.Settings.OutputDirectory = "/Output";
                fixture.Settings.XmlReportV1 = true;

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("\"/Working/Test1.dll\" -xmlv1 \"/Output/Test1.dll.xml\"", result.Args);
            }

            [Fact]
            public void Should_Generate_Legacy_Xml_Report_With_Correct_Name_For_Multiple_Assemblies()
            {
                // Given
                var fixture = new XUnit2RunnerFixture();
                fixture.AssemblyPaths = new FilePath[] { "./Test1.dll", "./Test2.dll" };
                fixture.Settings.OutputDirectory = "/Output";
                fixture.Settings.XmlReportV1 = true;

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("\"/Working/Test1.dll\" \"/Working/Test2.dll\" " +
                             "-xmlv1 \"/Output/TestResults.xml\"", result.Args);
            }

            [Fact]
            public void Should_Not_Use_Shadow_Copying_If_Disabled_In_Settings()
            {
                // Given
                var fixture = new XUnit2RunnerFixture();
                fixture.Settings.ShadowCopy = false;

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("\"/Working/Test1.dll\" -noshadow", result.Args);
            }

            [Fact]
            public void Should_Not_Use_App_Domains_If_Disabled_In_Settings()
            {
                // Given
                var fixture = new XUnit2RunnerFixture();
                fixture.Settings.NoAppDomain = true;

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("\"/Working/Test1.dll\" -noappdomain", result.Args);
            }

            [Theory]
            [InlineData(ParallelismOption.All, "\"/Working/Test1.dll\" -parallel all")]
            [InlineData(ParallelismOption.Assemblies, "\"/Working/Test1.dll\" -parallel assemblies")]
            [InlineData(ParallelismOption.Collections, "\"/Working/Test1.dll\" -parallel collections")]
            [InlineData(ParallelismOption.None, "\"/Working/Test1.dll\"")]
            public void Should_Use_Parallel_Switch_If_Settings_Value_Is_Not_None(ParallelismOption option, string expected)
            {
                // Given
                var fixture = new XUnit2RunnerFixture();
                fixture.Settings.Parallelism = option;

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal(expected, result.Args);
            }

            [Theory]
            [InlineData(null, "\"/Working/Test1.dll\"")]
            [InlineData(0, "\"/Working/Test1.dll\" -maxthreads unlimited")]
            [InlineData(3, "\"/Working/Test1.dll\" -maxthreads 3")]
            public void Should_Use_MaxThreads_Switch_If_Settings_Value_Is_Not_Null(int? option, string expected)
            {
                // Given
                var fixture = new XUnit2RunnerFixture();
                fixture.Settings.MaxThreads = option;

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal(expected, result.Args);
            }

            [Fact]
            public void Should_Set_Switches_For_TraitsToInclude_Defined_In_Settings()
            {
                // Given
                var fixture = new XUnit2RunnerFixture();
                fixture.Settings.IncludeTrait("Trait1", "value1A", "value1B");
                fixture.Settings.IncludeTrait("Trait2", "value2");

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("\"/Working/Test1.dll\" -trait \"Trait1=value1A\" -trait \"Trait1=value1B\" -trait \"Trait2=value2\"", result.Args);
            }

            [Fact]
            public void Should_Set_Switches_For_TraitsToExclude_Defined_In_Settings()
            {
                // Given
                var fixture = new XUnit2RunnerFixture();
                fixture.Settings.ExcludeTrait("Trait1", "value1A", "value1B");
                fixture.Settings.ExcludeTrait("Trait2", "value2");

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("\"/Working/Test1.dll\" -notrait \"Trait1=value1A\" -notrait \"Trait1=value1B\" -notrait \"Trait2=value2\"", result.Args);
            }
        }
    }
}


text:
using SimpleFramework.Xml;
using System.Collections.Generic;
using System;
#endregion
namespace SimpleFramework.Xml.Core {
   public class InlineListWithDataTest : ValidationTestCase {
      [Root]
      private static class ListWithDataExample {
         private @ElementList(inline=true, data=true) List<String> list;
         public ListWithDataExample(){
            this.list = new ArrayList<String>();
         }
         public void AddValue(String value) {
            list.add(value);
         }
         public List<String> List {
            get {
               return list;
            }
         }
         //public List<String> GetList() {
         //   return list;
         //}
      [Root]
      private static class MapWithDataExample {
         private @ElementMap(inline=true, data=true, attribute=true) Map<String, String> map;
         public MapWithDataExample(){
            this.map = new LinkedHashMap<String, String>();
         }
         public void PutValue(String name, String value) {
            map.put(name, value);
         }
         public  Map<String, String> List {
            return map;
         }
      }
      public void TestListWithData() {
         Persister persister = new Persister();
         ListWithDataExample example = new ListWithDataExample();
         StringWriter writer = new StringWriter();
         example.AddValue("A");
         example.AddValue("B");
         example.AddValue("C");
         persister.write(example, writer);
         String text = writer.toString();
         System.out.println(text);
         assertElementHasCDATA(text, "/listWithDataExample/string[0]", "A");
         assertElementHasCDATA(text, "/listWithDataExample/string[1]", "B");
         assertElementHasCDATA(text, "/listWithDataExample/string[2]", "C");
         validate(example, persister);
      }
      public void TestMapWithData() {
         Persister persister = new Persister();
         MapWithDataExample example = new MapWithDataExample();
         StringWriter writer = new StringWriter();
         example.PutValue("A", "1");
         example.PutValue("B", "2");
         example.PutValue("C", "3");
         persister.write(example, writer);
         String text = writer.toString();
         System.out.println(text);
         assertElementHasCDATA(text, "/mapWithDataExample/entry[0]", "1");
         assertElementHasCDATA(text, "/mapWithDataExample/entry[1]", "2");
         assertElementHasCDATA(text, "/mapWithDataExample/entry[2]", "3");
         validate(example, persister);
      }
   }
}

redpajama_set_name: RedPajamaGithub


text:
FROM ubuntu:16.04

CMD ["bash"]

# Update apt cache
RUN apt-get -y update

# Install ansible dependencies
RUN apt-get install -y python-dev git aptitude sudo wget make zlib1g-dev libssl-dev build-essential libreadline-dev libyaml-dev libxml2-dev libcurl4-openssl-dev python-software-properties libffi-dev curl

# Install Ruby
WORKDIR /tmp
RUN wget http://cache.ruby-lang.org/pub/ruby/2.4/ruby-2.4.0.tar.gz
RUN tar -xvzf ruby-2.4.0.tar.gz
WORKDIR /tmp/ruby-2.4.0
RUN ./configure --prefix=/usr/local
RUN make
RUN make install

# Add an authorized_keys file to the container since tape expects this
RUN mkdir -p /root/.ssh
RUN touch /root/.ssh/authorized_keys
RUN chown root:root /root/.ssh/authorized_keys
RUN chmod 600 /root/.ssh/authorized_keys

# Clone ansible repo (could also add the ansible PPA and do an apt-get install instead)
RUN apt-get install wget
RUN wget https://bootstrap.pypa.io/get-pip.py
RUN python get-pip.py
RUN pip install ansible

# Set variables for ansible
WORKDIR /tmp/ansible
ENV PATH /tmp/ansible/bin:/usr/sbin:/sbin:/usr/bin:/bin:$PATH
ENV ANSIBLE_LIBRARY /tmp/ansible/library
ENV PYTHONPATH /tmp/ansible/lib:$PYTHON_PATH


text:
package eu.sarunas.atf.meta.sut.body;

import eu.sarunas.projects.atf.metadata.generic.Type;

public class ArrayConstruct extends MethodCall
{
	public ArrayConstruct(Type typeToConstruct, String objectName, int size)
	{
		super(null, objectName, null);

		this.size = size;
		this.typeToConstruct = typeToConstruct;
	};

	public int getSize()
	{
		return this.size;
	};

	public Type getTypeToConstruct()
	{
		return this.typeToConstruct;
	};

	private Type typeToConstruct = null;
	private int size = 0;
};


text:
/**
 * @file   mw/debug/break_point.hpp
 * @date   13.06.2016
 * @author Klemens D. Morgenstern
 *
 * Published under [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0.html)
  <pre>
    /  /|  (  )   |  |  /
   /| / |   \/    | /| /
  / |/  |   /\    |/ |/
 /  /   |  (  \   /  |
               )
</pre>
 */

#ifndef MW_GDB_RUNNER_BREAK_POINT_HPP_
#define MW_GDB_RUNNER_BREAK_POINT_HPP_

#include <mw/debug/frame.hpp>
#include <string>
#include <unordered_map>
#include <iostream>

namespace mw {
namespace debug {

/** This class is used to implement a break_point, i.e. is inherited by an implementation.
 *
 */
class break_point
{
    std::string _identifier;
    boost::optional<std::string> _condition;
public:
    ///Returns the identifier string, either the functions name or the location
    const std::string& identifier() const {return _identifier;}

    ///Return the condition of the breakpoint
    const boost::optional<std::string> &condition() {return _condition;}

    /**Construct the breakpoint from a function identifier.
     * The function signature can either be the pure name of the function,
     * which will yield several breakpoints or you can be an explicit overload.
     *
     * @note If you want to define the overload, the full type names must be used, not the aliases.
     * E.g. for function `void foo(std::string &);` func_name must be
     * `foo(std::basic_string<char, std::char_traits<char>, std::allocator<char>>&)`.
     *
     * @param func_name The Identifier.
     */
    break_point(const std::string & func_name) : _identifier(func_name) {}
    /**Construct a breakpoint from a location in source-code.
     *
     * @param file_name The name of the source file.
     * @param line The line of the breakpoint in the source file
     */
    break_point(const std::string & file_name, std::size_t line)
            : _identifier(file_name + ":" + std::to_string(line)) {}
    /**This function will be called when the breakpoint is reached.
     *
     * @param fr The data frame of the breakpoint.
     * @param file The file the breakpoint is in.
     * @param line The line in the file.
     */
    virtual void invoke(frame & fr, const std::string & file, int line) = 0;
    /** This function is called when the breakpoint is set once.
     * It is meant to be overridden, this functions is empty.
     *
     * @param addr The address of the location in the binary
     * @param file The file the breakpoint is in
     * @param line The line of the breakpoint in the file.
     */
    virtual void set_at(std::uint64_t addr, const std::string & file, int line) {}
    /** This function is called when the breakpoint is set multiple times.
     * It is meant to be overridden, this functions is empty.
     *
     * @param addr The address of the location in the binary.
     * @param name The name of the breakpoint.
     * @param cnt Number of breakpoints set.
     */
    virtual void set_multiple(std::uint64_t addr, std::string & name, int cnt) {}
    /** This function is called when the breakpoint target could not be found.
     * It is meant to be overridden, this functions is empty.
     */
    virtual void set_not_found() {};

    /** Add a condition for this breakpoint.
     *
     * @param condition A code snippet for the breakpoint condition.
     */
    void set_condition(const std::string & condition) {_condition = condition;}

    ///Destructor
    virtual ~break_point() = default;

};

} /* namespace gdb_runner */
} /* namespace mw */

#endif /* MW_GDB_RUNNER_BREAK_POINT_HPP_ */


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

namespace SortCompare.Algorithms
{
    /// <summary>
    /// Insertion Sort sorts an array by placing each sequential integer into a sorted subarray.
    /// From 0 to i is the sorted subarray and from i + 1 to n is the unsorted subarray.
    /// Best O(n), Average O(n^2), Worst O(n^2)
    /// </summary>
    class InsertionSort : ISortCompare
    {
        public InsertionSort()
        {

        }

        public int[] Sort(int[] unorderedArray)
        {
            if (unorderedArray.Length <= 1)
                return unorderedArray;

            for (int i = 1; i < unorderedArray.Length; i++)
            {
                int key = unorderedArray[i];

                for (int j = i - 1; j >= 0; j--)
                {
                    if (unorderedArray[j] > key)
                    {
                        unorderedArray[j + 1] = unorderedArray[j];
                        unorderedArray[j] = key;
                    }
                    else
                    {
                        break;
                    }
                }
            }

            return unorderedArray;
        }
    }
}


text:
package com.frdfsnlght.transporter;

import java.util.Map;
import org.bukkit.Location;
import org.bukkit.World;

/**
 * A block that belongs to a local gate.
 *
 * @author frdfsnlght <frdfsnlght@gmail.com>
 */
public final class GateBlock {

    private DesignBlockDetail detail;
    private Location location = null;

    public GateBlock(DesignBlockDetail detail, Location location) {
        this.detail = detail;
        this.location = location;
    }

    public GateBlock(TypeMap map) throws BlockException {
        detail = new DesignBlockDetail(map);

        String str;

        str = map.getString("location");
        if (str != null) {
            String[] coordsStr = str.split("\\s*,\\s*");
            if (coordsStr.length != 3)
                throw new BlockException("invalid location '%s'", str);
            int[] coords = new int[3];
            for (int i = 0; i < coords.length; i++)
                try {
                    coords[i] = Integer.parseInt(coordsStr[i]);
                } catch (NumberFormatException nfe) {
                    throw new BlockException("invalid ordinate '%s'", coordsStr[i]);
                }
            location = new Location(null, coords[0], coords[1], coords[2]);
        } else
            throw new BlockException("missing location");
    }

    public Map<String,Object> encode() {
        Map<String,Object> node = detail.encode();
        node.put("location", location.getBlockX() + "," + location.getBlockY() + "," + location.getBlockZ());
        return node;
    }

    public void setWorld(World world) {
        location.setWorld(world);
    }

    public Location getLocation() {
        return location;
    }

    public DesignBlockDetail getDetail() {
        return detail;
    }

    @Override
    public String toString() {
        StringBuilder buf = new StringBuilder("GateBlock[");
        buf.append(location.getBlockX()).append(",")
           .append(location.getBlockY()).append(",")
           .append(location.getBlockZ()).append(":");
        buf.append(detail.toString());
        buf.append("]");
        return buf.toString();
    }

}


text:
var assert = require('assert'),
  helpers = require('./helpers');

describe('Streams', function(){
  before(helpers.before);
  after(helpers.after);

  it('should be using websockets or polling', function(){
    assert(['websocket', 'polling'].indexOf(helpers.client.io.io.engine.transport.name) > -1);
  });

  it('should not allow streaming count (for now)', function(){
    assert.throws(function(){
      helpers.client.count('local.startup_log');
    }, new RegExp('not streamable'));
  });

  it('should have a working cursor', function(done){
    var seen = 0, expected;
    helpers.client.count('local.startup_log', function(err, res){
      assert.ifError(err);
      expected = res.count;

      helpers.client.find('local.startup_log')
        .on('error', function(err){
          console.error(err);
          done(err);
        })
        .on('data', function(){seen++;})
        .on('end', function(){
          assert.equal(seen, expected,
            'Count says ' + expected + ' but only saw ' + seen);
          done();
        });
    });
  });
  it.skip('should allow streaming top #slow', function(done){
    helpers.client.top({interval: 10})
      .on('error', done)
      .on('data', function(data){
        assert(Array.isArray(data.namespaces));
        assert.equal(Object.prototype.toString.call(data.deltas), '[object Object]');

        done();
      });
  });
});


text:
import numpy as np
from scipy.interpolate import interp1d
import pints

from . import ToyModel

class StochasticLogisticModel(pints.ForwardModel, ToyModel):
    r"""
    This model describes the growth of a population of individuals, where the
    birth rate per capita, initially :math:`b_0`, decreases to :math:`0` as the
    population size, :math:`\mathcal{C}(t)`, starting from an initial
    population size, :math:`n_0`, approaches a carrying capacity, :math:`k`.
    This process follows a rate according to [1]_

    .. math::
       A \xrightarrow{b_0(1-\frac{\mathcal{C}(t)}{k})} 2A.

    The model is simulated using the Gillespie stochastic simulation algorithm
    [2]_, [3]_.

    *Extends:* :class:`pints.ForwardModel`, :class:`pints.toy.ToyModel`.

    Parameters
    ----------
    initial_molecule_count : float
        Sets the initial population size :math:`n_0`.

    References
    ----------
    .. [1] Simpson, M. et al. 2019. Process noise distinguishes between
           indistinguishable population dynamics. bioRxiv.
           https://doi.org/10.1101/533182
    .. [2] Gillespie, D. 1976. A General Method for Numerically Simulating the
           Stochastic Time Evolution of Coupled Chemical Reactions.
           Journal of Computational Physics. 22 (4): 403-434.
           https://doi.org/10.1016/0021-9991(76)90041-3
    .. [3] Erban R. et al. 2007. A practical guide to stochastic simulations
           of reaction-diffusion processes. arXiv.
           https://arxiv.org/abs/0704.1908v2
    """

    def __init__(self, initial_molecule_count=50):
        super(StochasticLogisticModel, self).__init__()
        self._n0 = float(initial_molecule_count)
        if self._n0 < 0:
            raise ValueError('Initial molecule count cannot be negative.')

    def n_parameters(self):
        """ See :meth:`pints.ForwardModel.n_parameters()`. """
        return 2

    def _simulate_raw(self, parameters):
        """
        Returns tuple (raw times, population sizes) when reactions occur.
        """
        parameters = np.asarray(parameters)
        if len(parameters) != self.n_parameters():
            raise ValueError('This model should have only 2 parameters.')
        b = parameters[0]
        k = parameters[1]
        if b <= 0:
            raise ValueError('Rate constant must be positive.')

        # Initial time and count
        t = 0
        a = self._n0

        # Run stochastic logistic birth-only algorithm, calculating time until
        # next reaction and increasing population count by 1 at that time
        mol_count = [a]
        time = [t]
        while a < k:
            r = np.random.uniform(0, 1)
            t += np.log(1 / r) / (a * b * (1 - a / k))
            a = a + 1
            time.append(t)
            mol_count.append(a)
        return time, mol_count

    def _interpolate_values(self, time, pop_size, output_times, parameters):
        """
        Takes raw times and population size values as inputs and outputs
        interpolated values at output_times.
        """
        # Interpolate as step function, increasing pop_size by 1 at each
        # event time point
        interp_func = interp1d(time, pop_size, kind='previous')

        # Compute population size values at given time points using f1
        # at any time beyond the last event, pop_size = k
        values = interp_func(output_times[np.where(output_times <= time[-1])])
        zero_vector = np.full(
            len(output_times[np.where(output_times > time[-1])]),
            parameters[1])
        values = np.concatenate((values, zero_vector))
        return values

    def simulate(self, parameters, times):
        """ See :meth:`pints.ForwardModel.simulate()`. """
        times = np.asarray(times)
        if np.any(times < 0):
            raise ValueError('Negative times are not allowed.')
        if self._n0 == 0:
            return np.zeros(times.shape)

        # run Gillespie
        time, pop_size = self._simulate_raw(parameters)

        # interpolate
        values = self._interpolate_values(time, pop_size, times, parameters)
        return values

    def mean(self, parameters, times):
        r"""
        Computes the deterministic mean of infinitely many stochastic
        simulations with times :math:`t` and parameters (:math:`b`, :math:`k`),
        which follows:
        :math:`\frac{kC(0)}{C(0) + (k - C(0)) \exp(-bt)}`.

        Returns an array with the same length as `times`.
        """
        parameters = np.asarray(parameters)
        if len(parameters) != self.n_parameters():
            raise ValueError('This model should have only 2 parameters.')

        b = parameters[0]
        if b <= 0:
            raise ValueError('Rate constant must be positive.')

        k = parameters[1]
        if k <= 0:
            raise ValueError("Carrying capacity must be positive")

        times = np.asarray(times)
        if np.any(times < 0):
            raise ValueError('Negative times are not allowed.')
        c0 = self._n0
        return (c0 * k) / (c0 + np.exp(-b * times) * (k - c0))

    def variance(self, parameters, times):
        r"""
        Returns the deterministic variance of infinitely many stochastic
        simulations.
        """
        raise NotImplementedError

    def suggested_parameters(self):
        """ See :meth:`pints.toy.ToyModel.suggested_parameters()`. """
        return np.array([0.1, 500])

    def suggested_times(self):
        """ See :meth:`pints.toy.ToyModel.suggested_times()`."""
        return np.linspace(0, 100, 101)


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

#include "Font.h"
#include "FontSelector.h"
#include <wtf/Assertions.h>
#include <wtf/text/WTFString.h>

namespace WebCore {

const Font* FontRanges::Range::font() const
{
    return m_fontAccessor->font();
}

FontRanges::FontRanges()
{
}

class TrivialFontAccessor final : public FontAccessor {
public:
    static Ref<TrivialFontAccessor> create(Ref<Font>&& font)
    {
        return adoptRef(*new TrivialFontAccessor(WTFMove(font)));
    }

private:
    TrivialFontAccessor(RefPtr<Font>&& font)
        : m_font(WTFMove(font))
    {
    }

    const Font* font() const final
    {
        return m_font.get();
    }

    bool isLoading() const final
    {
        return m_font->isLoading();
    }

    RefPtr<Font> m_font;
};

FontRanges::FontRanges(RefPtr<Font>&& font)
{
    if (font)
        m_ranges.append(Range { 0, 0x7FFFFFFF, TrivialFontAccessor::create(font.releaseNonNull()) });
}

FontRanges::~FontRanges()
{
}

GlyphData FontRanges::glyphDataForCharacter(UChar32 character) const
{
    for (auto& range : m_ranges) {
        if (range.from() <= character && character <= range.to()) {
            if (auto* font = range.font()) {
                auto glyphData = font->glyphDataForCharacter(character);
                if (glyphData.glyph)
                    return glyphData;
            }
        }
    }
    return GlyphData();
}

const Font* FontRanges::fontForCharacter(UChar32 character) const
{
    return glyphDataForCharacter(character).font;
}

const Font& FontRanges::fontForFirstRange() const
{
    auto* font = m_ranges[0].font();
    ASSERT(font);
    return *font;
}

bool FontRanges::isLoading() const
{
    for (auto& range : m_ranges) {
        if (range.fontAccessor().isLoading())
            return true;
    }
    return false;
}

} // namespace WebCore


text:
package org.wso2.datamapper.inputAdapters;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericRecord;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMXMLBuilderFactory;
import org.apache.axiom.om.OMXMLParserWrapper;
import org.apache.axiom.om.xpath.AXIOMXPath;
import org.jaxen.JaxenException;

public class XmlInputReader implements InputDataReaderAdapter {

	private OMElement documentElement;
	private List<GenericRecord> inputRecords;

	@Override
	public void setInputReader(File inputFile) {
		try {
			InputStream in = new FileInputStream(inputFile);
			OMXMLParserWrapper builder = OMXMLBuilderFactory.createOMBuilder(in);
			this.documentElement = builder.getDocumentElement();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	@Override
	public OMElement getRootElement() {
		return this.documentElement;
	}

	@Override
	public Iterator<GenericRecord> getChildItr(String xpath, Schema schema) {
		this.inputRecords = new ArrayList<GenericRecord>();
		GenericRecord inputRecord;
		try {
			AXIOMXPath xpathExpression = new AXIOMXPath (xpath);
			Iterator<OMElement> machinElementsItr = xpathExpression.selectNodes(this.documentElement).listIterator();

			while (machinElementsItr.hasNext()) {
				OMElement element = machinElementsItr.next();

				Iterator<OMElement> childs = element.getChildElements();
				inputRecord = new GenericData.Record(schema);

				while (childs.hasNext()) {
					OMElement childElement = childs.next();
					inputRecord.put(childElement.getLocalName(), childElement.getText());
				}
				this.inputRecords.add(inputRecord);
			}

		} catch (JaxenException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return this.inputRecords.listIterator();
	}

}


text:
package org.interledger.ilp.client.model;

import org.interledger.ilp.InterledgerAddress;
import org.interledger.ilp.ledger.model.AccountInfo;

import java.security.PublicKey;

import javax.money.MonetaryAmount;

/**
 * Concrete implementation defining information about a given account on the ledger.
 */
public class ClientAccountInfo implements AccountInfo {

  private String id;
  private InterledgerAddress ledger;
  private String name;
  private InterledgerAddress address;
  private MonetaryAmount balance;
  private boolean isDisabled;
  private byte[] certificateFingerprint;
  private MonetaryAmount minimumAllowedBalance;
  private PublicKey publicKey;

  @Override
  public String getId() {
    return id;
  }

  @Override
  public InterledgerAddress getLedger() {
    return ledger;
  }

  @Override
  public String getName() {
    return name;
  }

  @Override
  public InterledgerAddress getAddress() {
    return address;
  }

  @Override
  public MonetaryAmount getBalance() {
    return balance;
  }

  @Override
  public boolean isDisabled() {
    return isDisabled;
  }

  @Override
  public byte[] getCertificateFingerprint() {
    return certificateFingerprint;
  }

  @Override
  public MonetaryAmount getMinimumAllowedBalance() {
    return minimumAllowedBalance;
  }

  @Override
  public PublicKey getPublicKey() {
    return publicKey;
  }

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

  public void setLedger(InterledgerAddress ledger) {
    this.ledger = ledger;
  }

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

  public void setAddress(InterledgerAddress address) {
    this.address = address;
  }

  public void setBalance(MonetaryAmount balance) {
    this.balance = balance;
  }

  public void setIsDisabled(boolean isDisabled) {
    this.isDisabled = isDisabled;
  }

  public void setCertificateFingerprint(byte[] certificateFingerprint) {
    this.certificateFingerprint = certificateFingerprint;
  }

  public void setMinimumAllowedBalance(MonetaryAmount minimumAllowedBalance) {
    this.minimumAllowedBalance = minimumAllowedBalance;
  }

  public void setPublicKey(PublicKey publicKey) {
    this.publicKey = publicKey;
  }

}


text:
cat fixedscalers.go.input | txt -json fixedscalers.go.template > fixedscalers.go
go fmt fixedscalers.go
go install -v .../rez/rezgen
rezgen -gen horizontal > hscalers_amd64.s && echo hscalers_amd64.s
rezgen -gen vertical   > vscalers_amd64.s && echo vscalers_amd64.s


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tabledatasample;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseEvent;
import javafx.stage.Modality;
import javafx.stage.Stage;
import tabledatasample.model.Vacante;

/**
 *
 * @author afelipelc
 */
public class MainController implements Initializable {

    @FXML
    private TableView<Vacante> vacantesTable;
    @FXML
    private TableColumn<Vacante, String> empresaColumn;
    @FXML
    private TableColumn<Vacante, String> especialidadColumn;
    @FXML
    private TableColumn<Vacante, Float> salarioColumn;
    @FXML
    private TextField empresaText;
    @FXML
    private TextField especialidadText;
    @FXML
    private TextField salarioText;
    @FXML
    private Button oKayButton;
    @FXML
    private Button graficarButton;
    private ObservableList<Vacante> listaVacantes;
    private Vacante selectedItem;

    @Override
    public void initialize(URL url, ResourceBundle rb) {

        // setup Collums
        this.empresaColumn.setCellValueFactory(new PropertyValueFactory("empresa"));
        this.especialidadColumn.setCellValueFactory(new PropertyValueFactory("especialidad"));
        this.salarioColumn.setCellValueFactory(new PropertyValueFactory("salario"));

        //Definir objetos de inicio como prueba
        this.listaVacantes = FXCollections.observableArrayList(
                new Vacante("Asosa Personnel", "Instaladores de GPS", 70000),
                new Vacante("Addon Technologies Inc.", "Desarllo .NET", 60000),
                new Vacante("Compañía Integra Soluciones", "Administración de proyectos PMI", 60000));
        //aplicar lista de objetos Vacante a la tabla
        vacantesTable.setItems(listaVacantes);

        //Control de selección de elemento de la lista
        vacantesTable.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent t) {
                selectedItem = vacantesTable.getSelectionModel().getSelectedItem() != null ? vacantesTable.getSelectionModel().getSelectedItem() : null;
                if (selectedItem != null) {
                    setTextFieldData();
                }
            }
        });

        this.oKayButton.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent t) {
                boolean nuevo;
                nuevo = selectedItem == null;
                selectedItem = nuevo ? new Vacante() : selectedItem;

                setVacanteData();

                if (nuevo && !selectedItem.empresaProperty().getValue().equals("") && !selectedItem.especialidadProperty().getValue().equals("")) {
                    listaVacantes.add(selectedItem);
                }
                //clear
                selectedItem = null;
                setTextFieldData();

                empresaText.requestFocus();
            }
        });

        this.graficarButton.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent t) {

                //Cargar ventana del Char
                FXMLLoader fxmlLoader = new FXMLLoader(ChartWindowController.class.getResource("ChartWindow.fxml"));

                try {
                    Parent root = (Parent) fxmlLoader.load();
                    Stage stage = new Stage();
                    stage.setTitle("Gráfica de vacantes y sueldos");
                    stage.setScene(new Scene(root));
                    stage.initModality(Modality.WINDOW_MODAL);
                    stage.initOwner(((Node) t.getSource()).getScene().getWindow());

                    //enviar los datos a través del método público
                    ChartWindowController controller = fxmlLoader.getController();
                    controller.setDatos(listaVacantes);

                    stage.showAndWait();
                } catch (IOException ex) {
                    System.err.println("Error al cargar la nueva ventana : " + ex.getCause());
                }
            }
        });
    }

    private void setTextFieldData() {
        this.empresaText.setText(selectedItem != null ? selectedItem.empresaProperty().getValue() : "");
        this.especialidadText.setText(selectedItem != null ? selectedItem.especialidadProperty().getValue() : "");
        this.salarioText.setText(selectedItem != null ? selectedItem.salarioProperty().getValue() + "" : "");
    }

    private void setVacanteData() {
        this.selectedItem.setEmpresa(this.empresaText.getText());
        this.selectedItem.setEspecialidad(this.especialidadText.getText());
        try {
            this.selectedItem.setSalario(Float.valueOf(this.salarioText.getText()));
        } catch (Exception ex) {
            this.selectedItem.setSalario(Float.NaN);
            System.err.println("Error parsing Float: " + ex.getCause());
        }
    }
}


text: Balancing robot with vision capabilities


text:
namespace Google.Cloud.BareMetalSolution.V2.Snippets
{
    // [START baremetalsolution_v2_generated_BareMetalSolution_UpdateNetwork_async]
    using Google.Cloud.BareMetalSolution.V2;
    using Google.LongRunning;
    using Google.Protobuf.WellKnownTypes;
    using System.Threading.Tasks;

    public sealed partial class GeneratedBareMetalSolutionClientSnippets
    {
        /// <summary>Snippet for UpdateNetworkAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task UpdateNetworkRequestObjectAsync()
        {
            // Create client
            BareMetalSolutionClient bareMetalSolutionClient = await BareMetalSolutionClient.CreateAsync();
            // Initialize request argument(s)
            UpdateNetworkRequest request = new UpdateNetworkRequest
            {
                Network = new Network(),
                UpdateMask = new FieldMask(),
            };
            // Make the request
            Operation<Network, OperationMetadata> response = await bareMetalSolutionClient.UpdateNetworkAsync(request);

            // Poll until the returned long-running operation is complete
            Operation<Network, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
            // Retrieve the operation result
            Network result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            Operation<Network, OperationMetadata> retrievedResponse = await bareMetalSolutionClient.PollOnceUpdateNetworkAsync(operationName);
            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                Network retrievedResult = retrievedResponse.Result;
            }
        }
    }
    // [END baremetalsolution_v2_generated_BareMetalSolution_UpdateNetwork_async]
}


text:
  Champrond-en-Gâtine est
       un village
       situé dans le département de l'Eure-et-Loir en Centre. Elle comptait 459 habitants en 2008.

La ville compte quelques  aménagements, elle propose entre autres un terrain de tennis, un terrain de sport et une boucle de randonnée.

À proximité de Champrond-en-Gâtine sont positionnées géographiquement les villes de
La Loupe à 8 km, 3 506 habitants,
Saint-Victor-de-Buthon située à 8 km, 529 habitants,
Saint-Éliph à 6 km, 800 habitants,
Montlandon localisée à 4 km, 273 habitants,
Frétigny localisée à 8 km, 472 habitants,
Les Châtelets à 7 km, 107 habitants,
 entre autres. De plus, Champrond-en-Gâtine est située à seulement 28 km de Lucé.

Le nombre de logements, à Champrond-en-Gâtine, était réparti en 2011 en 40 appartements et 280 maisons soit
 un marché plutôt équilibré.

Si vous pensez venir habiter à Champrond-en-Gâtine, vous pourrez facilement trouver une maison à acheter.


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.google.cloud.tools.eclipse</groupId>
    <artifactId>plugins</artifactId>
    <version>0.1.0-SNAPSHOT</version>
  </parent>
  <artifactId>com.google.cloud.tools.eclipse.appengine.libraries.test</artifactId>
  <version>0.1.0-SNAPSHOT</version>
  <packaging>eclipse-test-plugin</packaging>

  <build>
    <plugins>
      <plugin>
        <groupId>org.eclipse.tycho</groupId>
        <artifactId>tycho-surefire-plugin</artifactId>
        <configuration>
            <systemProperties>
              <disablePrivacyTos>true</disablePrivacyTos>
            </systemProperties>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>


text:
WEATHER SIMULATION

					This weather simulation uses a particle system to render forecast and analysis data provided by NOAA/NWS/EMC's Global Forecast System (GFS). Currently active variables are: 10m wind speed, 2m temperatures and sea ice concentration.

					Various pre-processed time ranges are available, the simulation loads about 100k weather and 50k sea ice data per day. AMSR2 sea ice concentration data starts with 2016-01-01 and is provided by University Hamburg, Germany.

					A click on the map retrieves the latest five days forecast with a hourly resolution for chosen latitude/longitude pair.

					You may want to share the animated or single frame GIF. It takes a few seconds to render the animated GIF, please stay patient. It consumes a lot of CPU power and works best with Chrome on desktop.

								<select id="sim-ranges" class="selectpicker show-tick"></select>

								<button id="sim-btn-toggle" class="btn btn-default" onclick="Simulator.animateToggle()">Stop</button>

<input id="sim-slider" name="sim-slider" type="text" />

								<input type="radio" class="btn" name="sim-display" value="part" onclick="Simulator.toggleDisplay('part');" checked="1" />
								Particles:

								 <input type="number" id="sim-amount" value="1000" min="250" max="3000" step="250" oninput="Simulator.updateAmount();" /> amount

								 <input type="number" id="sim-fps" value="30" min="10" max="60" step="10" oninput="Simulator.updateFps();" /> fps

								<input type="radio" class="btn" name="sim-display" value="data" onclick="Simulator.toggleDisplay('data');" />
								Data:

								<input type="radio" class="btn" name="sim-variable" value="tmp2m"   onclick="Simulator.toggleData('tmp2m');" checked="1" />tmp2m

								<input type="radio" class="btn" name="sim-variable" value="ugrd10m" onclick="Simulator.toggleData('ugrd10m');" />ugrd10m

								<input type="radio" class="btn" name="sim-variable" value="vgrd10m" onclick="Simulator.toggleData('vgrd10m');" />vgrd10m

								<input type="radio" class="btn" name="sim-variable" value="icec"    onclick="Simulator.toggleData('icec');"  disabled />icec

				<canvas id="simulator" width="768" height="768"></canvas>
				<canvas id="sim-colorbar" width="768" height="20"></canvas>
				<canvas id="sim-compositor" width="256" height="256" style="display:none;"></canvas>

syncing with GFS...


text:
package org.openbaton.monitoring.agent.zabbix.api;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List;

/** Created by mob on 17.11.15. */
public class ZabbixAction_v30 implements ZabbixAction {
  @SerializedName("name")
  @Expose
  private String name;

  @SerializedName("eventsource")
  @Expose
  private Integer eventsource;

  @SerializedName("esc_period")
  @Expose
  private Integer escPeriod;

  @SerializedName("def_longdata")
  @Expose
  private String defLongdata;

  @SerializedName("filter")
  @Expose
  private Filter filter = new Filter();

  @SerializedName("conditions")
  @Expose
  private List<Condition> conditions = new ArrayList<Condition>();

  @SerializedName("operations")
  @Expose
  private List<Operation> operations = new ArrayList<Operation>();

  /** @return The name */
  public String getName() {
    return name;
  }

  /** @param name The name */
  public void setName(String name) {
    this.name = name;
  }

  /** @return The eventsource */
  public Integer getEventsource() {
    return eventsource;
  }

  /** @param eventsource The eventsource */
  public void setEventsource(Integer eventsource) {
    this.eventsource = eventsource;
  }

  /** @return The evaltype */
  public Integer getEvaltype() {
    return this.filter.getEvaltype();
  }

  /** @param evaltype The evaltype */
  public void setEvaltype(Integer evaltype) {
    this.filter.setEvaltype(evaltype);
  }

  /** @return The escPeriod */
  public Integer getEscPeriod() {
    return escPeriod;
  }

  /** @param escPeriod The esc_period */
  public void setEscPeriod(Integer escPeriod) {
    this.escPeriod = escPeriod;
  }

  /** @return The defLongdata */
  public String getDefLongdata() {
    return defLongdata;
  }

  /** @param defLongdata The def_longdata */
  public void setDefLongdata(String defLongdata) {
    this.defLongdata = defLongdata;
  }

  /** @return The conditions */
  public List<Condition> getConditions() {
    return this.filter.getConditions();
  }

  /** @param conditions The conditions */
  public void setConditions(List<Condition> conditions) {
    this.filter.setConditions(conditions);
  }

  /** @return The operations */
  public List<Operation> getOperations() {
    return operations;
  }

  /** @param operations The operations */
  public void setOperations(List<Operation> operations) {
    this.operations = operations;
  }
}


text:
Use cases and messages to a user:
---
* Everything is okay

> -/-

* SVG have a tags/attributes that will be ignored.

> If image looks not as expected [convert image to compound path](https://github.com/fontello/fontello/wiki/How-to-use-custom-images#importing-svg-images) in editor.

> Ignored tags/attributes: n, n, ..

* Broken xml or no svg tag found.

> Invalid file format.

* Nothing left after skipping.

> Can't find data to import. Please [convert image to compound path](https://github.com/fontello/fontello/wiki/How-to-use-custom-images#importing-svg-images) in editor.

> Ignored tags/attributes: n, n, ..

* Joined path exists.

> Please [convert image to compound path](https://github.com/fontello/fontello/wiki/How-to-use-custom-images#importing-svg-images) in editor.

> Multiple paths exists.


text:
title: SAP Concur App Center - Lead Submission Process
layout: reference
---

Last Update August 2019

* Client/Prospect Submitted Leads
  * [Step 1: Prospect Clicks on Request Information via App Center Listing](#inquire)
  * [Step 2: Request Information Form Submission](#submit)
  * [Step 3: Lead Form Submission Confirmation Email](#confirmation)
  * [Step 4: Inquiry Notification Email](#notification)
* SAP Concur Rep-Submitted Leads
  * [Step 1: Rep Clicks App Center Referral on the Client/Prospect Salesforce Contact Record](#referral)
  * [Step 2: Referral Form Submission](#refsubmit)
  * [Step 3: Referral Form Submission Confirmation Email](#refconfirm)
* [Lead Set Up Requirements](#requirements)

## Client/Prospect Submitted Leads

## Step 1: Prospect Clicks on Request Information via App Center Listing

The first step is for a prospect or client to click on the Request Information button via the unique App Center listing.

**Sample App Center Request Information Link**:

![Sample App Center Request Information Link](./app-center-lead-submission-process-request-info-link.png)

Depending upon the authentication method the app is using, the Request Information link may also appear as a button as shown below:

![Sample App Center Request Information Button](./app-center-lead-submission-process-request-info-button.png)

## Step 2: Request Information Form Submission

After clicking Request Information the prospect is redirected to the App Center Inquiry form which is dynamic and customized for each partner. The prospect must then complete the form and submit it. After submitting the form the prospect will receive a confirmation page. Thereafter, they will be redirected back to the partner's App Center listing.

**Sample App Center Request Information Form**:

![Sample App Center Request Information Form](./app-center-lead-submission-process-request-information-form.png)

**Sample Confirmation Page**:

![Sample Confirmation Page](./app-center-lead-submission-process-request-information-confirmation.png)

## Step 3: Lead Form Submission Confirmation Email

After submitting the form the prospect will also receive a confirmation email. If the lead was submitted by a SAP Concur employee the email confirmation will be slightly modified.

**Sample Confirmation Email**:

![Sample Confirmation Email](./app-center-lead-submission-process-confirmation-email.png)

## Step 4: Inquiry Notification Email

The App Center partner will receive an inquiry notification email. Partners must click on the "Accept/Reject" button to be redirected to the Accept/Reject Form for completion within 20 days of receipt.

**Sample Inquiry Notification Email**:

![Sample Inquiry Notification Email](./app-center-lead-submission-process-inquiry-notification-email.png)

**Sample Accept/Reject Form**:

![Sample Accept/Reject Form](./app-center-lead-submission-process-accept-reject-form.png)

## SAP Concur Rep-Submitted Leads

## Step 1: Rep Clicks App Center Referral on the Client/Prospect's Salesforce Contact Record

The first step is for the SAP Concur sales representative to click the App Center Referral button on the contact's Salesforce record.

**Sample Salesforce App Center Referral**:

![Sample Salesforce App Center Referral](./app-center-lead-submission-salesforce-lead-submission.png)

## Step 2: Referral Form Submission

The representative will select the correct App Center partner and complete the referral form in Salesforce. In the Comments field, they should include any relevant information or notes for the partner. For internal tracking purposes, they will also list the SAP Concur account members involved in the conversations. The representative may also select "Contact me first" if they would like to have a discussion prior to the partner following up with the client.

**Sample Salesforce Task Information Form**:

![Sample Salesforce Task Information Form](./app-center-lead-submission-salesforce-task-information-form.png)

## Step 3: Referral Form Submission Confirmation Email

Partners will receive a notification email that a lead has been submitted. Unlike customer-submitted leads, there is no Accept/Reject button on rep-submitted lead notifications. Partners should instead use the following process:

* **ACCEPT**: No action is required. *Best practice – partners should reach out to the rep to let them know that their referral was received.*
* **REJECT**: If a lead is invalid because they are already a customer, or are already engaged in an open sales cycle, partners should email **concur_PartnerClientActivation@sap.com within 20 days of receipt**. *If SAP Concur does not receive a "reject email" within 20 days, the lead will be considered accepted.*

**Sample Rep-Submitted Lead Notification Email**:

![Sample Rep-Submitted Lead Notification Email](./app-center-lead-submssion-salesforce-lead-notification-email.png)

## Lead Set Up Requirements

Leads will be sent to the partner from the SAP Concur marketing automation tool Marketo. To ensure receipt of all leads the following steps must be completed by the partner:

1. Verify the lead email address provided in the App Center Listing Form to receive leads is correct.
1. Provide their IT team the following details to whitelist the Concur IP address and place Concur on the safe sender list.
  1. Email From Address: appcenterreferral@sap.com
  1. From Sender: Concur App Center Referral
  1. Subject: AppCenter Inquiry Submission
  1. Domain: et.concur.com, concur.com


text:
/*! @file OrbitMainModule.h */

#ifndef ORBITMAINMODULE_H
#define ORBITMAINMODULE_H
#pragma once

#include "Game/MainModule.h"

namespace OrbitMain
{
	/*!
	@brief Definition of the MainModule for this assembly.
	*/
	class OrbitMainModule final : public Orbit::MainModule
	{
	public:
		/*!
		@brief Default constructor for the class.
		*/
		OrbitMainModule() = default;

		/*!
		@brief Destructor for the class.
		*/
		virtual ~OrbitMainModule() = default;

		/*!
		@brief Loads in the module's custom data.
		*/
		void load() override;

		/*!
		@brief Unloads the module's custom data.
		*/
		void unload() override;

		/*!
		@brief Initializes and returns the initial scene to be run by the engine.
		@return The initial scene used by the engine.
		*/
		std::unique_ptr<Orbit::Scene> getInitialScene() override;
	};
}

#endif //ORBITMAINMODULE_H


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <artifactId>giftwrap-example</artifactId>
  <parent>
    <groupId>com.github.andrasbeni</groupId>
    <artifactId>giftwrap-parent</artifactId>
    <version>1.0.0</version>
  </parent>
  <dependencies>
    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>giftwrap-compiler</artifactId>
      <version>${project.version}</version>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>giftwrap-runtime</artifactId>
      <version>${project.version}</version>
    </dependency>
  </dependencies>
</project>


text:
'use strict'

const assert = require('assert');

/* Region tag in top-level 'describe' */
describe('region_tag', () => {
	describe('bar baz', () => {
		it('should pass', () => {
			assert.ok(true);
		});

		it('should fail', () => {
			assert.fail('top-level region tag');
		});
	});
});


text:
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program.  If not, see http://www.gnu.org/licenses/.
//

#ifndef SRC_VEINS_MODULES_APPLICATION_PVEINS_PROVIDENCIA_EXTTRACISCENARIOMANAGERLAUNCHD_H_
#define SRC_VEINS_MODULES_APPLICATION_PVEINS_PROVIDENCIA_EXTTRACISCENARIOMANAGERLAUNCHD_H_

#include "veins/modules/mobility/traci/TraCIScenarioManagerLaunchd.h"

class ExtTraCIScenarioManagerLaunchd: public Veins::TraCIScenarioManagerLaunchd {
public:
    ExtTraCIScenarioManagerLaunchd(): shut_down(false) {}
    virtual ~ExtTraCIScenarioManagerLaunchd(){}

    virtual void initialize(int stage);
    virtual void finish();

    bool shuttingDown();

protected:
    virtual void init_traci();

private:
    bool shut_down;
};

#endif /* SRC_VEINS_MODULES_APPLICATION_PVEINS_PROVIDENCIA_EXTTRACISCENARIOMANAGERLAUNCHD_H_ */


text:
@interface MusicViewController : UIViewController<UITableViewDataSource, UITableViewDelegate, AVAudioPlayerDelegate>
{
    AppDelegate *appDelegate;
//    AVAudioPlayer *audioPlayer;
    NSMutableArray *musicArray;
    BOOL isPlay;
    BOOL musicTableViewHidden;
    float tempVolume;
    Music *currentMusic;
    NSMutableArray *timeArray;
    NSMutableDictionary *LRCDictionary;
    NSUInteger lrcLineNumber;
    IntroControll *introControll;
//    NSUInteger musicArrayNumber;
}
@property (nonatomic, strong) NSMutableArray *musicArray;

- (IBAction)aboveMusic:(id)sender;
- (IBAction)nextMusic:(id)sender;

- (IBAction)play:(id)sender;
@property (strong, nonatomic) IBOutlet UIButton *playBtn;
@property (strong, nonatomic) IBOutlet UIImageView *playImage;

@property (strong, nonatomic) IBOutlet UISlider *progressSlider;
- (IBAction)progressChange:(id)sender;

- (IBAction)circle:(id)sender;
@property (strong, nonatomic) IBOutlet UIButton *circleBtn;

@property (strong, nonatomic) IBOutlet UIButton *rightBtn;

@property (strong, nonatomic) IBOutlet UILabel *currentTimeLabel;
@property (strong, nonatomic) IBOutlet UILabel *totalTimeLabel;

@property (strong, nonatomic) IBOutlet UITableView *musicTableView;

@property (strong, nonatomic) IBOutlet UITableView *lrcTableView;
//显示歌曲目录

- (IBAction)rightView:(id)sender;

@property (strong, nonatomic) IBOutlet UIView *imageview;

- (IBAction)openLeftMenu:(id)sender;

- (IBAction)openSettings:(id)sender;

- (void)playWithIndex:(int) index;

- (void)playTable:(NSUInteger)tableNumber;
@end


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

namespace zsm
{
    public class SnapshotPolicy
    {
        public SnapshotPolicy()
        {
            this.Format = "{0}@{1}{2}";
            this.Prefix = "auto-";
            this.DateFormat = "{0:yyyy.MM.dd-HH.mm.ss}";
        }

        public string Format { get; set; }

        public string Prefix { get; set; }

        public string DateFormat { get; set; }

        public DatasetPolicy[] Datasets { get; set; }

        public Schedule[] Schedules { get; set; }

        public string GetSnapshotName(Snapshot snap)
        {
            return string.Format(this.Format, snap.Dataset, this.Prefix, string.Format(this.DateFormat, snap.Creation));
        }

        /// <summary>
        /// Calculates the next snapshot action based on the configured schedules and datasets in the current policy.
        /// </summary>
        /// <param name="reference"></param>
        /// <returns></returns>
        public SnapAction GetNextAction(DateTime reference)
        {

            var run = this.Schedules
                .Select(e => new SnapAction(e.GetNextOccurrence(reference), e.RetentionPeriod))
                .GroupBy(k => k.Creation)
                .Select(s => new SnapAction(s.Key, s.Max(g => g.Expiration)))
                .OrderBy(e => e.Creation)
                .FirstOrDefault();

            if (run != null)
            {
                run.Datasets = this.Datasets;
                return run;
            }

            throw new NotImplementedException();
        }
    }
}


text:
using Mntone.SvgForXaml.Interfaces;
using System;

namespace Mntone.SvgForXaml.Primitives
{
	public sealed class SvgIri : ICssValue
	{
		public SvgIri(string iri)
		{
			if (iri.StartsWith("url(") && iri[iri.Length - 1] == ')')
			{
				this.Uri = iri.Substring(4, iri.Length - 5);
				return;
			}
			throw new ArgumentException(nameof(iri));
		}

		public string Uri { get; }
	}
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import dao.BillDAO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import model.Cart;
import model.Users;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 *
 * @author NguyenIT
 */
public class CheckOutServletTest {

    public CheckOutServletTest() {
    }

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

     @Before
    public void setUp() {
        System.out.println("Bat dau test case moi _____________________");
    }
    //delete from <table> where id not in
    //(select id from <table> order by <datecol> desc limit 20)
    //DELETE FROM user WHERE user_id NOT IN (SELECT user_id FROM (SELECT user_id FROM user ORDER BY user_id DESC LIMIT 0) x)
    @After
    public void tearDown() {
        System.out.println("Ket thuc test case    _____________________");
    }

    @Test
    public void testInsertBill() {
        System.out.println("Thanh toan -> them ");
        HttpServletRequest request = mock(HttpServletRequest.class);
        HttpSession session = mock(HttpSession.class);
        when(request.getSession()).thenReturn(session);
        request.setAttribute("bill_id", 1000);
        request.setAttribute("payment", "s");
        request.setAttribute("address", "s");
        request.setAttribute("adress1", "s");
        request.setAttribute("name", "s");
        request.setAttribute("provincial", "s");
        request.setAttribute("email", "s@s.con");
        request.setAttribute("message", "s");

        Cart cart = new Cart();
        cart.setTotalCart(1000);
        Users users = new Users();
        users.setUserID(1000);
        CheckOutServlet instance = new CheckOutServlet();
        boolean result = instance.InsertBill(request, cart, users);
        assertEquals(true,result);
        /*result = instance.InsertBill(request, null);
        assertEquals(expResult, result);*/
        // TODO review the generated test code and remove the default call to fail.
        BillDAO billDao = new BillDAO();
        billDao.deleteBillUser(1000);

        System.out.println("Thanh toan -> them -> thanh cong");
    }

}


text:
import threading
import unittest
from Queue import Queue
import random

from coapserver import CoAPServer
from coapthon import defines
from coapthon.client.helperclient import HelperClient
from coapthon.messages.option import Option
from coapthon.messages.request import Request
from coapthon.messages.response import Response

class Tests(unittest.TestCase):

    def setUp(self):
        self.server_address = ("127.0.0.1", 5683)
        self.current_mid = random.randint(1, 1000)
        self.server_mid = random.randint(1000, 2000)
        self.server = CoAPServer("127.0.0.1", 5683)
        self.server_thread = threading.Thread(target=self.server.listen, args=(10,))
        self.server_thread.start()
        self.queue = Queue()

    def tearDown(self):
        self.server.close()
        self.server_thread.join(timeout=25)
        self.server = None

    def _test_with_client(self, message_list):  # pragma: no cover
        client = HelperClient(self.server_address)
        for message, expected in message_list:
            if message is not None:
                received_message = client.send_request(message)
            if expected is not None:

                if expected.type is not None:
                    self.assertEqual(received_message.type, expected.type)
                if expected.mid is not None:
                    self.assertEqual(received_message.mid, expected.mid)
                self.assertEqual(received_message.code, expected.code)
                if expected.source is not None:
                    self.assertEqual(received_message.source, self.server_address)
                if expected.token is not None:
                    self.assertEqual(received_message.token, expected.token)
                if expected.payload is not None:
                    self.assertEqual(received_message.payload, expected.payload)
                if expected.options:
                    self.assertEqual(len(received_message.options), len(expected.options))
                    for o in expected.options:
                        assert isinstance(o, Option)
                        option_value = getattr(expected, o.name.lower().replace("-", "_"))
                        option_value_rec = getattr(received_message, o.name.lower().replace("-", "_"))
                        self.assertEqual(option_value, option_value_rec)
        client.stop()

    def client_callback(self, response):
        print "Callback"
        self.queue.put(response)

    def test_advanced(self):
        print "TEST_ADVANCED"
        path = "/advanced"
        req = Request()
        req.code = defines.Codes.GET.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.CONTENT.number
        expected.max_age = 20
        expected.token = None

        exchange1 = (req, expected)

        self.current_mid += 1

        req = Request()
        req.code = defines.Codes.POST.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.CREATED.number
        expected.payload = "Response changed through POST"
        expected.token = None

        exchange2 = (req, expected)

        self.current_mid += 1

        req = Request()
        req.code = defines.Codes.PUT.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.CHANGED.number
        expected.payload = "Response changed through PUT"
        expected.token = None

        exchange3 = (req, expected)

        self.current_mid += 1

        req = Request()
        req.code = defines.Codes.DELETE.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address

        expected = Response()
        expected.type = defines.Types["ACK"]
        expected._mid = self.current_mid
        expected.code = defines.Codes.DELETED.number
        expected.payload = "Response deleted"
        expected.token = None

        exchange4 = (req, expected)

        self.current_mid += 1
        self._test_with_client([exchange1, exchange2, exchange3, exchange4])

    def test_advanced_separate(self):
        print "TEST_ADVANCED_SEPARATE"
        path = "/advancedSeparate"
        req = Request()
        req.code = defines.Codes.GET.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address

        expected = Response()
        expected.type = defines.Types["CON"]
        expected._mid = None
        expected.code = defines.Codes.CONTENT.number
        expected.max_age = 20
        expected.token = None

        exchange1 = (req, expected)

        self.current_mid += 1

        req = Request()
        req.code = defines.Codes.POST.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address

        expected = Response()
        expected.type = defines.Types["CON"]
        expected._mid = None
        expected.code = defines.Codes.CREATED.number
        expected.payload = "Response changed through POST"
        expected.token = None

        exchange2 = (req, expected)

        self.current_mid += 1

        req = Request()
        req.code = defines.Codes.PUT.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address

        expected = Response()
        expected.type = defines.Types["CON"]
        expected._mid = None
        expected.code = defines.Codes.CHANGED.number
        expected.payload = "Response changed through PUT"
        expected.token = None

        exchange3 = (req, expected)

        self.current_mid += 1

        req = Request()
        req.code = defines.Codes.DELETE.number
        req.uri_path = path
        req.type = defines.Types["CON"]
        req._mid = self.current_mid
        req.destination = self.server_address

        expected = Response()
        expected.type = defines.Types["CON"]
        expected._mid = None
        expected.code = defines.Codes.DELETED.number
        expected.payload = "Response deleted"
        expected.token = None

        exchange4 = (req, expected)

        self.current_mid += 1
        self._test_with_client([exchange1, exchange2, exchange3, exchange4])

if __name__ == '__main__':
    unittest.main()


text:
from amiens.core import asserts
from amiens.core import util
from amiens.core.util import Log

import sqlite3

class ArliDb():

    def __init__(self, l_db):
        #UNTESTED
        goal='asked to connect to db at {}, '.format(l_db)
        util.Log.debug('opening database at ' + l_db)
        asserts.exists(goal, l_db)
        self.conn = sqlite3.connect(l_db)

    def one_off_update(self, colvalpairs, query_filter, data):
        ArliDb.quick_update(self.conn.cursor(),
                              colvalpairs, query_filter, data)
        self.conn.commit()

    def one_off_select(self, cols, query_filter='',
                       data=[], return_raw=False):
        return ArliDb.quick_select(self.conn.cursor(),
                                   cols, query_filter, data, return_raw)

    @staticmethod
    def quick_update(cursor, colvalpairs, query_filter, data):
        cols, vals = zip(*colvalpairs)
        vals = list(vals)
        vals.extend(data)

        q=''.join(['UPDATE items SET ',
                   '=?, '.join(cols),
                   '=? ',
#        postgres
#        q=''.join(['UPDATE items SET (',
#                   '=?, '.join(cols),
#                   ') = (',
#                   ''.join(['?' for c in cols]),
#                   ') ',
                   query_filter])
        Log.debug('U_sql:'+q)
        Log.debug('U_data:'+repr(vals))
        cursor.execute(q, vals)

    @staticmethod
    def quick_select(cursor,
                     cols, query_filter='', data=[],
                     return_raw=False):
        c = cursor
        sqlstr=''.join(['SELECT ',
                           ', '.join(cols),
                           ' FROM items ',
                           query_filter])
        Log.debug('Q_sql: ' + sqlstr)
        Log.debug('Q_data: ' + repr(data))
        c.execute(sqlstr, data)
        if return_raw:
            return c.fetchall()
        tmpresults= c.fetchall()
        results = [ ]
        for x in tmpresults:
            row={}
            for i in range(0, len(cols)):
                row[cols[i]] = x[i]
            results.append(row)
        return results

    @classmethod
    def create_new(cls, l_db):
        #UNTESTED
        goal='asked to create db at {}, '.format(l_db)
        asserts.dne(goal, l_db)

        conn = sqlite3.connect(l_db)
        c = conn.cursor()
        c.execute('''CREATE TABLE items
        (tmpId INTEGER PRIMARY KEY AUTOINCREMENT, ident TEXT UNIQUE, mediaType INTEGER NOT NULL DEFAULT 0, existsStatus INTEGER NOT NULL DEFAULT 0, totalAudioLength INTEGER, totalAudioSize INTEGER, checkedOnUnixDate INTEGER, hasMetadata INTEGER NOT NULL DEFAULT 0, metadata TEXT, blockDownload INTEGER NOT NULL DEFAULT 0, rating INTEGER NOT NULL DEFAULT 0, comment TEXT)''')
        conn.commit()
        conn.close()
        return cls(l_db)


text:
var _gaq = _gaq || [];

(function () {

///////////////////////////////////////////////////////////////////////////////
// Setup
///////////////////////////////////////////////////////////////////////////////
var version = "1.1.0";

Data.def("charge-interval", 10);
Data.def("charge-size", 1);

Data.def("target-block", []);
Data.def("target-allow", []);

Data.def("balance", 0);

_gaq.push(
	["_setAccount", "##GAID##"],
	["_setSessionCookieTimeout", 0],
	["_setCustomVar", 1, "Version", version, 1],
	["_setCustomVar", 2, "ChargeInterval", Data.get("charge-interval").toString(), 1],
	["_setCustomVar", 3, "ChargeSize", Data.get("charge-size").toString(), 1],
	["_trackPageview", "/"]
);

!Data.has("version") && window.open("options.html?firstrun");
Data.set("version", version);

document.body.appendChild(function () {
	var el = document.createElement("script");
	el.src = "https://ssl.google-analytics.com/ga.js";
	return el;
}());

///////////////////////////////////////////////////////////////////////////////
// State
///////////////////////////////////////////////////////////////////////////////
var state = window.state = {
	get balance () {
		return Data.get("balance");
	},
	set balance (v) {
		Data.set("balance", v)
	},
	meter: 0,
	add: {
		id: -1,
		fn: function () {
			var size = Data.get("charge-size");
			var balance = state.balance + size;
			var max = Math.floor((size * (60 / Data.get("charge-interval"))) * 6);

			state.balance = Math.min(balance, max);
			state.sync();
		},
		start: function () {
			clearInterval(state.add.id);

			state.add.id = setInterval(state.add.fn, 1000 * 60 * Data.get("charge-interval"));
		}
	},
	use: {
		id: null,
		seconds: null,
		fn: function () {
			if (--state.meter === 0) {
				clearInterval(state.use.id);
				state.use.id = null;

				checkall();
			}

			state.use.display();
		},
		start: function () {
			if (!state.use.id) {
				state.use.id = setInterval(state.use.fn, 1000 * 60);
			}

			state.use.seconds = null;

			state.use.display();
		},
		display: function () {
			var text = state.meter.toString();

			if (text === "0") {
				text = "";
			} else if (text === "1") {
				var seconds = state.use.seconds || 60;

				text = "0:" + (seconds < 10 ? 0 : "") + seconds;

				if (state.use.seconds = --seconds) {
					setTimeout(state.use.display, 1000);
				}
			}

			chrome.browserAction.setBadgeBackgroundColor({ color: state.meter > 1 ? [0, 0, 255, 255] : [255, 0, 0, 255] });
			chrome.browserAction.setBadgeText({ text: text });

			state.sync();
		}
	},
	sync: function () {
		chrome.extension.getViews().forEach(function (tab) {
			typeof tab.update === "function" && tab.update();
		});
	}
};

state.add.start();

///////////////////////////////////////////////////////////////////////////////
// Monitoring
///////////////////////////////////////////////////////////////////////////////
var check = function (url, tID) {
	if (state.meter) {
		return;
	}

	var block = Data.get("target-block");
	var allow = Data.get("target-allow");
	var uri = new Uri(url);
	var match;

	var apply = function (rule) {
		var rule = new Uri(rule);
		var uhost = uri.host();
		var rhost = rule.host();
		var upath = uri.path();
		var rpath = rule.path();
		var index = uhost.indexOf(rhost);

		return index !== -1 && index === uhost.length - rhost.length && (index > 0 ? uhost[index - 1] === "." : true)
			&& upath.indexOf(rpath) === 0 && (upath.length > rpath.length ? (rpath.substr(-1) === "/" || upath[rpath.length] === "/") : true);
	};

	var matches = block.some(function (rule) {
		match = rule;

		return apply(rule) && !allow.some(apply);
	});

	matches && chrome.tabs.update(tID, {
		url: "popup.html?" + encodeURIComponent(JSON.stringify({ url: url, rule: match }))
	});
};

var checkall = function () {
	chrome.tabs.query({}, function (tabs) {
		tabs.forEach(function (tab) {
			check(tab.url, tab.id);
		});
	});
};

chrome.tabs.onCreated.addListener(function (tab) {
	tab.url && check(tab.url, tab.id);
});

chrome.tabs.onUpdated.addListener(function (tID, changed, tab) {
	changed.url && check(changed.url, tID);
});

})();


text:
layout: page
published: true
permalink: recipes/indian/bobby-flay-basmati-rice
title: "Bobby Flay's Basmati Rice"
---

[Source](http://www.foodnetwork.com/recipes/bobby-flay/basmati-rice-pilaf-with-peas-recipe.html)

### Ingredients

- 1.5 cups basmati rice
- 1.5 tablespoons vegetable oil
- 1.25 teaspoons black mustard seeds
- 0.5 cup finely diced yellow onion
- 6 cardamom pods
- 4 whole cloves
- 1 (3-inch) cinnamon stick
- 2.25 cups simmering water
- 1.5 teaspoons kosher salt
- 0.25 teaspoon freshly ground black pepper
- 2 teaspoons fresh lime juice
- 0.75 cup frozen green peas

###Mis en place
- Rince rice in a mesh strainer with cold water several times. Set aside to drain
- Dice the onion
- Place mustard seed in a dish
- Measure out green peas to a bowl
- Add dry ingredients to bowl (cardamom, cloves, cinnamon, salt, pepper)
- Add wet ingredients to another bowl (simmering water, lime juice)

###Begin cooking
- Heat the vegetable oil in a large saucepan over medium-high heat until it begins to shimmer
- Add the mustard seeds and cook until they just begin to pop, about 20 seconds.
- Add the onion and saute until lightly browned, about 3 minutes.
- Add the cardamom, cloves, cinnamon, rice, the simmering water, salt, pepper and lime juice, and bring to a boil.
- Reduce the heat to medium, and cook until liquid is nearly absorbed, about 10 minutes
- Fold in the peas, then over, reduce heat to low, and cook 8 to 10 minutes longer.
- Remove from the heat and let stand for 5 minutes, uncovered.
- Remove and discard the cardamom, cloves, and cinnamon and fluff with a fork.
- Transfer the pilaf to a serving dish and serve.


text:
from datetime import datetime
from werkzeug.security import generate_password_hash, check_password_hash
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from flask import current_app
from flask.ext.login import UserMixin, AnonymousUserMixin
from . import db, login_manager

class Article(db.Model):
    __tablename__ = 'articles'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.Text)
    url = db.Column(db.Text)
    date_collected = db.Column(db.DateTime(), default=datetime.utcnow)
    tweeted = db.Column(db.Boolean, default=False)
    date_tweeted = db.Column(db.DateTime())
    feed_id = db.Column(db.Integer, db.ForeignKey('feeds.id'))

class Feed(db.Model):
    __tablename__ = 'feeds'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(256))
    url = db.Column(db.String(512))
    hashtag = db.Column(db.String(128))
    # tweets / day
    frequency = db.Column(db.Integer, default=2)
    collect_actif = db.Column(db.Boolean, default=True)
    Tweet_actif = db.Column(db.Boolean, default=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    articles = db.relationship('Article', backref='feed', lazy='dynamic')

class Permission:
    FOLLOW = 0x01
    COMMENT = 0x02
    WRITE_ARTICLES = 0x04
    MODERATE_COMMENTS = 0x08
    ADMINISTER = 0x80

class Role(db.Model):
    __tablename__ = 'roles'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), unique=True)
    default = db.Column(db.Boolean, default=False, index=True)
    permissions = db.Column(db.Integer)
    users = db.relationship('User', backref='role', lazy='dynamic')

    @staticmethod
    def insert_roles():
        roles = {
            'User': (Permission.FOLLOW |
                     Permission.COMMENT |
                     Permission.WRITE_ARTICLES, True),
            'Moderator': (Permission.FOLLOW |
                          Permission.COMMENT |
                          Permission.WRITE_ARTICLES |
                          Permission.MODERATE_COMMENTS, False),
            'Administrator': (0xff, False)
        }
        for r in roles:
            role = Role.query.filter_by(name=r).first()
            if role is None:
                role = Role(name=r)
            role.permissions = roles[r][0]
            role.default = roles[r][1]
            db.session.add(role)
        db.session.commit()

    def __repr__(self):
        return '<Role %r>' % self.name

class User(UserMixin, db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(64), unique=True, index=True)
    username = db.Column(db.String(64), unique=True, index=True)
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))
    feeds = db.relationship('Feed', backref='user', lazy='dynamic')
    password_hash = db.Column(db.String(128))
    confirmed = db.Column(db.Boolean, default=False)
    name = db.Column(db.String(64))
    telephone = db.Column(db.String(15))
    location = db.Column(db.String(64))
    codepostal = db.Column(db.String(5))
    about_me = db.Column(db.Text())
    member_since = db.Column(db.DateTime(), default=datetime.utcnow)
    last_seen = db.Column(db.DateTime(), default=datetime.utcnow)

    def __init__(self, **kwargs):
        super(User, self).__init__(**kwargs)
        if self.role is None:
            if self.email == current_app.config['FLASKY_ADMIN']:
                self.role = Role.query.filter_by(permissions=0xff).first()
            if self.role is None:
                self.role = Role.query.filter_by(default=True).first()

    @property
    def password(self):
        raise AttributeError('password is not a readable attribute')

    @password.setter
    def password(self, password):
        self.password_hash = generate_password_hash(password)

    def verify_password(self, password):
        return check_password_hash(self.password_hash, password)

    def generate_confirmation_token(self, expiration=3600):
        s = Serializer(current_app.config['SECRET_KEY'], expiration)
        return s.dumps({'confirm': self.id})

    def confirm(self, token):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except:
            return False
        if data.get('confirm') != self.id:
            return False
        self.confirmed = True
        db.session.add(self)
        return True

    def generate_reset_token(self, expiration=3600):
        s = Serializer(current_app.config['SECRET_KEY'], expiration)
        return s.dumps({'reset': self.id})

    def reset_password(self, token, new_password):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except:
            return False
        if data.get('reset') != self.id:
            return False
        self.password = new_password
        db.session.add(self)
        return True

    def generate_email_change_token(self, new_email, expiration=3600):
        s = Serializer(current_app.config['SECRET_KEY'], expiration)
        return s.dumps({'change_email': self.id, 'new_email': new_email})

    def change_email(self, token):
        s = Serializer(current_app.config['SECRET_KEY'])
        try:
            data = s.loads(token)
        except:
            return False
        if data.get('change_email') != self.id:
            return False
        new_email = data.get('new_email')
        if new_email is None:
            return False
        if self.query.filter_by(email=new_email).first() is not None:
            return False
        self.email = new_email
        db.session.add(self)
        return True

    def can(self, permissions):
        return self.role is not None and \
            (self.role.permissions & permissions) == permissions

    def is_administrator(self):
        return self.can(Permission.ADMINISTER)

    def ping(self):
        self.last_seen = datetime.utcnow()
        db.session.add(self)

    def __repr__(self):
        return '<User %r>' % self.username

class AnonymousUser(AnonymousUserMixin):
    def can(self, permissions):
        return False

    def is_administrator(self):
        return False

login_manager.anonymous_user = AnonymousUser

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))


text:
package org.renjin.primitives.io.connections;

import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.renjin.eval.EvalException;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileConnection extends AbstractConnection {

  private InputStream in;
  private OutputStream out;

  private FileObject file;
  private OpenSpec openSpec = null;

  public FileConnection(FileObject file) throws IOException {
    this.file = file;
  }

  @Override
  public void open(OpenSpec spec) throws IOException {
    this.openSpec = spec;
    if(spec.forReading() && spec.forWriting()) {
      throw new EvalException("Read/write file connections not yet implemented");
    }
    if(spec.forReading()) {
      if(spec.isBinary()) {
        assureOpenForInput();
      } else {
        getReader();
      }
    } else if(spec.forWriting()) {
      if(spec.isBinary()) {
        assureOpenForOutput();
      } else {
        getPrintWriter();
      }
    }
  }

  private final InputStream assureOpenForInput() throws IOException {
    if(out != null) {
      throw new EvalException("connection is already opened for output, cannot open for input");
    }
    if(in == null) {
      this.in = doOpenForInput();
    }
    return this.in;
  }

  protected InputStream doOpenForInput() throws FileSystemException, IOException {
    return file.getContent().getInputStream();
  }

  private OutputStream assureOpenForOutput() throws IOException {
    if(in != null) {
      throw new EvalException("connection is already opened for input, cannot open for output");
    }
    if(out == null) {
      this.out = doOpenForOutput();
    }
    return this.out;
  }

  protected OutputStream doOpenForOutput() throws FileSystemException, IOException {
    return file.getContent().getOutputStream();
  }

  @Override
  public final InputStream getInputStream() throws IOException {
    return assureOpenForInput();
  }

  @Override
  public final OutputStream getOutputStream() throws IOException {
    return assureOpenForOutput();
  }

  @Override
  protected void closeInputIfOpen() throws IOException {
    if(in != null) {
      in.close();
    }
  }

  @Override
  protected void closeOutputIfOpen() throws IOException {
    if(out != null) {
      out.close();
    }
  }

  @Override
  public boolean isOpen() {
    return in!=null || out!=null;
  }

  @Override
  public String getClassName() {
    return "file";
  }

  @Override
  public String getDescription() {
    return file.getName().getPath();
  }

  @Override
  public Type getType() {
    if(openSpec == null) {
      return Type.TEXT;
    } else {
      return openSpec.getType();
    }
  }

  @Override
  public String getMode() {
    if(openSpec == null) {
      return "r";
    } else {
      return openSpec.toString();
    }
  }

  @Override
  public boolean canRead() {
    return !isOpen() || openSpec == null || openSpec.forReading();
  }

  @Override
  public boolean canWrite() {
    return !isOpen() || openSpec == null || openSpec.forWriting();
  }

}


text:
namespace content {

typedef ContentBrowserTest WebKitBrowserTest;

const char kAsyncScriptThatAbortsOnEndPage[] =
    "files/webkit/async_script_abort_on_end.html";

// This is a browser test because it is hard to reproduce reliably in a
// layout test without races. http://crbug.com/75604 deals with a request
// for an async script which gets data in the response and immediately
// after aborts. This test creates that condition, and it is passed
// if chrome does not crash.

IN_PROC_BROWSER_TEST_F(WebKitBrowserTest, AbortOnEnd) {
  ASSERT_TRUE(test_server()->Start());
  URLRequestAbortOnEndJob::AddUrlHandler();
  GURL url = test_server()->GetURL(kAsyncScriptThatAbortsOnEndPage);

  NavigateToURL(shell(), url);

  // If you are seeing this test fail, please strongly investigate the
  // possibility that http://crbug.com/75604 and
  // https://bugs.webkit.org/show_bug.cgi?id=71122 have reverted before
  // marking this as flakey.
  EXPECT_FALSE(shell()->web_contents()->IsCrashed());
}

// This is a browser test because the DumpRenderTree framework holds
// onto a Document* reference that blocks this reproduction from
// destroying the Document, so it is not a use after free unless
// you don't have DumpRenderTree loaded.

// TODO(gavinp): remove this browser_test if we can get good LayoutTest
// coverage of the same issue.
const char kXsltBadImportPage[] =
    "files/webkit/xslt-bad-import.html";
IN_PROC_BROWSER_TEST_F(WebKitBrowserTest, XsltBadImport) {
  ASSERT_TRUE(test_server()->Start());
  URLRequestAbortOnEndJob::AddUrlHandler();
  GURL url = test_server()->GetURL(kXsltBadImportPage);

  NavigateToURL(shell(), url);

  EXPECT_FALSE(shell()->web_contents()->IsCrashed());
}

// This is a browser test because DumpRenderTree has a PrerendererClient
// implementation, and the purpose of this test is to ensure that content_shell
// does not crash when prerender elements are encountered with no Prererering
// implementation supplied to WebKit.

// TODO(gavinp,jochen): This browser_test depends on there not being a
// prerendering client and prerendering platform provided by the test_shell.
// But both will exist when we use content_shell to run layout tests. We must
// then add a mechanism to start content_shell without these, or else this
// test is not very interesting.
const char kPrerenderNoCrashPage[] =
    "files/prerender/prerender-no-crash.html";
IN_PROC_BROWSER_TEST_F(WebKitBrowserTest, PrerenderNoCrash) {
  ASSERT_TRUE(test_server()->Start());
  GURL url = test_server()->GetURL(kPrerenderNoCrashPage);

  NavigateToURL(shell(), url);

  EXPECT_FALSE(shell()->web_contents()->IsCrashed());
}

}  // namespace content


text:
from random import randint

glyph = CurrentGlyph()

for contour in glyph:
    for bPoint in contour.bPoints:
        print "anchor:", bPoint.anchor
        print "bcp in:",  bPoint.bcpIn
        print "bcp out:",  bPoint.bcpOut
        print
        x, y = bPoint.anchor
        bcpIn = bPoint.bcpIn
        bcpOut = bPoint.bcpOut

        bPoint.anchor = (x + randint(-10, 10), y)
        bPoint.bcpIn = bcpIn
        bPoint.bcpOut = bcpOut

glyph.update()


text:
/*global define:false*/
define(['text!views/forbidden/forbiddenView.html', 'resources', 'constants'],
    function (template, resources, constants) {
        'use strict';

        return {
            name : 'forbiddenView',
            modelData : {},
            browserTitle : 'Forbidden',
            appendTo : '#stage',
            wrapper : false,
            template : template,
            events : {},
            listeners : [],
            breadcrumbs : {
                icon: 'fa-moon-o',
                crumbs: [
                    {
                        text : constants.home,
                        href : constants.internalRoutes.content
                    },
                    {
                        text : resources.forbidden,
                        href : constants.internalRoutes.forbidden
                    }
                ]
            }
        };
    });


text:
var env = require('../helpers/env');
var paths = require('../helpers/paths');
var resolveCwd = require('../helpers/resolveCwd');
var path = require('path');

module.exports = function scripts (webpackConfig) {
  var browserPath = path.resolve(__dirname, '../../browser');
  var basenjiToolsPath = resolveCwd('node_modules/basenji-tools');

  // babel + preprocess
  webpackConfig.module.loaders.push({
    test: /\.js$/,
    loader: 'happypack/loader?id=scripts',
    include: [
      paths.srcPath,
      paths.testPath,
      browserPath,
      basenjiToolsPath
    ]
  })

  // json
  webpackConfig.module.loaders.push({
    test: /\.json$/,
    loader: 'json'
  })

  return webpackConfig;
}


text:
@implementation PlaceMark

@synthesize title;
@synthesize subTitle;
@synthesize coordinate;

-(id)initWithCoordinates:(CLLocationCoordinate2D)coords
{
    self = [super init];
    if (self)
    {
        coordinate = coords;
    }
    return self;
}

-(NSString *)title
{
    return title;
}

-(NSString *)subtitle
{
    return subTitle;
}

-(void)dealloc
{
    [title release];
    [subTitle release];
    [super dealloc];
}

@end