text:
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 317928 $ -->
<refentry xmlns="http://docbook.org/ns/docbook" xml:id="function.is-file">
 <refnamediv>
  <refname>is_file</refname>
  <refpurpose>Tells whether the filename is a regular file</refpurpose>
 </refnamediv>

 <refsect1 role="description">
  &reftitle.description;
  <methodsynopsis>
   <type>bool</type><methodname>is_file</methodname>
   <methodparam><type>string</type><parameter>filename</parameter></methodparam>
  </methodsynopsis>
  <para>
   Tells whether the given file is a regular file.
  </para>
 </refsect1>

 <refsect1 role="parameters">
  &reftitle.parameters;
  <para>
   <variablelist>
    <varlistentry>
     <term><parameter>filename</parameter></term>
     <listitem>
      <para>
       Path to the file.
      </para>
     </listitem>
    </varlistentry>
   </variablelist>
  </para>
 </refsect1>

 <refsect1 role="returnvalues">
  &reftitle.returnvalues;
  <para>
   Returns &true; if the filename exists and is a regular file, &false;
   otherwise.
  </para>
  &fs.file.32bit;
 </refsect1>

 <refsect1 role="examples">
  &reftitle.examples;
  <para>
   <example>
    <title><function>is_file</function> example</title>
    <programlisting role="php">
<![CDATA[
<?php
var_dump(is_file('a_file.txt')) . "\n";
var_dump(is_file('/usr/bin/')) . "\n";
?>
]]>
    </programlisting>
    &example.outputs;
    <screen>
<![CDATA[
bool(true)
bool(false)
]]>
    </screen>
   </example>
  </para>
 </refsect1>

 <refsect1 role="errors">
  &reftitle.errors;
  &fs.emits.warning.on.failure;
 </refsect1>

 <refsect1 role="notes">
  &reftitle.notes;
  &note.clearstatcache;
  &tip.fopen-wrapper.stat;
 </refsect1>

 <refsect1 role="seealso">
  &reftitle.seealso;
  <para>
   <simplelist>
    <member><function>is_dir</function></member>
    <member><function>is_link</function></member>
   </simplelist>
  </para>
 </refsect1>

</refentry>

<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->


text:
require 'spec_helper'
require 'worker'

describe Worker do
  subject { described_class.run! }

  let(:predata) { ['elevator0', 'elevator1', 'elevator2'] }
  let(:bart_data) { ['elevator2', 'elevator3'] }
  let(:muni_data) { ['elevator0', 'elevator4'] }

  before :each do
    elevators = predata.map do |e|
      Models::Elevator.first_or_create(:name => e)
    end

    elevators.map do |e|
      Models::Outage.create(:started_at => DateTime.now - rand(1..3),
                            :elevator => e)
    end

    expect(Models::Outage.all_open.count).to eql predata.size

    allow(BartApi).to receive(:get_data)
    allow(BartApi).to receive(:parse_data).and_return(bart_data)
    allow(MuniApi).to receive(:get_data).and_return(muni_data)
  end

  # We end with two ended outages (elevator0, elevator2), one that remains open
  # (elevator2) and two new outages (elevator3, elevator4)
  it 'should call BartApi and MuniApi, end two of the outages, and open another 2' do
    subject

    # Not sure why the #to_a is required here
    expect(Models::Outage.all_open.to_a.map(&:elevator).map(&:name)).to match_array ( bart_data + muni_data )
    expect(Models::Outage.all_open.size).to eql ( bart_data + muni_data ).size
    expect(Models::Outage.all_closed.size).to be 1
    expect(Models::Outage.count).to be 5
  end

  # elevator1, elevator3, and elevator 4; elevator0 and elevator2 do not change state
  it 'should call Notifier.send_elevator_notifications with four elevators' do
    expect(Notifier).to receive(:send_elevator_notifications!) do |elevators|
      expect(elevators.map(&:name)).to match_array(['elevator1', 'elevator3', 'elevator4'])
    end

    subject
  end

  context 'if one of the received elevators is an alias' do
    before :each do
      orig_elevator = Models::Elevator.first_or_create(:name => 'orig_elevator')
      # We create an alias elevator; this is the one that is in our input data,
      # not the orig_elevator
      Models::Elevator.first_or_create(:name => 'alias elevator', :alias_id => orig_elevator.id)

      allow(BartApi).to receive(:get_data)
      allow(BartApi).to receive(:parse_data).and_return(bart_data)
      allow(MuniApi).to receive(:get_data).and_return(muni_data)
    end

    let(:bart_data) { ['alias elevator'] }
    let(:muni_data) { [] }
    let(:predata) { [] }

    it 'should look up the original elevator' do
      # It'll notify for the original elevator, not the alias
      expect(Notifier).to receive(:send_elevator_notifications!) do |elevators|
        expect(elevators.map(&:name)).to match_array('orig_elevator')
      end

      subject

      expect(Models::Outage.all_open.to_a.map(&:elevator).map(&:name)).to match_array('orig_elevator')
    end
  end

  context 'if there are no out elevators' do
    let(:bart_data) { [] }
    let(:muni_data) { [] }

    it "should not notify (or change DB state) the 1st or 3rd time 'all elevators are in service', but should the 2nd time" do
      expect(Notifier).to receive(:send_elevator_notifications!).once do |elevators|
        expect(elevators).not_to be_empty
      end

      # First run
      described_class.run!
      expect(Models::Outage.all_open).not_to be_empty

      # Second run
      described_class.run!
      expect(Models::Outage.all_open).to be_empty

      # Third run
      described_class.run!
      expect(Models::Outage.all_open).to be_empty
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
namespace MassTransit.Events
{
    using System;
    using System.Linq;

    [Serializable]
    public class ReceiveFaultEvent :
        ReceiveFault
    {
        public ReceiveFaultEvent()
        {
        }

        public ReceiveFaultEvent(HostInfo host, Exception exception, string contentType, Guid? faultedMessageId, string[] faultMessageTypes)
        {
            Timestamp = DateTime.UtcNow;
            FaultId = NewId.NextGuid();

            Host = host;
            ContentType = contentType;
            FaultedMessageId = faultedMessageId;
            FaultMessageTypes = faultMessageTypes;

            var aggregateException = exception as AggregateException;
            Exceptions = aggregateException?.InnerExceptions.Select(x => (ExceptionInfo)new FaultExceptionInfo(x)).ToArray()
                ?? new ExceptionInfo[] { new FaultExceptionInfo(exception) };
        }

        public Guid FaultId { get; set; }
        public DateTime Timestamp { get; set; }
        public Guid? FaultedMessageId { get; set; }
        public ExceptionInfo[] Exceptions { get; set; }
        public HostInfo Host { get; set; }
        public string[] FaultMessageTypes { get; set; }
        public string ContentType { get; set; }
    }
}


text:
from unittest import TestCase

from cStringIO import StringIO
from nose.tools import *
from pymantic.parsers import *
from pymantic.primitives import *
from pymantic.serializers import *

def test_parse_ntriples_named_nodes():
    test_ntriples = """<http://example.com/objects/1> <http://example.com/predicates/1> <http://example.com/objects/2> .
<http://example.com/objects/2> <http://example.com/predicates/2> <http://example.com/objects/1> .
"""
    g = Graph()
    ntriples_parser.parse(StringIO(test_ntriples), g)
    f = StringIO()
    serialize_ntriples(g, f)
    f.seek(0)
    g2 = Graph()
    ntriples_parser.parse(f, g2)
    assert len(g) == 2
    assert Triple(NamedNode('http://example.com/objects/1'),
                  NamedNode('http://example.com/predicates/1'),
                  NamedNode('http://example.com/objects/2')) in g2
    assert Triple(NamedNode('http://example.com/objects/2'),
                  NamedNode('http://example.com/predicates/2'),
                  NamedNode('http://example.com/objects/1')) in g2

class TestTurtleRepresentation(TestCase):
    def setUp(self):
        from pymantic.serializers import turtle_repr
        self.turtle_repr = turtle_repr
        import pymantic.primitives
        self.primitives = pymantic.primitives
        self.profile = self.primitives.Profile()

    def test_integer(self):
        lit = self.primitives.Literal(value='42', datatype=self.profile.resolve('xsd:integer'))
        name = self.turtle_repr(node = lit, profile = self.profile, name_map = None, bnode_name_maker = None)
        self.assertEqual(name, '42')

    def test_decimal(self):
        lit = self.primitives.Literal(value='4.2', datatype=self.profile.resolve('xsd:decimal'))
        name = self.turtle_repr(node = lit, profile = self.profile, name_map = None, bnode_name_maker = None)
        self.assertEqual(name, '4.2')

    def test_double(self):
        lit = self.primitives.Literal(value='4.2e1', datatype=self.profile.resolve('xsd:double'))
        name = self.turtle_repr(node = lit, profile = self.profile, name_map = None, bnode_name_maker = None)
        self.assertEqual(name, '4.2e1')

    def test_boolean(self):
        lit = self.primitives.Literal(value='true', datatype=self.profile.resolve('xsd:boolean'))
        name = self.turtle_repr(node = lit, profile = self.profile, name_map = None, bnode_name_maker = None)
        self.assertEqual(name, 'true')

    def test_bare_string(self):
        lit = self.primitives.Literal(value='Foo', datatype=self.profile.resolve('xsd:string'))
        name = self.turtle_repr(node = lit, profile = self.profile, name_map = None, bnode_name_maker = None)
        self.assertEqual(name, '"Foo"')

    def test_language_string(self):
        lit = self.primitives.Literal(value='Foo', language="en")
        name = self.turtle_repr(node = lit, profile = self.profile, name_map = None, bnode_name_maker = None)
        self.assertEqual(name, '"Foo"@en')

    def test_random_datatype_bare_url(self):
        lit = self.primitives.Literal(value='Foo', datatype=self.primitives.NamedNode("http://example.com/garply"))
        name = self.turtle_repr(node = lit, profile = self.profile, name_map = None, bnode_name_maker = None)
        self.assertEqual(name, '"Foo"^<http://example.com/garply>')

    def test_random_datatype_prefixed(self):
        self.profile.setPrefix('ex', self.primitives.NamedNode('http://example.com/'))
        lit = self.primitives.Literal(value='Foo', datatype=self.primitives.NamedNode("http://example.com/garply"))
        name = self.turtle_repr(node = lit, profile = self.profile, name_map = None, bnode_name_maker = None)
        self.assertEqual(name, '"Foo"^ex:garply')

    def test_named_node_bare(self):
        node = self.primitives.NamedNode('http://example.com/foo')
        name = self.turtle_repr(node = node, profile = self.profile, name_map = None, bnode_name_maker = None)
        self.assertEqual(name, '<http://example.com/foo>')

    def test_named_node_prefixed(self):
        self.profile.setPrefix('ex', self.primitives.NamedNode('http://example.com/'))
        node = self.primitives.NamedNode('http://example.com/foo')
        name = self.turtle_repr(node = node, profile = self.profile, name_map = None, bnode_name_maker = None)
        self.assertEqual(name, 'ex:foo')

class TestTurtleSerializer(TestCase):
    def setUp(self):
        from pymantic.parsers import turtle_parser
        from pymantic.serializers import serialize_turtle
        self.turtle_parser = turtle_parser
        self.serialize_turtle = serialize_turtle
        import pymantic.primitives
        self.primitives = pymantic.primitives
        self.profile = self.primitives.Profile()

    def testSimpleSerialization(self):
        from cStringIO import StringIO
        basic_turtle = """@prefix dc: <http://purl.org/dc/terms/> .
        @prefix example: <http://example.com/> .

        example:foo dc:title "Foo" .
        example:bar dc:title "Bar" .
        example:baz dc:subject example:foo ."""

        graph = self.turtle_parser.parse(basic_turtle)
        f = StringIO()
        self.profile.setPrefix('ex', self.primitives.NamedNode('http://example.com/'))
        self.profile.setPrefix('dc', self.primitives.NamedNode('http://purl.org/dc/terms/'))
        self.serialize_turtle(graph = graph, f = f, profile = self.profile)
        f.seek(0)
        graph2 = self.turtle_parser.parse(f.read())
        f.seek(0)
        self.assertEqual(f.read().strip(), """@prefix ex: <http://example.com/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix dc: <http://purl.org/dc/terms/> .
ex:bar dc:title "Bar" ;
       .

ex:baz dc:subject ex:foo ;
       .

ex:foo dc:title "Foo" ;
       .""")

    def testMultiplePredicates(self):
        from cStringIO import StringIO
        basic_turtle = """@prefix dc: <http://purl.org/dc/terms/> .
        @prefix example: <http://example.com/> .

        example:foo dc:title "Foo" ;
                    dc:author "Bar" ;
                    dc:subject example:yesfootoo .

        example:garply dc:title "Garply" ;
                    dc:author "Baz" ;
                    dc:subject example:thegarply ."""

        graph = self.turtle_parser.parse(basic_turtle)
        f = StringIO()
        self.profile.setPrefix('ex', self.primitives.NamedNode('http://example.com/'))
        self.profile.setPrefix('dc', self.primitives.NamedNode('http://purl.org/dc/terms/'))
        self.serialize_turtle(graph = graph, f = f, profile = self.profile)
        f.seek(0)
        graph2 = self.turtle_parser.parse(f.read())
        f.seek(0)
        self.assertEqual(f.read().strip(), """@prefix ex: <http://example.com/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix dc: <http://purl.org/dc/terms/> .
ex:foo dc:author "Bar" ;
       dc:subject ex:yesfootoo ;
       dc:title "Foo" ;
       .

ex:garply dc:author "Baz" ;
          dc:subject ex:thegarply ;
          dc:title "Garply" ;
          .""")

    def testListSerialization(self):
        from cStringIO import StringIO
        basic_turtle = """@prefix dc: <http://purl.org/dc/terms/> .
        @prefix example: <http://example.com/> .

        example:foo dc:author ("Foo" "Bar" "Baz") ."""

        graph = self.turtle_parser.parse(basic_turtle)
        f = StringIO()
        self.profile.setPrefix('ex', self.primitives.NamedNode('http://example.com/'))
        self.profile.setPrefix('dc', self.primitives.NamedNode('http://purl.org/dc/terms/'))
        self.serialize_turtle(graph = graph, f = f, profile = self.profile)
        f.seek(0)
        print f.read()
        f.seek(0)
        graph2 = self.turtle_parser.parse(f.read())
        f.seek(0)
        self.assertEqual(f.read().strip(), """@prefix ex: <http://example.com/> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix dc: <http://purl.org/dc/terms/> .
ex:foo dc:author ("Foo" "Bar" "Baz") ;
       .""")


text:
import argparse
import sys
import os
import numpy as np
import urllib, urllib2
import cStringIO
from contextlib import closing
import csv

sys.path += [os.path.abspath('../../django')]
import OCP.settings
os.environ['DJANGO_SETTINGS_MODULE'] = 'OCP.settings'
from django.conf import settings

import ocpcaproj
import ocpcadb
import zindex

"""Extract all points above a threshhold for a specific channel and resolution."""

class ThreshholdStack:

  def __init__(self, token):
    """Load the annotation database and project"""

    projdb = ocpcaproj.OCPCAProjectsDB()
    self.proj = projdb.loadProject ( token )

    # Bind the annotation database
    self.annoDB = ocpcadb.OCPCADB ( self.proj )

  def findLocations ( self, channel, resolution, threshhold, outfile ):
    """Build the hierarchy of annotations"""

    # Get the source database sizes
    [ximagesz, yimagesz] = self.proj.datasetcfg.imagesz [ resolution ]
    [xcubedim, ycubedim, zcubedim] = self.proj.datasetcfg.cubedim [ resolution ]

    # Get the slices
    [ startslice, endslice ] = self.proj.datasetcfg.slicerange
    slices = endslice - startslice + 1

    # Set the limits for iteration on the number of cubes in each dimension
    xlimit = ximagesz / xcubedim
    ylimit = yimagesz / ycubedim

    #  Round up the zlimit to the next larger
    zlimit = (((slices-1)/zcubedim+1)*zcubedim)/zcubedim

    # Round up to the top of the range
    lastzindex = (zindex.XYZMorton([xlimit,ylimit,zlimit])/64+1)*64

    locs = []

    with closing (open(outfile, 'wb')) as csvfile:
      csvwriter = csv.writer ( csvfile )

      # Iterate over the cubes in morton order
      for mortonidx in range(0, lastzindex, 64):

        print "Working on batch %s at %s" % (mortonidx, zindex.MortonXYZ(mortonidx))

        # call the range query
        self.annoDB.queryRange ( mortonidx, mortonidx+64, resolution, channel );

        # Flag to indicate no data.  No update query
        somedata = False

        # get the first cube
        [key,cube]  = self.annoDB.getNextCube ()

        #  if there's a cube, there's data
        if key != None:
          somedata = True

        while key != None:

          xyz = zindex.MortonXYZ ( key )

          # Compute the offset in the output data cube
          #  we are placing 4x4x4 input blocks into a 2x2x4 cube
          offset = [xyz[0]*xcubedim, xyz[1]*ycubedim, xyz[2]*zcubedim]

          nzlocs = np.nonzero ( cube.data > threshhold )

          if len(nzlocs[1]) != 0:

            print "res : zindex = ", resolution , ":", key, ", location", zindex.MortonXYZ(key)
            # zip together the x y z and value
            cubelocs=zip(nzlocs[0],nzlocs[1],nzlocs[2],cube.data[nzlocs[0],nzlocs[1],nzlocs[2]])
            # translate from z,y,x,value to x,y,z,value and add global offset
            locs = [ (pt[2]+offset[0], pt[1]+offset[1], pt[0]+offset[2], pt[3]) for pt in cubelocs ]

            csvwriter.writerows ( [x for x in locs ] )

          [key,cube]  = self.annoDB.getNextCube ()

def main():

  parser = argparse.ArgumentParser(description='Find all points above a threshhold for a specific channel and resolution')
  parser.add_argument('token', action="store", help='Token for the annotation project.')
  parser.add_argument('channel', action="store", help='Channel.')
  parser.add_argument('resolution', action="store", type=int, help='Resolution')
  parser.add_argument('threshhold', action="store", type=int, help='Minimum value')
  parser.add_argument('outfile', action="store")

  result = parser.parse_args()

  # Create the annotation stack
  tholder = ThreshholdStack ( result.token )

  # Iterate over the database creating the hierarchy
  tholder.findLocations ( result.channel, result.resolution, result.threshhold, result.outfile )

if __name__ == "__main__":
  main()


text:
function r = getRebounds(peaksInd, trace, searchInterval)
    % Gets rebound as fraction of peak amplitude.

    %trace = abs(trace);
    peaks = trace(peaksInd);
    r = zeros(size(peaks));

    for i=1:length(peaks)
       endPoint = min(peaksInd(i)+searchInterval, length(trace));
       nextMin = edu.washington.riekelab.util.getPeaks(trace(peaksInd(i):endPoint), -1);
       if isempty(nextMin)
           nextMin = peaks(i);
       else
           nextMin = nextMin(1);
       end
       nextMax = edu.washington.riekelab.util.getPeaks(trace(peaksInd(i):endPoint), 1);
       if isempty(nextMax)
           nextMax = 0;
       else
           nextMax = nextMax(1);
       end

       if nextMin < peaks(i) % not the real spike min
           r(i) = 0;
       else
           r(i) = nextMax;
       end
    end
end


text:
import styled from 'styled-components'

import { Tile } from '../Grid'

const StyledTile = styled(Tile)`
  width: 100%;

  ${props => props.theme.media.tablet`width: 50%`};
  ${props => props.theme.media.desktop`width: 33.33%`};
  ${props => props.theme.media.giant`width: 25%`};
`

export default StyledTile


text:
package org.apache.pdfbox.pdmodel.graphics.blend;

import java.awt.AlphaComposite;
import java.awt.Composite;
import java.awt.CompositeContext;
import java.awt.RenderingHints;
import java.awt.color.ColorSpace;
import java.awt.image.ColorModel;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * AWT composite for blend modes.
 *
 * @author Kühn & Weyh Software GmbH
 */
public final class BlendComposite implements Composite {
  /**
   * Log instance.
   */
  private static final Log LOG = LogFactory.getLog(BlendComposite.class);

  /**
   * Creates a blend composite
   *
   * @param blendMode     Desired blend mode
   * @param constantAlpha Constant alpha, must be in the inclusive range
   *                      [0.0...1.0] or it will be clipped.
   * @return a blend composite.
   */
  public static Composite getInstance(BlendMode blendMode, float constantAlpha) {
    if (constantAlpha < 0) {
      LOG.warn("using 0 instead of incorrect Alpha " + constantAlpha);
      constantAlpha = 0;
    } else if (constantAlpha > 1) {
      LOG.warn("using 1 instead of incorrect Alpha " + constantAlpha);
      constantAlpha = 1;
    }
    if (blendMode == BlendMode.NORMAL) {
      return AlphaComposite.getInstance(AlphaComposite.SRC_OVER, constantAlpha);
    } else {
      return new BlendComposite(blendMode, constantAlpha);
    }
  }

  // TODO - non-separable blending modes
  private final BlendMode blendMode;
  private final float constantAlpha;

  private BlendComposite(BlendMode blendMode, float constantAlpha) {
    super();
    this.blendMode = blendMode;
    this.constantAlpha = constantAlpha;
  }

  @Override
  public CompositeContext createContext(ColorModel srcColorModel, ColorModel dstColorModel, RenderingHints hints) {
    return new BlendCompositeContext(srcColorModel, dstColorModel, hints);
  }

  class BlendCompositeContext implements CompositeContext {
    private final ColorModel srcColorModel;
    private final ColorModel dstColorModel;
    private final RenderingHints hints;

    BlendCompositeContext(ColorModel srcColorModel, ColorModel dstColorModel, RenderingHints hints) {
      this.srcColorModel = srcColorModel;
      this.dstColorModel = dstColorModel;
      this.hints = hints;
    }

    @Override
    public void dispose() {
      // nothing needed
    }

    @Override
    public void compose(Raster src, Raster dstIn, WritableRaster dstOut) {
      int x0 = src.getMinX();
      int y0 = src.getMinY();
      int width = Math.min(Math.min(src.getWidth(), dstIn.getWidth()), dstOut.getWidth());
      int height = Math.min(Math.min(src.getHeight(), dstIn.getHeight()), dstOut.getHeight());
      int x1 = x0 + width;
      int y1 = y0 + height;
      int dstInXShift = dstIn.getMinX() - x0;
      int dstInYShift = dstIn.getMinY() - y0;
      int dstOutXShift = dstOut.getMinX() - x0;
      int dstOutYShift = dstOut.getMinY() - y0;

      ColorSpace srcColorSpace = srcColorModel.getColorSpace();
      int numSrcColorComponents = srcColorModel.getNumColorComponents();
      int numSrcComponents = src.getNumBands();
      boolean srcHasAlpha = (numSrcComponents > numSrcColorComponents);
      ColorSpace dstColorSpace = dstColorModel.getColorSpace();
      int numDstColorComponents = dstColorModel.getNumColorComponents();
      int numDstComponents = dstIn.getNumBands();
      boolean dstHasAlpha = (numDstComponents > numDstColorComponents);

      int colorSpaceType = dstColorSpace.getType();
      boolean subtractive = (colorSpaceType != ColorSpace.TYPE_RGB) && (colorSpaceType != ColorSpace.TYPE_GRAY);

      boolean blendModeIsSeparable = blendMode instanceof SeparableBlendMode;
      SeparableBlendMode separableBlendMode = blendModeIsSeparable ? (SeparableBlendMode) blendMode : null;

      boolean needsColorConversion = !srcColorSpace.equals(dstColorSpace);

      Object srcPixel = null;
      Object dstPixel = null;
      float[] srcComponents = new float[numSrcComponents];
      // PDFBOX-3501 let getNormalizedComponents allocate to avoid
      // ArrayIndexOutOfBoundsException for bitonal target
      float[] dstComponents = null;

      float[] srcColor = new float[numSrcColorComponents];
      float[] srcConverted;

      for (int y = y0; y < y1; y++) {
        for (int x = x0; x < x1; x++) {
          srcPixel = src.getDataElements(x, y, srcPixel);
          dstPixel = dstIn.getDataElements(dstInXShift + x, dstInYShift + y, dstPixel);

          srcComponents = srcColorModel.getNormalizedComponents(srcPixel, srcComponents, 0);
          dstComponents = dstColorModel.getNormalizedComponents(dstPixel, dstComponents, 0);

          float srcAlpha = srcHasAlpha ? srcComponents[numSrcColorComponents] : 1.0f;
          float dstAlpha = dstHasAlpha ? dstComponents[numDstColorComponents] : 1.0f;

          srcAlpha = srcAlpha * constantAlpha;

          float resultAlpha = dstAlpha + srcAlpha - srcAlpha * dstAlpha;
          float srcAlphaRatio = (resultAlpha > 0) ? srcAlpha / resultAlpha : 0;

          // convert color
          System.arraycopy(srcComponents, 0, srcColor, 0, numSrcColorComponents);
          if (needsColorConversion) {
            // TODO - very very slow - Hash results???
            float[] cieXYZ = srcColorSpace.toCIEXYZ(srcColor);
            srcConverted = dstColorSpace.fromCIEXYZ(cieXYZ);
          } else {
            srcConverted = srcColor;
          }

          if (separableBlendMode != null) {
            for (int k = 0; k < numDstColorComponents; k++) {
              float srcValue = srcConverted[k];
              float dstValue = dstComponents[k];

              if (subtractive) {
                srcValue = 1 - srcValue;
                dstValue = 1 - dstValue;
              }

              float value = separableBlendMode.blendChannel(srcValue, dstValue);
              value = srcValue + dstAlpha * (value - srcValue);
              value = dstValue + srcAlphaRatio * (value - dstValue);

              if (subtractive) {
                value = 1 - value;
              }

              dstComponents[k] = value;
            }
          } else {
            // TODO - nonseparable modes
          }

          if (dstHasAlpha) {
            dstComponents[numDstColorComponents] = resultAlpha;
          }

          dstPixel = dstColorModel.getDataElements(dstComponents, 0, dstPixel);
          dstOut.setDataElements(dstOutXShift + x, dstOutYShift + y, dstPixel);
        }
      }
    }
  }
}


text:
import React, { useMemo, useCallback } from 'react'
import faker from 'faker'
import { createEditor } from 'slate'
import { Slate, Editable, withReact } from 'slate-react'

const HEADINGS = 100
const PARAGRAPHS = 7
const initialValue = []

for (let h = 0; h < HEADINGS; h++) {
  initialValue.push({
    type: 'heading',
    children: [{ text: faker.lorem.sentence(), marks: [] }],
  })

  for (let p = 0; p < PARAGRAPHS; p++) {
    initialValue.push({
      children: [{ text: faker.lorem.paragraph(), marks: [] }],
    })
  }
}

const HugeDocumentExample = () => {
  const renderElement = useCallback(props => <Element {...props} />, [])
  const editor = useMemo(() => withReact(createEditor()), [])
  return (
    <Slate editor={editor} defaultValue={initialValue}>
      <Editable renderElement={renderElement} spellCheck autoFocus />
    </Slate>
  )
}

const Element = ({ attributes, children, element }) => {
  switch (element.type) {
    case 'heading':
      return
{children}

    default:
      return
{children}

  }
}

export default HugeDocumentExample


text:
package org.talend.components.snowflake.tsnowflakeconnection;

import java.util.EnumSet;
import java.util.Set;

import org.talend.components.api.component.ConnectorTopology;
import org.talend.components.api.component.runtime.ExecutionEngine;
import org.talend.components.api.properties.ComponentProperties;
import org.talend.components.snowflake.SnowflakeConnectionProperties;
import org.talend.components.snowflake.SnowflakeDefinition;
import org.talend.daikon.properties.property.Property;
import org.talend.daikon.runtime.RuntimeInfo;

public class TSnowflakeConnectionDefinition extends SnowflakeDefinition {

    public static final String COMPONENT_NAME = "tSnowflakeConnection"; //$NON-NLS-1$

    public TSnowflakeConnectionDefinition() {
        super(COMPONENT_NAME);
    }

    @Override
    public Class<? extends ComponentProperties> getPropertyClass() {
        return SnowflakeConnectionProperties.class;
    }

    @Override
    public Property<?>[] getReturnProperties() {
        return new Property[]{RETURN_ERROR_MESSAGE_PROP};
    }

    @Override
    public boolean isStartable() {
        return true;
    }

    @Override
    public RuntimeInfo getRuntimeInfo(ExecutionEngine engine, ComponentProperties properties, ConnectorTopology componentType) {
        assertEngineCompatibility(engine);
        if (componentType == ConnectorTopology.NONE) {
            return getCommonRuntimeInfo(SnowflakeDefinition.SOURCE_OR_SINK_CLASS);
        } else {
            return null;
        }
    }

    @Override
    public Set<ConnectorTopology> getSupportedConnectorTopologies() {
        return EnumSet.of(ConnectorTopology.NONE);
    }

}


text:
/**
 * fuzzy.js v0.1.0
 * (c) 2016 Ben Ripkens
 * @license: MIT
 */
(function (context) {
  'use strict';

  var fuzzy = function fuzzy(term, query) {
    var max = calcFuzzyScore(term, query);
    var termLength = term.length;

    if (fuzzy.analyzeSubTerms) {

      for (var i = 1; i < termLength && i < fuzzy.analyzeSubTermDepth; i++) {
        var subTerm = term.substring(i);
        var score = calcFuzzyScore(subTerm, query);
        if (score.score > max.score) {
          // we need to correct 'term' and 'matchedTerm', as calcFuzzyScore
          // does not now that it operates on a substring. Doing it only for
          // new maximum score to save some performance.
          score.term = term;
          score.highlightedTerm = term.substring(0, i) + score.highlightedTerm;
          max = score;
        }
      }
    }

    return max;
  };

  var calcFuzzyScore = function calcFuzzyScore(term, query) {
    var score = 0;
    var termLength = term.length;
    var queryLength = query.length;
    var highlighting = '';
    var ti = 0;
    // -1 would not work as this would break the calculations of bonus
    // points for subsequent character matches. Something like
    // Number.MIN_VALUE would be more appropriate, but unfortunately
    // Number.MIN_VALUE + 1 equals 1...
    var previousMatchingCharacter = -2;

    for (var qi = 0; qi < queryLength && ti < termLength; qi++) {
      var qc = query.charAt(qi);
      var lowerQc = qc.toLowerCase();

      for (; ti < termLength; ti++) {
        var tc = term.charAt(ti);

        if (lowerQc === tc.toLowerCase()) {
          score++;

          if ((previousMatchingCharacter + 1) === ti) {
            score += 2;
          }

          highlighting += fuzzy.highlighting.before +
              tc +
              fuzzy.highlighting.after;
          previousMatchingCharacter = ti;
          ti++;
          break;
        } else {
          highlighting += tc;
        }
      }
    }

    highlighting += term.substring(ti, term.length);

    return {
      score: score,
      term: term,
      query: query,
      highlightedTerm: highlighting
    };
  };

  fuzzy.matchComparator = function matchComparator(m1, m2) {
    return (m2.score - m1.score != 0) ? m2.score - m1.score : m1.term.length - m2.term.length;
  };

  /*
   * Whether or not fuzzy.js should analyze sub-terms, i.e. also
   * check term starting positions != 0.
   *
   * Example:
   * Given the term 'Halleluja' and query 'luja'
   *
   * Fuzzy.js scores this combination with an 8, when analyzeSubTerms is
   * set to false, as the following matching string will be calculated:
   * Ha[l]lel[uja]
   *
   * If you activate sub temr analysis though, the query will reach a score
   * of 10, as the matching string looks as following:
   * Halle[luja]
   *
   * Naturally, the second version is more expensive than the first one.
   * You should therefore configure how many sub terms you which to analyse.
   * This can be configured through fuzzy.analyzeSubTermDepth = 10.
   */
  fuzzy.analyzeSubTerms = false;

  /*
   * How many sub terms should be analyzed.
   */
  fuzzy.analyzeSubTermDepth = 10;

  fuzzy.highlighting = {
    before: '<em>',
    after: '</em>'
  };

  /*
   * Exporting the public API
   * ------------------------
   * In a browser, the library will be available through this.fuzzy. Should
   * requireJS be used, we register fuzzy.js through requireJS.
   * For other environments, CommonJS is supported.
   */
  if (typeof module !== 'undefined' && module.exports) {
    module.exports = fuzzy;
  } else if (typeof define === 'function') {
    define(function() {
      return fuzzy;
    });
  } else {
    /*
     * In case the global variable fuzzy needs to be reset to its previous
     * value, the fuzzy library is returned by this method.
     */
    var previousFuzzy = context.fuzzy;
    fuzzy.noConflict = function() {
      context.fuzzy = previousFuzzy;
      return fuzzy;
    };

    context.fuzzy = fuzzy;
  }
})(this);


text:
package org.jboss.jbossts.qa.Utils;

import org.omg.CosTransactions.TransactionFactory;
import org.omg.CosTransactions.TransactionFactoryHelper;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.File;

/*
 * Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003
 *
 * Arjuna Technology Ltd.
 * Newcastle upon Tyne,
 * Tyne and Wear,
 * UK.
 *
 * $Id: RegisterOTSServer.java,v 1.2 2003/06/26 11:45:07 rbegg Exp $
 */

public class RegisterOTSServer2
{
	public final static String NAME_SERVICE_BIND_NAME_PROPERTY = "ots.server.bindname";

	public static void main(String[] args)
	{
		String bindName = System.getProperty(NAME_SERVICE_BIND_NAME_PROPERTY);

		if (bindName != null)
		{
			System.out.println("Registering OTS Server '" + bindName + "'");

			try
			{
				ORBInterface.initORB(args, null);

				String[] transactionFactoryParams = new String[1];
				transactionFactoryParams[0] = ORBServices.otsKind;

				TransactionFactory transactionFactory = TransactionFactoryHelper.narrow(ORBServices.getService(ORBServices.transactionService, transactionFactoryParams));

				registerService(bindName, ORBInterface.orb().object_to_string(transactionFactory));

                System.out.println("Ready");
            }
			catch (Exception e)
			{
				e.printStackTrace(System.err);
				System.out.println("Failed");
			}
		}
		else
		{
			System.out.println("Bind name '" + NAME_SERVICE_BIND_NAME_PROPERTY + "' not specified");
			System.out.println("Failed");
		}
	}

    public static void registerService(String name, String ior) throws IOException
    {
        File file = new File(name);
        if(file.getParentFile() != null) {
            file.getParentFile().mkdirs();
        }
        FileOutputStream fout = new FileOutputStream(file);
        fout.write(ior.getBytes());
        fout.close();
    }
}


text:
Installation - Step #3

<?php
    if( isset( $_POST['db_username'] ) && isset( $_POST['db_password'] ) && isset( $_POST['db_name'] ) && isset( $_POST['twitch_apikey'] ) && isset( $_POST['twitch_secret'] ) && isset( $_POST['downloads_location'] ) ) {
        $pre_db_host = ( !isset( $_POST['db_host'] ) || $_POST['db_host'] == '' ? 'localhost' : $_POST['db_host'] );
        $db_host_values = explode( ':', $pre_db_host );
        if( isset( $db_host_values[ 1 ] ) && intval( $db_host_values[ 1 ] ) ) {
            $db_host = $db_host_values[ 0 ];
            $db_port = intval( $db_host_values[ 1 ] );
        } else {
            $db_host = $pre_db_host;
            $db_port = ini_get( "mysqli.default_port" );
        }
        $db_user = $_POST['db_username'];
        $db_pass = $_POST['db_password'];
        $db_name = $_POST['db_name'];
        $twitch_api_key = $_POST['twitch_apikey'];
        $twitch_secret = $_POST['twitch_secret'];
        $downloads_location = $_POST['downloads_location'];
        $twitch_redirect = ( !isset( $_POST['twitch_redirect'] ) || $_POST['twitch_redirect'] == '' ? $_SESSION['TSAURL'] : $_POST['twitch_redirect'] );
        $db_tblprefix = ( !isset( $_POST['db_tableprefix'] ) || str_replace( ' ', '', $_POST['db_tableprefix'] ) == '' ? 'tsa_' : str_replace( ' ', '', preg_replace( '([^A-Z,^0-9,^a-z,^_])', '', $_POST['db_tableprefix'] ) ) ); // Should work for making sure that table prefixes are MySQL-valid.
        $missing = false;
        $configFile = implode( DIRECTORY_SEPARATOR, array( 'includes', 'config.php' ) );

        if( empty( $db_user ) || empty( $db_pass ) || empty( $db_name ) || empty( $twitch_api_key ) || empty( $twitch_secret ) || empty( $downloads_location ) ) { $missing = true; }
        if( empty( $db_user ) ) { echo '
Missing MySQL username
'; }
        if( empty( $db_pass ) ) { echo '
Missing MySQL password
'; }
        if( empty( $db_name ) ) { echo '
Missing MySQL database name
'; }
        if( empty( $twitch_api_key ) ) { echo '
Missing Twitch API key
'; }
        if( empty( $twitch_secret ) ) { echo '
Missing Twitch API secret
'; }
        if( empty( $downloads_location ) ) { echo '
Missing folder location of subscriber downloads
'; }
        if( $missing ) { echo 'Back to step #2'; } else {
            $con = mysqli_connect( $db_host, $db_user, $db_pass, $db_name, $db_port ) or die( 'Error connecting to database.' );
            if( !$con ) {
                echo '
MySQL Error! ' . mysqli_error( $con ) . '
';
            } else {
                $dbConstants = array(
                    'TSA_DB_HOST' => $pre_db_host,
                    'TSA_DB_USER' => $db_user,
                    'TSA_DB_PASS' => $db_pass,
                    'TSA_DB_NAME' => $db_name,
                    'TSA_DB_PREFIX' => $db_tblprefix
                );
                $twitchConstants = array(
                    'TSA_APIKEY' => $twitch_api_key,
                    'TSA_APISECRET' => $twitch_secret,
                    'TSA_REDIRECTURL' => $twitch_redirect
                );
                chdir( '..' ); // Go up one directory for writing files.
                if( is_writeable( $configFile ) ) {
                    $config = "<?php \n";
                    $config .= "    // MySQL database information\n";
                    foreach( $dbConstants as $const => $value ) {
                        $config .= "    define( '" . $const . "', '" . $value . "' );\n";
                    }
                    $config .= "\n    // Twitch API stuff\n";
                    foreach( $twitchConstants as $const => $value ) {
                        $config .= "    define( '" . $const . "', '" . $value . "' );\n";
                    }
                    $confWrite = fopen( $configFile, 'w' ) or die( 'Cannot open configuration file. Please make sure the web server user has the correct permissions to \'includes/config.php\'.' );
                    fwrite( $confWrite, $config, strlen( $config ) );
                    fclose( $confWrite );

                    if( file_exists( $downloads_location ) ) {
                        if( is_dir( $downloads_location ) ) {
                            if( !is_writeable( $downloads_location ) ) {
                                echo '
' . $downloads_location . ' is not writable.
';
                                exit();
                            }
                        } else {
                            echo '
' . $downloads_location . ' is not a folder.
';
                            exit();
                        }
                    } else {
                        if( !mkdir( $downloads_location, 0777, true ) ) {
                            echo '
Unable to create folder for downloadable files at: ' . $downloads_location . '
';
                            exit();
                        }
                    }

                    $writeDlIndex = fopen( $downloads_location . DIRECTORY_SEPARATOR . 'index.php', 'w' ) or die( 'Unable to write file inside ' . $downloads_location . '. Please make sure the web server user has the correct permissions.' );
                    fwrite( $writeDlIndex, "<?php // Nothing to see here ?>" );
                    fclose( $writeDlIndex );

                    $writeDlHtaccess = fopen( $downloads_location . DIRECTORY_SEPARATOR . '.htaccess', 'w' ) or die( 'Unable to write file inside ' . $downloads_location . '. Please make sure the web server user has the correct permissions.' );
                    fwrite( $writeDlHtaccess, "Deny from all" );
                    fclose( $writeDlHtaccess );

                    $db_tblprefix = mysqli_real_escape_string( $con, $db_tblprefix );
                    // I am so sorry for making this the spaghetti it is...
                    $result = mysqli_query( $con, "CREATE TABLE " . $db_tblprefix . "posts( id int NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), title varchar(255), body text);" );
                    if( $result ) {
                        echo '
Created "' . $db_tblprefix . 'posts" table.
';
                        $result = mysqli_query( $con, "CREATE TABLE " . $db_tblprefix . "settings( setting_id int NOT NULL AUTO_INCREMENT, PRIMARY KEY(setting_id), meta_key varchar(64) UNIQUE, meta_value mediumtext);" );
                        if( $result ) {
                            echo '
Created "' . $db_tblprefix . 'settings" table.
';
                            $result = mysqli_query( $con, "CREATE TABLE " . $db_tblprefix . "whitelist( id int NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), name varchar(25), uid int UNIQUE );" );
                            if( $result ) {
                                echo '
Created "' . $db_tblprefix . 'whitelist" table.
';
                                $result = mysqli_query( $con, "CREATE TABLE " . $db_tblprefix . "blacklist( id int NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), name varchar(25), uid int UNIQUE, reason mediumtext );" );
                                if( $result ) {
                                    echo '
Created "' . $db_tblprefix . 'blacklist" table.
';
                                    $result = mysqli_query( $con, "CREATE TABLE " . $db_tblprefix . "downloads( id int NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), post_id int(11), hash char(40), filetype varchar(255), original_file_name varchar(255), size int(11), date date );" );
                                    if( $result ) {
                                        echo '
Created "' . $db_tblprefix . 'downloads" table.
';
                                        $dlFileTypes = array(
                                            'png' => 'image/png',
                                            'jpeg' => 'image/jpeg',
                                            'jpg' => 'image/jpeg',
                                            'gif' => 'image/gif',
                                            'bmp' => 'image/bmp',
                                            'pdf' => 'application/pdf',
                                            'zip' => 'application/octet-stream',
                                            'rar' => 'application/octet-stream',
                                            'doc' => 'application/msword',
                                            'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                                            'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
                                            'txt' => 'text/plain',
                                            'log' => 'text/plain',
                                            'mp3' => 'audio/mpeg',
                                            'wav' => 'audio/wav',
                                            'ogg' => 'audio/ogg',
                                            'm4v' => 'video/mp4',
                                            'mp4' => 'video/mp4',
                                            'webm' => 'video/webm'
                                        );
                                        $downloads_location = mysqli_real_escape_string( $con, $downloads_location );
                                        $insertDlFiletypes = "INSERT INTO " . $db_tblprefix . "settings( meta_key, meta_value ) VALUES( 'downloads_whitelist', '" . json_encode( $dlFileTypes ) . "' );";
                                        $insertDlPlaceholder = "INSERT INTO " . $db_tblprefix . "settings( meta_key, meta_value ) VALUES( 'downloads_location', '" . $downloads_location . "' );";
                                        $result = mysqli_multi_query( $con, $insertDlFiletypes . $insertDlPlaceholder );
                                        if( $result ) {
                                            ?>
                                            <form method="get" action="install.php"><input type="hidden" name="step" value="4" /><button class="btn btn-success">Continue to step #4    </button></form>
                                            <?php
                                        } else {
                                            echo '
' . mysqli_error( $con ) . '
';
                                        }
                                    } else {
                                        echo '
' . mysqli_error( $con ) . '
';
                                    }
                                } else {
                                    echo '
' . mysqli_error( $con ) . '
';
                                }
                            } else {
                                echo '
' . mysqli_error( $con ) . '
';
                            }
                        } else {
                            echo '
' . mysqli_error( $con ) . '
';
                        }
                    } else {
                        echo '
' . mysqli_error( $con ) . '
';
                    }
                } else {
                    ?>

Unable to write to configuration file 'includes/config.php'.

                    <?php
                }
            }
            mysqli_close( $con );
        }
    } else {
        ?>

Missing parameter(s).

        <?php
    }
?>


text:
<?php

/**
* <auto-generated>
*     This code was generated by Codezu.
*
*     Changes to this file may cause incorrect behavior and will be lost if
*     the code is regenerated.
* </auto-generated>
*/

namespace Mozu\Api\Clients\Commerce\Catalog\Admin\Products;

use Mozu\Api\MozuClient;
use Mozu\Api\Urls\Commerce\Catalog\Admin\Products\ProductVariationUrl;

use Mozu\Api\Headers;

/**
* Use the product variations sub-resource to manage the variations of a product based on its attributes. For example, a t-shirt product could be offered in six variations: Small Black, Medium Black, Large Black, Small White, Medium White, and Large White.
*/
class ProductVariationClient {

	/**
	* Retrieves a collection of the localized delta price values for a product variation. Localized delta prices are deltas between two differing monetary conversion amounts between countries, such as US Dollar vs Euro.
	*
	* @param string $productCode The unique, user-defined product code of a product, used throughout  to reference and associate to a product.
	* @param string $variationKey System-generated key that represents the attribute values that uniquely identify a specific product variation.
	* @return MozuClient
	*/
	public static function getProductVariationLocalizedDeltaPricesClient($dataViewMode, $productCode, $variationKey)
	{
		$url = ProductVariationUrl::getProductVariationLocalizedDeltaPricesUrl($productCode, $variationKey);
		$mozuClient = new MozuClient();
		$mozuClient->withResourceUrl($url)->withHeader(Headers::X_VOL_DATAVIEW_MODE ,$dataViewMode);
		return $mozuClient;

	}

	/**
	* Retrieves the localized delta price value for a product variation. Localized delta prices are deltas between two differing monetary conversion amounts between countries, such as US Dollar vs Euro.
	*
	* @param string $currencyCode The three character ISO currency code, such as USD for US Dollars.
	* @param string $productCode The unique, user-defined product code of a product, used throughout  to reference and associate to a product.
	* @param string $responseFields Use this field to include those fields which are not included by default.
	* @param string $variationKey System-generated key that represents the attribute values that uniquely identify a specific product variation.
	* @return MozuClient
	*/
	public static function getProductVariationLocalizedDeltaPriceClient($dataViewMode, $productCode, $variationKey, $currencyCode, $responseFields =  null)
	{
		$url = ProductVariationUrl::getProductVariationLocalizedDeltaPriceUrl($currencyCode, $productCode, $responseFields, $variationKey);
		$mozuClient = new MozuClient();
		$mozuClient->withResourceUrl($url)->withHeader(Headers::X_VOL_DATAVIEW_MODE ,$dataViewMode);
		return $mozuClient;

	}

	/**
	* Retrieves a list of details of the localized price values for a product variation.
	*
	* @param string $productCode The unique, user-defined product code of a product, used throughout  to reference and associate to a product.
	* @param string $variationKey System-generated key that represents the attribute values that uniquely identify a specific product variation.
	* @return MozuClient
	*/
	public static function getProductVariationLocalizedPricesClient($dataViewMode, $productCode, $variationKey)
	{
		$url = ProductVariationUrl::getProductVariationLocalizedPricesUrl($productCode, $variationKey);
		$mozuClient = new MozuClient();
		$mozuClient->withResourceUrl($url)->withHeader(Headers::X_VOL_DATAVIEW_MODE ,$dataViewMode);
		return $mozuClient;

	}

	/**
	* Retrieves the details of the localized price value for a product variation and a specific localized currency.
	*
	* @param string $currencyCode The three character ISO currency code, such as USD for US Dollars.
	* @param string $productCode The unique, user-defined product code of a product, used throughout  to reference and associate to a product.
	* @param string $responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
	* @param string $variationKey System-generated key that represents the attribute values that uniquely identify a specific product variation.
	* @return MozuClient
	*/
	public static function getProductVariationLocalizedPriceClient($dataViewMode, $productCode, $variationKey, $currencyCode, $responseFields =  null)
	{
		$url = ProductVariationUrl::getProductVariationLocalizedPriceUrl($currencyCode, $productCode, $responseFields, $variationKey);
		$mozuClient = new MozuClient();
		$mozuClient->withResourceUrl($url)->withHeader(Headers::X_VOL_DATAVIEW_MODE ,$dataViewMode);
		return $mozuClient;

	}

	/**
	* Retrieves the details of a product variation based on the supplied product code and variation key.
	*
	* @param string $productCode Merchant-created code that uniquely identifies the product such as a SKU or item number. Once created, the product code is read-only.
	* @param string $responseFields Use this field to include those fields which are not included by default.
	* @param string $variationKey System-generated key that represents the attribute values that uniquely identify a specific product variation.
	* @return MozuClient
	*/
	public static function getProductVariationClient($dataViewMode, $productCode, $variationKey, $responseFields =  null)
	{
		$url = ProductVariationUrl::getProductVariationUrl($productCode, $responseFields, $variationKey);
		$mozuClient = new MozuClient();
		$mozuClient->withResourceUrl($url)->withHeader(Headers::X_VOL_DATAVIEW_MODE ,$dataViewMode);
		return $mozuClient;

	}

	/**
	* Retrieves a list of the product variations configured for the specified product code.
	*
	* @param string $filter A set of expressions that consist of a field, operator, and value and represent search parameter syntax when filtering results of a query. Valid operators include equals (eq), does not equal (ne), greater than (gt), less than (lt), greater than or equal to (ge), less than or equal to (le), starts with (sw), or contains (cont). For example - "filter=IsDisplayed+eq+true"
	* @param int $pageSize The number of results to display on each page when creating paged results from a query. The maximum value is 200.
	* @param string $productCode Merchant-created code that uniquely identifies the product such as a SKU or item number. Once created, the product code is read-only.
	* @param string $responseFields Use this field to include those fields which are not included by default.
	* @param string $sortBy The property by which to sort results and whether the results appear in ascending (a-z) order, represented by ASC or in descending (z-a) order, represented by DESC. The sortBy parameter follows an available property. For example: "sortBy=productCode+asc"
	* @param int $startIndex When creating paged results from a query, this value indicates the zero-based offset in the complete result set where the returned entities begin. For example, with a PageSize of 25, to get the 51st through the 75th items, use startIndex=3.
	* @return MozuClient
	*/
	public static function getProductVariationsClient($dataViewMode, $productCode, $startIndex =  null, $pageSize =  null, $sortBy =  null, $filter =  null, $responseFields =  null)
	{
		$url = ProductVariationUrl::getProductVariationsUrl($filter, $pageSize, $productCode, $responseFields, $sortBy, $startIndex);
		$mozuClient = new MozuClient();
		$mozuClient->withResourceUrl($url)->withHeader(Headers::X_VOL_DATAVIEW_MODE ,$dataViewMode);
		return $mozuClient;

	}

	/**
	* Adds the localized delta price value for a product variation. Localized delta prices are deltas between two differing monetary conversion amounts between countries, such as US Dollar vs Euro.
	*
	* @param string $productCode The unique, user-defined product code of a product, used throughout  to reference and associate to a product.
	* @param string $responseFields Use this field to include those fields which are not included by default.
	* @param string $variationKey System-generated key that represents the attribute values that uniquely identify a specific product variation.
	* @param ProductVariationDeltaPrice $localizedDeltaPrice The difference between the base price for the product and this variation of the product, which can be a positive or negative decimal value. For example, if the base price for a t-shirt product is $10, but the XL variation should cost $12, the DeltaPrice value should be "2". However, if the XS variation should only cost $8, the DeltaPrice value should be "-2".
	* @return MozuClient
	*/
	public static function addProductVariationLocalizedDeltaPriceClient($dataViewMode, $localizedDeltaPrice, $productCode, $variationKey, $responseFields =  null)
	{
		$url = ProductVariationUrl::addProductVariationLocalizedDeltaPriceUrl($productCode, $responseFields, $variationKey);
		$mozuClient = new MozuClient();
		$mozuClient->withResourceUrl($url)->withBody($localizedDeltaPrice)->withHeader(Headers::X_VOL_DATAVIEW_MODE ,$dataViewMode);
		return $mozuClient;

	}

	/**
	* Adds the localized price value for a product variation and a specific localized currency.
	*
	* @param string $productCode The unique, user-defined product code of a product, used throughout  to reference and associate to a product.
	* @param string $responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
	* @param string $variationKey System-generated key that represents the attribute values that uniquely identify a specific product variation.
	* @param ProductVariationFixedPrice $localizedPrice The details of the product variation localized price.
	* @return MozuClient
	*/
	public static function addProductVariationLocalizedPriceClient($dataViewMode, $localizedPrice, $productCode, $variationKey, $responseFields =  null)
	{
		$url = ProductVariationUrl::addProductVariationLocalizedPriceUrl($productCode, $responseFields, $variationKey);
		$mozuClient = new MozuClient();
		$mozuClient->withResourceUrl($url)->withBody($localizedPrice)->withHeader(Headers::X_VOL_DATAVIEW_MODE ,$dataViewMode);
		return $mozuClient;

	}

	/**
	* Updates all localized delta price values for a product variation. Localized delta prices are deltas between two differing monetary conversion amounts between countries, such as US Dollar vs Euro.
	*
	* @param string $productCode The unique, user-defined product code of a product, used throughout  to reference and associate to a product.
	* @param string $variationKey System-generated key that represents the attribute values that uniquely identify a specific product variation.
	* @param array|ProductVariationDeltaPrice $localizedDeltaPrice The difference between the base price for the product and this variation of the product, which can be a positive or negative decimal value. For example, if the base price for a t-shirt product is $10, but the XL variation should cost $12, the DeltaPrice value should be "2". However, if the XS variation should only cost $8, the DeltaPrice value should be "-2".
	* @return MozuClient
	*/
	public static function updateProductVariationLocalizedDeltaPricesClient($dataViewMode, $localizedDeltaPrice, $productCode, $variationKey)
	{
		$url = ProductVariationUrl::updateProductVariationLocalizedDeltaPricesUrl($productCode, $variationKey);
		$mozuClient = new MozuClient();
		$mozuClient->withResourceUrl($url)->withBody($localizedDeltaPrice)->withHeader(Headers::X_VOL_DATAVIEW_MODE ,$dataViewMode);
		return $mozuClient;

	}

	/**
	* Updates the localized delta price value for a product variation. Localized delta prices are deltas between two differing monetary conversion amounts between countries, such as US Dollar vs Euro.
	*
	* @param string $currencyCode The three character ISO currency code, such as USD for US Dollars.
	* @param string $productCode The unique, user-defined product code of a product, used throughout  to reference and associate to a product.
	* @param string $responseFields Use this field to include those fields which are not included by default.
	* @param string $variationKey System-generated key that represents the attribute values that uniquely identify a specific product variation.
	* @param ProductVariationDeltaPrice $localizedDeltaPrice The difference between the base price for the product and this variation of the product, which can be a positive or negative decimal value. For example, if the base price for a t-shirt product is $10, but the XL variation should cost $12, the DeltaPrice value should be "2". However, if the XS variation should only cost $8, the DeltaPrice value should be "-2".
	* @return MozuClient
	*/
	public static function updateProductVariationLocalizedDeltaPriceClient($dataViewMode, $localizedDeltaPrice, $productCode, $variationKey, $currencyCode, $responseFields =  null)
	{
		$url = ProductVariationUrl::updateProductVariationLocalizedDeltaPriceUrl($currencyCode, $productCode, $responseFields, $variationKey);
		$mozuClient = new MozuClient();
		$mozuClient->withResourceUrl($url)->withBody($localizedDeltaPrice)->withHeader(Headers::X_VOL_DATAVIEW_MODE ,$dataViewMode);
		return $mozuClient;

	}

	/**
	* Updates a list of localized price values for a product variation.
	*
	* @param string $productCode The unique, user-defined product code of a product, used throughout  to reference and associate to a product.
	* @param string $variationKey System-generated key that represents the attribute values that uniquely identify a specific product variation.
	* @param array|ProductVariationFixedPrice $localizedPrice The details of the product variation localized price.
	* @return MozuClient
	*/
	public static function updateProductVariationLocalizedPricesClient($dataViewMode, $localizedPrice, $productCode, $variationKey)
	{
		$url = ProductVariationUrl::updateProductVariationLocalizedPricesUrl($productCode, $variationKey);
		$mozuClient = new MozuClient();
		$mozuClient->withResourceUrl($url)->withBody($localizedPrice)->withHeader(Headers::X_VOL_DATAVIEW_MODE ,$dataViewMode);
		return $mozuClient;

	}

	/**
	* Updates the localized price value for a product variation and a specific localized currency.
	*
	* @param string $currencyCode The three character ISO currency code, such as USD for US Dollars.
	* @param string $productCode The unique, user-defined product code of a product, used throughout  to reference and associate to a product.
	* @param string $responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
	* @param string $variationKey System-generated key that represents the attribute values that uniquely identify a specific product variation.
	* @param ProductVariationFixedPrice $localizedPrice The details of the product variation localized price.
	* @return MozuClient
	*/
	public static function updateProductVariationLocalizedPriceClient($dataViewMode, $localizedPrice, $productCode, $variationKey, $currencyCode, $responseFields =  null)
	{
		$url = ProductVariationUrl::updateProductVariationLocalizedPriceUrl($currencyCode, $productCode, $responseFields, $variationKey);
		$mozuClient = new MozuClient();
		$mozuClient->withResourceUrl($url)->withBody($localizedPrice)->withHeader(Headers::X_VOL_DATAVIEW_MODE ,$dataViewMode);
		return $mozuClient;

	}

	/**
	* Modifies the details of a variation, based on the supplied variation key, for the specified product code.
	*
	* @param string $productCode Merchant-created code that uniquely identifies the product such as a SKU or item number. Once created, the product code is read-only.
	* @param string $responseFields Use this field to include those fields which are not included by default.
	* @param string $variationKey System-generated key that represents the attribute values that uniquely identify a specific product variation.
	* @param ProductVariation $productVariation Properties of a specific product variation.
	* @return MozuClient
	*/
	public static function updateProductVariationClient($dataViewMode, $productVariation, $productCode, $variationKey, $responseFields =  null)
	{
		$url = ProductVariationUrl::updateProductVariationUrl($productCode, $responseFields, $variationKey);
		$mozuClient = new MozuClient();
		$mozuClient->withResourceUrl($url)->withBody($productVariation)->withHeader(Headers::X_VOL_DATAVIEW_MODE ,$dataViewMode);
		return $mozuClient;

	}

	/**
	* Modifies the collection of variations for the specified product code. Because this PUT replaces the existing resource, supply all information necessary to maintain for the product variation.
	*
	* @param string $productCode Merchant-created code that uniquely identifies the product such as a SKU or item number. Once created, the product code is read-only.
	* @param string $responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
	* @param ProductVariationCollection $productVariations Collection of variations configured for a product.
	* @return MozuClient
	*/
	public static function updateProductVariationsClient($dataViewMode, $productVariations, $productCode, $responseFields =  null)
	{
		$url = ProductVariationUrl::updateProductVariationsUrl($productCode, $responseFields);
		$mozuClient = new MozuClient();
		$mozuClient->withResourceUrl($url)->withBody($productVariations)->withHeader(Headers::X_VOL_DATAVIEW_MODE ,$dataViewMode);
		return $mozuClient;

	}

	/**
	* Deletes a variation, based on the supplied variation key, for the specified product code.
	*
	* @param string $productCode Merchant-created code that uniquely identifies the product such as a SKU or item number. Once created, the product code is read-only.
	* @param string $variationKey System-generated key that represents the attribute values that uniquely identify a specific product variation.
	*/
	public static function deleteProductVariationClient($dataViewMode, $productCode, $variationKey)
	{
		$url = ProductVariationUrl::deleteProductVariationUrl($productCode, $variationKey);
		$mozuClient = new MozuClient();
		$mozuClient->withResourceUrl($url)->withHeader(Headers::X_VOL_DATAVIEW_MODE ,$dataViewMode);
		return $mozuClient;

	}

	/**
	* Deletes the localized delta price value for a product variation. Localized delta prices are deltas between two differing monetary conversion amounts between countries, such as US Dollar vs Euro.
	*
	* @param string $currencyCode The three character ISO currency code, such as USD for US Dollars.
	* @param string $productCode The unique, user-defined product code of a product, used throughout  to reference and associate to a product.
	* @param string $variationKey System-generated key that represents the attribute values that uniquely identify a specific product variation.
	*/
	public static function deleteProductVariationLocalizedDeltaPriceClient($dataViewMode, $productCode, $variationKey, $currencyCode)
	{
		$url = ProductVariationUrl::deleteProductVariationLocalizedDeltaPriceUrl($currencyCode, $productCode, $variationKey);
		$mozuClient = new MozuClient();
		$mozuClient->withResourceUrl($url)->withHeader(Headers::X_VOL_DATAVIEW_MODE ,$dataViewMode);
		return $mozuClient;

	}

	/**
	* Deletes the localized price value for a product variation and a specific localized currency.
	*
	* @param string $currencyCode The three character ISO currency code, such as USD for US Dollars.
	* @param string $productCode The unique, user-defined product code of a product, used throughout  to reference and associate to a product.
	* @param string $variationKey System-generated key that represents the attribute values that uniquely identify a specific product variation.
	*/
	public static function deleteProductVariationLocalizedPriceClient($dataViewMode, $productCode, $variationKey, $currencyCode)
	{
		$url = ProductVariationUrl::deleteProductVariationLocalizedPriceUrl($currencyCode, $productCode, $variationKey);
		$mozuClient = new MozuClient();
		$mozuClient->withResourceUrl($url)->withHeader(Headers::X_VOL_DATAVIEW_MODE ,$dataViewMode);
		return $mozuClient;

	}

}

?>


text:
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import SearchBar from './components/searchbar';
import Videolist from './components/videolist';

import YTSearch from "youtube-api-search";

const API_KEY = 'AIzaSyCyFh_8n1hKjU2tFVyVVArpK9OLgtTPZ4c';

//  JONAS-- TESTING STATE MANIPULATION
class App extends Component {
    constructor(props) {
        super(props);
        this.state = {videos: [], search: ''};

        YTSearch({key: API_KEY, term: 'surfing'}), (videos, term) => {
            this.setState({videos});
            this.setState({search:term});
        }

    }

    render() {
        return (
            <div>
                <SearchBar/>
                <Videolist videos={this.state.videos} search={this.state.search}/>
            </div>
        );
    }
}

ReactDOM.render(<App />, document.querySelector(".container"));


text:
var win = Ti.UI.currentWindow;
win.backgroundColor = 'blue';

var shopName = Ti.UI.createLabel({
    top:-345,
    text:'Mike\'s Bikes',
    font:{fontSize:38, fontStyle:'bold'},
    left:70
});
win.add(shopName);

/*
//Create a drop shadow view
var shadow = Ti.UI.createView({
  width:300,
  height:55,
  top:85,
  left:15,
  borderRadius:10,
  opacity:0.5,
  backgroundColor:"black"
});
win.add(shadow);

var shadowPhone = Ti.UI.createView({
  width:300,
  height:30,
  top:160,
  left:15,
  borderRadius:5,
  opacity:0.5,
  backgroundColor:"black"
});
win.add(shadowPhone);
*/

var shopAddrButton = Ti.UI.createButton({
    width:300,
    height: 55,
    top:160,
    boarderRadius:5

});
win.add(shopAddrButton);

var phoneButton = Ti.UI.createButton({
	width:300,
	height:30,
    left:10,
    borderRadius:5,
    top:80
});
win.add(phoneButton);

var urlButton = Ti.UI.createButton({
	width:300,
	height:30,
    left:10,
    borderRadius:5,
    top:120
});
win.add(urlButton);

var shopLogo =  Titanium.UI.createImageView({
    image:'../appicon.png',
    height:57,
    width:57,
    left:8,
    top:5
});
win.add(shopLogo);

// add button labels and text
////////////////////////////////////////////////////////
titlePhoneLabel = Ti.UI.createLabel({
  text:'phone',
  color:'#093EB0',
  top:-230,
  left:20,
  fontweight:'bold'
});
win.add(titlePhoneLabel);

PhoneLabel = Ti.UI.createLabel({
  text:'1-800-492-1266',
  color:'black',
  top:-230,
  left:94
});
win.add(PhoneLabel);

titleUrlLabel = Ti.UI.createLabel({
  text:'website',
  color:'#093EB0',
  top:-150,
  left:20,
  fontweight:'bold'
});
win.add(titleUrlLabel);

urlLabel = Ti.UI.createLabel({
  text:'http://www.mikesbike.com/',
  color:'black',
  top:-150,
  left:94
});
win.add(urlLabel);

titleAddrLabel = Ti.UI.createLabel({
  text:'Address',
  color:'#093EB0',
  top:-68,
  left:20,
  fontweight:'bold'
});
win.add(titleAddrLabel);

addrLabel = Ti.UI.createLabel({
  text:'248 N. Spruce\nCannon Beach OR 97110',
  color:'black',
  top:-45,
  left:94
});
win.add(addrLabel);

detailsLabel = Ti.UI.createLabel({
  text:'Offering touring bicyclists:\n- Full service shop\n- Clothing, parts and accessories',
  color:'black',
  top:165,
  left:20
});
win.add(detailsLabel);

//Add event listners

// first lets dial the phone number when clicked
phoneButton.addEventListener('click', function(){
     Titanium.Platform.openURL('tel:18004921266');
     Ti.API.info('calling phone number...');
});

shopAddrButton.addEventListener('click', function(){
    // place holder for event
    Ti.API.info('Clicked on shop address...');
});

urlButton.addEventListener('click', function(){
    Titanium.Platform.openURL('http://www.mikesbike.com/');
    Ti.API.info('user clicked on shop website address...');
});


text:
<?php

class CompileCest
{
    public function _before(FunctionalTester $I)
    {
        $I->cleanUp();
    }

    public function _after(FunctionalTester $I)
    {
        $I->cleanUp();
    }

    public function getInternalErrorIfAssetsNotDumped(FunctionalTester $I)
    {
        $I->bootKernelWith();
        try {
            $I->amOnPage('/');
            $I->canSeeResponseCodeIs(500);
            $I->see('Manifest file not found');
        } catch (\LogicException $logicException) {
            // handle case for earlier symfony where there is no error listener
        }
    }

    public function getNoErrorIfAssetsAreDumped(FunctionalTester $I)
    {
        $I->bootKernelWith();
        $I->runCommand('maba:webpack:setup');
        $I->seeFileFound(__DIR__ . '/Fixtures/package.json');
        $I->seeFileFound(__DIR__ . '/Fixtures/app/config/webpack.config.js');

        $I->runCommand('maba:webpack:compile');
        $I->seeCommandStatusCode(0);
        $I->seeInCommandDisplay('webpack');
        $I->dontSeeInCommandDisplay('error');

        $I->amOnPage('/');
        $I->canSeeResponseCodeIs(200);
        $I->dontSee('Manifest file not found');

        $I->dontSeeInSource('<link rel="stylesheet"');

        $I->seeInSource('<script src="/compiled/');
        $src = $I->grabAttributeFrom('script', 'src');

        preg_match('#/compiled/(.*)#', $src, $matches);
        $I->seeFileFound(__DIR__ . '/Fixtures/web/compiled/' . $matches[1]);
        $I->openFile(__DIR__ . '/Fixtures/web/compiled/' . $matches[1]);
        $I->canSeeInThisFile('.green');
        $I->canSeeInThisFile('.red');
    }

    public function getErrorFromBundleWithoutErrorSuppressing(FunctionalTester $I)
    {
        $I->bootKernelWith('bundle_error');

        $I->runCommand('maba:webpack:setup');
        $I->runCommand('maba:webpack:compile');
        $I->seeCommandStatusCode(1);
    }

    public function getErrorWithTwigParseError(FunctionalTester $I)
    {
        $I->bootKernelWith('parse_error');

        $I->runCommand('maba:webpack:setup');
        $I->runCommand('maba:webpack:compile');
        $I->seeCommandStatusCode(1);
    }

    public function getErrorWithTwigParseErrorIfIgnoringUnknowns(FunctionalTester $I)
    {
        $I->bootKernelWith('parse_error2');

        $I->runCommand('maba:webpack:setup');
        $I->runCommand('maba:webpack:compile');
        $I->seeCommandStatusCode(1);
    }

    public function getNoErrorWithTwigParseErrorIfSuppressing(FunctionalTester $I)
    {
        $I->bootKernelWith('parse_error_suppress');

        $I->runCommand('maba:webpack:setup');
        $I->runCommand('maba:webpack:compile');
        $I->seeCommandStatusCode(0);
    }

    public function getErrorWithTwigUnknowns(FunctionalTester $I)
    {
        $I->bootKernelWith('unknowns');

        $I->runCommand('maba:webpack:setup');
        $I->runCommand('maba:webpack:compile');
        $I->seeCommandStatusCode(1);
    }

    public function getNoErrorWithTwigUnknownsIfIgnoring(FunctionalTester $I)
    {
        $I->bootKernelWith('unknowns_suppress');

        $I->runCommand('maba:webpack:setup');
        $I->runCommand('maba:webpack:compile');
        $I->seeCommandStatusCode(0);
    }
}


text:
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.

import {
  ArrayExt, IIterator, iter
} from '@phosphor/algorithm';

import {
  JSONExt
} from '@phosphor/coreutils';

import {
  ISignal, Signal
} from '@phosphor/signaling';

import {
  ServerConnection
} from '..';

import {
  TerminalSession
} from './terminal';

/**
 * A terminal session manager.
 */
export
class TerminalManager implements TerminalSession.IManager {
  /**
   * Construct a new terminal manager.
   */
  constructor(options: TerminalManager.IOptions = {}) {
    this.serverSettings = options.serverSettings || ServerConnection.makeSettings();

    // Set up state handling if terminals are available.
    if (TerminalSession.isAvailable()) {
      // Initialize internal data.
      this._readyPromise = this._refreshRunning();

      // Set up polling.
      this._refreshTimer = (setInterval as any)(() => {
        this._refreshRunning();
      }, 10000);
    }
  }

  /**
   * A signal emitted when the running terminals change.
   */
  get runningChanged(): ISignal<this, TerminalSession.IModel[]> {
    return this._runningChanged;
  }

  /**
   * Test whether the terminal manager is disposed.
   */
  get isDisposed(): boolean {
    return this._isDisposed;
  }

  /**
   * The server settings of the manager.
   */
  readonly serverSettings: ServerConnection.ISettings;

  /**
   * Test whether the manger is ready.
   */
  get isReady(): boolean {
    return this._isReady;
  }

  /**
   * Dispose of the resources used by the manager.
   */
  dispose(): void {
    if (this.isDisposed) {
      return;
    }
    this._isDisposed = true;
    clearInterval(this._refreshTimer);
    Signal.clearData(this);
    this._running = [];
  }

  /**
   * A promise that fulfills when the manager is ready.
   */
  get ready(): Promise<void> {
    return this._readyPromise || Promise.reject('Terminals unavailable');
  }

  /**
   * Whether the terminal service is available.
   */
  isAvailable(): boolean {
    return TerminalSession.isAvailable();
  }

  /**
   * Create an iterator over the most recent running terminals.
   *
   * @returns A new iterator over the running terminals.
   */
  running(): IIterator<TerminalSession.IModel> {
    return iter(this._running);
  }

  /**
   * Create a new terminal session.
   *
   * @param options - The options used to connect to the session.
   *
   * @returns A promise that resolves with the terminal instance.
   *
   * #### Notes
   * The manager `serverSettings` will be used unless overridden in the
   * options.
   */
  startNew(options?: TerminalSession.IOptions): Promise<TerminalSession.ISession> {
    return TerminalSession.startNew(this._getOptions(options)).then(session => {
      this._onStarted(session);
      return session;
    });
  }

  /*
   * Connect to a running session.
   *
   * @param name - The name of the target session.
   *
   * @param options - The options used to connect to the session.
   *
   * @returns A promise that resolves with the new session instance.
   *
   * #### Notes
   * The manager `serverSettings` will be used unless overridden in the
   * options.
   */
  connectTo(name: string, options?: TerminalSession.IOptions): Promise<TerminalSession.ISession> {
    return TerminalSession.connectTo(name, this._getOptions(options)).then(session => {
      this._onStarted(session);
      return session;
    });
  }

  /**
   * Shut down a terminal session by name.
   */
  shutdown(name: string): Promise<void> {
    return TerminalSession.shutdown(name, this.serverSettings).then(() => {
      this._onTerminated(name);
    });
  }

  /**
   * Force a refresh of the running sessions.
   *
   * @returns A promise that with the list of running sessions.
   *
   * #### Notes
   * This is not typically meant to be called by the user, since the
   * manager maintains its own internal state.
   */
  refreshRunning(): Promise<void> {
    return this._refreshRunning();
  }

  /**
   * Handle a session terminating.
   */
  private _onTerminated(name: string): void {
    let index = ArrayExt.findFirstIndex(this._running, value => value.name === name);
    if (index !== -1) {
      this._running.splice(index, 1);
      this._runningChanged.emit(this._running.slice());
    }
  }

  /**
   * Handle a session starting.
   */
  private _onStarted(session: TerminalSession.ISession): void {
    let name = session.name;
    let index = ArrayExt.findFirstIndex(this._running, value => value.name === name);
    if (index === -1) {
      this._running.push(session.model);
      this._runningChanged.emit(this._running.slice());
    }
    session.terminated.connect(() => {
      this._onTerminated(name);
    });
  }

  /**
   * Refresh the running sessions.
   */
  private _refreshRunning(): Promise<void> {
    return TerminalSession.listRunning(this.serverSettings).then(running => {
      this._isReady = true;
      if (!JSONExt.deepEqual(running, this._running)) {
        this._running = running.slice();
        this._runningChanged.emit(running);
      }
    });
  }

  /**
   * Get a set of options to pass.
   */
  private _getOptions(options: TerminalSession.IOptions = {}): TerminalSession.IOptions {
    return { ...options, serverSettings: this.serverSettings };
  };

  private _running: TerminalSession.IModel[] = [];
  private _isDisposed = false;
  private _isReady = false;
  private _refreshTimer = -1;
  private _readyPromise: Promise<void>;
  private _runningChanged = new Signal<this, TerminalSession.IModel[]>(this);
}

/**
 * The namespace for TerminalManager statics.
 */
export
namespace TerminalManager {
  /**
   * The options used to initialize a terminal manager.
   */
  export
  interface IOptions {
    /**
     * The server settings used by the manager.
     */
    serverSettings?: ServerConnection.ISettings;
  }
}


text:
serve
=====

A very simple static HTTP server

install
=======

```sh
go get github.com/fkautz/serve
```

usage
=====

```
NAME:
   serve - Simple HTTP Server

USAGE:
   serve [global options] command [command options] [arguments...]

VERSION:
   0.0.0

COMMANDS:
   help, h	Shows a list of commands or help for one command

GLOBAL OPTIONS:
   --dir, -d '.'		Directory to serve
   --address, -a ':8080'	Address to listen on
   --log, -l			Log to stderr
   --help, -h			show help
   --version, -v		print the version
```

examples
========

```sh
# current directory port 8080
serve

# specified directory port 8080
serve -d '/opt/webpage'

# current directory port 8081
serve -a '8081'

# current directory localhost access only port 8082
serve -a '127.0.0.1:8082'

# specified directory localhost port 8081 with logging
serve -d '/opt/webpage' -a '127.0.0.1:8081' -l
```


text:
<?php
/**
 * Piwik - free/libre analytics platform
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 */

namespace Piwik\Plugins\CustomVariables\Commands;

use Piwik\Plugin\ConsoleCommand;
use Piwik\Plugins\CustomVariables\Model;
use Piwik\Tracker\Cache;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 */
class SetNumberOfCustomVariables extends ConsoleCommand
{
    /**
     * @var \Symfony\Component\Console\Helper\ProgressHelper
     */
    private $progress;

    protected function configure()
    {
        $this->setName('customvariables:set-max-custom-variables');
        $this->setDescription('Change the number of available custom variables');
        $this->setHelp("Example:
./console customvariables:set-max-custom-variables 10
=> 10 custom variables will be available in total
");
        $this->addArgument('maxCustomVars', InputArgument::REQUIRED, 'Set the number of max available custom variables');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $numVarsToSet = $this->getNumVariablesToSet($input);
        $numChangesToPerform = $this->getNumberOfChangesToPerform($numVarsToSet);

        if (0 === $numChangesToPerform) {
            $this->writeSuccessMessage($output, array(
                'Your Piwik is already configured for ' . $numVarsToSet . ' custom variables.'
            ));
            return;
        }

        $output->writeln('');
        $output->writeln(sprintf('Configuring Piwik for %d custom variables', $numVarsToSet));

        foreach (Model::getScopes() as $scope) {
            $this->printChanges($scope, $numVarsToSet, $output);
        }

        if (!$this->confirmChange($output)) {
            return;
        }

        $output->writeln('');
        $output->writeln('Starting to apply changes');
        $output->writeln('');

        $this->progress = $this->initProgress($numChangesToPerform, $output);

        foreach (Model::getScopes() as $scope) {
            $this->performChange($scope, $numVarsToSet, $output);
        }

        Cache::clearCacheGeneral();
        $this->progress->finish();

        $this->writeSuccessMessage($output, array(
            'Your Piwik is now configured for ' . $numVarsToSet . ' custom variables.'
        ));
    }

    private function initProgress($numChangesToPerform, OutputInterface $output)
    {
        /** @var \Symfony\Component\Console\Helper\ProgressHelper $progress */
        $progress = $this->getHelperSet()->get('progress');
        $progress->start($output, $numChangesToPerform);

        return $progress;
    }

    private function performChange($scope, $numVarsToSet, OutputInterface $output)
    {
        $model = new Model($scope);
        $numCurrentVars = $model->getCurrentNumCustomVars();
        $numDifference  = $this->getAbsoluteDifference($numCurrentVars, $numVarsToSet);

        if ($numVarsToSet > $numCurrentVars) {
            $this->addCustomVariables($model, $numDifference, $output);
            return;
        }

        $this->removeCustomVariables($model, $numDifference, $output);
    }

    private function getNumVariablesToSet(InputInterface $input)
    {
        $maxCustomVars = $input->getArgument('maxCustomVars');

        if (!is_numeric($maxCustomVars)) {
            throw new \InvalidArgumentException('The number of available custom variables has to be a number');
        }

        $maxCustomVars = (int) $maxCustomVars;

        if ($maxCustomVars < 5) {
            throw new \InvalidArgumentException('There has to be at least five custom variables');
        }

        return $maxCustomVars;
    }

    private function confirmChange(OutputInterface $output)
    {
        $output->writeln('');

        $dialog = $this->getHelperSet()->get('dialog');
        return $dialog->askConfirmation(
            $output,
            '<question>Are you sure you want to perform these actions? (y/N)</question>',
            false
        );
    }

    private function printChanges($scope, $numVarsToSet, OutputInterface $output)
    {
        $model                = new Model($scope);
        $scopeName            = $model->getScopeName();
        $highestIndex         = $model->getHighestCustomVarIndex();
        $numCurrentCustomVars = $model->getCurrentNumCustomVars();
        $numVarsDifference    = $this->getAbsoluteDifference($numCurrentCustomVars, $numVarsToSet);

        $output->writeln('');
        $output->writeln(sprintf('Scope "%s"', $scopeName));

        if ($numVarsToSet > $numCurrentCustomVars) {

            $indexes = $highestIndex + 1;
            if (1 !== $numVarsDifference) {
                $indexes .= ' - ' . ($highestIndex + $numVarsDifference);
            }

            $output->writeln(
                sprintf('%s new custom variables having the index(es) %s will be ADDED', $numVarsDifference, $indexes)
            );

        } elseif ($numVarsToSet < $numCurrentCustomVars) {

            $indexes = $highestIndex - $numVarsDifference + 1;

            if (1 !== $numVarsDifference) {
                $indexes .= ' - ' . $highestIndex;
            }

            $output->writeln(
                sprintf("%s existing custom variables having the index(es) %s will be REMOVED.", $numVarsDifference, $indexes)
            );
            $output->writeln('<comment>This is an irreversible change</comment>');
        }
    }

    private function getAbsoluteDifference($currentNumber, $numberToSet)
    {
        return abs($numberToSet - $currentNumber);
    }

    private function removeCustomVariables(Model $model, $numberOfVarsToRemove, OutputInterface $output)
    {
        for ($index = 0; $index < $numberOfVarsToRemove; $index++) {
            $indexRemoved = $model->removeCustomVariable();
            $this->progress->advance();
            $output->writeln('  <info>Removed a variable in scope "' . $model->getScopeName() .  '" having the index ' . $indexRemoved . '</info>');
        }
    }

    private function addCustomVariables(Model $model, $numberOfVarsToAdd, OutputInterface $output)
    {
        for ($index = 0; $index < $numberOfVarsToAdd; $index++) {
            $indexAdded = $model->addCustomVariable();
            $this->progress->advance();
            $output->writeln('  <info>Added a variable in scope "' . $model->getScopeName() .  '" having the index ' . $indexAdded . '</info>');
        }
    }

    private function getNumberOfChangesToPerform($numVarsToSet)
    {
        $numChangesToPerform = 0;

        foreach (Model::getScopes() as $scope) {
            $model = new Model($scope);
            $numCurrentCustomVars = $model->getCurrentNumCustomVars();
            $numChangesToPerform += $this->getAbsoluteDifference($numCurrentCustomVars, $numVarsToSet);
        }

        return $numChangesToPerform;
    }
}


text:
// Fraunhofer Institute for Computer Graphics Research (IGD)
// Department Information Visualization and Visual Analytics
//
// Copyright (c) Fraunhofer IGD. All rights reserved.
//
// This source code is property of the Fraunhofer IGD and underlies
// copyright restrictions. It may only be used with explicit
// permission from the respective owner.

package colormaps;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.Timer;

import de.fhg.igd.iva.colormaps.Colormap;
import de.fhg.igd.iva.colormaps.impl.FourCornersAnchorRBGY;
import de.fhg.igd.iva.colormaps.impl.Ziegler;

/**
 * Opens a small JFrame window that draws a colormap
 * @author Martin Steiger
 */
public class ColorMapTestApp
{
	/**
	 * @param args ignored
	 */
	public static void main(String[] args)
	{
		final JFrame frame = new JFrame("Colormap Testing Application");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JComponent comp = new JComponent()
        {
			private static final long serialVersionUID = -5658146923830045505L;

			@Override
			public void paint(Graphics g)
			{
//				RGBColorMap2DKonstanzLike cm = new RGBColorMap2DKonstanzLike();
//				Colormap cm = new Ziegler();
				Colormap cm = new FourCornersAnchorRBGY();

				double width = this.getWidth();
				double height = this.getHeight();

				int bs = 2;

				for (int x = bs / 2; x < width; x += bs)
				{
					for (int y = bs / 2; y < height; y += bs)
					{
						Color c = cm.getColor((float)(x / width), (float)(y / height));
						g.setColor(c);
						g.fillRect(x - bs / 2, y - bs / 2, bs, bs);
					}
				}
			}
		};

		comp.setPreferredSize(new Dimension(512, 512));

		frame.add(comp);

		// repaint continuously to reflect code changes ^^
        Timer t = new Timer(500, new ActionListener()
		{
			@Override
			public void actionPerformed(ActionEvent e)
			{
				frame.invalidate();
				frame.repaint();
				System.out.println("REPAINT");
			}
		});

        t.start();
        frame.pack();
		frame.setVisible(true);
	}

}


text:
package com.aqua.jsystemobject.handlers;

import org.netbeans.jemmy.operators.DialogOperator;
import org.netbeans.jemmy.operators.JButtonOperator;
import org.netbeans.jemmy.operators.JTextFieldOperator;

import utils.DBPropertiesKeys;

import com.aqua.jsystemobject.RunnerComponentChooser;

public class JReporterHandler extends BaseHandler {
	String DBPropertiesDialogTitle = "Database Properties";
	public int pressLogButton() throws Exception{
		JButtonOperator btnOp = jemmyOperation.getButtonOperator(mainFrame, jmap.getLogButton());
		btnOp.push();
		return 0;
	}

	public boolean isReportsButtonEnabled() throws Exception{
		JButtonOperator op = jemmyOperation.getButtonOperator(mainFrame, jmap.getOpenReportApplicationButton());
		return op.isEnabled();
	}

	/**
	 * gets the relevant compnent's name from dbproperties dialog
	 * according to the specified key.
	 * @param key
	 * @return
	 */
	private String getComponantNamebyKey(String key){
		if(key.equals(DBPropertiesKeys.BROWSERPORT.toString())){
			return jmap.getDbPropertiesPortTextField();
		}
		if(key.equals(DBPropertiesKeys.DBDRIVER.toString())){
			return jmap.getDbPropertiesDriverCombobox();
		}
		if(key.equals(DBPropertiesKeys.DBHOST.toString())){
			return jmap.getDbPropertiesHostTextField();
		}
		if(key.equals(DBPropertiesKeys.DBNAME.toString())){
			return jmap.getDbPropertiesNameTextField();
		}
		if(key.equals(DBPropertiesKeys.DBTYPE.toString())){
			return jmap.getDbPropertiesTypeJComboBox();
		}
		if(key.equals(DBPropertiesKeys.PASSWORD.toString())){
			return jmap.getDbPropertiesPasswordField();
		}
		if(key.equals(DBPropertiesKeys.SERVERIP.toString())){
			return jmap.getDbPropertiesServerIpTextField();
		}
		if(key.equals(DBPropertiesKeys.USER.toString())){
			return jmap.getDbPropertiesUserTextField();
		}
		else{
			return null;
		}
	}
}


text:
namespace zap { namespace maths { namespace geometry {

template <typename T>
struct rect {
    rect() = default;
    rect(const rect& rhs) = default;
    rect(const T& left, const T& right, const T& bottom, const T& top) :
            left(left), right(right), bottom(bottom), top(top) { }
    rect(const vec2<T> horz, const vec2<T> vert) : left(horz.x), right(horz.y), bottom(vert.x), top(vert.y) { }

    rect& operator=(const rect& rhs) = default;

    void set(const T& left, const T& right, const T& bottom, const T& top) {
        this->left = left; this->right = right; this->bottom = bottom; this->top = top;
    }

    T width() const { return right - left; }
    T height() const { return top - bottom; }

    void translate(T x, T y) {
        left += x; right += x;
        bottom += y; top += y;
    }

    void translate(const vec2<T>& v) { translate(v.x, v.y); }

    bool intersection(T x, T y) const { return left <= x && x <= right && bottom <= y && y <= top; }
    bool intersection(const vec2<T>& P) const { return intersection(P.x, P.y); }
    bool intersection(const rect& rhs, rect* overlap=nullptr) const {
        rect test{
                std::max(left, rhs.left), std::min(right, rhs.right),
                std::min(bottom, rhs.bottom), std::max(top, rhs.top)
        };
        if(test.left < test.right && test.bottom < test.top) {
            if(overlap) *overlap = test;
            return true;
        }
        return false;
    }

    bool contains(const rect& rhs) const {
        return left <= rhs.left && right >= rhs.right && bottom <= rhs.bottom && top >= rhs.top;
    }

    vec2<T> centre() const { return vec2<T>((right-left)/2, (top-bottom)/2); }
    vec2<T> left_bottom() const { return vec2<T>(left, bottom); }
    vec2<T> right_bottom() const { return vec2<T>(right, bottom); }
    vec2<T> left_top() const { return vec2<T>(left, top); }
    vec2<T> right_top() const { return vec2<T>(right, top); }

    T left, right, bottom, top;
};

using rectb = rect<int8_t>;
using rects = rect<int16_t>;
using recti = rect<int32_t>;
using rectf = rect<float>;

}}}

#endif //ZAP_RECT_HPP