text:
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License.  You may obtain a copy
// of the License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
namespace Microsoft.Hadoop.Avro.Serializers
{
    using System.Diagnostics.CodeAnalysis;
    using System.Linq.Expressions;
    using Microsoft.Hadoop.Avro.Schema;

    /// <summary>
    /// Serializes C# long/ulong into Avro long.
    /// </summary>
    internal sealed class LongSerializer : ObjectSerializerBase<LongSchema>
    {
        public LongSerializer(LongSchema schema) : base(schema)
        {
        }

        protected override Expression BuildSerializerSafe(Expression encoder, Expression value)
        {
            return Expression.Call(
                encoder,
                this.Encode<long>(),
                new Expression[] { Expression.Convert(value, typeof(long)) });
        }

        protected override Expression BuildDeserializerSafe(Expression decoder)
        {
            return Expression.Convert(
                Expression.Call(decoder, this.Decode<long>()),
                this.Schema.RuntimeType);
        }

        protected override Expression BuildSkipperSafe(Expression decoder)
        {
            return Expression.Call(decoder, this.Skip<long>());
        }

        [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", Justification = "Internal + done in base class.")]
        protected override void SerializeSafe(IEncoder encoder, object @object)
        {
            encoder.Encode((long)@object);
        }

        [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", Justification = "Internal + done in base class.")]
        protected override object DeserializeSafe(IDecoder decoder)
        {
            return decoder.DecodeLong();
        }

        [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", Justification = "Internal + done in base class.")]
        protected override void SkipSafe(IDecoder decoder)
        {
            decoder.SkipLong();
        }
    }
}


text:
Transform /^the number "([^\"]*)"$/ do |to_convert|
  to_convert.to_i
end

When /^I convert (the number "[^\"]*") to LCD$/ do |number|
  @converted = NumberToLcd.convert(number)
end

Then /^I should get the following representation$/ do |lcd_representation|
  @converted.should == lcd_representation
end

redpajama_set_name: RedPajamaGithub


text:
package org.orekit.propagation.analytical;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.math3.exception.MathIllegalArgumentException;
import org.apache.commons.math3.geometry.euclidean.threed.Vector3D;
import org.apache.commons.math3.util.FastMath;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.orekit.Utils;
import org.orekit.bodies.CelestialBodyFactory;
import org.orekit.errors.OrekitException;
import org.orekit.errors.OrekitMessages;
import org.orekit.frames.Frame;
import org.orekit.frames.FramesFactory;
import org.orekit.orbits.EquinoctialOrbit;
import org.orekit.orbits.KeplerianOrbit;
import org.orekit.orbits.Orbit;
import org.orekit.orbits.PositionAngle;
import org.orekit.propagation.AdditionalStateProvider;
import org.orekit.propagation.Propagator;
import org.orekit.propagation.SpacecraftState;
import org.orekit.time.AbsoluteDate;
import org.orekit.time.DateComponents;
import org.orekit.time.TimeComponents;
import org.orekit.time.TimeScale;
import org.orekit.time.TimeScalesFactory;
import org.orekit.utils.PVCoordinates;

public class TabulatedEphemerisTest {

    @Test
    public void testInterpolation() throws ParseException, OrekitException {

        double mass = 2500;
        double a = 7187990.1979844316;
        double e = 0.5e-4;
        double i = 1.7105407051081795;
        double omega = 1.9674147913622104;
        double OMEGA = FastMath.toRadians(261);
        double lv = 0;

        final AbsoluteDate initDate = new AbsoluteDate(new DateComponents(2004, 01, 01),
                                                       TimeComponents.H00,
                                                       TimeScalesFactory.getUTC());
        final AbsoluteDate finalDate = new AbsoluteDate(new DateComponents(2004, 01, 02),
                                                        TimeComponents.H00,
                                                        TimeScalesFactory.getUTC());
        double deltaT = finalDate.durationFrom(initDate);

        Orbit transPar = new KeplerianOrbit(a, e, i, omega, OMEGA, lv, PositionAngle.TRUE,
                                            FramesFactory.getEME2000(), initDate, mu);

        int nbIntervals = 720;
        EcksteinHechlerPropagator eck =
            new EcksteinHechlerPropagator(transPar, mass,
                                          ae, mu, c20, c30, c40, c50, c60);
        AdditionalStateProvider provider = new AdditionalStateProvider() {

            public String getName() {
                return "dt";
            }

           public double[] getAdditionalState(SpacecraftState state) {
                return new double[] { state.getDate().durationFrom(initDate) };
            }
        };
        eck.addAdditionalStateProvider(provider);
        try {
            eck.addAdditionalStateProvider(provider);
            Assert.fail("an exception should have been thrown");
        } catch (OrekitException oe) {
            Assert.assertEquals(OrekitMessages.ADDITIONAL_STATE_NAME_ALREADY_IN_USE,
                                oe.getSpecifier());
        }
        List<SpacecraftState> tab = new ArrayList<SpacecraftState>(nbIntervals + 1);
        for (int j = 0; j<= nbIntervals; j++) {
            AbsoluteDate current = initDate.shiftedBy((j * deltaT) / nbIntervals);
            tab.add(eck.propagate(current));
        }

        try {
            new Ephemeris(tab, nbIntervals + 2);
            Assert.fail("an exception should have been thrown");
        } catch (MathIllegalArgumentException miae) {
            // expected
        }
        Ephemeris te = new Ephemeris(tab, 2);

        Assert.assertEquals(0.0, te.getMaxDate().durationFrom(finalDate), 1.0e-9);
        Assert.assertEquals(0.0, te.getMinDate().durationFrom(initDate), 1.0e-9);

        checkEphemerides(eck, te, initDate.shiftedBy(3600),  1.0e-9, true);
        checkEphemerides(eck, te, initDate.shiftedBy(3660), 30, false);
        checkEphemerides(eck, te, initDate.shiftedBy(3720),  1.0e-9, true);

    }

    @Test
    public void testPiWraping() throws OrekitException {

        TimeScale utc= TimeScalesFactory.getUTC();
        Frame frame = FramesFactory.getEME2000();
        double mu=CelestialBodyFactory.getEarth().getGM();
        AbsoluteDate t0 = new AbsoluteDate(2009, 10, 29, 0, 0, 0, utc);

        AbsoluteDate t1 = new AbsoluteDate(t0, 1320.0);
        Vector3D p1 = new Vector3D(-0.17831296727974E+08,  0.67919502669856E+06, -0.16591008368477E+07);
        Vector3D v1 = new Vector3D(-0.38699705630724E+04, -0.36209408682762E+04, -0.16255053872347E+03);
        SpacecraftState s1 = new SpacecraftState(new EquinoctialOrbit(new PVCoordinates(p1, v1), frame, t1, mu));

        AbsoluteDate t2 = new AbsoluteDate(t0, 1440.0);
        Vector3D p2 = new Vector3D(-0.18286942572033E+08,  0.24442124296930E+06, -0.16777961761695E+07);
        Vector3D v2 = new Vector3D(-0.37252897467918E+04, -0.36246628128896E+04, -0.14917724596280E+03);
        SpacecraftState s2 = new SpacecraftState(new EquinoctialOrbit(new PVCoordinates(p2, v2), frame, t2, mu));

        AbsoluteDate t3 = new AbsoluteDate(t0, 1560.0);
        Vector3D p3 = new Vector3D(-0.18725635245837E+08, -0.19058407701834E+06, -0.16949352249614E+07);
        Vector3D v3 = new Vector3D(-0.35873348682393E+04, -0.36248828501784E+04, -0.13660045394149E+03);
        SpacecraftState s3 = new SpacecraftState(new EquinoctialOrbit(new PVCoordinates(p3, v3), frame, t3, mu));

        Ephemeris ephem= new Ephemeris(Arrays.asList(s1, s2, s3), 2);

        AbsoluteDate tA = new AbsoluteDate(t0, 24 * 60);
        Vector3D pA = ephem.propagate(tA).getPVCoordinates(frame).getPosition();
        Assert.assertEquals(1.766,
                            Vector3D.distance(pA, s1.shiftedBy(tA.durationFrom(s1.getDate())).getPVCoordinates(frame).getPosition()),
                            1.0e-3);
        Assert.assertEquals(0.000,
                            Vector3D.distance(pA, s2.shiftedBy(tA.durationFrom(s2.getDate())).getPVCoordinates(frame).getPosition()),
                            1.0e-3);
        Assert.assertEquals(1.556,
                            Vector3D.distance(pA, s3.shiftedBy(tA.durationFrom(s3.getDate())).getPVCoordinates(frame).getPosition()),
                            1.0e-3);

        AbsoluteDate tB = new AbsoluteDate(t0, 25 * 60);
        Vector3D pB = ephem.propagate(tB).getPVCoordinates(frame).getPosition();
        Assert.assertEquals(2.646,
                            Vector3D.distance(pB, s1.shiftedBy(tB.durationFrom(s1.getDate())).getPVCoordinates(frame).getPosition()),
                            1.0e-3);
        Assert.assertEquals(2.619,
                            Vector3D.distance(pB, s2.shiftedBy(tB.durationFrom(s2.getDate())).getPVCoordinates(frame).getPosition()),
                            1.0e-3);
        Assert.assertEquals(2.632,
                            Vector3D.distance(pB, s3.shiftedBy(tB.durationFrom(s3.getDate())).getPVCoordinates(frame).getPosition()),
                            1.0e-3);

        AbsoluteDate tC = new AbsoluteDate(t0, 26 * 60);
        Vector3D pC = ephem.propagate(tC).getPVCoordinates(frame).getPosition();
        Assert.assertEquals(6.851,
                            Vector3D.distance(pC, s1.shiftedBy(tC.durationFrom(s1.getDate())).getPVCoordinates(frame).getPosition()),
                            1.0e-3);
        Assert.assertEquals(1.605,
                            Vector3D.distance(pC, s2.shiftedBy(tC.durationFrom(s2.getDate())).getPVCoordinates(frame).getPosition()),
                            1.0e-3);
        Assert.assertEquals(0.000,
                            Vector3D.distance(pC, s3.shiftedBy(tC.durationFrom(s3.getDate())).getPVCoordinates(frame).getPosition()),
                            1.0e-3);

    }

    @Test
    public void testGetFrame() throws MathIllegalArgumentException, IllegalArgumentException, OrekitException {
        // setup
        Frame frame = FramesFactory.getICRF();
        AbsoluteDate date = AbsoluteDate.JULIAN_EPOCH;
        // create ephemeris with 2 arbitrary points
        SpacecraftState state = new SpacecraftState(
                new KeplerianOrbit(1e9, 0.01, 1, 1, 1, 1, PositionAngle.TRUE, frame, date, mu));
        Ephemeris ephem = new Ephemeris(Arrays.asList(state, state.shiftedBy(1)), 2);

        // action + verify
        Assert.assertSame(ephem.getFrame(), frame);
    }

    private void checkEphemerides(Propagator eph1, Propagator eph2, AbsoluteDate date,
                                  double threshold, boolean expectedBelow)
        throws OrekitException {

        Assert.assertEquals(eph1.getManagedAdditionalStates().length, eph2.getManagedAdditionalStates().length);
        for (String name : eph1.getManagedAdditionalStates()) {
            Assert.assertTrue(eph2.isAdditionalStateManaged(name));
        }
        SpacecraftState state1 = eph1.propagate(date);
        SpacecraftState state2 = eph2.propagate(date);
        double maxError = FastMath.abs(state1.getA() - state2.getA());
        maxError = FastMath.max(maxError, FastMath.abs(state1.getEquinoctialEx() - state2.getEquinoctialEx()));
        maxError = FastMath.max(maxError, FastMath.abs(state1.getEquinoctialEy() - state2.getEquinoctialEy()));
        maxError = FastMath.max(maxError, FastMath.abs(state1.getHx() - state2.getHx()));
        maxError = FastMath.max(maxError, FastMath.abs(state1.getHy() - state2.getHy()));
        maxError = FastMath.max(maxError, FastMath.abs(state1.getLv() - state2.getLv()));
        for (String name : eph1.getManagedAdditionalStates()) {
            double[] add1 = state1.getAdditionalState(name);
            double[] add2 = state2.getAdditionalState(name);
            Assert.assertEquals(add1.length, add2.length);
            for (int i = 0; i < add1.length; ++i) {
                maxError = FastMath.max(maxError, FastMath.abs(add1[i] - add2[i]));
            }
            Assert.assertTrue(eph2.isAdditionalStateManaged(name));
        }
        if (expectedBelow) {
            Assert.assertTrue(maxError <= threshold);
        } else {
            Assert.assertTrue(maxError >= threshold);
        }
    }

    @Before
    public void setUp() {
        Utils.setDataRoot("regular-data");
        mu  = 3.9860047e14;
        ae  = 6.378137e6;
        c20 = -1.08263e-3;
        c30 = 2.54e-6;
        c40 = 1.62e-6;
        c50 = 2.3e-7;
        c60 = -5.5e-7;
    }

    @After
    public void tearDown() {
        mu  = Double.NaN;
        ae  = Double.NaN;
        c20 = Double.NaN;
        c30 = Double.NaN;
        c40 = Double.NaN;
        c50 = Double.NaN;
        c60 = Double.NaN;
    }

    private double mu;
    private double ae;
    private double c20;
    private double c30;
    private double c40;
    private double c50;
    private double c60;

}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".TranscoderActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/select_video_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="Select Video File" />

    <ProgressBar
        android:id="@+id/progress_bar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:progress="0" />

    <Button
        android:id="@+id/cancel_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:enabled="false"
        android:text="cancel" />

</LinearLayout>


text:
namespace Framework.Templates.Impl
{
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Diagnostics;
    using System.IO;
    using System.Linq;
    using System.Text.RegularExpressions;

    using Framework.Ioc;

    /// -------------------------------------------------------------------------------------------------
    /// <summary>
    ///     Mustache Template engine.
    /// </summary>
    /// -------------------------------------------------------------------------------------------------
    [InjectBind(typeof(ITemplateEngine), LifetimeType.Singleton)]
    public class TemplateEngine : ITemplateEngine
    {
        private static readonly Regex ExpressionParamRegex1 = new Regex(
            @"([\w]+)\s*=\'\s*([^']*)\'\s*",
            RegexOptions.Compiled | RegexOptions.CultureInvariant);

        private static readonly Regex ExpressionParamRegex2 = new Regex(
            @"([\w]+)\s*=""\s*([^""]*)""\s*",
            RegexOptions.Compiled | RegexOptions.CultureInvariant);

        private static readonly Regex ExpressionParamRegex3 = new Regex(
            @"([\w]+)\s*=\s*(\[.*\])\s*",
            RegexOptions.Compiled | RegexOptions.CultureInvariant);

        private static readonly Regex ExpressionParamRegex4 = new Regex(
            @"([\w]+)\s*=\s*(\{.*\})\s*",
            RegexOptions.Compiled | RegexOptions.CultureInvariant);

        private static readonly Regex ExpressionRegex = new Regex(
            @"^([\w]+)\s*\:\s*([\w]+)\s*(.*)\s*",
            RegexOptions.Compiled | RegexOptions.CultureInvariant);

        private static readonly Regex MarkerRegex = new Regex(
            @"(\s)*\{\{([{]?.+?\}?)\}\}",
            RegexOptions.Compiled | RegexOptions.CultureInvariant);

        private static readonly Regex StripRegex = new Regex(
            @"\G[\r\t\v ]+\n",
            RegexOptions.Compiled | RegexOptions.CultureInvariant);

        /// -------------------------------------------------------------------------------------------------
        /// <summary>
        ///     Compiles the template and return as <see cref="ICompiledTemplate" />.
        /// </summary>
        /// <param name="template">
        ///     The template.
        /// </param>
        /// <returns>
        ///     An Instance of <see cref="ICompiledTemplate" />.
        /// </returns>
        /// -------------------------------------------------------------------------------------------------
        public ICompiledTemplate Compile(string template)
        {
            IEnumerable<ITemplatePart> parts = Scan(template);
            return new CompiledTemplate(parts);
        }

        /// -------------------------------------------------------------------------------------------------
        /// <summary>
        ///     Compiles the template and return as <see cref="ICompiledTemplate" />.
        /// </summary>
        /// <remarks>
        ///     Anwar Javed, 09/17/2013 12:51 PM.
        /// </remarks>
        /// <param name="templatePath">
        ///     Full pathname of the template file.
        /// </param>
        /// <returns>
        ///     An Instance of <see cref="ICompiledTemplate" />.
        /// </returns>
        /// -------------------------------------------------------------------------------------------------
        public ICompiledTemplate CompileFile(string templatePath)
        {
            return this.Compile(File.ReadAllText(templatePath));
        }

        [DebuggerStepThrough]
        internal static IEnumerable<ITemplatePart> Scan(string template)
        {
            int index = 0;
            Match match;

            var partStack = new Stack<SectionInfo>();

            while ((match = MarkerRegex.Match(template, index)).Success)
            {
                string literal = template.Substring(index, match.Index - index);

                if (!string.IsNullOrWhiteSpace(literal))
                {
                    if (partStack.Count == 0)
                    {
                        yield return new LiteralPart(literal);
                    }
                    else
                    {
                        partStack.Peek().Parts.Add(new LiteralPart(literal));
                    }
                }

                string whiteSpace = match.Groups[1].Value;

                if (whiteSpace.Length > 0)
                {
                    if (partStack.Count == 0)
                    {
                        index += whiteSpace.Length;
                        yield return new LiteralPart(whiteSpace);
                    }
                    else
                    {
                        partStack.Peek().Parts.Add(new LiteralPart(whiteSpace));
                    }
                }

                string marker = match.Groups[2].Value.Trim();

                bool stripOutNewLine = false;

                if (marker[0] == '#')
                {
                    string sectionName = marker.Substring(1).Trim();
                    partStack.Push(new SectionInfo(sectionName, false, false));

                    stripOutNewLine = true;
                }
                else if (marker[0] == '^')
                {
                    string sectionName = marker.Substring(1).Trim();
                    if (ExpressionRegex.IsMatch(sectionName))
                    {
                        if (sectionName.EndsWith("/"))
                        {
                            var section = new SectionInfo(sectionName.Substring(0, sectionName.Length - 1), false, true);
                            if (partStack.Count == 0)
                            {
                                yield return
                                    new ExpressionPart(
                                        section.Name,
                                        true,
                                        section.Properties,
                                        section.JsonKeys,
                                        section.Parts);
                            }
                            else
                            {
                                partStack.Peek()
                                    .Parts.Add(
                                        new ExpressionPart(
                                            section.Name,
                                            true,
                                            section.Properties,
                                            section.JsonKeys,
                                            section.Parts));
                            }
                        }
                        else
                        {
                            partStack.Push(new SectionInfo(sectionName, true, false));
                            stripOutNewLine = true;
                        }
                    }
                    else
                    {
                        partStack.Push(new SectionInfo(sectionName, true, false));
                        stripOutNewLine = true;
                    }
                }
                else if (marker[0] == '/')
                {
                    string sectionName = marker.Substring(1).Trim();
                    SectionInfo sectionInfo = partStack.Pop();

                    if (sectionInfo.Name != sectionName)
                    {
                        throw new ArgumentOutOfRangeException(
                            "Expecting section:" + sectionInfo.Name + " at position " + index);
                    }

                    if (ExpressionRegex.IsMatch(sectionName))
                    {
                        if (partStack.Count == 0)
                        {
                            yield return
                                new ExpressionPart(
                                    sectionName,
                                    sectionInfo.Inverted,
                                    sectionInfo.Properties,
                                    sectionInfo.JsonKeys,
                                    sectionInfo.Parts);
                        }
                        else
                        {
                            partStack.Peek()
                                .Parts.Add(
                                    new ExpressionPart(
                                        sectionName,
                                        sectionInfo.Inverted,
                                        sectionInfo.Properties,
                                        sectionInfo.JsonKeys,
                                        sectionInfo.Parts));
                        }
                    }
                    else
                    {
                        if (partStack.Count == 0)
                        {
                            yield return new SectionPart(sectionName, sectionInfo.Inverted, sectionInfo.Parts);
                        }
                        else
                        {
                            partStack.Peek()
                                .Parts.Add(new SectionPart(sectionName, sectionInfo.Inverted, sectionInfo.Parts));
                        }
                    }

                    stripOutNewLine = true;
                }
                else if (marker[0] == '>')
                {
                    yield return new TemplateInclude(marker.Substring(1).Trim());
                    stripOutNewLine = true;
                }
                else if (marker[0] != '!')
                {
                    if (ExpressionRegex.IsMatch(marker))
                    {
                        marker = marker.Trim();
                        if (marker.EndsWith("/"))
                        {
                            var section = new SectionInfo(marker.Substring(0, marker.Length - 1), false, true);
                            if (partStack.Count == 0)
                            {
                                yield return
                                    new ExpressionPart(
                                        section.Name,
                                        false,
                                        section.Properties,
                                        section.JsonKeys,
                                        section.Parts);
                            }
                            else
                            {
                                partStack.Peek()
                                    .Parts.Add(
                                        new ExpressionPart(
                                            section.Name,
                                            false,
                                            section.Properties,
                                            section.JsonKeys,
                                            section.Parts));
                            }
                        }
                        else
                        {
                            var section = new SectionInfo(marker, false, true);
                            partStack.Push(section);
                            stripOutNewLine = true;
                        }
                    }
                    else
                    {
                        if (partStack.Count == 0)
                        {
                            yield return new VariablePart(marker.Trim());
                        }
                        else
                        {
                            partStack.Peek().Parts.Add(new VariablePart(marker.Trim()));
                        }
                    }
                }

                index = match.Index + match.Length;

                Match s;
                if (stripOutNewLine && (s = StripRegex.Match(template, index)).Success)
                {
                    index += s.Length;
                }
            }

            if (index < template.Length)
            {
                yield return new LiteralPart(template.Substring(index));
            }
        }

        private class SectionInfo
        {
            private readonly bool inverted;

            private readonly Collection<string> jsonKeys;

            private readonly string name;

            private readonly Collection<ITemplatePart> parts;

            private readonly IDictionary<string, object> properties;

            public SectionInfo(string name, bool inverted, bool expression)
            {
                this.name = name;
                this.inverted = inverted;
                this.parts = new Collection<ITemplatePart>();
                this.properties = new Dictionary<string, object>();
                this.jsonKeys = new Collection<string>();
                if (expression)
                {
                    Match match = ExpressionRegex.Match(name);

                    if (match.Success)
                    {
                        this.name = match.Groups[1].Value.Trim() + ":" + match.Groups[2].Value.Trim();
                        string values = match.Groups[3].Value.Trim();

                        IEnumerable<KeyValuePair<string, string>> attributesMatches =
                            ExpressionParamRegex1.Matches(values)
                                .Cast<Match>()
                                .Concat(ExpressionParamRegex2.Matches(values).Cast<Match>())
                                .Where(
                                    x =>
                                    x.Success && !string.IsNullOrWhiteSpace(x.Groups[1].Value)
                                    && !string.IsNullOrWhiteSpace(x.Groups[2].Value))
                                .Select(x => new KeyValuePair<string, string>(x.Groups[1].Value, x.Groups[2].Value));
                        IEnumerable<KeyValuePair<string, string>> jsonMatches =
                            ExpressionParamRegex3.Matches(values)
                                .Cast<Match>()
                                .Concat(ExpressionParamRegex4.Matches(values).Cast<Match>())
                                .Where(
                                    x =>
                                    x.Success && !string.IsNullOrWhiteSpace(x.Groups[1].Value)
                                    && !string.IsNullOrWhiteSpace(x.Groups[2].Value))
                                .Select(x => new KeyValuePair<string, string>(x.Groups[1].Value, x.Groups[2].Value));

                        foreach (var attributesMatch in attributesMatches)
                        {
                            if (!this.properties.ContainsKey(attributesMatch.Key))
                            {
                                this.properties.Add(attributesMatch.Key, attributesMatch.Value);
                            }
                        }

                        foreach (var jsonMatch in jsonMatches)
                        {
                            if (!this.jsonKeys.Contains(jsonMatch.Key))
                            {
                                this.jsonKeys.Add(jsonMatch.Key);
                                this.properties.Add(jsonMatch.Key, jsonMatch.Value);
                            }
                        }
                    }
                }
            }

            public bool Inverted
            {
                get
                {
                    return this.inverted;
                }
            }

            public ICollection<string> JsonKeys
            {
                get
                {
                    return this.jsonKeys;
                }
            }

            public string Name
            {
                get
                {
                    return this.name;
                }
            }

            public Collection<ITemplatePart> Parts
            {
                get
                {
                    return this.parts;
                }
            }

            public IDictionary<string, object> Properties
            {
                get
                {
                    return this.properties;
                }
            }
        }
    }
}


text:
"""runpy.py - locating and running Python code using the module namespace

Provides support for locating and running Python scripts using the Python
module namespace instead of the native filesystem.

This allows Python code to play nicely with non-filesystem based PEP 302
importers when locating support scripts as well as when importing modules.
"""
# Written by Nick Coghlan <ncoghlan at gmail.com>
#    to implement PEP 338 (Executing Modules as Scripts)

import sys
import imp
try:
    from imp import get_loader
except ImportError:
    from pkgutil import get_loader

__all__ = [
    "run_module",
]

def _run_code(code, run_globals, init_globals=None,
              mod_name=None, mod_fname=None,
              mod_loader=None, pkg_name=None):
    """Helper for _run_module_code"""
    if init_globals is not None:
        run_globals.update(init_globals)
    run_globals.update(__name__ = mod_name,
                       __file__ = mod_fname,
                       __loader__ = mod_loader,
                       __package__ = pkg_name)
    exec(code, run_globals)
    return run_globals

def _run_module_code(code, init_globals=None,
                    mod_name=None, mod_fname=None,
                    mod_loader=None, pkg_name=None):
    """Helper for run_module"""
    # Set up the top level namespace dictionary
    temp_module = imp.new_module(mod_name)
    mod_globals = temp_module.__dict__
    # Modify sys.argv[0] and sys.module[mod_name]
    saved_argv0 = sys.argv[0]
    restore_module = mod_name in sys.modules
    if restore_module:
        saved_module = sys.modules[mod_name]
    sys.argv[0] = mod_fname
    sys.modules[mod_name] = temp_module
    try:
        _run_code(code, mod_globals, init_globals,
                    mod_name, mod_fname,
                    mod_loader, pkg_name)
    finally:
        sys.argv[0] = saved_argv0
        if restore_module:
            sys.modules[mod_name] = saved_module
        else:
            del sys.modules[mod_name]
    # Copy the globals of the temporary module, as they
    # may be cleared when the temporary module goes away
    return mod_globals.copy()

# This helper is needed due to a missing component in the PEP 302
# loader protocol (specifically, "get_filename" is non-standard)
# Since we can't introduce new features in maintenance releases,
# support was added to zipimporter under the name '_get_filename'
def _get_filename(loader, mod_name):
    for attr in ("get_filename", "_get_filename"):
        meth = getattr(loader, attr, None)
        if meth is not None:
            return meth(mod_name)
    return None

# Helper to get the loader, code and filename for a module
def _get_module_details(mod_name):
    loader = get_loader(mod_name)
    if loader is None:
        raise ImportError("No module named %s" % mod_name)
    if loader.is_package(mod_name):
        if mod_name == "__main__" or mod_name.endswith(".__main__"):
            raise ImportError(("Cannot use package as __main__ module"))
        try:
            pkg_main_name = mod_name + ".__main__"
            return _get_module_details(pkg_main_name)
        except ImportError as e:
            raise ImportError(("%s; %r is a package and cannot " +
                               "be directly executed") %(e, mod_name))
    code = loader.get_code(mod_name)
    if code is None:
        raise ImportError("No code object available for %s" % mod_name)
    filename = _get_filename(loader, mod_name)
    return mod_name, loader, code, filename

# XXX ncoghlan: Should this be documented and made public?
# (Current thoughts: don't repeat the mistake that lead to its
# creation when run_module() no longer met the needs of
# mainmodule.c, but couldn't be changed because it was public)
def _run_module_as_main(mod_name, set_argv0=True):
    """Runs the designated module in the __main__ namespace

       These __*__ magic variables will be overwritten:
           __file__
           __loader__
    """
    try:
        mod_name, loader, code, fname = _get_module_details(mod_name)
    except ImportError as exc:
        # Try to provide a good error message
        # for directories, zip files and the -m switch
        if set_argv0:
            # For -m switch, just display the exception
            info = str(exc)
        else:
            # For directories/zipfiles, let the user
            # know what the code was looking for
            info = "can't find '__main__.py' in %r" % sys.argv[0]
        msg = "%s: %s" % (sys.executable, info)
        sys.exit(msg)
    pkg_name = mod_name.rpartition('.')[0]
    main_globals = sys.modules["__main__"].__dict__
    if set_argv0:
        sys.argv[0] = fname
    return _run_code(code, main_globals, None,
                     "__main__", fname, loader, pkg_name)

def run_module(mod_name, init_globals=None,
               run_name=None, alter_sys=False):
    """Execute a module's code without importing it

       Returns the resulting top level namespace dictionary
    """
    mod_name, loader, code, fname = _get_module_details(mod_name)
    if run_name is None:
        run_name = mod_name
    pkg_name = mod_name.rpartition('.')[0]
    if alter_sys:
        return _run_module_code(code, init_globals, run_name,
                                fname, loader, pkg_name)
    else:
        # Leave the sys module alone
        return _run_code(code, {}, init_globals, run_name,
                         fname, loader, pkg_name)

if __name__ == "__main__":
    # Run the module specified as the next command line argument
    if len(sys.argv) < 2:
        print("No module specified for execution", file=sys.stderr)
    else:
        del sys.argv[0] # Make the requested module sys.argv[0]
        _run_module_as_main(sys.argv[0])


text:
package Net::LDAP::Constant;

$VERSION = "0.06";

use Carp;

my %const;

sub import {
  shift;
  my $callpkg = caller(0);
  _find(@_);
  my $oops;
  my $all = grep /:all/, @_;
  foreach my $sym ($all ? keys %const : @_) {
    if (my $sub = $const{$sym}) {
      *{$callpkg . "::$sym"} = $sub;
    }
    else {
      ++$oops;
      carp(qq["$sym" is not exported by the Net::LDAP::Constant module]);
    }
  }
  croak("Can't continue after import errors") if $oops;
}

sub _find {
  if (my @need = grep { ! $const{$_} } @_) {
    my %need; @need{@need} = ();
    my $all = exists $need{':all'};
    seek(DATA,0,0);
    local $/=''; # paragraph mode
    local $_;
    while(<DATA>) {
      next unless /^=item\s+(LDAP_\S+)\s+\((.*)\)/ and ($all or exists $need{$1});
      my ($name, $value) = ($1,$2);
      delete $need{$name};
      $const{$name} = sub () { $value };
      last unless keys %need;
    }
  }
  @const{@_};
}

sub AUTOLOAD {
  (my $name = $AUTOLOAD) =~ s/^.*:://;
  my $sub = _find($name) or croak("Undefined subroutine &$AUTOLOAD");
  my $val = &$sub; # Avoid prototype error caused by *$AUTOLOAD = $sub
  *$AUTOLOAD = sub { $val };
  goto &$AUTOLOAD;
}

# These subs are really in Net::LDAP::Util, but need to access <DATA>
# so its easier for them to be here.

my @err2name;

sub Net::LDAP::Util::ldap_error_name {
  my $code = 0 + (ref($_[0]) ? $_[0]->code : $_[0]);

  unless (@err2name) {
    seek(DATA,0,0);
    local $/=''; # paragraph mode
    local $_;
    my $n = -1;
    while(<DATA>) {
      last if /^=head2/ and ++$n;
      next if $n;
      $err2name[$2] = $1 if /^=item\s+(LDAP_\S+)\s+\((\d+)\)/;
    }
  }
  $err2name[$code] || sprintf("LDAP error code %d(0x%02X)",$code,$code);
}

sub Net::LDAP::Util::ldap_error_text {
  my $code = 0 + (ref($_[0]) ? $_[0]->code : $_[0]);
  my $text;

  seek(DATA,0,0);
  local $/=''; # paragraph mode
  local $_;
  my $n = -1;
  while(<DATA>) {
    last if /^=head2/ and ++$n;
    next if $n;
    if (/^=item\s+(LDAP_\S+)\s+\((\d+)\)/) {
      last if defined $text;
      $text = '' if $2 == $code;
    }
    elsif (defined $text) {
      $text .= $_;
    }
  }

  if (defined $text) {
    # Do some cleanup. Really should use a proper pod parser here.

    $text =~ s/^=item\s+\*\s+/ * /msg;
    $text =~ s/^=(over\s*\d*|back)//msg;
    $text =~ s/ +\n//g;
    $text =~ s/\n\n+/\n\n/g;
    $text =~ s/\n+\Z/\n/ if defined $text;
  }

  return $text;
}

1;

__DATA__

=head1 NAME

Net::LDAP::Constant - Constants for use with Net::LDAP

=head1 SYNOPSIS

 use Net::LDAP qw(LDAP_SUCCESS LDAP_PROTOCOL_ERROR);

=head1 DESCRIPTION

B<Net::LDAP::Constant> exports constant subroutines for the following LDAP
error codes.

=head2 Protocol Constants

=over 4

=item LDAP_SUCCESS (0)

Operation completed without error

=item LDAP_OPERATIONS_ERROR (1)

Server encountered an internal error

=item LDAP_PROTOCOL_ERROR (2)

Unrecognized version number or incorrect PDU structure

=item LDAP_TIMELIMIT_EXCEEDED (3)

The time limit on a search operation has been exceeded

=item LDAP_SIZELIMIT_EXCEEDED (4)

The maximum number of search results to return has been exceeded.

=item LDAP_COMPARE_FALSE (5)

This code is returned when a compare request completes and the attribute value
given is not in the entry specified

=item LDAP_COMPARE_TRUE (6)

This code is returned when a compare request completes and the attribute value
given is in the entry specified

=item LDAP_AUTH_METHOD_NOT_SUPPORTED (7)

Unrecognized SASL mechanism name

=item LDAP_STRONG_AUTH_NOT_SUPPORTED (7)

Unrecognized SASL mechanism name

=item LDAP_STRONG_AUTH_REQUIRED (8)

The server requires authentication be performed with a SASL mechanism

=item LDAP_PARTIAL_RESULTS (9)

Returned to version 2 clients when a referral is returned. The response
will contain a list of URL's for other servers.

=item LDAP_REFERRAL (10)

The server is referring the client to another server. The response will
contain a list of URL's

=item LDAP_ADMIN_LIMIT_EXCEEDED (11)

The server has exceed the maximum number of entries to search while gathering
a list of search result candidates

=item LDAP_UNAVAILABLE_CRITICAL_EXT (12)

A control or matching rule specified in the request is not supported by
the server

=item LDAP_CONFIDENTIALITY_REQUIRED (13)

This result code is returned when confidentiality is required to perform
a given operation

=item LDAP_SASL_BIND_IN_PROGRESS (14)

The server requires the client to send a new bind request, with the same SASL
mechanism, to continue the authentication process

=item LDAP_NO_SUCH_ATTRIBUTE (16)

The request referenced an attribute that does not exist

=item LDAP_UNDEFINED_TYPE (17)

The request contains an undefined attribute type

=item LDAP_INAPPROPRIATE_MATCHING (18)

An extensible matching rule in the given filter does not apply to the specified
attribute

=item LDAP_CONSTRAINT_VIOLATION (19)

The request contains a value which does not meet with certain constraints.
This result can be returned as a consequence of

=over 4

=item *

The request was to add or modify a user password, and the password fails to
meet the criteria the server is configured to check. This could be that the
password is too short, or a recognizable word (e.g. it matches one of the
attributes in the users entry) or it matches a previous password used by
the same user.

=item *

The request is a bind request to a user account that has been locked

=back

=item LDAP_TYPE_OR_VALUE_EXISTS (20)

The request attempted to add an attribute type or value that already exists

=item LDAP_INVALID_SYNTAX (21)

Some part of the request contained an invalid syntax. It could be a search
with an invalid filter or a request to modify the schema and the given
schema has a bad syntax.

=item LDAP_NO_SUCH_OBJECT (32)

The server cannot find an object specified in the request

=item LDAP_ALIAS_PROBLEM (33)

Server encountered a problem while attempting to dereference an alias

=item LDAP_INVALID_DN_SYNTAX (34)

The request contained an invalid DN

=item LDAP_IS_LEAF (35)

The specified entry is a leaf entry

=item LDAP_ALIAS_DEREF_PROBLEM (36)

Server encountered a problem while attempting to dereference an alias

=item LDAP_INAPPROPRIATE_AUTH (48)

The server requires the client which had attempted to bind anonymously or
without supplying credentials to provide some form of credentials

=item LDAP_INVALID_CREDENTIALS (49)

The wrong password was supplied or the SASL credentials could not be processed

=item LDAP_INSUFFICIENT_ACCESS (50)

The client does not have sufficient access to perform the requested
operation

=item LDAP_BUSY (51)

The server is too busy to perform requested operation

=item LDAP_UNAVAILABLE (52)

The server in unavailable to perform the request, or the server is
shutting down

=item LDAP_UNWILLING_TO_PERFORM (53)

The server is unwilling to perform the requested operation

=item LDAP_LOOP_DETECT (54)

The server was unable to perform the request due to an internal loop detected

=item LDAP_SORT_CONTROL_MISSING (60)

The search contained a "virtual list view" control, but not a server-side
sorting control, which is required when a "virtual list view" is given.

=item LDAP_INDEX_RANGE_ERROR (61)

The search contained a control for a "virtual list view" and the results
exceeded the range specified by the requested offsets.

=item LDAP_NAMING_VIOLATION (64)

The request violates the structure of the DIT

=item LDAP_OBJECT_CLASS_VIOLATION (65)

The request specifies a change to an existing entry or the addition of a new
entry that does not comply with the servers schema

=item LDAP_NOT_ALLOWED_ON_NONLEAF (66)

The requested operation is not allowed on an entry that has child entries

=item LDAP_NOT_ALLOWED_ON_RDN (67)

The requested operation ill affect the RDN of the entry

=item LDAP_ALREADY_EXISTS (68)

The client attempted to add an entry that already exists. This can occur as
a result of

=over 4

=item *

An add request was submitted with a DN that already exists

=item *

A modify DN requested was submitted, where the requested new DN already exists

=item *

The request is adding an attribute to the schema and an attribute with the
given OID or name already exists

=back

=item LDAP_NO_OBJECT_CLASS_MODS (69)

Request attempt to modify the object class of an entry that should not be
modified

=item LDAP_RESULTS_TOO_LARGE (70)

The results of the request are to large

=item LDAP_AFFECTS_MULTIPLE_DSAS (71)

The requested operation needs to be performed on multiple servers where
the requested operation is not permitted

=item LDAP_OTHER (80)

An unknown error has occurred

=item LDAP_SERVER_DOWN (81)

C<Net::LDAP> cannot establish a connection or the connection has been lost

=item LDAP_LOCAL_ERROR (82)

An error occurred in C<Net::LDAP>

=item LDAP_ENCODING_ERROR (83)

C<Net::LDAP> encountered an error while encoding the request packet that would
have been sent to the server

=item LDAP_DECODING_ERROR (84)

C<Net::LDAP> encountered an error while decoding a response packet from
the server.

=item LDAP_TIMEOUT (85)

C<Net::LDAP> timeout while waiting for a response from the server

=item LDAP_AUTH_UNKNOWN (86)

The method of authentication requested in a bind request is unknown to
the server

=item LDAP_FILTER_ERROR (87)

An error occurred while encoding the given search filter.

=item LDAP_USER_CANCELED (88)

The user canceled the operation

=item LDAP_PARAM_ERROR (89)

An invalid parameter was specified

=item LDAP_NO_MEMORY (90)

Out of memory error

=item LDAP_CONNECT_ERROR (91)

A connection to the server could not be established

=item LDAP_NOT_SUPPORTED (92)

An attempt has been made to use a feature not supported by Net::LDAP

=item LDAP_CONTROL_NOT_FOUND (93)

The controls required to perform the requested operation were not
found.

=item LDAP_NO_RESULTS_RETURNED (94)

No results were returned from the server.

=item LDAP_MORE_RESULTS_TO_RETURN (95)

There are more results in the chain of results.

=item LDAP_CLIENT_LOOP (96)

A loop has been detected. For example when following referals.

=item LDAP_REFERRAL_LIMIT_EXCEEDED (97)

The referral hop limit has been exceeded.

=back

=head2 Control OIDs

=over 4

=item LDAP_CONTROL_SORTREQUEST (1.2.840.113556.1.4.473)

=item LDAP_CONTROL_SORTRESULT (1.2.840.113556.1.4.474)

=item LDAP_CONTROL_VLVREQUEST (2.16.840.1.113730.3.4.9)

=item LDAP_CONTROL_VLVRESPONSE (2.16.840.1.113730.3.4.10)

=item LDAP_CONTROL_PROXYAUTHENTICATION (2.16.840.1.113730.3.4.18)

=item LDAP_CONTROL_PAGED (1.2.840.113556.1.4.319)

=item LDAP_CONTROL_TREE_DELETE (1.2.840.113556.1.4.805)

=item LDAP_CONTROL_MATCHEDVALS (1.2.826.0.1.3344810.2.2)

=item LDAP_CONTROL_MATCHEDVALUES (1.2.826.0.1.3344810.2.3)

=item LDAP_CONTROL_MANAGEDSAIT (2.16.840.1.113730.3.4.2)

=item LDAP_CONTROL_PERSISTENTSEARCH (2.16.840.1.113730.3.4.3)

=item LDAP_CONTROL_ENTRYCHANGE (2.16.840.1.113730.3.4.7)

=item LDAP_CONTROL_PWEXPIRED (2.16.840.1.113730.3.4.4)

=item LDAP_CONTROL_PWEXPIRING (2.16.840.1.113730.3.4.5)

=item LDAP_CONTROL_REFERRALS (1.2.840.113556.1.4.616)

=item LDAP_CONTROL_PASSWORDPOLICY (1.3.6.1.4.1.42.2.27.8.5.1)

=item LDAP_CONTROL_PREREAD (1.3.6.1.1.13.1)

=item LDAP_CONTROL_POSTREAD (1.3.6.1.1.13.2)

=item LDAP_CONTROL_ASSERTION (1.3.6.1.1.12)

=back

=head2 Control constants

=over 4

=item LDAP_PP_PASSWORD_EXPIRED (0) [LDAP_CONTROL_PASSWORDPOLICY]

The account's password has expired.

=item LDAP_PP_ACCOUNT_LOCKED (1) [LDAP_CONTROL_PASSWORDPOLICY]

The account is locked.

=item LDAP_PP_CHANGE_AFTER_RESET (2) [LDAP_CONTROL_PASSWORDPOLICY]

The account's password has been reset and now must be changed.

=item LDAP_PP_PASSWORD_MOD_NOT_ALLOWED (3) [LDAP_CONTROL_PASSWORDPOLICY]

The account's password may not be modified.

=item LDAP_PP_MUST_SUPPLY_OLD_PASSWORD (4) [LDAP_CONTROL_PASSWORDPOLICY]

The old password must also be supplied when setting a new password.

=item LDAP_PP_INSUFFICIENT_PASSWORD_QUALITY (5) [LDAP_CONTROL_PASSWORDPOLICY]

The new password was not of sufficient quality.

=item LDAP_PP_PASSWORD_TOO_SHORT (6) [LDAP_CONTROL_PASSWORDPOLICY]

The new password was too short.

=item LDAP_PP_PASSWORD_TOO_YOUNG (7) [LDAP_CONTROL_PASSWORDPOLICY]

The previous password was changed too recently.

=item LDAP_PP_PASSWORD_IN_HISTORY (8) [LDAP_CONTROL_PASSWORDPOLICY]

The new password was used too recently.

=back

=head2 Extension OIDs

B<Net::LDAP::Constant> exports constant subroutines for the following LDAP
extension OIDs.

=over 4

=item LDAP_EXTENSION_START_TLS (1.3.6.1.4.1.1466.20037)

Indicates if the server supports the Start TLS extension (RFC 2830)

=item LDAP_EXTENSION_PASSWORD_MODIFY (1.3.6.1.4.1.4203.1.11.1)

Indicates that the server supports the Password Modify extension (RFC 3062)

=item LDAP_EXTENSION_WHO_AM_I (1.3.6.1.4.1.4203.1.11.3)

Indicates that the server supports the "Who am I?" extension (draft-zeilenga-ldap-authzid-09)

=back

=head1 SEE ALSO

L<Net::LDAP>,
L<Net::LDAP::Message>

=head1 AUTHOR

Graham Barr E<lt>gbarr@pobox.comE<gt>

Please report any bugs, or post any suggestions, to the perl-ldap mailing list
E<lt>perl-ldap@perl.orgE<gt>

=head1 COPYRIGHT

Copyright (c) 1998-2008 Graham Barr. All rights reserved. This program is
free software; you can redistribute it and/or modify it under the same
terms as Perl itself.

=cut


text:
:; echo "stderr output" 1>&2; exit 0
@ECHO OFF
ECHO stderr output 1>&2


text:
package org.fusesource.fabric.api;

public interface Version extends Comparable<Version> {

    String getName();

    VersionSequence getSequence();

    Version getDerivedFrom();

    Profile[] getProfiles();

    /**
     * Gets a profile with the given name.
     * @param name name of the profile to get.
     * @return {@link Profile} with the given name. Returns null if it doesn't exist.
     */
    Profile getProfile(String name);

    Profile createProfile(String name);

    void delete();

}


text:
package ts.eclipse.ide.internal.core.resources;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.WorkspaceJob;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.osgi.util.NLS;
import org.osgi.service.prefs.BackingStoreException;

import ts.eclipse.ide.core.TypeScriptCorePlugin;
import ts.eclipse.ide.internal.core.TypeScriptCoreMessages;

/**
 * Job to save project preferences.
 *
 */
class SaveProjectPreferencesJob extends WorkspaceJob {

	private final IEclipsePreferences preferences;
	private final IProject project;

	public SaveProjectPreferencesJob(IEclipsePreferences preferences, IProject project) {
		super(TypeScriptCoreMessages.SaveProjectPreferencesJob_name);
		this.preferences = preferences;
		this.project = project;
	}

	@Override
	public IStatus runInWorkspace(IProgressMonitor monitor) throws CoreException {
		if (monitor.isCanceled()) {
			return Status.CANCEL_STATUS;
		}
		monitor.beginTask(NLS.bind(TypeScriptCoreMessages.SaveProjectPreferencesJob_taskName, project.getName()), 1);

		try {
			preferences.flush();
		} catch (BackingStoreException e) {
			IStatus status = new Status(Status.ERROR, TypeScriptCorePlugin.PLUGIN_ID,
					"Error while saving  project preferences", e);
			throw new CoreException(status);
		}

		monitor.worked(1);
		monitor.done();

		return Status.OK_STATUS;
	}

}


text:
import glob,sys,re,os,getopt,time,signal,gzip,ConfigParser
from pprint import pprint

time_unit_seconds="1/1000000"

## This function processes one logfile with regexes and stores
## the results in the global hash "dashboard"

def readAccessLog(file):

  # open file
  print "reading from '%s'" % file
  if file == "-":
       accesslog = sys.stdin
  elif file.upper().endswith(".gz".upper()):
       accesslog = gzip.open(file, 'rb')
  else:
       accesslog = open(file, 'r')

  count =  0
  skipped = 0
  unmatched = 0

  service_classes_tmpl = {}
  for i in service_classes:
     service_classes_tmpl[i] = 0

  if (include_match != None):
    re_includematch = re.compile(include_match)

  while 1:
    lineStr = accesslog.readline().rstrip()

    if (include_match != None) and not re_includematch.match(lineStr):
        if "debug" in flags: print "[skip, does not match] " + lineStr
        skipped += 1
        continue

    # end of file
    if not(lineStr):
        break
    count += 1
    if (count % 1000000 == 0):
        print "%i lines read...%s" % (count,file)
    lineElements = re_parselogs.match(lineStr)
    if (not lineElements):
       print "INFO: line does to match (global/line_regex): %s" % lineStr
       continue

    if not re_http_status_code_regex.match(lineElements.group("code")):
       if "debug" in flags: print "[skip, wrong http status code] " + lineStr
       skipped += 1
       continue

    hashmatched = 0
    for value in dashboard.itervalues():
      urlmatch = value["regex"].match(lineElements.group("url"))

      if value["negate"] == True:
      	if urlmatch :
            continue
        ident_string = "total-negate"
      else:
      	if not urlmatch :
            continue
        if urlmatch.groupdict().has_key("ident"):
            ident_string = urlmatch.group("ident")
        else:
            ident_string = "total-no-named-match"

      hashmatched += 1

      value["count"] += 1
      value.setdefault("matches",{})

      value["matches"].setdefault(ident_string,0)
      value["matches"][ident_string] += 1

      value.setdefault("exectime",{})
      exectime = int(lineElements.group("exectime"))
      value["exectime"].setdefault(ident_string,0)
      value["exectime"][ident_string] += exectime

      value.setdefault("classes",{})
      value["classes"].setdefault(ident_string,service_classes_tmpl.copy())

      value["stats"].setdefault("exectime",0)
      value["stats"]["exectime"] += exectime

      iter = -1
      for cclass in service_classes:
         iter += 1
         # The infinity service class
         if (cclass == "-1"):
           break
         elif int(exectime) < int(cclass):
           break

      value["classes"][ident_string][service_classes[iter]] += 1

    if (hashmatched == 0):
       unmatched += 1
       if "debug" in flags: print "[line not matched by any group] " + lineStr
  accesslog.close()
  return (count,skipped,unmatched)

# This method calculates statistics after all logfiles were processed
#
def createStats():

  print "\n** creating statistics\n"

  # Assemble the header data
  arr_header = [ "category name","match","count","average response time per hit ("+time_unit_seconds+" seconds)" ]

  last = 0
  for i in service_classes:
    if (i == "-1"):
        arr_header.append("> "+ str(last) + " ("+time_unit_seconds+" seconds)")
    else:
        arr_header.append((str(last) + "-" + str(i))+" ("+time_unit_seconds+" seconds)")
    last = i

  dict_data = {}

  # Assemble data of the total stats
  for catname,catdata in dashboard.iteritems():
    # Write total stats
    stats = catdata["stats"]
    if catdata["count"] > 0:
        avg_exec = "%f" % (stats["exectime"] / catdata["count"])
    else:
        avg_exec = "0"
    dataset = [str(catdata["count"]),avg_exec]

    for service_class in service_classes:
        totalcount = 0
        if (catdata.has_key("classes")):
            for classname,classdata in catdata["classes"].iteritems():
                totalcount += classdata[service_class]
        dataset.append(str(totalcount))

    dict_data.setdefault(catname, {})
    dict_data[catname]["total"] = dataset

  # pprint(dashboard)

  # Assemble data of the detail stats
  for catname,catdata in dashboard.iteritems():
    if (catdata.has_key("classes")):
        for classname,classdata in catdata["classes"].iteritems():
            if classname == "total-no-named-match":
              continue
            if classname == "total-negate":
              continue
            dict_data[catname][classname] = []
            dict_data[catname][classname].append(str(catdata["matches"][classname]))
            avg_exec = "%f" % ( catdata["exectime"][classname] / catdata["matches"][classname] )
            dict_data[catname][classname].append(avg_exec)

            for service_class in service_classes:
                dict_data[catname][classname].append(str(classdata[service_class]))

  return (arr_header,dict_data)

# This method creates human readable results
def outputStatsReadable(arr_header,dict_data):

  for catname,catdata in sorted(dict_data.iteritems()):
    print "\n===> Category %s <===========================================================================" % catname
    print
    outarr = [i for i in sorted(catdata) if (i != "total")]
    outarr.insert(0,"total")

    maxlen=0
    for i in arr_header:
        if (maxlen < len(i)):
            maxlen=len(i)

    format_string = "  %-"+str(maxlen)+"s => %s"
    for matchname in outarr:
       if matchname == "":
            continue
       print "\n[%s]" % matchname
       for i_header in range(2,len(arr_header)):
            if (i_header == 4):
                print
            print format_string % (arr_header[i_header],catdata[matchname][i_header-2])

# This method creates a comma separated result file which can be used in libreoffice of excel
def outputStatsCSV(arr_header,dict_data):
  fout = file(outputfile_csv, "w")
  fout.write("#" + ";".join(arr_header)+";\n")
  for catname,catdata in sorted(dict_data.iteritems()):
    out = "%s;%s;" % (catname,"total") + ";".join(catdata["total"])+";\n"
    fout.write(out.replace(".",","))
    for matchname,dataset in sorted(catdata.iteritems()):
        if ( matchname == "total"):
            continue
        out = "%s;%s;" % (catname,matchname) + ";".join(dataset)+";\n"
        fout.write(out.replace(".",","))

  fout.close()

# This method creates a javascript results file
def outputStatsJavascript(arr_header,dict_data):
  fout = file(outputfile_js, "w")
  fout.write('var data = [\n')
  count=1
  for header in arr_header:
    fout.write("    // Column %i : %s\n" % (count,header));
    count +=1

  formatstring_front = '    [%-20s, %-20s, %-20s'
  formatstring_back = ', %12s'

  for catname,catdata in sorted(dict_data.iteritems()):
    fout.write(formatstring_front % ('"'+outputfile_js+'"','"'+catname+'"','"total"'))
    for i in catdata["total"]:
        fout.write(formatstring_back % i)
    fout.write("],\n");
    for matchname,dataset in sorted(catdata.iteritems()):
        if ( matchname == "total"):
            continue
        fout.write(formatstring_front % ('"'+outputfile_js+'"','"'+catname+'"','"'+matchname+'"'))
        for i in catdata[matchname]:
            fout.write(formatstring_back % i)
        fout.write("],\n");

  fout.write(']\n')
  fout.close()

####################################################################
###
### Helpers

def usage():
  print sys.argv[0]+" [options] file..."
  print '''
 -h  view this help message
 -c  configfile
 -d  debug
 -m  regex, only parse matching lines
 -o  output a comma seperated file (csv - suitable spreadsheet calculators)
 -j  output a javascript array
 -r  output in readable format to stdout
'''
  sys.exit(1)

##################################################################
###
### MAIN

if len(sys.argv) < 2:
  usage()

flags = []
## evaluate the commandline arguments
try:
    opt, argv = getopt.getopt(sys.argv[1:], "hdo:c:m:j:r")
except:
    print "Error parsing commandline arguments"
    usage()
    sys.exit(1)

cfgfile = None
include_match = None

for o, a in opt:
    if a.startswith("-"):
      usage()
      sys.exit(1)
    if o == "-h":
      usage()
      sys.exit(1)
    elif o == "-d":
      flags.append("debug")
    elif o == "-o":
      flags.append("output")
      outputfile_csv = a
    elif o == "-j":
      flags.append("javascript")
      outputfile_js = a
    elif o == "-r":
      flags.append("readable")
    elif o == "-c":
      cfgfile = a
    elif o == "-m":
      include_match = a
    else:
      usage()
      sys.exit(1)

if (len(argv) == 0):
   usage()
   sys.exit(1)

if ("output" not in flags) and ("javascript" not in flags) and ("readable" not in flags):
    print "No output defined, exiting"
    sys.exit(1)

if ("output" in flags) and (outputfile_csv == None):
   print "csv outputfile not defined, exiting"
   sys.exit(1)

if ("javascript" in flags) and (outputfile_js == None):
   print "javascript outputfile not defined, exiting"
   sys.exit(1)

print "** reading configuration"
if (cfgfile == None):
  print "error: undefined configfile"
  print
  usage()

# get configuration
cfg = ConfigParser.ConfigParser()
cfg.readfp(open(cfgfile, "r"))

if cfg.has_section("global") and cfg.has_option("global","line_regex"):
  match = re.match("^.*?'(.+)'.*?$",cfg.get("global","line_regex"))
  if match:
     print "line parsing string : '%s'" % match.group(1)
     re_parselogs = re.compile(match.group(1))
  else:
     print "error: please quote the line_regex string"
     sys.exit(1)
else:
  print "missing key 'line_regex' in section 'global'"
  sys.exit(1)

if cfg.has_section("global") and cfg.has_option("global","service_classes"):
  service_classes = re.compile(r'\s*,\s*').split(cfg.get("global","service_classes"))
  service_classes = [int(a) for a in service_classes]
  service_classes.sort()
  # The infinity service class
  service_classes.append("-1")
  print "service classes     : %s " % str(service_classes)
else:
  print "missing key 'service_classes' in section 'global'"
  sys.exit(1)

if cfg.has_section("global") and cfg.has_option("global","http_status_code_regex"):
  match = re.match("^.*?'(.+)'.*?$",cfg.get("global","http_status_code_regex"))
  if match:
     print "matched status code string : '%s'" % match.group(1)
     re_http_status_code_regex = re.compile(match.group(1))
  else:
     print "error: please quote the http_status_code_regex string"
     sys.exit(1)

if cfg.has_section("global") and cfg.has_option("global","time_unit_seconds"):
  time_unit_seconds = cfg.get("global","time_unit_seconds")

# request types
dashboard = {}
for sect in cfg.sections():
  if sect == "global":
     continue
  print "=> section '%s'" % sect
  if cfg.has_option(sect,"url_regex"):
     match = re.match("^.*?'(.+)'.*?$",cfg.get(sect,"url_regex"))
     if match:
        print "  url parsing string: '%s'" % match.group(1)

        dashboard[sect] = {}
        try:
           dashboard[sect]["regex"] = re.compile(match.group(1))
        except:
           print "regex '%s' seems to be broken, unable to compile" % match.group(1)
        dashboard[sect]["regex_uncompiled"] = match.group(1)
        dashboard[sect]["count"] = 0
        dashboard[sect]["stats"] = { "exectime" : 0 }
        if cfg.has_option(sect,"negate") and cfg.get(sect,"negate") == "true":
           dashboard[sect]["negate"] = True
        else:
           dashboard[sect]["negate"] = False
     else:
        print "error: please quote the url_regex string"
        sys.exit(1)
  else:
     print "missing key: url_regex"
     sys.exit(1)

# start processing the files
starttime = time.time()
lines = 0
skipped = 0
umlines = 0

print "\n** processing files"
# read the logfiles

processed_files=0
total_files=len(argv)
for access_log in argv:
  try:
   tlines,skipped,unmatchedlines = readAccessLog(access_log)
   currenttime = time.time()
   processed_files += 1
   if ( processed_files != 0 ):
     time_perfile = (currenttime - starttime) / processed_files
     remaining_time = (total_files - processed_files) * time_perfile
     print "%i of %i files processed (%d seconds per file, remaining time %d hours)" % (processed_files,total_files, time_perfile, remaining_time/60/60)
   lines += tlines
   skipped += skipped
   umlines += unmatchedlines
  except KeyboardInterrupt:
        print "\nWARNING => file processing interupted\n"
        break

endtime = time.time()
# processing finished, print stats
print "processed %d lines in %s seconds (%d lines per second)" % (
    lines,(endtime-starttime),lines/(endtime-starttime)
    )
print "%s unmatched lines" % umlines
print "%s skipped lines" % skipped

(arr_header,dict_data) = createStats()

if ("output" in flags):
    outputStatsCSV(arr_header,dict_data)

if ("javascript" in flags):
    outputStatsJavascript(arr_header,dict_data)

if ("readable" in flags):
    outputStatsReadable(arr_header,dict_data)

# vim: ai et ts=2 shiftwidth=2


text:
steal('./typedef.js','./param.js','./return','funcunit/qunit',function(typedef, param,returns){

	module("documentjs/tags/typedef")

	test("basic",function(){

		var obj = {};
		var docMap = {Foo: {name: "Foo", type: "constructor"}}
		typedef.add.call(obj,"@typedef {{}} name title",null,docMap.Foo, docMap );

		deepEqual(obj,{
			name: "name",
			title: "title",
			type: "typedef",
			types: [{type: "Object", options: []}]
		})

	})

	test("function typedef followed by params",function(){

		var obj = {};
		var docMap = {Foo: {name: "Foo", type: "constructor"}}
		typedef.add.call(obj,"@typedef {function(String):Number} func(name) functionjunction",null,docMap.Foo, docMap );
		param.add.call(obj,"@param {String} name DESCRIPTION",null,docMap.Foo, docMap );
		returns.add.call(obj,"@return {Number} RET DESCRIPTION",null,docMap.Foo, docMap );

		delete obj._curParam;

		deepEqual(obj,{
			name: "func",
			title: "functionjunction",
			type: "typedef",
			types: [{
				type: "function",
				constructs: undefined,
				context: undefined,
				params:[{
		          "description": "DESCRIPTION",
		          "name": "name",
		          "types": [
		            {
		              "type": "String"
		            }
		          ]
		        }],
		        returns: {
		        	description: "RET DESCRIPTION",
		        	types: [
		        		{

		        			type: "Number"

		        		}
		        	]
		        }
			}]
		})

	})

})


text:
require_relative "helper"

class TestForkSafety < Test::Unit::TestCase

  include Helper::Client

  driver(:ruby, :hiredis) do
    def test_fork_safety
      redis = Redis.new(OPTIONS)
      redis.set "foo", 1

      child_pid = fork do
        begin
          # InheritedError triggers a reconnect,
          # so we need to disable reconnects to force
          # the exception bubble up
          redis.without_reconnect do
            redis.set "foo", 2
          end
        rescue Redis::InheritedError
          exit 127
        end
      end

      _, status = Process.wait2(child_pid)

      assert_equal 127, status.exitstatus
      assert_equal "1", redis.get("foo")

    rescue NotImplementedError => error
      raise unless error.message =~ /fork is not available/
    end

    def test_fork_safety_with_enabled_inherited_socket
      redis = Redis.new(OPTIONS.merge(:inherit_socket => true))
      redis.set "foo", 1

      child_pid = fork do
        begin
          # InheritedError triggers a reconnect,
          # so we need to disable reconnects to force
          # the exception bubble up
          redis.without_reconnect do
            redis.set "foo", 2
          end
        rescue Redis::InheritedError
          exit 127
        end
      end

      _, status = Process.wait2(child_pid)

      assert_equal 0, status.exitstatus
      assert_equal "2", redis.get("foo")

    rescue NotImplementedError => error
      raise unless error.message =~ /fork is not available/
    end
  end
end


text:
"""

Given an integer n, return true if it is a power of three. Otherwise, return false.
An integer n is a power of three, if there exists an integer x such that n == 3x.

Example 1:
Input: n = 27
Output: true
Example 2:
Input: n = 0
Output: false
Example 3:
Input: n = 9
Output: true
Example 4:
Input: n = 45
Output: false

Constraints:

-231 <= n <= 231 - 1

Follow up: Could you do it without using any loop / recursion?
"""

class Solution:
    def isPowerOfThree(self, n: int) -> bool:
        while n > 3:
            n, r = divmod(n, 3)
            if r != 0:
                return False
        return n == 1 or n == 3


text:
@extends('layouts.app')

@section('content')

Informe abaixo os dados do estoque
                        Listagem Estoque

                    {!! Form::open(['url' => 'estoque/salvar']) !!}

                    {!! Form::label('Tipo', 'Tipo')!!}
                    {!! Form::input('text', 'Tipo', '',['class' => 'form-control', 'autofocus', 'placeholder' => 'Tipo']) !!}

                    {!! Form::label('Código de Localização', 'Código de Localização')!!}
                    {!! Form::input('text', 'Codigo de Localizacao', '',['class' => 'form-control', 'autofocus', 'placeholder' => 'Código de Localização']) !!}

                    {!! Form::label('Fornecedor', 'Fornecedor')!!}
                    {!! Form::input('text', 'Fornecedor', '',['class' => 'form-control', 'autofocus', 'placeholder' => 'Fornecedor']) !!}

                    {!! Form::label('Quantidade', 'Quantidade')!!}
                    {!! Form::input('text', 'Quantidade', '',['class' => 'form-control', 'autofocus', 'placeholder' => 'Quantidade']) !!}

                    {!! Form::submit('Salvar',['class' => 'btn btn primary']) !!}

                    {!! Form::close() !!}

@endsection


text:
//
//  CZApiManager.h
//  09News
//
//  Created by gzxzmac on 16/2/26.
//  Copyright © 2016年 gzxzmac. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface CZApiManager : NSObject
+ (instancetype)sharedApi;
/**
 *  请求头条的广告数据
 *
 *  @param url     请求的路径
 *  @param success 成功回调
 *  @param error   失败回调
 */
- (void)requestHeadLineDataWithURL:(NSString *)url success:(void(^)(id responseObject))success error:(void(^)(NSError *errorInfo))error;

@end


text:
from geoscript.layer.raster import Raster
from org.geotools.coverageio.gdal.mrsid import MrSIDFormat

class MrSID(Raster):

  def __init__(self, file, proj=None):
    Raster.__init__(self, MrSIDFormat(), file, proj)


text:
import xml.etree.ElementTree as ET
from .exceptions import UnpopulatedPropertyError
from .property_decorators import property_not_nullable
from .tag_item import TagItem
from .. import NAMESPACE
from ..datetime_helpers import parse_datetime

class DatasourceItem(object):
    def __init__(self, project_id, name=None):
        self._connections = None
        self._content_url = None
        self._created_at = None
        self._id = None
        self._project_name = None
        self._tags = set()
        self._datasource_type = None
        self._updated_at = None
        self.name = name
        self.owner_id = None
        self.project_id = project_id

    @property
    def connections(self):
        if self._connections is None:
            error = 'Datasource item must be populated with connections first.'
            raise UnpopulatedPropertyError(error)
        return self._connections

    @property
    def content_url(self):
        return self._content_url

    @property
    def created_at(self):
        return self._created_at

    @property
    def id(self):
        return self._id

    @property
    def project_id(self):
        return self._project_id

    @project_id.setter
    @property_not_nullable
    def project_id(self, value):
        self._project_id = value

    @property
    def project_name(self):
        return self._project_name

    @property
    def tags(self):
        return self._tags

    @property
    def datasource_type(self):
        return self._datasource_type

    @property
    def updated_at(self):
        return self._updated_at

    def _set_connections(self, connections):
        self._connections = connections

    def _parse_common_tags(self, datasource_xml):
        if not isinstance(datasource_xml, ET.Element):
            datasource_xml = ET.fromstring(datasource_xml).find('.//t:datasource', namespaces=NAMESPACE)
        if datasource_xml is not None:
            (_, _, _, _, _, updated_at, _, project_id, project_name, owner_id) = self._parse_element(datasource_xml)
            self._set_values(None, None, None, None, None, updated_at, None, project_id, project_name, owner_id)
        return self

    def _set_values(self, id, name, datasource_type, content_url, created_at,
                    updated_at, tags, project_id, project_name, owner_id):
        if id is not None:
            self._id = id
        if name:
            self.name = name
        if datasource_type:
            self._datasource_type = datasource_type
        if content_url:
            self._content_url = content_url
        if created_at:
            self._created_at = created_at
        if updated_at:
            self._updated_at = updated_at
        if tags:
            self._tags = tags
        if project_id:
            self.project_id = project_id
        if project_name:
            self._project_name = project_name
        if owner_id:
            self.owner_id = owner_id

    @classmethod
    def from_response(cls, resp):
        all_datasource_items = list()
        parsed_response = ET.fromstring(resp)
        all_datasource_xml = parsed_response.findall('.//t:datasource', namespaces=NAMESPACE)

        for datasource_xml in all_datasource_xml:
            (id, name, datasource_type, content_url, created_at, updated_at,
             tags, project_id, project_name, owner_id) = cls._parse_element(datasource_xml)
            datasource_item = cls(project_id)
            datasource_item._set_values(id, name, datasource_type, content_url, created_at, updated_at,
                                        tags, None, project_name, owner_id)
            all_datasource_items.append(datasource_item)
        return all_datasource_items

    @staticmethod
    def _parse_element(datasource_xml):
        id = datasource_xml.get('id', None)
        name = datasource_xml.get('name', None)
        datasource_type = datasource_xml.get('type', None)
        content_url = datasource_xml.get('contentUrl', None)
        created_at = parse_datetime(datasource_xml.get('createdAt', None))
        updated_at = parse_datetime(datasource_xml.get('updatedAt', None))

        tags = None
        tags_elem = datasource_xml.find('.//t:tags', namespaces=NAMESPACE)
        if tags_elem is not None:
            tags = TagItem.from_xml_element(tags_elem)

        project_id = None
        project_name = None
        project_elem = datasource_xml.find('.//t:project', namespaces=NAMESPACE)
        if project_elem is not None:
            project_id = project_elem.get('id', None)
            project_name = project_elem.get('name', None)

        owner_id = None
        owner_elem = datasource_xml.find('.//t:owner', namespaces=NAMESPACE)
        if owner_elem is not None:
            owner_id = owner_elem.get('id', None)

        return id, name, datasource_type, content_url, created_at, updated_at, tags, project_id, project_name, owner_id


text:
package org.orienteer.notifications.service;

import com.orientechnologies.orient.core.record.impl.ODocument;
import org.apache.http.util.Args;
import org.orienteer.core.dao.DAO;
import org.orienteer.notifications.model.IOMailNotificationTransport;
import org.orienteer.notifications.model.IONotificationTransport;
import org.orienteer.notifications.model.IOSmsNotificationTransport;

/**
 * Default implementation of {@link IONotificationTransportFactory}
 */
public class ONotificationTransportFactory implements IONotificationTransportFactory {

  @Override
  public IONotificationTransport create(ODocument document) {
    Args.notNull(document, "document");
    IONotificationTransport transport = null;

    switch (document.getSchemaClass().getName()) {
      case IOMailNotificationTransport.CLASS_NAME:
        transport = DAO.create(IOMailNotificationTransport.class);
        break;
      case IOSmsNotificationTransport.CLASS_NAME:
        transport = DAO.create(IOSmsNotificationTransport.class);
        break;
    }

    if (transport != null) {
      transport.fromStream(document);
    }

    return transport;
  }

}


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="AppTheme.Base">
        <item name="android:colorPrimary">@color/primaryColor</item>
        <item name="android:colorPrimaryDark">@color/primaryColorDark</item>
        <item name="android:windowTranslucentStatus">true</item>
    </style>

    <style name="ToolBarStyle" parent="">
        <item name="android:elevation">@dimen/toolbar_elevation</item>
        <item name="popupTheme">@style/ThemeOverlay.AppCompat.Light</item>
        <item name="theme">@style/ThemeOverlay.AppCompat.Dark.ActionBar</item>
    </style>
</resources>


text:
//*******************************************************************************************//
//                                                                                //
// Download Free Evaluation Version From: https://bytescout.com/download/web-installer       //
//                                                                                //
// Also available as Web API! Get Your Free API Key: https://app.pdf.co/signup               //
//                                                                                //
// Copyright © 2017-2020 ByteScout, Inc. All rights reserved.                                //
// https://www.bytescout.com                                                                 //
// https://pdf.co                                                                            //
//                                                                                //
//*******************************************************************************************//

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Threading;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace ByteScoutWebApiExample
{
    class Program
    {
        // The authentication key (API Key).
        // Get your own by registering at https://app.pdf.co
        const String API_KEY = "*****************************************";

        // Source PDF file
        const string SourceFile = @".\sample.pdf";

        // Comma-separated list of page indices (or ranges) to process. Leave empty for all pages. Example: '0,2-5,7-'.
        const string Pages = "";

        // PDF document password. Leave empty for unprotected documents.
        const string Password = "";

        // (!) Make asynchronous job
        const bool Async = true;

        static void Main(string[] args)
        {
            // Create standard .NET web client instance
            WebClient webClient = new WebClient();

            // Set API Key
            webClient.Headers.Add("x-api-key", API_KEY);

            // 1. RETRIEVE THE PRESIGNED URL TO UPLOAD THE FILE.
            // * If you already have a direct file URL, skip to the step 3.

            // Prepare URL for `Get Presigned URL` API call
            string query = Uri.EscapeUriString(string.Format(
                "https://api.pdf.co/v1/file/upload/get-presigned-url?contenttype=application/octet-stream&name={0}",
                Path.GetFileName(SourceFile)));

            try
            {
                // Execute request
                string response = webClient.DownloadString(query);

                // Parse JSON response
                JObject json = JObject.Parse(response);

                if (json["error"].ToObject<bool>() == false)
                {
                    // Get URL to use for the file upload
                    string uploadUrl = json["presignedUrl"].ToString();
                    string uploadedFileUrl = json["url"].ToString();

                    // 2. UPLOAD THE FILE TO CLOUD.
                    webClient.Headers.Add("content-type", "application/octet-stream");
                    webClient.UploadFile(uploadUrl, "PUT", SourceFile); // You can use UploadData() instead if your file is byte[] or Stream

                    // 3. PERFORM TABLE SEARCH

                    // URL for `PDF Table Search` API call
                    // See documentation: https://apidocs.pdf.co
                    var url = "https://api.pdf.co/v1/pdf/find/table";

                    // Prepare requests params as JSON
                    Dictionary<string, object> parameters = new Dictionary<string, object>();
                    parameters.Add("password", Password);
                    parameters.Add("pages", Pages);
                    parameters.Add("url", uploadedFileUrl);
                    parameters.Add("async", Async);

                    // Convert dictionary of params to JSON
                    string jsonPayload = JsonConvert.SerializeObject(parameters);

                    // Execute POST request with JSON payload
                    response = webClient.UploadString(url, jsonPayload);

                    // Parse JSON response
                    json = JObject.Parse(response);

                    if (json["error"].ToObject<bool>() == false)
                    {
                        // Asynchronous job ID
                        string jobId = json["jobId"].ToString();

                        // URL of generated json file that will available after the job completion
                        string resultFileUrl = json["url"].ToString();

                        // Check the job status in a loop.
                        // If you don't want to pause the main thread you can rework the code
                        // to use a separate thread for the status checking and completion.
                        do
                        {
                            string status = CheckJobStatus(jobId); // Possible statuses: "working", "failed", "aborted", "success".

                            // Display timestamp and status (for demo purposes)
                            Console.WriteLine(DateTime.Now.ToLongTimeString() + ": " + status);

                            if (status == "success")
                            {
                                // Execute request
                                string respFileJson = webClient.DownloadString(resultFileUrl);

                                Console.WriteLine(respFileJson);

                                break;
                            }
                            else if (status == "working")
                            {
                                // Pause for a few seconds
                                Thread.Sleep(3000);
                            }
                            else
                            {
                                Console.WriteLine(status);
                                break;
                            }
                        }
                        while (true);
                    }
                    else
                    {
                        Console.WriteLine(json["message"].ToString());
                    }
                }
                else
                {
                    Console.WriteLine(json["message"].ToString());
                }
            }
            catch (WebException ex)
            {
                Console.WriteLine(ex.ToString());
            }

            webClient.Dispose();

            Console.WriteLine();
            Console.WriteLine("Press any key...");
            Console.ReadKey();
        }

        static string CheckJobStatus(string jobId)
        {
            using (WebClient webClient = new WebClient())
            {
                // Set API Key
                webClient.Headers.Add("x-api-key", API_KEY);

                string url = "https://api.pdf.co/v1/job/check?jobid=" + jobId;

                string response = webClient.DownloadString(url);
                JObject json = JObject.Parse(response);

                return Convert.ToString(json["status"]);
            }
        }

    }
}


text:
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    style="@style/AppTheme"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.newsnap.activities.ThreadActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:background="@color/primary"
        android:layout_margin="5dp">

        <Button
            android:id="@+id/refresh_thread_button"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:layout_marginRight="5dp"
            android:background="@drawable/button_selector"
            android:text="Refresh"
            android:textSize="18dp"
            android:textColor="@color/text_light"
            android:textStyle="bold"/>

    </LinearLayout>

    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipe_refresh_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/thread_recycler_view"
            android:scrollbars="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/primary"/>

    </android.support.v4.widget.SwipeRefreshLayout>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/new_reply_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|right"
        android:src="@drawable/pen"
        app:elevation="4dp"
        app:borderWidth="0dp"
        app:fabSize="normal" />

</android.support.design.widget.CoordinatorLayout>


text:
import * as ts from 'typescript';
interface Options extends ts.CompilerOptions {
    genDir?: string;
    basePath?: string;
    skipMetadataEmit?: boolean;
    strictMetadataEmit?: boolean;
    skipTemplateCodegen?: boolean;
    flatModuleOutFile?: string;
    flatModuleId?: string;
    generateCodeForLibraries?: boolean;
    annotateForClosureCompiler?: boolean;
    annotationsAs?: 'decorators' | 'static fields';
    trace?: boolean;
    /** @deprecated since v4 this option has no effect anymore. */
    debug?: boolean;
    enableLegacyTemplate?: boolean;
    enableSummariesForJit?: boolean;
    alwaysCompileGeneratedCode?: boolean;
    preserveWhitespaces?: boolean;
}
export default Options;


text:
var Server = require('./server');
var Q = require('q');
var _ = require('lodash');

module.exports = function(gemini, opts) {
  var server = Server(opts.root);

  gemini.on('startRunner', function(runner) {
    var deferred = Q.defer();

    server.start(opts, function(rootUrl) {

      _.forEach(gemini.config._browsers, function(browser) {
        browser.rootUrl = rootUrl;
      });

      deferred.resolve();
    });

    return deferred.promise;
  });

  gemini.on('endRunner', function(runner, data) {
    var deferred = Q.defer();

    server.stop(function() {
      deferred.resolve();
    });

    return deferred.promise;
  });
};


text:
{{'ModalDialogCreateRegression.Header' | translate}}

        {{'DependentVariable' | translate}}

          <select
            class      ="ui dropdown"
            id         ="dependentVariable"
            name       ="dependentVariable"
            [(ngModel)]="dependentVariable"
          >
            <option *ngFor="let v of variables" [attr.value]="v.id">{{v.key}}</option>
          </select>

            <input
              type       ="checkbox"
              name       ="variable"
              [(ngModel)]="checkboxModel[i]"
            >

              {{v.key}}

  <button
    class  ="ui button"
    (click)="onClickSecondary()"
  >{{'Cancel' | translate}}</button>

  <button
    class  ="ui primary button"
    (click)="onClickPrimary()"
  >{{'OK' | translate}}</button>


text:
/**
 * Created by airswoop1 on 7/21/14.
 */
angular.module('formApp.modalDirective',[]).directive('modalDialog',function(){
    return {
        restrict: 'E',
        scope: {
            show: '='
        },
        replace: true, // Replace with the template below
        transclude: true, // we want to insert custom content inside the directive
        link: function(scope, element, attrs) {
            scope.dialogStyle = {};
            if (attrs.width)
                scope.dialogStyle.width = attrs.width;
            if (attrs.height)
                scope.dialogStyle.height = attrs.height;
            scope.hideModal = function() {
                scope.show = false;
            };

            scope.goToAddress = function() {
                scope.show = false;
                goAddress();
            }
        },
        controller : function($state){
          goAddress = function(){
              $state.go('form.address');
          };

        },
        templateUrl: 'templates/basic/modal.html'
    };
})


text:
<?php

/**
 * Action controller exception
 *
 * @package		Todoyu
 * @subpackage	Core
 */
class TodoyuControllerException extends Exception {
	/**
	 * Extension key
	 *
	 * @var	String
	 */
	private $ext;

	/**
	 * Controller
	 *
	 * @var	String
	 */
	private $ctrl;

	/**
	 * Action
	 *
	 * @var	String
	 */
	private $action;

	/**
	 * Initialize
	 *
	 * @param	String		$ext
	 * @param	String		$ctrl
	 * @param	String		$action
	 * @param	String		$message
	 * @param	Integer		$code
	 */
	public function __construct($ext, $ctrl, $action, $message, $code = 0) {
		parent::__construct($message, $code);

		$this->ext		= $ext;
		$this->ctrl		= $ctrl;
		$this->action	= $action;
	}

	/**
	 * Get extension key
	 *
	 * @return	String
	 */
	public function getExt() {
		return $this->ext;
	}

	/**
	 * Get controller name
	 *
	 * @return	String
	 */
	public function getController() {
		return $this->ctrl;
	}

	/**
	 * Get action
	 *
	 * @return	String
	 */
	public function getAction() {
		return $this->action;
	}

	/**
	 * Print exception with TodoyuDebug
	 */
	public function printError() {
		TodoyuDebug::printInFirebug($this->getMessage(), 'Controller Exception');
	}

}

?>


text:
> Replace the attribute of any html tag

## Getting Started
> This plugin requires Grunt `~0.4.5`

If you haven't used [Grunt](http://gruntjs.com/) before, be sure to check out the [Getting Started](http://gruntjs.com/getting-started) guide, as it explains how to create a [Gruntfile](http://gruntjs.com/sample-gruntfile) as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command:

```shell
npm install grunt-replace-attribute --save-dev
```

Once the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:

```js
grunt.loadNpmTasks('grunt-replace-attribute');
```

## The "replace_attribute" task

### Overview
In your project's Gruntfile, add a section named `replace_attribute` to the data object passed into `grunt.initConfig()`.

```js
grunt.initConfig({
  replace_attribute: {
    options: {
      upsert: true
    },
    your_target: {
      options: {
        replace: {
          'div.batman': { class: '%value% > superman' }
        }
      }
      files: {
          'destination.html': 'source.html'
      }
    },
  },
});
```

### Options

#### options.upsert
Type: `Object|Boolean`
Default value: `false`

Determines whether to add a new attribute to an element if it is not already present.

Either set the option globally, for all selectors:

```js
upsert: true|false // always|never insert a new attribute
```

or for individual tags:

```js
upsert: { div: false, input: true }
```
#### options.placeholder
Type `String`
Default value: `'%value%'`

This is the placeholder for the current attribute value. See the examples below for more detail.

#### options.replace
Type: `Object`

An Object containing the configuration for your target selectors.

`grunt-replace-attribute` uses [node-trumpet](https://github.com/substack/node-trumpet), so any of the following selectors should work:

* *
* E
* E F
* E > F
* E + F
* E.class
* E#id
* E[attr=value]
* E[attr~=search]
* E[attr|=prefix]
* E[attr^=prefix]
* E[attr$=suffix]
* E[attr*=search]

#### options.replace.{tag name}
Type: `Object`

An Object which maps attribute names to their replacements.
Each attribute name can be one of the following types:
***
###### Type: `String`
The new attribute value. The current attribute value can be referenced using the syntax `%value%`. (See options.placeholder to change this).
###### Type `Array`
An array containing a regular expression and a string to be passed as arguments to String's `replace` method.
###### Type `Function`
A function which returns the new attribute value. The current attribute is available as the first argument.
***

### Usage Examples

#### Basic example using Strings
In this example, we replace all the `class` attributes on each `span` element with the value `text-center`. `options.upsert` is omitted, so only elements which already have a `class` attribute will be modified.

```js
grunt.initConfig({
  replace_attribute: {
    target: {
      options: {
        replace: {
          span: { class: 'text-center' }
        }
      },
      files: {
        'path/to/destination.html': 'path/to/source.html'
      }
    }
  }
});
```

```html
<!-- source.html -->
<div class="container">
    <span class="text-left">My class will be modified</span>
    <span>My class will not be modified</span>
</div>

<!-- destination.html -->
<div class="container">
    <span class="text-center">My class will be modified</span>
    <span>My class will not be modified</span>
</div>
```

#### Using Strings with `%value%`
In this example, we append `pull-right` on to the value of all the `class` attributes of each `div` element. `options.upsert` is set to `true`, so all div elements will be modified.

```js
grunt.initConfig({
  replace_attribute: {
    target: {
      options: {
        upsert: true,
          replace: {
          div: { class: '%value% pull-right' }
        }
      },
      files: {
        'path/to/destination.html': 'path/to/source.html'
      }
    }
  }
});
```

```html
<!-- source.html -->
<div class="label">
    <div>My class will be modified</div>
</div>

<!-- destination.html -->
<div class="label pull-right">
    <div class="pull-right">My class will be modified</div>
</div>
```

#### Using Regular Expressions
In this example, we use a regex to modify each `li`'s `class` attribute, appending `-banana` onto the match.
The two arguments are given to `String.replace` so we can use the `$1, $2, $3 ...` syntax to reference each match.

```js
grunt.initConfig({
  replace_attribute: {
    target: {
      options: {
        replace: {
          li: { class: [/(one|two|three)/g, '$1-banana'] }
        }
      },
      files: {
        'path/to/destination.html': 'path/to/source.html'
      }
    }
  }
});
```

```html
<!-- source.html -->
<li class="one"></li>
<li class="two"></li>
<li class="three"></li>
<li class="four"></li>

<!-- destination.html -->
<li class="one-banana"></li>
<li class="two-banana"></li>
<li class="three-banana"></li>
<li class="four"></li>
```

#### Using Functions
In this example we reverse the path of the `src` value on all `img` elements using a function.

```js
grunt.initConfig({
  replace_attribute: {
    target: {
      options: {
        replace: {
          img: {
            src: function (original) {
              return original.split('/').reverse().join('/');
            }
          }
        }
      },
      files: {
        'path/to/destination.html': 'path/to/source.html'
      }
    }
  }
});
```

```html
<!-- source.html -->
<img src="path/to/an/img" >

<!-- destination.html -->
<img src="img/an/to/path" >
```

#### Using more complex selectors
In this example, we use a more complex selector to add a `style="opacicty:0.5;"` attribute to `span`s within `li` elements which have the class `disabled` and all other elements which have the attribute `data-fade="true"`.

```js
grunt.initConfig({
  replace_attribute: {
    target: {
      options: {
        upsert: { h1: true, span: true },
        replace: {
          '*[data-fade=true], li.disabled > span': { style: 'opacicty:0.5;' }
        }
      },
      files: {
        'path/to/destination.html': 'path/to/source.html'
      }
    }
  }
});
```

```html
<!-- source.html -->
<div class="heading">
    <h1 data-fade="true" >Heading</h1>
    <span>Description</span>
</div>
<ul class="list-group">
    <li class="list-group-item disabled">
        <span>Item 1</span>
    </li>
    <li class="list-group-item">
        <span>Item 2</span>
    </li>
    <li class="list-group-item disabled">
        <span>Item 3</span>
    </li>
</ul>

<!-- destination.html -->
<div class="heading">
    <h1 data-fade="true" style="opacicty:0.5;">Heading</h1>
    <span>Description</span>
</div>
<ul class="list-group">
    <li class="list-group-item disabled" style="opacicty:0.5;">
        <span>Item 1</span>
    </li>
    <li class="list-group-item">
        <span>Item 2</span>
    </li>
    <li class="list-group-item disabled" style="opacicty:0.5;">
        <span>Item 3</span>
    </li>
</ul>
```

## Known Issues
* self-closing tags

if an input tag which closes itself is modified, the output tag is stripped of the forward slash. This may pose a problem if it conflicts with your htmlhint options.
```html
<input class="foo" />
<!-- becomes -->
<input class="bar">
```

## Contributing
In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [Grunt](http://gruntjs.com/).

## Release History
* v 1.0.0 - Initial Release