text:
using System.Linq;
using System.Reflection;
using Xunit;

namespace System.Runtime.InteropServices.Tests
{
    public class HandleRefTests
    {
        [Fact]
        public void Properties()
        {
            var obj = new object();
            var ptr = new IntPtr(1337);
            var handleRef = new HandleRef(obj, ptr);
            Assert.Equal(ptr, (IntPtr)handleRef);
            Assert.Equal(ptr, HandleRef.ToIntPtr(handleRef));
            Assert.Equal(ptr, handleRef.Handle);
            Assert.Same(obj, handleRef.Wrapper);
        }
    }
}


text:
<?php

use app\core\helpers\Html;
use app\core\helpers\ArrayHelper;

use yii\widgets\ActiveForm;
use kartik\select2\Select2;
?>

                    <form action="">

                    </form>

redpajama_set_name: RedPajamaGithub


text:
I haven't mentioned them before, but many times in the past, I've played around
with from-scratch implementations of conduit to test out new theories. I've
tried having versions without automatic termination of any sort, different
orderings of finalizers, various different ways of handling leftovers, and
strict adherence to the category laws. Each one of them has taught me
something, but since the 1.0 release, none of them were enough of an
improvement on what exists already to warrant the pain in switching. And
frankly, most of them were far worse than what we already have.

A few days ago, Gabriel Gonzalez [wrote a blog
post](http://www.haskellforall.com/2014/02/pipes-parse-30-lens-based-parsing.html)
about the newest release of pipes-parse. Given that we've had many
conversations over the years- both publicly and privately- about the directions
of our libraries, I wasn't surprised that the core idea behind this library is
something we'd discussed once before, and in fact was an idea I'd even tried
out for conduit once. Based on that experience, I'd like to share some ideas on
how Gabriel (or others) could approach the problem a bit differently, and
possibly avoid some user-facing issues.

## Proliferation of APIs

Before discussing the details of leftovers themselves, let mention what I
consider the primary issue. It seems that each new feature added to pipes is
introducing a completely separate API. Consider, for example, a simple
question: how do you get the next value in a stream? In the conduit world, the
answer is `await`. There are also some convenience functions built on
top of `await`: `awaitForever`, `peek`, `mapM_`, etc. But there is just one
primitive for awaiting values, and it has the same type everywhere:

    await :: Monad m => Consumer i m (Maybe i)

In the pipes world, there are now (to my knowledge) three different "get the
next value" primitives:

```haskell
await :: Monad m => Consumer' a m a
next :: Monad m => Producer a m r -> m (Either r (a, Producer a m r))
draw :: Monad m => Parser a m (Maybe a)
```

This in turn means that utility functions need to be written multiple times, in
different ways, depending on the context in which they're needed. For example,
`takeWhile` in `Pipes.Prelude` works on a "normal" `Pipe`, but will silently
discard one extra value from the stream since a normal `Pipe` does not support
leftovers. `span` from `Pipes.Parse` performs essentially the same
functionality, but works in the `Parser`/leftover aware realm.

One of the biggest changes to come to the conduit library was the unification
of the `Source`, `Sink`, and `Conduit` datatypes into a single datatype, called
`Pipe`. And the reason it's called `Pipe` is, as you might guess, because it
was inspired from the `pipes` world (via [Twan van
Laarhoven](http://twanvl.nl/blog/haskell/conduits-vs-pipes)). Though I was
skeptical at first about the confusion in error messages and type signatures
which may have ensued, the net result was, in my mind, undeniably positive.

It seems to me like pipes is now at that same kind of crossroads. There are a
large number of different data types and type synonyms, different ways of
composing things together, and different functionality depending on what type
you're using. I'd recommend standardizing on one as the canonical entry point
to pipes, and make the standard libraries all use that API.

It seems like the `Parser` API is the best suited for this task. Unless I'm
mistaken, all of the folding functions in `Pipes.Prelude` (e.g., `toList`) can
be implemented in terms of `Parser`, and it adds the capability of leftovers.
If this change happened, then functions like `takeWhile` would no longer have
to silently discard data from the data stream either.

Side note: you might think that `conduit` has lots of different kinds of
composition due to the three different fusion operators, `$=`, `=$`, and `=$=`.
In reality, they're all type-restricted aliases for the same function. The
question of whether they should be type restricted at all is a good debate to
have, but that's not my topic here.

## Overview of approaches

With that more general comment out of the way, let's get into the details of
`Parser`.  Leftovers may seem like a really complicated concept, and (at least
to me) lens-based parsing sounds pretty intimidating. However, the core
concepts here are pretty trivial, and I think most people faced with the same
constraints would end up with similar solutions to what the major streaming
data libraries have. To motivate this, let's consider the simplest of all
streaming data: pure lists.

In our case, we'll store our "data producer" (i.e., a list) in a `State` monad.
Getting another value from the stream (a.k.a., awaiting, drawing) means getting
the list, popping an element off the top, putting back the smaller list, and
returning the popped element. Putting a value back in the stream (a.k.a.,
undrawing, leftover) means getting the list, sticking an element at the
beginning, and putting it back. This can all be embodied in very little
Haskell code:

```haskell
import Control.Monad.Trans.State.Strict

type Parser a r = State [a] r

-- In conduit, this is await
draw :: Parser a (Maybe a)
draw = do
    list <- get
    case list of
        [] -> return Nothing
        x:xs -> do
            put xs
            return (Just x)

-- In conduit, this is leftover
unDraw :: a -> Parser a ()
unDraw a = do
    list <- get
    put $ a:list
```

At its core, this is what pipes-parse is doing. Instead of a pure list, it's
using a `Producer`, which is really just a list transformer. But there's
another, slightly less obvious approach that we could take instead. Right now,
we're sticking leftovers right back on the same stack, making it impossible to
distinguish between values taken from the original stream, and values leftover
from the `Parser`. Instead, we could store a tuple in the `State` monad: the
original list, and the leftovers. This is also pretty easy to code:

```haskell
import Control.Monad.Trans.State.Strict

type Parser a r = State ([a], [a]) r

-- In conduit, this is await
draw :: Parser a (Maybe a)
draw = do
    (list, leftovers) <- get
    case leftovers of
        x:leftovers' -> do
            put (list, leftovers')
            return (Just x)
        [] ->
            case list of
                [] -> return Nothing
                x:list' -> do
                    put (list', leftovers)
                    return (Just x)

-- In conduit, this is leftover
unDraw :: a -> Parser a ()
unDraw a = do
    (list, leftovers) <- get
    put (list, a:leftovers)
```

While this certainly works, it seems a little overkill: what possible benefit
is there in having this separation? Well, it would allow us to distinguish
between "completely unparsed values" and "parsed and leftovered" values. In our
discussion so far, and in the documentation for pipes-parse, I see absolutely
no reason why this feature would be relevant. However, let me introduce a
non-trivial parsing example to motivate things a bit further.

## An archive file format

Let's say for some (probably bad) reason we've decided that the tar file format
is unsuitable for our purposes. Instead, we've come up with a new file format
that works as follows:

* Each file consists of a textual filename and binary contents.
* The filename will be UTF8 encoded.
* We will encode lengths using a variation on netstrings: the decimal representation of the length followed by a colon.
* Each file will be encoded as the length of the textual filename, its UTF-8 representation, the length of its binary contents, and the contents.

Yes, this example is ridiculous, but I wanted to find something that would
demonstrate pipes-parse's ability to handle leftover preserving. To make the
above description a bit easier to understand, here's the Haskell code to encode
a list of these files:

```haskell
data File = File
    { fileName     :: !Text
    , fileContents :: !ByteString
    }
    deriving Show

encodeFile :: File -> Builder
encodeFile (File name contents) =
    tellLen (T.length name) <>
    fromByteString (TEE.encodeUtf8 name) <>
    tellLen (S.length contents) <>
    fromByteString contents
  where
    tellLen i = fromByteString $ TEE.encodeUtf8 $ T.pack $ shows i ":"

encodeFiles :: [File] -> Builder
encodeFiles = mconcat . map encodeFile
```

What's important for the parsing is that we will need to switch back and forth
between a binary and a textual stream of data in order to handle this
correctly. (Note: in reality, if for some terrible reason you decide to
actually implement this format, you should encode the filename length using the
__byte count__, not the character count. I specifically used the character
count to force this awkward kind of stream switching.)

I've [implemented the parser in conduit](https://gist.github.com/snoyberg/8888288) if anyone's interested in checking it out. The magic leftover-preserving occurs in the `withUtf8` function:

```haskell
withUtf8 :: MonadThrow m
         => ConduitM Text o m r
         -> ConduitM ByteString o m r
withUtf8 =
    fuseLeftovers toBS (CT.decode CT.utf8)
  where
    toBS = L.toChunks . TLE.encodeUtf8 . TL.fromChunks
```

We're saying to convert the stream to text assuming a UTF8 encoding. We'll
generate chunks of text on demand (i.e., lazily), and will stop once we hit an
invalid UTF8 sequence (that's the behavior of `Data.Conduit.Text`). Then, after
downstream is done, collect all of the leftovers that it generated, and convert
them back to their binary representation.

Obviously, in order to do this, we need to be able to distinguish between the
consumed upstream and the leftovers from downstream. If we cannot make that
distinction, we'd be forced to encode the *entire* stream into text, take out
the text that we need, and then convert the rest of the stream *back* to
binary. Moreover, we'd have to perform the conversion back and forth for each
time we call `withUtf8`. And even worse than the performance hit is the fact
that it may not work: if the byte stream contains invalid UTF8 character
sequences, this may break, depending on how your parser handles such invalid
sequences.

I'm fairly certain that pipes-parse falls prey to this issue. (If I've
misunderstood the library, please correct me, and I'll include the correction
here.) `conduit` handles the issue differently: the "parser" (a.k.a., `Sink`)
has an explicit command for reporting leftovers, and it's up to the composition
operator to decide how to handle the leftovers. The standard operators- `$=`,
`=$` and `=$=`- use a similar trick to pipes-parse, and stick the leftovers
onto the upstream `Source`. And that's precisely why they have the behavior of
discarding downstream leftovers. However, this is just a sensible default, not
a requirement of conduit. It took me under five minutes to write [an
alternative composition
function](http://hackage.haskell.org/package/conduit-extra-0.1.4/docs/Data-Conduit-Extra.html#v:fuseReturnLeftovers)
that had leftover preserving behavior instead.

### Simpler example

I tried to make the above example somewhat realistic, but the details may be a
bit overwhelming. Instead, let's consider something much simpler: an
isomorphism between two data types. We want to convert the stream from type `A`
to type `B`, perform some peeking, and then deal with the rest of the stream.
An example of doing this with conduit would be:

```haskell
import           Control.Applicative ((<$>), (<*>))
import           Data.Conduit        (yield, ($$), (=$=))
import           Data.Conduit.Extra  (fuseLeftovers)
import qualified Data.Conduit.List   as CL
import           Debug.Trace         (traceShow)

newtype A = A Int
    deriving Show
newtype B = B Int
    deriving Show

atob (A i) = traceShow ("atob", i) (B i)
btoa (B i) = traceShow ("btoa", i) (A i)

main :: IO ()
main = do
    let src = mapM_ (yield . A) [1..10]
    res <- src $$ (,,,)
        <$> fuseLeftovers (map btoa) (CL.map atob) CL.peek
        <*> CL.take 3
        <*> (CL.map atob =$= CL.take 3)
        <*> CL.consume
    print res
```

We have the numbers 1 through 10 as type `A`. In our `Sink`, we first convert
the stream to type `B`, peek, and then return the leftovers upstream. Then we
take three `A`s, again convert to `B` and take three more elements, and finally
consume the remainder of the stream. I've added trace statements to demonstrate
exactly how many conversions are performed:

```
("atob",1)
("btoa",1)
("atob",4)
("atob",5)
("atob",6)
(Just (B 1),[A 1,A 2,A 3],[B 4,B 5,B 6],[A 7,A 8,A 9,A 10])
```

The conversions that occur are the absolute bare minimum than could occur: the
first element has to be converted to `B` in order to be `peek`ed at, and then
converted back to `A` to return to the original stream. Then, when we later
take three more elements of type `B`, they obviously need to be converted.

Let's look at the equivalent in pipes-parse, [courtesy of Joseph Abrahamson](http://stackoverflow.com/questions/21649920/using-pipes-parse-to-preserve-leftovers-with-a-map/21650705):

```haskell
{-# LANGUAGE RankNTypes #-}
import           Control.Applicative
import           Control.Lens               (Iso', from, iso, view, zoom)
import           Control.Monad.State.Strict (evalState)
import           Debug.Trace
import           Pipes
import           Pipes.Core                 as Pc
import qualified Pipes.Parse                as Pp
import qualified Pipes.Prelude              as P

newtype A = A Int
    deriving Show
newtype B = B Int
    deriving Show

atob (A i) = traceShow ("atob", i) (B i)
btoa (B i) = traceShow ("btoa", i) (A i)

ab :: Iso' A B
ab = iso atob btoa

piso :: Monad m => Iso' a b -> Iso' (Producer a m r) (Producer b m r)
piso i = iso (P.map (view i) <-<) (>-> P.map (view $ from i))

main :: IO ()
main = do
  let src = P.map A <-< each [1..10]
  let parser = (,,,) <$> zoom (piso ab) Pp.peek
                     <*> zoom (Pp.splitAt 3) Pp.drawAll
                     <*> zoom (Pp.splitAt 3 . piso ab) Pp.drawAll
                     <*> Pp.drawAll
  let res = evalState parser src
  print res
```

The result is the same, but look at the traces:

```
("atob",1)
("btoa",1)
("atob",2)
("btoa",2)
("atob",3)
("btoa",3)
("atob",4)
("btoa",4)
("atob",4)
("atob",5)
("btoa",5)
("atob",5)
("atob",6)
("btoa",6)
("atob",6)
("atob",7)
("btoa",7)
("atob",8)
("btoa",8)
("atob",9)
("btoa",9)
("atob",10)
("btoa",10)
(Just (B 1),[A 1,A 2,A 3],[B 4,B 5,B 6],[A 7,A 8,A 9,A 10])
```

As described above, in pipes-parse you need to convert the entire stream. In
our example, the conversion is trivial, and therefore not too worrying. But in
the case of either an expensive conversion, or a possibly-failing conversion,
this behavior would be incredibly problematic.

__UPDATE__: Davorak on Reddit helped me [come up with a better
example](http://www.reddit.com/r/haskell/comments/1xmmtn/some_ideas_for_pipesparse/cfcr1jq)
which demonstrates not just doubled encoding, but a program not completing
correctly. The conduit/pipes comparison code is [available as a
Gist](https://gist.github.com/snoyberg/8943391).

So my second recommendation would be to tweak `Parser` to have a stack of
leftovers in addition to a `Producer`, which would allow for more powerful
leftover preserving

## Drop lenses

If you take the two recommendations above, you'll end up with a large
collection of pipes-parse-ready functions, like `take` and `takeWhile`. And
each of these functions will maintain a stack of leftovers, either to be used
by the next monadically-composed `Parser`, or to perhaps propagate upstream. At
this point, the lens-based approach to leftovers is overkill.

The problem with the lens approach is twofold. Firstly, it's difficult for
people to understand. The core concept is not complex, but the machinery around
it obscures its simplicity. But more importantly, it does not seem to compose
well. I don't mean that in the sense of lens or function composition: clearly
those work as expected. What I mean is that you won't be able to take the
existing utility functions I mentioned above and automatically use them in a
leftover-propagating manner.

I'd recommend borrowing from the conduit solution here directly: just have a
separate composition function or operator that returns the downstream
leftovers. It's a simple concept, it's easy to show in a type signature, and
it's easy to build more complex solutions on top of it.

I'll even argue that Gabriel's announcement post is in line with this
recommendation: as pointed out, the lens laws are being bent by pipes-parse. If
there's a separate solution that requires no law bending, why not use that?

Let me be clear: I'm not at all implying that lenses themselves are the problem
here. I think the problem is treating leftover propagation as an isomorphism
between two producers. I think lenses can actually play very nicely with a
streaming data package. I've been working on some conduit data analysis
libraries that make heavy usage of lens to let users write much simpler code
(things like `filterField stockDate (< today)`).

So to reiterate my third recommendation: provide a composition operator for
dealing with leftovers explicitly, let users reuse your existing library of
functions, and don't force them to try to write isomorphisms on entire streams
where a simple predicate function will suffice.

I hope these ideas come across the right way: ideas that I think would improve
the pipes ecosystem. These ideas should be taken with a large grain of salt.
They are strongly inspired by my experience with conduit, and with the kinds of
work I tend to see conduit applied to.


text:
using JohnLambe.Util.Collections;
using JohnLambe.Util.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MvpFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using static JohnLambe.Tests.JLUtilsTest.TestUtil;

namespace MvpFrameworkTest
{
    [TestClass]
    public class AcceleratorCaptionUtilTest
    {
        [TestMethod]
        public virtual void GetAccelerator()
        {
            Multiple(
                () => Assert.AreEqual('P',util.GetAccelerator("&Print")),
                () => Assert.AreEqual('p', util.GetAccelerator("&print")),
                () => Assert.AreEqual('&', util.GetAccelerator("A&&B")),
                () => Assert.AreEqual(null, util.GetAccelerator(null)),
                () => Assert.AreEqual(null, util.GetAccelerator("No accelerator")),
                () => Assert.AreEqual('t', util.GetAccelerator("A but&ton")),
                () => Assert.AreEqual(null, util.GetAccelerator("A button&")),
                () => Assert.AreEqual('o', util.GetAccelerator("Tw&o accelerato&rs"))
            );
        }

        [TestMethod]
        public virtual void DisplayNameToCaption()
        {
            Multiple(
                () => Assert.AreEqual("Print and Store", util.DisplayNameToCaption("Print & Store")),
                () => Assert.AreEqual("Print / Store", util.DisplayNameToCaption("Print / Store")),
                () => Assert.AreEqual("Print and &Store", util.DisplayNameToCaption("Print & Store", 's')),
                () => Assert.AreEqual("A and B and C", util.DisplayNameToCaption("A & B & C"))
            //TODO: heuristic adding of space and capitalisation
            );
        }

        [TestMethod]
        public virtual void CaptionToDisplayName()
        {
            Multiple(
                () => Assert.AreEqual("Print and Store", util.CaptionToDisplayName("Print and Store")),
                () => Assert.AreEqual("Print", util.CaptionToDisplayName("&Print")),
                () => Assert.AreEqual("Abcde", util.CaptionToDisplayName("A&bc&de"))
            );
        }

        [TestMethod]
        public virtual void SetAccelerator()
        {
            util.AcceleratorsUsed = null;  // no duplicate tracking

            Multiple(
                () => Assert.AreEqual("Prin&t and Store", util.SetAccelerator("Print and Store",'t')),
                () => Assert.AreEqual("Prin&t and Store", util.SetAccelerator("Print and Store", 'T'), "Different letter case"),
                () => Assert.AreEqual("Print and Store", util.SetAccelerator("Print and Store", null)),
                () => Assert.AreEqual("Print and Store [&z]", util.SetAccelerator("Print and Store", 'z')),
                () => Assert.AreEqual("Print and Store [&Z]", util.SetAccelerator("Print & Store", 'Z')),
                () => Assert.AreEqual("Print and &Archive", util.SetAccelerator("Print and Archive", 'a')),
                () => Assert.AreEqual("Print &and Store", util.SetAccelerator("Print & Store", 'A')),
                () => Assert.AreEqual("&Print page", util.SetAccelerator("Print page", 'p'), "First character"),
                () => Assert.AreEqual("print &Page", util.SetAccelerator("print Page", 'p'), "Prefer capital"),
                () => Assert.AreEqual(" [&+]", util.SetAccelerator("", '+'), "Blank original"),
                () => Assert.AreEqual(null, util.SetAccelerator(null, '+'), "null original")
            );
        }

        [TestMethod]
        public virtual void SetAccelerator_Remove()
        {
            util.AcceleratorsUsed = null;  // no duplicate tracking

            Multiple(
                () => Assert.AreEqual("Undo", util.SetAccelerator("Undo [&Z]", null, AcceleratorCaptionUtil.ExistingAccelerartorAction.Remove)),
                () => Assert.AreEqual("&Undo", util.SetAccelerator("Undo [&Z]", 'u', AcceleratorCaptionUtil.ExistingAccelerartorAction.Remove)),
                () => Assert.AreEqual("Undo [&.]", util.SetAccelerator("Undo [&Z]", '.', AcceleratorCaptionUtil.ExistingAccelerartorAction.Remove)),
                () => Assert.AreEqual("Undo", util.SetAccelerator("Und&o [&U]", null, AcceleratorCaptionUtil.ExistingAccelerartorAction.Remove))
            );
        }

        [TestMethod]
        [ExpectedException(typeof(KeyExistsException))]
        public virtual void SetAccelerator_Duplicate()
        {
            // Arrange:
            Console.Out.WriteLine(util.SetAccelerator("Print and Archive", 'a'));

            // Act:
            Console.Out.WriteLine(util.SetAccelerator("Print & Store", 'A'));
        }

        [TestMethod]
        [ExpectedException(typeof(KeyExistsException))]
        public virtual void SetAccelerator_Automatic()
        {
            // Arrange:
            util.SetAccelerator("Print and Archive", 'a');

            // Act:
            util.SetAccelerator("Print & Store", 'A');
        }

        [TestMethod]
        public virtual void GenerateAccelerator()
        {
            Multiple(
                () => Assert.AreEqual("&Print and Store", util.GenerateAccelerator("Print and Store")),
                () => Assert.AreEqual("Print and &Store", util.GenerateAccelerator("Print and Store")),
                () => Assert.AreEqual("PPS 4&b", util.GenerateAccelerator("PPS 4b"), "Chooses the lowercase letter over the digit"),
                () => Assert.AreEqual("PS-&2", util.GenerateAccelerator("PS-2"), "Chooses the digit because all others are used"),
                () => Assert.AreEqual("pPSB [&A]", util.GenerateAccelerator("pPSB"), ""),
                () => Assert.AreEqual("P2SB [&C]", util.GenerateAccelerator("P2SB"), "")
            );
        }

        /// <summary>
        /// Chooses a digit because all letters are used.
        /// </summary>
        [TestMethod]
        public virtual void GenerateAccelerator_AllLettersUsed()
        {
            // Arrange:
            foreach(var c in CharacterUtil.AsciiLowercaseLetters)   // flag all letters as used
                util.AddAcceleratorUsed(c);
            util.AddAcceleratorUsed('0');

            // Act / Assert:
            Assert.AreEqual("New Blog Entry [&1]", util.GenerateAccelerator("New Blog Entry"));
        }

        /// <summary>
        /// Can't assign any accelerator character because all valid ones are used.
        /// </summary>
        [TestMethod]
        public virtual void GenerateAccelerator_AllUsed()
        {
            // Arrange:
            foreach (var c in util.AllowedAddedAcceleratorCharacters)   // flag all valid as used
                util.AddAcceleratorUsed(c);

            // Act / Assert:
            Assert.AreEqual("New Blog Entry 5", util.GenerateAccelerator("New Blog Entry 5"));
        }

        //TODO: Test with other configuration settings

        protected MvpFramework.AcceleratorCaptionUtil util = new MvpFramework.AcceleratorCaptionUtil();
    }
}


text:
package org.apache.jmeter.modifiers.gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JCheckBox;

import org.apache.jmeter.config.gui.AbstractConfigGui;
import org.apache.jmeter.modifiers.CounterConfig;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.gui.JLabeledTextField;
import org.apache.jorphan.gui.layout.VerticalLayout;

public class CounterConfigGui extends AbstractConfigGui implements ActionListener {
    private static final long serialVersionUID = 240L;

    private JLabeledTextField startField;
    private JLabeledTextField incrField;
    private JLabeledTextField endField;
    private JLabeledTextField varNameField;
    private JLabeledTextField formatField;
    private JCheckBox resetCounterOnEachThreadGroupIteration;

    private JCheckBox perUserField;

    public CounterConfigGui() {
        super();
        init();
    }

    @Override
    public String getLabelResource() {
        return "counter_config_title";//$NON-NLS-1$
    }

    /**
     * @see org.apache.jmeter.gui.JMeterGUIComponent#createTestElement()
     */
    @Override
    public TestElement createTestElement() {
        CounterConfig config = new CounterConfig();
        modifyTestElement(config);
        return config;
    }

    /**
     * Modifies a given TestElement to mirror the data in the gui components.
     *
     * @see org.apache.jmeter.gui.JMeterGUIComponent#modifyTestElement(TestElement)
     */
    @Override
    public void modifyTestElement(TestElement c) {
        if (c instanceof CounterConfig) {
            CounterConfig config = (CounterConfig) c;
            config.setStart(startField.getText());
            // Bug 22820 if (endField.getText().length() > 0)
            {
                config.setEnd(endField.getText());
            }
            config.setIncrement(incrField.getText());
            config.setVarName(varNameField.getText());
            config.setFormat(formatField.getText());
            config.setIsPerUser(perUserField.isSelected());
            config.setResetOnThreadGroupIteration(resetCounterOnEachThreadGroupIteration.isEnabled()
                    && resetCounterOnEachThreadGroupIteration.isSelected());
        }
        super.configureTestElement(c);
    }

    /**
     * Implements JMeterGUIComponent.clearGui
     */
    @Override
    public void clearGui() {
        super.clearGui();

        startField.setText(""); //$NON-NLS-1$
        incrField.setText(""); //$NON-NLS-1$
        endField.setText(""); //$NON-NLS-1$
        varNameField.setText(""); //$NON-NLS-1$
        formatField.setText(""); //$NON-NLS-1$
        perUserField.setSelected(false);
        resetCounterOnEachThreadGroupIteration.setEnabled(false);
    }

    @Override
    public void configure(TestElement element) {
        super.configure(element);
        CounterConfig config = (CounterConfig) element;
        startField.setText(config.getStartAsString());
        endField.setText(config.getEndAsString());
        incrField.setText(config.getIncrementAsString());
        formatField.setText(config.getFormat());
        varNameField.setText(config.getVarName());
        perUserField.setSelected(config.isPerUser());
        if(config.isPerUser()) {
            resetCounterOnEachThreadGroupIteration.setEnabled(true);
            resetCounterOnEachThreadGroupIteration.setSelected(config.isResetOnThreadGroupIteration());
        } else {
            resetCounterOnEachThreadGroupIteration.setEnabled(false);
        }
    }

    private void init() {
        setBorder(makeBorder());
        setLayout(new VerticalLayout(5, VerticalLayout.BOTH));

        startField = new JLabeledTextField(JMeterUtils.getResString("start"));//$NON-NLS-1$
        incrField = new JLabeledTextField(JMeterUtils.getResString("increment"));//$NON-NLS-1$
        endField = new JLabeledTextField(JMeterUtils.getResString("max"));//$NON-NLS-1$
        varNameField = new JLabeledTextField(JMeterUtils.getResString("var_name"));//$NON-NLS-1$
        formatField = new JLabeledTextField(JMeterUtils.getResString("format"));//$NON-NLS-1$
        perUserField = new JCheckBox(JMeterUtils.getResString("counter_per_user"));//$NON-NLS-1$
        resetCounterOnEachThreadGroupIteration = new JCheckBox(JMeterUtils.getResString("counter_reset_per_tg_iteration"));//$NON-NLS-1$
        add(makeTitlePanel());
        add(startField);
        add(incrField);
        add(endField);
        add(formatField);
        add(varNameField);
        add(perUserField);
        add(resetCounterOnEachThreadGroupIteration);

        perUserField.addActionListener(this);
    }

    /**
     * Disable/Enable resetCounterOnEachThreadGroupIteration when perUserField is disabled / enabled
     */
    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == perUserField) {
            resetCounterOnEachThreadGroupIteration.setEnabled(perUserField.isSelected());
        }
    }
}


text: from eda.components.LDO import *


text:
package com.twitter.hraven.etl;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;

import com.twitter.hraven.Constants;

/**
 * Class that handles Job files, whether confs files or history files.
 *
 */
public class JobFile implements Writable {

  private static final Pattern PATTERN = Pattern
      .compile(Constants.JOB_FILENAME_PATTERN_REGEX);

  private static final Pattern CONF_PATTERN = Pattern
      .compile(Constants.JOB_CONF_FILE_END);

  private static final Log LOG = LogFactory.getLog(JobFile.class);
  private String filename;
  private String jobid = null;
  private boolean isJobConfFile = false;
  private boolean isJobHistoryFile = false;

  /**
   * Default constructor. Used by reflection utils in combination with {@link #readFields(DataInput)}
   */
  public JobFile() {

  }

  /**
   * Constructor
   *
   * @param name
   *          of the file (that may or may not be a job file).
   */
  public JobFile(String filename) {
    if (null == filename) {
      this.filename = "";
    } else {
      this.filename = filename;
    }
    parseFilename();
  }

  /**
   * Parse the filename and pull the jobtracker and jobid out of it.
   */
  private void parseFilename() {

    // Add additional filtering to discard empty files, or files ending in .crc
    if ((filename != null) && (filename.length() > 0)
        && (!filename.endsWith(".crc"))) {

      Matcher matcher = PATTERN.matcher(filename);

      if (matcher.matches()) {
    	//  jobTracker = "";
    	  jobid = matcher.group(1);
    	  Matcher confMatcher = CONF_PATTERN.matcher(filename);
    	  if (confMatcher.matches()) {
        	isJobConfFile = true;
        	LOG.debug("Job Conf file  " + filename + " with job id: " + jobid);
        	} else {
        		isJobHistoryFile = true;
        		LOG.debug("Job History file " + filename + " with job id: " + jobid);
        		}
    	  }
      else {
          LOG.info(" file does not match any format: " + filename);
      }
    }
  }

  /**
   * @return the name of this file.
   */
  public String getFilename() {
    return filename;
  }

  /**
   * @return the job ID for this job as parsed through the filename or null if
   *         this is not a valid job file.
   */
  public String getJobid() {
    return jobid;
  }

  /**
   * @return whether this file is a JobConfFile
   */
  public boolean isJobConfFile() {
    return isJobConfFile;
  }

  /**
   * @return whether this file is a JobHistoryFile
   */
  public boolean isJobHistoryFile() {
    return isJobHistoryFile;
  }

  /*
   * (non-Javadoc)
   *
   * @see org.apache.hadoop.io.Writable#write(java.io.DataOutput)
   */
  @Override
  public void write(DataOutput out) throws IOException {
    Text.writeString(out, filename);
    Text.writeString(out, jobid);
    out.writeBoolean(isJobConfFile);
    out.writeBoolean(isJobHistoryFile);
  }

  /*
   * (non-Javadoc)
   *
   * @see org.apache.hadoop.io.Writable#readFields(java.io.DataInput)
   */
  @Override
  public void readFields(DataInput in) throws IOException {
    this.filename = Text.readString(in);
    this.jobid = Text.readString(in);
    this.isJobConfFile = in.readBoolean();
    this.isJobHistoryFile = in.readBoolean();
  }

}


text:
<?php
	function initialize_page()
	{
		$post_action = "";
		if(isset($_POST['submit']))
		{
			$post_action = $_POST['submit'];
		}

		if($post_action == "Add New Section" || $post_action == "Add and Return to List")
		{
			$section_display_name = $_POST['display_name'];
			if (ALLOW_SHORT_PAGE_NAMES) {
				if ($_POST['name'] == "") {
					$section_name = slug($_POST['display_name']);
				} else {
					$section_name = slug($_POST['name']);
				}
			} else {
				$section_name = slug($_POST['display_name']);
			}
			$section_content = $_POST['section_content'];
			$section_template = $_POST['template'];
			$section_public = isset($_POST['public']) ? 1 : 0;

			$new_section = MyActiveRecord::Create('Sections', array( 'name'=>$section_name, 'display_name'=>$section_display_name, 'template'=>$section_template, 'public'=>$section_public, "content"=>$section_content));
			$new_section->save();

			// synchronize the users area selections
			$selected_areas = array();
			if(isset($_POST['selected_areas']))
			{
				$selected_areas = $_POST['selected_areas'];
			} else {
				$selected_areas = array('2');
			}

			$new_section->updateSelectedAreas($selected_areas);

			setFlash("
New section added
");

			if ($post_action == "Add and Return to List")
			{
				$main_portlink = ( DISPLAY_ITEMS_AS_LIST ) ? "admin/portfolio_list/alphabetical" : "admin/portfolio_list";
				redirect( $main_portlink );
			} else {
				redirect("admin/portfolio_add_section/".$section->id);
			}
		}
	}

	function display_page_content()
	{
		$areas = Areas::FindPortAreas(); // get all Portfolio Areas, public or not
		$user = Users::GetCurrentUser();
?>

Add Portfolio Section

	<form method="POST" id="add_section">

If a text box is underlined in red, it is a required field

			Display Name:
			<?php textField("display_name", "", "required: true"); ?>

			This is the Proper Name of the section; how it will display in the navigation. Keep it simple, but use capitals and spaces, please.

		<?php if (ALLOW_SHORT_PAGE_NAMES) { ?>

			Name
			<?php textField("name", "", "required: true"); ?>

			This is the short name of the section for the link and the database. No spaces, commas, or quotes, please.

		<?php } ?>

	<?php if ($user->email == "admin@highchairdesign.com") { ?>

Template:
			<select id="template" name="template">
			<?php
				$templates = list_available_templates();
				foreach($templates as $template)
				{
					$text = $template;
					echo "<option value=\"$template\">$text</option>";
				}
			?>

			</select>

	<?php } else {
			hiddenField("template", "portfolio");
		}
	?>

			Public?<input type="checkbox" name="public" class="boxes"/>

			This determines whether or not the Section will appear in the navigation as a “Public” link. If this Section is not public, then no items within it – Public or not – will be visible. A nice way to create a new Section and make sure it works well is to make the Section NOT Public, and all the items within it Public, so one click can turn it all on when it is ready.

			Section Description:
			<?php textArea("section_content", "", 98, EDIT_WINDOW_HEIGHT); ?>

<?php require_once(snippetPath("admin-insert_configs")); ?>

<?php require_once(snippetPath("admin-portfolio-area")); ?>

					<input type="submit" class="submitbutton" name="submit" value="Add New Section" />

					<input type="submit" class="submitbuttonsmall" name="submit" value="Add and Return to List" />

To ensure that a new Section does not become public without any Items inside of it, a new section will automatically be set to Not Public. Add some Items and edit this Section later to make it public and visible.

	</form>

<?php } ?>


text:
package dk.gp.gpr

import breeze.linalg.DenseMatrix
import breeze.linalg.DenseVector
import dk.gp.cov.CovFunc
import breeze.optimize.LBFGS
import breeze.linalg.VectorConstructors

object gpr {

  def apply(x: DenseMatrix[Double], y: DenseVector[Double], covFunc: CovFunc, covFuncParams: DenseVector[Double], noiseLogStdDev: Double, mean: Double = 0d,gpMaxIter:Int=100): GprModel = {

    val initialGpModel = GprModel(x, y, covFunc, covFuncParams, noiseLogStdDev, mean)

    val diffFunc = GprDiffFunction(initialGpModel)
    val initialParams = DenseVector(covFuncParams.toArray :+ noiseLogStdDev)

    val optimizer = new LBFGS[DenseVector[Double]](maxIter = gpMaxIter, m = 3, tolerance = 1.0E-6)
    val optIterations = optimizer.iterations(diffFunc, initialParams).toList

    val newParams = optIterations.last.x

    val newCovFuncParams = DenseVector(newParams.toArray.dropRight(1))
    val newNoiseLogStdDev = newParams.toArray.last

    val trainedGpModel = GprModel(x,y,covFunc,newCovFuncParams,newNoiseLogStdDev,mean)
    trainedGpModel
  }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>easywechat - undefined</title>

    <meta name="HandheldFriendly" content="True">
    <meta name="MobileOptimized" content="320">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <meta name="description" content="">

    <meta name="twitter:card" content="summary">
    <meta name="twitter:title" content="easywechat - undefined">
    <meta name="twitter:description" content="">

    <meta property="og:type" content="article">
    <meta property="og:title" content="easywechat - undefined">
    <meta property="og:description" content="">

    <link href="/favicon.ico" rel="shortcut icon" type="image/x-icon">
    <link href="/apple-touch-icon-precomposed.png" rel="apple-touch-icon">

    <link rel="stylesheet" type="text/css" href="//oppemism.github.io/themes/uno/assets/css/uno.css?v=1468402333339" />

    <link rel="canonical" href="https://oppemism.github.io/https://oppemism.github.io/tag/easywechat/" />
    <meta name="referrer" content="origin" />

    <meta property="og:type" content="website" />
    <meta property="og:title" content="easywechat - undefined" />
    <meta property="og:url" content="https://oppemism.github.io/https://oppemism.github.io/tag/easywechat/" />
    <meta name="twitter:card" content="summary" />
    <meta name="twitter:title" content="easywechat - undefined" />
    <meta name="twitter:url" content="https://oppemism.github.io/https://oppemism.github.io/tag/easywechat/" />

    <meta name="generator" content="HubPress" />
    <link rel="alternate" type="application/rss+xml" title="" href="https://oppemism.github.io/rss/" />

Blog

Tag: easywechat

easywechat的简单使用

1.发送模板消息:  $url = U('Pay/Confirm/ifOrder',array('tradeno' => $tradeno),'',true);  $orderData= array(  // 头信息  'first' => '您好,新订单通知',  // 学员姓名  'keyword1' => $stuname,  // 预约时间  'keyword2' => $timer,  //预约科目  'keyword3'=> $num,  // 结束语  'remark' => '感谢您的使用,是否接单',  ); pushMsg($teaopenid,$url,$orderData); /**  * easywechat推送模版消息  */…

            <time datetime="02 Jul 2016" class="post-list__meta--date date">02 Jul 2016</time> •
            easywechat的简单使用

    Page 1 of 1

                © 2016. All rights reserved.
                Uno theme by Dale-Anthony
                Proudly published with Hubpress


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright 2012 Research In Motion Limited.
  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

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<widget xmlns="http://www.w3.org/ns/widgets"
        xmlns:rim="http://www.blackberry.com/ns/widgets"
        version="1.0.0.1" id="LocalizationExample">
    <content src="index.html"/>

    <name>Localization Example</name>
    <name xml:lang="ca_ES">exemple de localització</name>
    <name xml:lang="fr_FR">Exemple de localisation</name>
    <name xml:lang="de_DE">Localization Probe</name>
    <name xml:lang="es_ES">Localización de muestra</name>
    <name xml:lang="it_IT">Esempio di localizzazione</name>
    <name xml:lang="id_ID">lokalisasi Contoh</name>
    <name xml:lang="ja_JP">ローカライズの例</name>
    <name xml:lang="ko_KR">현지화의 예</name>
    <name xml:lang="pl_PL">Przykład lokalizacji</name>
    <name xml:lang="ru_RU">Локализация пример</name>
    <name xml:lang="ar_EG">مثال التعريب</name>
    <name xml:lang="zh_CN">本土化样本</name>

    <author>Research In Motion Ltd.</author>

    <description>A simple localization sample</description>
    <description xml:lang="fr_FR">Un échantillon simple localisation</description>
    <description xml:lang="de_DE">Eine einfache Lokalisierung Probe</description>
    <description xml:lang="es_ES">Una muestra simple localización</description>
    <description xml:lang="it_IT">Un campione di localizzazione semplice</description>
    <description xml:lang="zh_CN">一个简单的本土化样本</description>

    <icon src="icon.png"/>
    <feature id="blackberry.system" required="true" version="1.0.0.0"/>
    <access origin="*"/>
    <license href="http://www.apache.org/licenses/LICENSE-2.0">My License</license>
</widget>


text:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require("@angular/core");
var BaScrollPosition = (function () {
    function BaScrollPosition() {
        this.scrollChange = new core_1.EventEmitter();
    }
    BaScrollPosition.prototype.ngOnInit = function () {
        this.onWindowScroll();
    };
    BaScrollPosition.prototype.onWindowScroll = function () {
        var isScrolled = window.scrollY > this.maxHeight;
        if (isScrolled !== this._isScrolled) {
            this._isScrolled = isScrolled;
            this.scrollChange.emit(isScrolled);
        }
    };
    return BaScrollPosition;
}());
__decorate([
    core_1.Input(),
    __metadata("design:type", Number)
], BaScrollPosition.prototype, "maxHeight", void 0);
__decorate([
    core_1.Output(),
    __metadata("design:type", core_1.EventEmitter)
], BaScrollPosition.prototype, "scrollChange", void 0);
__decorate([
    core_1.HostListener('window:scroll'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", void 0)
], BaScrollPosition.prototype, "onWindowScroll", null);
BaScrollPosition = __decorate([
    core_1.Directive({
        selector: '[baScrollPosition]'
    })
], BaScrollPosition);
exports.BaScrollPosition = BaScrollPosition;
//# sourceMappingURL=baScrollPosition.directive.js.map


text:
from httplib import HTTPException
import os
import socket
import sys
from time import sleep
from urlparse import urlparse
import functools
from nose import SkipTest

from test import get_config

from swiftclient import get_auth, http_connection
from test.functional.swift_test_client import Connection

conf = get_config('func_test')
web_front_end = conf.get('web_front_end', 'integral')
normalized_urls = conf.get('normalized_urls', False)

# If no conf was read, we will fall back to old school env vars
swift_test_auth = os.environ.get('SWIFT_TEST_AUTH')
swift_test_user = [os.environ.get('SWIFT_TEST_USER'), None, None]
swift_test_key = [os.environ.get('SWIFT_TEST_KEY'), None, None]
swift_test_tenant = ['', '', '']
swift_test_perm = ['', '', '']

if conf:
    swift_test_auth_version = str(conf.get('auth_version', '1'))

    swift_test_auth = 'http'
    if conf.get('auth_ssl', 'no').lower() in ('yes', 'true', 'on', '1'):
        swift_test_auth = 'https'
    if 'auth_prefix' not in conf:
        conf['auth_prefix'] = '/'
    try:
        suffix = '://%(auth_host)s:%(auth_port)s%(auth_prefix)s' % conf
        swift_test_auth += suffix
    except KeyError:
        pass  # skip

    if swift_test_auth_version == "1":
        swift_test_auth += 'v1.0'

        if 'account' in conf:
            swift_test_user[0] = '%(account)s:%(username)s' % conf
        else:
            swift_test_user[0] = '%(username)s' % conf
        swift_test_key[0] = conf['password']
        try:
            swift_test_user[1] = '%s%s' % (
                '%s:' % conf['account2'] if 'account2' in conf else '',
                conf['username2'])
            swift_test_key[1] = conf['password2']
        except KeyError as err:
            pass  # old conf, no second account tests can be run
        try:
            swift_test_user[2] = '%s%s' % ('%s:' % conf['account'] if 'account'
                                           in conf else '', conf['username3'])
            swift_test_key[2] = conf['password3']
        except KeyError as err:
            pass  # old conf, no third account tests can be run

        for _ in range(3):
            swift_test_perm[_] = swift_test_user[_]

    else:
        swift_test_user[0] = conf['username']
        swift_test_tenant[0] = conf['account']
        swift_test_key[0] = conf['password']
        swift_test_user[1] = conf['username2']
        swift_test_tenant[1] = conf['account2']
        swift_test_key[1] = conf['password2']
        swift_test_user[2] = conf['username3']
        swift_test_tenant[2] = conf['account']
        swift_test_key[2] = conf['password3']

        for _ in range(3):
            swift_test_perm[_] = swift_test_tenant[_] + ':' \
                + swift_test_user[_]

skip = not all([swift_test_auth, swift_test_user[0], swift_test_key[0]])
if skip:
    print >>sys.stderr, 'SKIPPING FUNCTIONAL TESTS DUE TO NO CONFIG'

skip2 = not all([not skip, swift_test_user[1], swift_test_key[1]])
if not skip and skip2:
    print >>sys.stderr, \
        'SKIPPING SECOND ACCOUNT FUNCTIONAL TESTS DUE TO NO CONFIG FOR THEM'

skip3 = not all([not skip, swift_test_user[2], swift_test_key[2]])
if not skip and skip3:
    print >>sys.stderr, \
        'SKIPPING THIRD ACCOUNT FUNCTIONAL TESTS DUE TO NO CONFIG FOR THEM'

class AuthError(Exception):
    pass

class InternalServerError(Exception):
    pass

url = [None, None, None]
token = [None, None, None]
parsed = [None, None, None]
conn = [None, None, None]

def retry(func, *args, **kwargs):
    """
    You can use the kwargs to override:
      'retries' (default: 5)
      'use_account' (default: 1) - which user's token to pass
      'url_account' (default: matches 'use_account') - which user's storage URL
      'resource' (default: url[url_account] - URL to connect to; retry()
          will interpolate the variable :storage_url: if present
    """
    global url, token, parsed, conn
    retries = kwargs.get('retries', 5)
    attempts, backoff = 0, 1

    # use account #1 by default; turn user's 1-indexed account into 0-indexed
    use_account = kwargs.pop('use_account', 1) - 1

    # access our own account by default
    url_account = kwargs.pop('url_account', use_account + 1) - 1

    while attempts <= retries:
        attempts += 1
        try:
            if not url[use_account] or not token[use_account]:
                url[use_account], token[use_account] = \
                    get_auth(swift_test_auth, swift_test_user[use_account],
                             swift_test_key[use_account],
                             snet=False,
                             tenant_name=swift_test_tenant[use_account],
                             auth_version=swift_test_auth_version,
                             os_options={})
                parsed[use_account] = conn[use_account] = None
            if not parsed[use_account] or not conn[use_account]:
                parsed[use_account], conn[use_account] = \
                    http_connection(url[use_account])

            # default resource is the account url[url_account]
            resource = kwargs.pop('resource', '%(storage_url)s')
            template_vars = {'storage_url': url[url_account]}
            parsed_result = urlparse(resource % template_vars)
            return func(url[url_account], token[use_account],
                        parsed_result, conn[url_account],
                        *args, **kwargs)
        except (socket.error, HTTPException):
            if attempts > retries:
                raise
            parsed[use_account] = conn[use_account] = None
        except AuthError:
            url[use_account] = token[use_account] = None
            continue
        except InternalServerError:
            pass
        if attempts <= retries:
            sleep(backoff)
            backoff *= 2
    raise Exception('No result after %s retries.' % retries)

def check_response(conn):
    resp = conn.getresponse()
    if resp.status == 401:
        resp.read()
        raise AuthError()
    elif resp.status // 100 == 5:
        resp.read()
        raise InternalServerError()
    return resp

cluster_info = {}

def get_cluster_info():
    conn = Connection(conf)
    conn.authenticate()
    global cluster_info
    cluster_info = conn.cluster_info()

def reset_acl():
    def post(url, token, parsed, conn):
        conn.request('POST', parsed.path, '', {
            'X-Auth-Token': token,
            'X-Account-Access-Control': '{}'
        })
        return check_response(conn)
    resp = retry(post, use_account=1)
    resp.read()

def requires_acls(f):
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        if skip:
            raise SkipTest
        if not cluster_info:
            get_cluster_info()
        # Determine whether this cluster has account ACLs; if not, skip test
        if not cluster_info.get('tempauth', {}).get('account_acls'):
            raise SkipTest
        if 'keystoneauth' in cluster_info:
            # remove when keystoneauth supports account acls
            raise SkipTest
        reset_acl()
        try:
            rv = f(*args, **kwargs)
        finally:
            reset_acl()
        return rv
    return wrapper


text:
Dockerised Pact Broker [![Build Status](https://travis-ci.org/DiUS/pact_broker-docker.svg)](https://travis-ci.org/DiUS/pact_broker-docker)
==================

This repository deploys [Pact Broker](https://github.com/pact-foundation/pact_broker) using lightweight containers using Docker. You can pull the dius/pact-broker image from [Dockerhub](https://hub.docker.com/r/dius/pact-broker/).

## Prerequisites

* A running postgresql database and the ability to connect to it (see [POSTGRESQL.md][postgres]).
* If on Mac, you will need the `timeout` or `gtimeout` function. You can install `gtimeout` using `brew install coreutils`.

## Getting Started

1. [Install Docker](https://docs.docker.com/engine/installation/)
2. Prepare your environment if you are not running postgresql in a docker container. Setup the pact broker connection to the database through the use of the following environment variables. If you want to use a disposable postgres docker container just do `export DISPOSABLE_PSQL=true` before running the [script/test.sh][test-script].

For a postgres or mysql database:

    * PACT_BROKER_DATABASE_ADAPTER (optional, defaults to 'postgres', see note below.)
    * PACT_BROKER_DATABASE_USERNAME
    * PACT_BROKER_DATABASE_PASSWORD
    * PACT_BROKER_DATABASE_HOST
    * PACT_BROKER_DATABASE_NAME

Adapter can be 'postgres' (recommended) or 'mysql2' (please note that future JSON search features may not be supported on mysql).

For an sqlite database (only recommended for investigation/spikes, as it will be disposed of with the container unless you mount it from an external file system):

  * PACT_BROKER_DATABASE_ADAPTER (set to 'sqlite')
  * PACT_BROKER_DATABASE_NAME (arbitrary name eg. pact_broker.sqlite)

3. Test the pact broker environment by executing [script/test.sh][test-script]

## Notes

* Use `-p 80:80` to start the docker image, as some of the Rack middleware gets confused by receiving requests for other ports and will return a 404 otherwise (port forwarding does not rewrite headers).
* On OSX, if you are not using Docker native, use `docker-machine ip $(docker-machine active)` to get the IP of the VirtualBox, and connect on port 80.
* The application makes use of the phusion passenger application server.
* Apart from creating a database no further preparation is required.

## Using basic auth

To enable basic auth, run your container with:

* `PACT_BROKER_BASIC_AUTH_USERNAME`
* `PACT_BROKER_BASIC_AUTH_PASSWORD`
* `PACT_BROKER_BASIC_AUTH_READ_ONLY_USERNAME`
* `PACT_BROKER_BASIC_AUTH_READ_ONLY_PASSWORD`

Developers should use the read only credentials on their local machines, and the CI should use the read/write credentials. This will ensure that pacts and verification results are only published from your CI.

Note that the [verification status badges][badges] are not protected by basic auth, so that you may embed them in README markdown.

## Heartbeat URL

If you are using the docker container within an AWS autoscaling group, and you need to make a heartbeat URL publicly available, set `PACT_BROKER_PUBLIC_HEARTBEAT=true`. No database connection will be made during the execution of this endpoint.

## Using SSL

See the [Pact Broker configuration documentation][reverse-proxy].

## Setting the log level

Set the environment variable `PACT_BROKER_LOG_LEVEL` to one of `DEBUG`, `INFO`, `WARN`, `ERROR`, or `FATAL`.

## Webhook whitelists

* PACT_BROKER_WEBHOOK_HOST_WHITELIST - a space delimited list of hosts (eg. `github.com`), network ranges (eg. `10.2.3.41/24`, or regular expressions (eg. `/.*\\.foo\\.com$/`). Regular expressions should start and end with a `/` to differentiate them from Strings. Note that backslashes need to be escaped with a second backslash. Please read the [Webhook whitelists](https://github.com/pact-foundation/pact_broker/wiki/Configuration#webhook-whitelists) section of the Pact Broker configuration documentation to understand how the whitelist is used. Remember to use quotes around this value as it may have spaces in it.
* PACT_BROKER_WEBHOOK_SCHEME_WHITELIST - a space delimited list (eg. `http https`). Defaults to `https`.

## Other environment variables

* PACT_BROKER_BASE_EQUALITY_ONLY_ON_CONTENT_THAT_AFFECTS_VERIFICATION_RESULTS - `true` by default, may be set to `false`.
* PACT_BROKER_ORDER_VERSIONS_BY_DATE - `true` by default, may be set to `false`.

## General Pact Broker configuration and usage

Documentation for the Pact Broker application itself can be found in the Pact Broker [wiki][pact-broker-wiki].

## Running with Docker Compose

For a quick start with the Pact Broker and Postgres, we have an example
[Docker Compose][docker-compose] setup you can use:

1. Modify the `docker-compose.yml` file as required.
2. Run `docker-compose up` to get a running Pact Broker and a clean Postgres database

Now you can access your local broker:

```sh
curl -v http://localhost # you can visit in your browser too!

# SSL endpoint, note that URLs in response contain https:// protocol
curl -v -k https://localhost:8443
```

_NOTE: this image should be modified before using in Production, in particular, the use of hard-coded credentials_

## Running with Openshift

See [pact-broker-openshift](https://github.com/jaimeniswonger/pact-broker-openshift) for an example config file.

# Troubleshooting

See the [Troubleshooting][troubleshooting] page on the wiki.

[badges]: https://github.com/pact-foundation/pact_broker/wiki/Provider-verification-badges
[troubleshooting]: https://github.com/DiUS/pact_broker-docker/wiki/Troubleshooting
[postgres]: https://github.com/DiUS/pact_broker-docker/blob/master/POSTGRESQL.md
[test-script]: https://github.com/DiUS/pact_broker-docker/blob/master/script/test.sh
[docker-compose]: https://github.com/DiUS/pact_broker-docker/blob/master/docker-compose.yml
[pact-broker-wiki]: https://github.com/pact-foundation/pact_broker/wiki
[reverse-proxy]: https://github.com/pact-foundation/pact_broker/wiki/Configuration#running-the-broker-behind-a-reverse-proxy


text:
function buildings = building_warmup(buildings,options,date,prev_data,hist_prof)
%%Need warm-up period if not currently running the model
n_b = length(buildings);
wu_date = linspace(date(1) + options.Resolution/24,date(1)+1,24)';
if isempty(hist_prof)
    f_names = fieldnames(prev_data.Weather);
    for f = 1:1:length(f_names)
        wu_weather.(f_names{f}) = interp1(prev_data.Timestamp,prev_data.Weather.(f_names{f}),wu_date);
    end
else
    wu_weather = weather_forecast(prev_data,hist_prof,wu_date);
end
for i = 1:1:n_b
    if  ~isfield(buildings(i),'Tzone') || isempty(buildings(i).Tzone) || abs(round(864000*(buildings(i).Timestamp+options.Resolution/24))/864000 - date(1))>1e-5
        zone = 20;
        wall = 20;
        if length(date) == 1
            wuDate = linspace(date(1) + options.Resolution/24,date(1)+1,24)';
        else
            wuDate = linspace(date(1),date(1)+1 - options.Resolution/24,24)';
        end
        wu_sg = solar_gain(buildings(i),wuDate,buildings(i).QPform.Location,wu_weather);
        wu_loads = building_loads(buildings(i),wuDate,wu_sg);
        wu_external_gains = wu_sg.Walls + wu_sg.Roof;
        for d = 1:1:6
            [~,~,~,zone,wall,~] = building_profile(buildings(i),wuDate,wu_loads.InternalGains,wu_external_gains,wu_weather.DrybulbC,wu_weather.RHum,zone(end,1),wall(end,1));
        end
        if zone(end)<10 || zone(end)>40
            disp('BuildingWarmUp Error')
        end
        buildings(i).Tzone = zone(end);
        buildings(i).Twall = wall(end);
        buildings(i).Timestamp = date(1);
    end
end
end%Ends function building_warmup


text:
package com.fireflysource.net.http.common.exception;

public class MissingRemoteHostException extends RuntimeException {

    public MissingRemoteHostException(String message) {
        super(message);
    }
}


text:
function ThemeValidationError(message, details) {
    this.message = message;
    this.stack = new Error().stack;
    this.statusCode = 422;
    if (details) {
        this.errorDetails = details;
    }

    this.errorType = this.name;
}

ThemeValidationError.prototype = Object.create(Error.prototype);
ThemeValidationError.prototype.name = 'ThemeValidationError';

module.exports = ThemeValidationError;


text:
import { TextInput } from "../../";

export = TextInput;


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<parent>
		<artifactId>qualitas-parent</artifactId>
		<groupId>com.googlecode.qualitas</groupId>
		<version>0.0.6-SNAPSHOT</version>
		<relativePath>../qualitas-parent</relativePath>
	</parent>
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.googlecode.qualitas.security.services</groupId>
	<artifactId>qualitas-security-services-spring</artifactId>
	<packaging>jar</packaging>

	<name>qualitas-services-security-spring</name>

	<dependencies>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-core</artifactId>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
		</dependency>
		<dependency>
			<groupId>com.googlecode.qualitas.internal.dao</groupId>
			<artifactId>qualitas-internal-dao-spring</artifactId>
		</dependency>
	</dependencies>
</project>


text:
import cmd

class HelloWorld(cmd.Cmd):

    prompt = 'prompt: '
    intro = "Simple command processor example."

    doc_header = 'doc_header'
    misc_header = 'misc_header'
    undoc_header = 'undoc_header'

    ruler = '-'

    def do_prompt(self, line):
        "Change the interactive prompt"
        self.prompt = line + ': '

    def do_EOF(self, line):
        return True

if __name__ == '__main__':
    HelloWorld().cmdloop()


text:
<?xml version="1.0" standalone="no"?>
<!--
  Openbiz Cubi Application Platform
  LICENSE http://code.google.com/p/openbiz-cubi/wiki/CubiLicense
  Copyright (c) 2005-2011, Openbiz Technology LLC
  Version $Id: chineseService.xml 3371 2012-05-31 06:17:21Z rockyswen@gmail.com $
-->
<PluginService Name="chineseService" Package="service" Class="chineseService" >
</PluginService>


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Jay Skript and the Domsters</title>

  <link rel="stylesheet" href="styles/basic.css" media="screen">

Home

About

Photos

Live

Contact

Lorem Ipsum Dolor

Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Nullam iaculis vestibulum turpis. Pellentesque mattis rutrum
nibh. Quisque orci orci, euismod sit amet, sollicitudin et,
ullamcorper at, lorem.
Pellentesque habitant morbi tristique senectus et netus
et malesuada fames ac turpis egestas.
Ut lectus. Mauris eu sapien non enim dapibus imperdiet.
Sed eu mauris sed pede mollis commodo.
Fusce eget est. Sed ullamcorper enim nec est.
Cras dui felis, porta vitae, faucibus laoreet, sollicitudin eget,
enim. Nulla auctor. Fusce interdum diam ac eros.
Mauris egestas. Fusce in elit et sem aliquet pretium.
Donec nunc erat, sodales ac, facilisis a, molestie eu, massa.
Aenean nec justo eu neque malesuada aliquet.


text:
CERTIFICATE_LIST=$(awscli acm list-certificates --output text --query "CertificateSummaryList[$(auto_filter DomainName CertificateArn -- $@)].[CertificateArn]")

select_one Certificate "$CERTIFICATE_LIST"

awscli acm describe-certificate --certificate-arn $SELECTED --output table --query "Certificate"


text:
package controller;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

import cell.AquaticCell;
import cell.Cell;
import cell.SharkCell;
import cellsociety.GridData;
import cellsociety.Strings;
import controller.ComplexController;

public class WatorController extends ComplexController{

	public WatorController(Map<String, String> parameters) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException{
		super(parameters);
	}

	private boolean deadShark(Cell cell) {
		if(cell instanceof SharkCell){
			return ((SharkCell) cell).isDead();
		}
		return false;
	}

	@Override
	protected void cellUpdate(GridData data) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException {
		if(deadShark(data.curCell())){
			data.getNewGrid()[data.getRow()][data.getCol()] = ((SharkCell) data.curCell()).reproducingResult();
		}
		else if(data.curCell().toString().equals(Strings.EMPTY_CELL)){
			data.getNewGrid()[data.getRow()][data.getCol()] = makeCell(Strings.EMPTY_CELL);
		}
		else{
			((AquaticCell) data.curCell()).ageOneChronon(data, myNeighbor);
		}
	}

	@Override
	protected List<String> typeTriage(List<String> list) {
		list.add(Strings.SHARK_CELL);
		list.add(Strings.FISH_CELL);
		list.add(Strings.EMPTY_CELL);
		return list;
	}
}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: grpc/file_system_master.proto

package alluxio.grpc;

public interface SetAttributePOptionsOrBuilder extends
    // @@protoc_insertion_point(interface_extends:alluxio.grpc.file.SetAttributePOptions)
    com.google.protobuf.MessageOrBuilder {

  /**
   * optional bool pinned = 1;
   */
  boolean hasPinned();
  /**
   * optional bool pinned = 1;
   */
  boolean getPinned();

  /**
   * optional bool persisted = 2;
   */
  boolean hasPersisted();
  /**
   * optional bool persisted = 2;
   */
  boolean getPersisted();

  /**
   * optional string owner = 3;
   */
  boolean hasOwner();
  /**
   * optional string owner = 3;
   */
  java.lang.String getOwner();
  /**
   * optional string owner = 3;
   */
  com.google.protobuf.ByteString
      getOwnerBytes();

  /**
   * optional string group = 4;
   */
  boolean hasGroup();
  /**
   * optional string group = 4;
   */
  java.lang.String getGroup();
  /**
   * optional string group = 4;
   */
  com.google.protobuf.ByteString
      getGroupBytes();

  /**
   * optional .alluxio.grpc.PMode mode = 5;
   */
  boolean hasMode();
  /**
   * optional .alluxio.grpc.PMode mode = 5;
   */
  alluxio.grpc.PMode getMode();
  /**
   * optional .alluxio.grpc.PMode mode = 5;
   */
  alluxio.grpc.PModeOrBuilder getModeOrBuilder();

  /**
   * optional bool recursive = 6;
   */
  boolean hasRecursive();
  /**
   * optional bool recursive = 6;
   */
  boolean getRecursive();

  /**
   * optional int32 replicationMax = 7;
   */
  boolean hasReplicationMax();
  /**
   * optional int32 replicationMax = 7;
   */
  int getReplicationMax();

  /**
   * optional int32 replicationMin = 8;
   */
  boolean hasReplicationMin();
  /**
   * optional int32 replicationMin = 8;
   */
  int getReplicationMin();

  /**
   * optional .alluxio.grpc.file.FileSystemMasterCommonPOptions commonOptions = 9;
   */
  boolean hasCommonOptions();
  /**
   * optional .alluxio.grpc.file.FileSystemMasterCommonPOptions commonOptions = 9;
   */
  alluxio.grpc.FileSystemMasterCommonPOptions getCommonOptions();
  /**
   * optional .alluxio.grpc.file.FileSystemMasterCommonPOptions commonOptions = 9;
   */
  alluxio.grpc.FileSystemMasterCommonPOptionsOrBuilder getCommonOptionsOrBuilder();

  /**
   * repeated string pinnedMedia = 10;
   */
  java.util.List<java.lang.String>
      getPinnedMediaList();
  /**
   * repeated string pinnedMedia = 10;
   */
  int getPinnedMediaCount();
  /**
   * repeated string pinnedMedia = 10;
   */
  java.lang.String getPinnedMedia(int index);
  /**
   * repeated string pinnedMedia = 10;
   */
  com.google.protobuf.ByteString
      getPinnedMediaBytes(int index);
}


text:
  <title>parent_overflow_test.html</title>

line1

line2

line3

line4

line5

line6

line7

line8

line9

    Clicked:


text:
package com.anhnguyen.data.webservice;

import com.anhnguyen.data.entity.SongEntity;

import java.util.ArrayList;
import java.util.List;

import retrofit.http.GET;
import retrofit.http.Headers;

public interface GetPopularSongsApi {

    class PopularSongResponse{
        String prevDate;
        List<TrackResponse> tracks;

        public List<SongEntity> map(){
            ArrayList<SongEntity> results = new ArrayList<>();
            for(TrackResponse story : tracks){
                results.add(story.map());
            }
            return results;
        }
    }

    class TrackResponse {
        private String date;
        private String country;
        private String track_url;
        private String track_name;
        private String artist_name;
        private String artist_url;
        private String album_name;
        private String album_url;
        private String artwork_url;
        private String num_streams;
        private String window_type;

        public SongEntity map() {
            SongEntity songEntity = new SongEntity();
            songEntity.setAlbumName(album_name);
            songEntity.setAlbumUrl(album_url);
            songEntity.setArtistName(artist_name);
            songEntity.setArtworkUrl(artwork_url);
            songEntity.setArtistUrl(artist_url);
            songEntity.setCountry(country);
            songEntity.setDate(date);
            songEntity.setNumStreams(num_streams);
            songEntity.setTrackName(track_name);
            songEntity.setTrackUrl(track_url);
            songEntity.setWindowType(window_type);

            return songEntity;
        }
    }

    @Headers({
        "Content-Type: application/json;charset=UTF-8"
    })
    @GET("/api/tracks/most_streamed/global/daily/latest")
    PopularSongResponse getPopularSongs();

}


text:
package java8professional.chapter10;

import java.sql.*;

public class ReadingDataFromAScrollableResultSet {

    public static void main(String[] args) {

        try {
            Connection connection = DriverManager.getConnection("jdbc:mysql:localhost:5230/books", "user", "pass");
            Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
            ResultSet resultSet = statement.executeQuery("SELECT * FROM books");

            resultSet.beforeFirst();
            while (resultSet.next()) {
                System.out.println(resultSet.getInt("id"));
            }

            resultSet.afterLast();
            while (resultSet.previous()) {
                System.out.println(resultSet.getInt("id"));
            }

            System.out.println(resultSet.first());
            System.out.println(resultSet.last());

            boolean isTheCursorPointingToAValidRow;

            isTheCursorPointingToAValidRow = resultSet.absolute(0); // goes to before first (and isTheCursorPointingToAValidRow = false)
            isTheCursorPointingToAValidRow = resultSet.absolute(3); // goes to row 3 (and isTheCursorPointingToAValidRow = true)
            isTheCursorPointingToAValidRow = resultSet.absolute(-1); // goes to the last row (and isTheCursorPointingToAValidRow = true)

            isTheCursorPointingToAValidRow = resultSet.relative(0); // stays in the same row
            isTheCursorPointingToAValidRow = resultSet.relative(3); // goes 3 rows forward
            isTheCursorPointingToAValidRow = resultSet.relative(-1); // goes 1 row backward
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

}


text:
FROM node:current

RUN apt-get update
RUN apt-get install -y curl xvfb chromium chromium-l10n firefox-esr ruby ruby-dev
RUN gem install sass

RUN npm install --global gulp eslint bower && \
        echo '{ "allow_root": true }' > /root/.bowerrc

# Add Chromium and Firefox with xvfb for karma tests

ADD xvfb-chromium /usr/bin/xvfb-chromium
RUN chmod +x /usr/bin/xvfb-chromium
ENV CHROMIUM_BIN=/usr/bin/xvfb-chromium

ADD xvfb-firefox /usr/bin/xvfb-firefox
RUN chmod +x /usr/bin/xvfb-firefox
ENV FIREFOX_BIN=/usr/bin/xvfb-firefox

WORKDIR /usr/src/app


text:
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('ontology', '__first__'),
        ('core', '0002_auto_20200623_1333'),
    ]

    operations = [
        migrations.AddField(
            model_name='job',
            name='vocabulary',
            field=models.ForeignKey(blank=True, help_text='Favorite words', null=True, on_delete=django.db.models.deletion.PROTECT, to='ontology.Vocabulary'),
        ),
    ]


text:
"""Disassembler of Python byte code into mnemonics."""

import sys
import types

from opcode import *
from opcode import __all__ as _opcodes_all

__all__ = ["dis","disassemble","distb","disco"] + _opcodes_all
del _opcodes_all

def dis(x=None):
    """Disassemble classes, methods, functions, or code.

    With no argument, disassemble the last traceback.

    """
    if x is None:
        distb()
        return
    if hasattr(x, '__func__'):
        x = x.__func__
    if hasattr(x, '__code__'):
        x = x.__code__
    if hasattr(x, '__dict__'):
        items = sorted(x.__dict__.items())
        for name, x1 in items:
            if isinstance(x1, (types.MethodType, types.FunctionType,
                               types.CodeType, type)):
                print("Disassembly of %s:" % name)
                try:
                    dis(x1)
                except TypeError as msg:
                    print("Sorry:", msg)
                print()
    elif hasattr(x, 'co_code'):
        disassemble(x)
    elif isinstance(x, (bytes, bytearray)):
        disassemble_string(x)
    else:
        raise TypeError("don't know how to disassemble %s objects" %
                        type(x).__name__)

def distb(tb=None):
    """Disassemble a traceback (default: last traceback)."""
    if tb is None:
        try:
            tb = sys.last_traceback
        except AttributeError:
            raise RuntimeError("no last traceback to disassemble")
        while tb.tb_next: tb = tb.tb_next
    disassemble(tb.tb_frame.f_code, tb.tb_lasti)

# XXX This duplicates information from code.h, also duplicated in inspect.py.
# XXX Maybe this ought to be put in a central location, like opcode.py?
flag2name = {
     1: "OPTIMIZED",
     2: "NEWLOCALS",
     4: "VARARGS",
     8: "VARKEYWORDS",
    16: "NESTED",
    32: "GENERATOR",
    64: "NOFREE",
}

def pretty_flags(flags):
    """Return pretty representation of code flags."""
    names = []
    for i in range(32):
        flag = 1<<i
        if flags & flag:
            names.append(flag2name.get(flag, hex(flag)))
            flags ^= flag
            if not flags:
                break
    else:
        names.append(hex(flags))
    return ", ".join(names)

def show_code(co):
    """Show details about a code object."""
    print("Name:             ", co.co_name)
    print("Filename:         ", co.co_filename)
    print("Argument count:   ", co.co_argcount)
    print("Kw-only arguments:", co.co_kwonlyargcount)
    print("Number of locals: ", co.co_nlocals)
    print("Stack size:       ", co.co_stacksize)
    print("Flags:            ", pretty_flags(co.co_flags))
    if co.co_consts:
        print("Constants:")
        for i_c in enumerate(co.co_consts):
            print("%4d: %r" % i_c)
    if co.co_names:
        print("Names:")
        for i_n in enumerate(co.co_names):
            print("%4d: %s" % i_n)
    if co.co_varnames:
        print("Variable names:")
        for i_n in enumerate(co.co_varnames):
            print("%4d: %s" % i_n)
    if co.co_freevars:
        print("Free variables:")
        for i_n in enumerate(co.co_freevars):
            print("%4d: %s" % i_n)
    if co.co_cellvars:
        print("Cell variables:")
        for i_n in enumerate(co.co_cellvars):
            print("%4d: %s" % i_n)

def disassemble(co, lasti=-1):
    """Disassemble a code object."""
    code = co.co_code
    labels = findlabels(code)
    linestarts = dict(findlinestarts(co))
    n = len(code)
    i = 0
    extended_arg = 0
    free = None
    while i < n:
        op = code[i]
        if i in linestarts:
            if i > 0:
                print()
            print("%3d" % linestarts[i], end=' ')
        else:
            print('   ', end=' ')

        if i == lasti: print('-->', end=' ')
        else: print('   ', end=' ')
        if i in labels: print('>>', end=' ')
        else: print('  ', end=' ')
        print(repr(i).rjust(4), end=' ')
        print(opname[op].ljust(20), end=' ')
        i = i+1
        if op >= HAVE_ARGUMENT:
            oparg = code[i] + code[i+1]*256 + extended_arg
            extended_arg = 0
            i = i+2
            if op == EXTENDED_ARG:
                extended_arg = oparg*65536
            print(repr(oparg).rjust(5), end=' ')
            if op in hasconst:
                print('(' + repr(co.co_consts[oparg]) + ')', end=' ')
            elif op in hasname:
                print('(' + co.co_names[oparg] + ')', end=' ')
            elif op in hasjrel:
                print('(to ' + repr(i + oparg) + ')', end=' ')
            elif op in haslocal:
                print('(' + co.co_varnames[oparg] + ')', end=' ')
            elif op in hascompare:
                print('(' + cmp_op[oparg] + ')', end=' ')
            elif op in hasfree:
                if free is None:
                    free = co.co_cellvars + co.co_freevars
                print('(' + free[oparg] + ')', end=' ')
        print()

def disassemble_string(code, lasti=-1, varnames=None, names=None,
                       constants=None):
    labels = findlabels(code)
    n = len(code)
    i = 0
    while i < n:
        op = code[i]
        if i == lasti: print('-->', end=' ')
        else: print('   ', end=' ')
        if i in labels: print('>>', end=' ')
        else: print('  ', end=' ')
        print(repr(i).rjust(4), end=' ')
        print(opname[op].ljust(15), end=' ')
        i = i+1
        if op >= HAVE_ARGUMENT:
            oparg = code[i] + code[i+1]*256
            i = i+2
            print(repr(oparg).rjust(5), end=' ')
            if op in hasconst:
                if constants:
                    print('(' + repr(constants[oparg]) + ')', end=' ')
                else:
                    print('(%d)'%oparg, end=' ')
            elif op in hasname:
                if names is not None:
                    print('(' + names[oparg] + ')', end=' ')
                else:
                    print('(%d)'%oparg, end=' ')
            elif op in hasjrel:
                print('(to ' + repr(i + oparg) + ')', end=' ')
            elif op in haslocal:
                if varnames:
                    print('(' + varnames[oparg] + ')', end=' ')
                else:
                    print('(%d)' % oparg, end=' ')
            elif op in hascompare:
                print('(' + cmp_op[oparg] + ')', end=' ')
        print()

disco = disassemble                     # XXX For backwards compatibility

def findlabels(code):
    """Detect all offsets in a byte code which are jump targets.

    Return the list of offsets.

    """
    labels = []
    n = len(code)
    i = 0
    while i < n:
        op = code[i]
        i = i+1
        if op >= HAVE_ARGUMENT:
            oparg = code[i] + code[i+1]*256
            i = i+2
            label = -1
            if op in hasjrel:
                label = i+oparg
            elif op in hasjabs:
                label = oparg
            if label >= 0:
                if label not in labels:
                    labels.append(label)
    return labels

def findlinestarts(code):
    """Find the offsets in a byte code which are start of lines in the source.

    Generate pairs (offset, lineno) as described in Python/compile.c.

    """
    byte_increments = list(code.co_lnotab[0::2])
    line_increments = list(code.co_lnotab[1::2])

    lastlineno = None
    lineno = code.co_firstlineno
    addr = 0
    for byte_incr, line_incr in zip(byte_increments, line_increments):
        if byte_incr:
            if lineno != lastlineno:
                yield (addr, lineno)
                lastlineno = lineno
            addr += byte_incr
        lineno += line_incr
    if lineno != lastlineno:
        yield (addr, lineno)

def _test():
    """Simple test program to disassemble a file."""
    if sys.argv[1:]:
        if sys.argv[2:]:
            sys.stderr.write("usage: python dis.py [-|file]\n")
            sys.exit(2)
        fn = sys.argv[1]
        if not fn or fn == "-":
            fn = None
    else:
        fn = None
    if fn is None:
        f = sys.stdin
    else:
        f = open(fn)
    source = f.read()
    if fn is not None:
        f.close()
    else:
        fn = "<stdin>"
    code = compile(source, fn, "exec")
    dis(code)

if __name__ == "__main__":
    _test()


text:
package org.ovirt.engine.core.vdsbroker.vdsbroker;

import java.util.HashMap;
import java.util.Map;

import org.ovirt.engine.core.common.businessentities.VmDevice;
import org.ovirt.engine.core.common.businessentities.network.VmNic;
import org.ovirt.engine.core.common.vdscommands.VmNicDeviceVDSParameters;

public class UpdateVmInterfaceVDSCommand extends VdsBrokerCommand<VmNicDeviceVDSParameters> {

    public UpdateVmInterfaceVDSCommand(VmNicDeviceVDSParameters parameters) {
        super(parameters);
    }

    @Override
    protected void executeVdsBrokerCommand() {
        status = getBroker().vmUpdateDevice(getParameters().getVm().getId().toString(), initDeviceStructure());
        proceedProxyReturnValue();
    }

    protected Map<String, Object> initDeviceStructure() {
        Map<String, Object> deviceStruct = new HashMap<>();
        deviceStruct.put(VdsProperties.DeviceType, getParameters().getVmDevice().getType().getValue());
        deviceStruct.put(VdsProperties.Alias, getParameters().getVmDevice().getAlias());

        VmNic nic = getParameters().getNic();
        deviceStruct.put(VdsProperties.LINK_ACTIVE, String.valueOf(nic.isLinked()));
        VmDevice vmDevice = getParameters().getVmDevice();

        VmInfoBuilder.addProfileDataToNic(deviceStruct, getParameters().getVm(), vmDevice, nic);

        return deviceStruct;
    }

}


text:
#include <QApplication>
#include <QDebug>
#include <QFile>
#include <QStringList>

#include "MainUI.h"
#include <LuminaOS.h>
#include <LuminaThemes.h>
#include <LuminaUtils.h>
#include <LuminaSingleApplication.h>

int main(int argc, char ** argv)
{
    /*QStringList in;
    for(int i=1; i<argc; i++){ //skip the first arg (app binary)
      QString path = argv[i];
      if(path=="."){
	//Insert the current working directory
	in << QDir::currentPath();
      }else{
	if(!path.startsWith("/")){ path.prepend(QDir::currentPath()+"/"); }
        in << path;
      }
    }
    if(in.isEmpty()){ in << QDir::homePath(); }*/

    LSingleApplication a(argc, argv, "lumina-xconfig"); //loads translations inside constructor
      if( !a.isPrimaryProcess()){ return 0; }
    //qDebug() << "Loaded QApplication";
    a.setApplicationName("Lumina Screen Configuration");
    LuminaThemeEngine themes(&a);

    //Start the UI
    MainUI w;
    QObject::connect(&a, SIGNAL(InputsAvailable(QStringList)), &w, SLOT(slotSingleInstance()) );
    QObject::connect(&themes, SIGNAL(updateIcons()), &w, SLOT(loadIcons()) );
    w.show();

    int retCode = a.exec();
    return retCode;
}


text:
#include "settings.h"
#include "logging.h"
#include "internal.h" /* for lcb_getenv* */
#include <stdio.h>
#include <stdarg.h>

#if defined(unix) || defined(__unix__) || defined(__unix) || defined(_POSIX_VERSION)
    #include <unistd.h>
    #include <pthread.h>
    #include <sys/types.h>

    #if defined(__linux__)
        #include <sys/syscall.h>
        #define GET_THREAD_ID() (long)syscall(SYS_gettid)
        #define THREAD_ID_FMT "ld"

    #elif defined(__APPLE__)
        #define GET_THREAD_ID() pthread_mach_thread_np(pthread_self())
        #define THREAD_ID_FMT "u"
    #else
        /* other unix? */
        #define GET_THREAD_ID() 0
        #define THREAD_ID_FMT "d"
    #endif
#elif defined(_WIN32)
    #define GET_THREAD_ID() GetCurrentThreadId()
    #define THREAD_ID_FMT "d"
#else
    #define GET_THREAD_ID() 0
    #define THREAD_ID_FMT "d"
#endif

static hrtime_t start_time = 0;

static void console_log(struct lcb_logprocs_st *procs,
                        unsigned int iid,
                        const char *subsys,
                        int severity,
                        const char *srcfile,
                        int srcline,
                        const char *fmt,
                        va_list ap);

static struct lcb_CONSOLELOGGER console_logprocs = {
        {0 /* version */, {{console_log} /* v1 */} /*v*/},
        /** Minimum severity */
        LCB_LOG_INFO
};

struct lcb_logprocs_st *lcb_console_logprocs = &console_logprocs.base;

/**
 * Return a string representation of the severity level
 */
static const char * level_to_string(int severity)
{
    switch (severity) {
    case LCB_LOG_TRACE:
        return "TRACE";
    case LCB_LOG_DEBUG:
        return "DEBUG";
    case LCB_LOG_INFO:
        return "INFO";
    case LCB_LOG_WARN:
        return "WARN";
    case LCB_LOG_ERROR:
        return "ERROR";
    case LCB_LOG_FATAL:
        return "FATAL";
    default:
        return "";
    }
}

/**
 * Default logging callback for the verbose logger.
 */
static void console_log(struct lcb_logprocs_st *procs,
                        unsigned int iid,
                        const char *subsys,
                        int severity,
                        const char *srcfile,
                        int srcline,
                        const char *fmt,
                        va_list ap)
{

    hrtime_t now;
    struct lcb_CONSOLELOGGER *vprocs = (struct lcb_CONSOLELOGGER *)procs;

    if (severity < vprocs->minlevel) {
        return;
    }

    if (!start_time) {
        start_time = gethrtime();
    }

    now = gethrtime();
    if (now == start_time) {
        now++;
    }

    fprintf(stderr, "%lums ", (unsigned long)(now - start_time) / 1000000);

    fprintf(stderr, "[I%d] {%"THREAD_ID_FMT"} [%s] (%s - L:%d) ",
            iid,
            GET_THREAD_ID(),
            level_to_string(severity),
            subsys,
            srcline);
    vfprintf(stderr, fmt, ap);
    fprintf(stderr, "\n");

    (void)procs;
    (void)srcfile;
}

LCB_INTERNAL_API
void lcb_log(const struct lcb_settings_st *settings,
             const char *subsys,
             int severity,
             const char *srcfile,
             int srcline,
             const char *fmt,
             ...)
{
    va_list ap;
    lcb_logging_callback callback;

    if (!settings->logger) {
        return;
    }

    if (settings->logger->version != 0) {
        return;
    }

    callback = settings->logger->v.v0.callback;

    va_start(ap, fmt);
    callback(settings->logger, settings->iid, subsys, severity, srcfile, srcline, fmt, ap);
    va_end(ap);
}

lcb_logprocs * lcb_init_console_logger(void)
{
    char vbuf[1024];
    int lvl = 0;

    if (!lcb_getenv_nonempty("LCB_LOGLEVEL", vbuf, sizeof(vbuf))) {
        return NULL;
    }

    if (sscanf(vbuf, "%d", &lvl) != 1) {
        return NULL;
    }

    if (!lvl) {
        /** "0" */
        return NULL;
    }

    /** The "lowest" level we can expose is WARN, e.g. ERROR-1 */
    lvl = LCB_LOG_ERROR - lvl;
    console_logprocs.minlevel = lvl;
    return lcb_console_logprocs;
}


text:
package main

import (
	"strings"

	"github.com/docker/docker/integration-cli/checker"
	"github.com/docker/docker/integration-cli/cli"
	"github.com/go-check/check"
)

func (s *DockerSuite) TestPause(c *check.C) {
	testRequires(c, IsPausable)

	name := "testeventpause"
	runSleepingContainer(c, "-d", "--name", name)

	cli.DockerCmd(c, "pause", name)
	pausedContainers := strings.Fields(
		cli.DockerCmd(c, "ps", "-f", "status=paused", "-q", "-a").Combined(),
	)
	c.Assert(len(pausedContainers), checker.Equals, 1)

	cli.DockerCmd(c, "unpause", name)

	out := cli.DockerCmd(c, "events", "--since=0", "--until", daemonUnixTime(c)).Combined()
	events := strings.Split(strings.TrimSpace(out), "\n")
	actions := eventActionsByIDAndType(c, events, name, "container")

	c.Assert(actions[len(actions)-2], checker.Equals, "pause")
	c.Assert(actions[len(actions)-1], checker.Equals, "unpause")
}

func (s *DockerSuite) TestPauseMultipleContainers(c *check.C) {
	testRequires(c, IsPausable)

	containers := []string{
		"testpausewithmorecontainers1",
		"testpausewithmorecontainers2",
	}
	for _, name := range containers {
		runSleepingContainer(c, "-d", "--name", name)
	}
	cli.DockerCmd(c, append([]string{"pause"}, containers...)...)
	pausedContainers := strings.Fields(
		cli.DockerCmd(c, "ps", "-f", "status=paused", "-q", "-a").Combined(),
	)
	c.Assert(len(pausedContainers), checker.Equals, len(containers))

	cli.DockerCmd(c, append([]string{"unpause"}, containers...)...)

	out := cli.DockerCmd(c, "events", "--since=0", "--until", daemonUnixTime(c)).Combined()
	events := strings.Split(strings.TrimSpace(out), "\n")

	for _, name := range containers {
		actions := eventActionsByIDAndType(c, events, name, "container")

		c.Assert(actions[len(actions)-2], checker.Equals, "pause")
		c.Assert(actions[len(actions)-1], checker.Equals, "unpause")
	}
}

func (s *DockerSuite) TestPauseFailsOnWindowsServerContainers(c *check.C) {
	testRequires(c, DaemonIsWindows, NotPausable)
	runSleepingContainer(c, "-d", "--name=test")
	out, _, _ := dockerCmdWithError("pause", "test")
	c.Assert(out, checker.Contains, "cannot pause Windows Server Containers")
}


text:
<?php

class FacebooksController extends FacebookAppController {

    public $layout = null;

    public function beforeFilter(){
        parent::beforeFilter();
    }

    public function fbChannel(){
        $locale = FB_APP_LOCALE;
		if(empty($locale)){
			$locale = 'en_US';
		}
        $this->set('locale', $locale);

		$cache_expire = 60*60*24*365;
		$this->response->sharable(true, $cache_expire);
		$this->response->expires(gmdate('D, d M Y H:i:s', time()+$cache_expire) . ' GMT');
    }

}


text:
<?php

/*
  Criado     : 01/12/2015
  Modificado : 01/12/2015
  Autor      : Raphaell
  Contato    : rafaelk-f@hotmail.com
  Descrição  :

       ...
 */

namespace Despesa\Model\Filtro\Validacao;

use Zend\Validator\AbstractValidator;
use Zend\Validator\StringLength;

class DespesaRepetirQuando extends AbstractValidator
{

    const MSG_DESPESA_REPETIR_QUANDO_REQUERIDA      = "msgDespesaRepetirQuandoRequerida";
    const MSG_DESPESA_REPETIR_QUANDO_NAO_INFORMAR   = "msgDespesaRepetirQuandoNaoInformar";
    const MSG_DESPESA_REPETIR_QUANDO_VALOR_INVALIDO = "msgDespesaRepetirQuandoValorInvalido";

    protected $messageTemplates = array(
        self::MSG_DESPESA_REPETIR_QUANDO_REQUERIDA      => "Campo obrigatório.",
        self::MSG_DESPESA_REPETIR_QUANDO_NAO_INFORMAR   => "Campo deve permanever vazio.",
        self::MSG_DESPESA_REPETIR_QUANDO_VALOR_INVALIDO => "Valor informado é diferente do esperado.",
    );

    public function __construct($options = null)
    {
        parent::__construct($options);
    }

    /*
     * @param  String  $valorCampo
     * @param  Array   $outrosCampos
     * @return Boolean
     */
    private function validarCampo($valorCampo, Array $outrosCampos = array())
    {
        if (isset($outrosCampos['repetir']) && $outrosCampos['repetir'] == 'S')
        {
            if (empty($valorCampo))
            {
                $this->error(self::MSG_DESPESA_REPETIR_QUANDO_REQUERIDA);
                return false;
            }
        }
        elseif (isset($outrosCampos['repetir']) && $outrosCampos['repetir'] == 'N')
        {
            if (!empty($valorCampo))
            {
                $this->error(self::MSG_DESPESA_REPETIR_QUANDO_NAO_INFORMAR);
                return false;
            }
        }

        if(!empty($valorCampo))
        {
            $stringLenght = new StringLength();
            $stringLenght->setMin('3');
            $stringLenght->setMax('3');
            $stringLenght->setEncoding("UTF-8");

            if(!$stringLenght->isValid($valorCampo))
            {
                $this->error(self::MSG_DESPESA_REPETIR_QUANDO_VALOR_INVALIDO);
                return false;
            }
        }

        return true;
    }

    /*
     * @param  String $value
     * @param  Array  $context
     * @return Boolean
     */
    public function isValid($value, Array $context = array())
    {
       $this->setValue($value);

       return $this->validarCampo($value, $context);
    }
}


text:
Monolith
===

Monolith ([pronunciation](https://dictionary.cambridge.org/pronunciation/english/monolith))
is a simple Vagrant/Ansible bootstrap for create a new virtual machine for web application developers.

Monolith is shipped with:

- Debian 9.1 (Stretch)
- Git

And an SSH role for add your local ssh key to your production server.

Setup
===

Install theses packages:
- [Virtualbox](https://www.virtualbox.org/) - v5.1.26,
- [Ansible](https://www.ansible.com/) - v2.3,
- [Vagrant](https://www.vagrantup.com/) - v2.0,
- [landrush](https://github.com/vagrant-landrush/landrush)

Then open `Vagrantfile` and update theses lines :
- 16: your favorite local domain tld,
- 61: name of your VM (ea your project)
- 64: hostname
- 65: domain
- 67: the folder name of your project (from git clone for example). If you don't have any project, remove this line.

Or if you love make, just edit `Makefile` vars and run `make init`.

After build, feel free to handle your project as your choice. My choice is to
add a new role to Ansible (named by my app) for deploying (like in a prod environment) my project.

If you want to have multiple VM, just copy line 66 to 114 and rename "app" to "front"
and add another "back" for example. It works fine.

Local config
===

If you want to add your local .gitconfig or composer.auth, you should create a `Vagrantfile` in
`~/.vagrant.d/` and add this:

```
Vagrant.configure("2") do |config|

    # Git
    if File.exists?(File.join(Dir.home, '.gitconfig')) then
      config.vm.provision :file do |file|
        file.source      = '~/.gitconfig'
        file.destination = '/home/vagrant/.gitconfig'
      end
    end

    # Composer
    if File.exists?(File.join(Dir.home, '.composer/auth.json')) then
      config.vm.provision :file do |file|
        file.source      = '~/.composer/auth.json'
        file.destination = '/home/vagrant/.composer/auth.json'
      end
    end

end
```
## Code of conduct

See the [CODE OF CONDUCT](CODE_OF_CONDUCT.md) file.

## Contributing

See the [CONTRIBUTING](CONTRIBUTING.md) file.

## License

For *this* project, I choose […drumroll…] the [MIT License](LICENSE.md).

## SUPPORT

See the [SUPPORT](SUPPORT.md) file. (Don't forget to change default email/slack/...)


text: Working examples of how to control various holonomic drivetrains