text:
package com.tinkerpop.gremlin.structure.server;

/**
 * @author Stephen Mallette (http://stephen.genoprime.com)
 */
public class IntervalVertexRange<V extends Comparable<V>> implements VertexRange<V> {

    /**
     * Generated uid on Dec 10 2013
     */
    private static final long serialVersionUID = -71905414131570157L;

    /**
     * Inclusive.
     */
    private final V startRange;

    /**
     * Exclusive
     */
    private final V endRange;

    public IntervalVertexRange(final V startRange, final V endRange, final int priority) {
        this.startRange = startRange;
        this.endRange = endRange;
    }

    @Override
    public V getStartRange() {
        return startRange;
    }

    @Override
    public V getEndRange() {
        return endRange;
    }

    @Override
    public boolean contains(V item) {
        return startRange.compareTo(item) <= 0 && endRange.compareTo(item) > 0;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        final IntervalVertexRange<?> that = (IntervalVertexRange<?>) o;

        if (!endRange.equals(that.endRange)) return false;
        if (!startRange.equals(that.startRange)) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = startRange.hashCode();
        result = 31 * result + endRange.hashCode();
        return result;
    }

    @Override
    public String toString() {
        return "ElementRange[start=" + startRange + ", end=" + endRange + "]";
    }
}


text:
using System.Collections.Generic;
using System.Reflection;
using Moq;
using NUnit.Framework;
using Simple.Migrations.ConsoleRunner.Process;
using Simple.Migrations.ConsoleRunner.UnitTests.Helpers;
using SimpleMigrations;

namespace Simple.Migrations.ConsoleRunner.UnitTests.Process
{
    [TestFixture]
    public class ApplyProcessTests
    {
        [TestFixture]
        public class GivenMigrationsToApply
        {
            private Mock<ISimpleMigrator> _migrator;
            private OutputWriterSpy _outputWriter;
            private List<long> _migrationsPerformed;

            [OneTimeSetUp]
            public void WhenRunningTheApplyProcess()
            {
                _outputWriter = new OutputWriterSpy();

                var allMigrations = new List<MigrationData>
                {
                    new MigrationData(1, "first", typeof(MigrationData).GetTypeInfo()),
                    new MigrationData(2, "second (current)", typeof(MigrationData).GetTypeInfo()),
                    new MigrationData(3, "third", typeof(MigrationData).GetTypeInfo()),
                    new MigrationData(4, "fourth", typeof(MigrationData).GetTypeInfo()),
                    new MigrationData(5, "fifth", typeof(MigrationData).GetTypeInfo()),
                };

                _migrator = new Mock<ISimpleMigrator>();
                _migrator.SetupGet(m => m.CurrentMigration).Returns(allMigrations[1]);
                _migrator.SetupGet(m => m.Migrations).Returns(allMigrations);

                _migrationsPerformed = new List<long>();
                _migrator
                    .Setup(m => m.MigrateTo(It.IsAny<long>()))
                    .Callback((long version) => _migrationsPerformed.Add(version));

                var applyProcess = new ApplyProcess(_outputWriter);
                applyProcess.Run(_migrator.Object, 4);
            }

            [Test]
            public void ThenTheCorrectMigrationsArePerformedInOrder()
            {
                Assert.That(_migrationsPerformed[0], Is.EqualTo(3));
                Assert.That(_migrationsPerformed[1], Is.EqualTo(4));
            }

            [Test]
            public void ThenEachMigrationVersionIsOutput()
            {
                Assert.That(_outputWriter.GetLine(0), Is.EqualTo("Applying version 3 (Up) - third...Done"));
                Assert.That(_outputWriter.GetLine(1), Is.EqualTo("Applying version 4 (Up) - fourth...Done"));
            }

        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
template <class T>
auto not_skipped() {
  int x;
  if (x = 10) {}
  // Check that this function is not skipped.
  // CHECK: 8:9: warning: using the result of an assignment as a condition without parentheses
  return 1;
}

template <class T>
auto lambda_not_skipped = []() {
  int x;
  if (x = 10) {}
  // Check that this function is not skipped.
  // CHECK: 17:9: warning: using the result of an assignment as a condition without parentheses
  return 1;
}

template <class T>
auto skipped() -> T {
  int x;
  if (x = 10) {}
  // Check that this function is skipped.
  // CHECK-NOT: 26:9: warning: using the result of an assignment as a condition without parentheses
  return 1;
};

auto lambda_skipped = []() -> int {
  int x;
  if (x = 10) {}
  // This could potentially be skipped, but it isn't at the moment.
  // CHECK: 34:9: warning: using the result of an assignment as a condition without parentheses
  return 1;
};

template <class T>
decltype(auto)** not_skipped_ptr() {
  int x;
  if (x = 10) {}
  // Check that this function is not skipped.
  // CHECK: 43:9: warning: using the result of an assignment as a condition without parentheses
  return T();
}

template <class T>
decltype(auto) not_skipped_decltypeauto() {
  int x;
  if (x = 10) {}
  // Check that this function is not skipped.
  // CHECK: 52:9: warning: using the result of an assignment as a condition without parentheses
  return 1;
}

int test() {
  int complete_in_this_function;
  // CHECK: COMPLETION: complete_in_this_function
}


text:
package org.jboss.weld.tests.beanManager.injectionTarget.ejb;

import jakarta.annotation.PostConstruct;
import jakarta.ejb.Stateless;

/**
 * @author Marko Luksa
 */
@Stateless
public class TheEJB {

    private boolean postConstructInvoked;

    @PostConstruct
    public void postConstruct() {
        postConstructInvoked = true;
    }

    public void foo() {
    }

    public boolean isPostConstructInvoked() {
        return postConstructInvoked;
    }
}


text:
export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64/jre

CASSANDRA_VERSION=2.1.1

curl -LO http://archive.apache.org/dist/cassandra/${CASSANDRA_VERSION}/apache-cassandra-${CASSANDRA_VERSION}-bin.tar.gz
tar xf apache-cassandra-${CASSANDRA_VERSION}-bin.tar.gz
ln -s apache-cassandra-${CASSANDRA_VERSION} cassandra
cd cassandra

sudo mkdir -p /var/lib/cassandra /var/log/cassandra
sudo chown `whoami` /var/lib/cassandra /var/log/cassandra

bin/cassandra

for i in {0..30}; do echo "Waiting server ($i)..." ; nc localhost 9042 </dev/null && exit 0 ; sleep 1; done;

exit 1


text:
#import "NSObject.h"

#import "TRTCPConnectionDelegate-Protocol.h"

@class NSMapTable, NSObject<OS_dispatch_queue>;

@interface TRDConnectionManager : NSObject <TRTCPConnectionDelegate>
{
    NSObject<OS_dispatch_queue> *_accessQueue;
    NSObject<OS_dispatch_queue> *_connectionDelegateQueue;
    NSMapTable *_connectionToXPCConnectionOwners;
    NSMapTable *_serviceToConnection;
    NSMapTable *_serviceToConnectionCompletionHandlers;
    NSMapTable *_XPCConnectionToConnectionToPacketEventClasses;
}

+ (id)sharedManager;
- (void).cxx_destruct;
- (void)TRXPCD_connectionWithUniqueIdentifier:(int)arg1 setRelevantReceivedPacketEventTypes:(id)arg2;
- (void)TRXPCD_connectionWithUniqueIdentifier:(int)arg1 sendPacketEvent:(id)arg2 withCompletionHandler:(id)arg3;
- (void)TRXPCD_closeConnectionWithUniqueIdentifier:(int)arg1;
- (void)TRXPCD_connectToService:(id)arg1 withCompletionHandler:(id)arg2;
- (id)_packetEventClassesForPacketEventTypes:(id)arg1;
- (id)_existingConnectionForService:(id)arg1;
- (id)_existingConnectionForConnectionUniqueIdentifier:(int)arg1;
- (void)_callConnectionCompletionHandlersForService:(id)arg1 withConnection:(id)arg2 error:(id)arg3;
- (void)_XPCServerDidInvalidateClientConnectionNotification:(id)arg1;
- (void)connectToService:(id)arg1 withCompletionHandler:(id)arg2;
- (void)connection:(id)arg1 didReceivePacketEvent:(id)arg2;
- (void)connectionDidClose:(id)arg1;
- (void)dealloc;
- (id)_init;
- (id)init;

@end


text:
'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');

var ZarizGenerator = module.exports = function ZarizGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);

  this.on('end', function () {
    this.installDependencies({ skipInstall: options['skip-install'] });
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(ZarizGenerator, yeoman.generators.Base);

/**
 * Ask for the Drupal host.
 */
ZarizGenerator.prototype.askForDrupalHost = function askFor() {
  var cb = this.async();

  // have Yeoman greet the user.
  console.log(this.yeoman);

  var prompts = [{
    name: 'drupalHost',
    message: 'What is your Drupal installation host? You may include the port number.',
    default: 'http://localhost'
  }];

  this.prompt(prompts, function (props) {
    this.drupalHost = props.drupalHost;

    cb();
  }.bind(this));
};

/**
 * Ask for the Drupal domain.
 */
ZarizGenerator.prototype.askForDrupalDomain = function askFor() {
  var cb = this.async();

  var prompts = [{
    name: 'drupalDomain',
    message: 'What is your domain? For example if your site is "http://localhost/drupal", the domain is "/drupal"',
    default: ''
  }];

  this.prompt(prompts, function (props) {
    this.drupalDomain = props.drupalDomain;

    cb();
  }.bind(this));
};

/**
 * Get the static site's base path.
 */
ZarizGenerator.prototype.askForBasePath = function askFor() {
  var cb = this.async();

  var prompts = [{
    name: 'basePath',
    message: 'What is the static site base path? For example if you host your site on example.github.io/your-site, then the base path should be "/your-site"',
    default: ''
  }];

  this.prompt(prompts, function (props) {
    this.basePath = props.basePath;

    cb();
  }.bind(this));
};

/**
 * Get the static site's "master" branch.
 */
ZarizGenerator.prototype.askForMasterBranch = function askFor() {
  var cb = this.async();

  var prompts = [{
    name: 'drupalMasterBranch',
    message: 'What is the name of the master branch.',
    default: 'live'
  }];

  this.prompt(prompts, function (props) {
    this.drupalMasterBranch = props.drupalMasterBranch;

    cb();
  }.bind(this));
};

ZarizGenerator.prototype.app = function app() {
  this.mkdir('app');

  this.template('Gruntfile.js', 'Gruntfile.js');

  this.copy('_package.json', 'package.json');
  this.copy('_bower.json', 'bower.json');
};

ZarizGenerator.prototype.projectfiles = function projectfiles() {
  this.copy('editorconfig', '.editorconfig');
  this.copy('gitignore', '.gitignore');
  this.copy('jshintrc', '.jshintrc');
};


text:
<page>

<title>O Nutch-u</title>

<menu>
 <item>Zasluge</item>
 <item>Status</item>
</menu>

Nutch je poduhvat implementiranja web pretraživača otvorenog koda.

Web pretraživanje je osnovni preduslov za internet navigaciju, a ipak se
broj web pretraživača smanjuje. Oligopol današnjice mogao bi uskoro lako
postati monopol, sa jednom kompanijom koja kotroliše gotovo sva pretraživanja
radi sopstvene finansijske dobiti. Po korisnike interneta to ne bi bilo dobro.

Nutch nudi transparentnu alternativu komercijalnim web pretraživačima.
Samo pretraživačima otvorenog koda možemo verovati da su njihovi rezultati nepristrasni.
(Ili je barem njihova pristrasnost javna.) Svi glavni postojeći pretraživači
imaju sopstvene formule rangiranja rezultata, i ne žele objašnjavati zašto se određena stranica
rangira baš tako. Takođe, nekim web pretraživačima moguće je platiti kako bi se uticalo na to
koji sajt i na koji način će biti rangiran u rezultatima, umesto da uslov za rangiranje bude sam sajt.
Nutch, sa druge strane, nema šta da krije i nema motiva da njegovi rezultati ili njegov crawler bude pristrasan u bilo kom
pogledu osim da pokuša da svakom korisniku ponudi najbolje moguće rezultate.

Cilj Nutch-a je omogući svakome da jednostavno i ekonomično razvije
kvalitetan web pretraživač.  To je veliki izazov.  Da bi uspeo, Nutch
softver mora biti sposoban da:

dohvata nekoliko milijardi stranica mesečno

održava indeks tih stranica

pretražuje indeks tih stranica i do 1000 puta u sekundi

obezbedi visokokvalitetne rezulate pretrage

ima minimalne operativne troškove

To je izazovan poduhvat. Ako veruješ u suštinu ovog projekta, možeš pomoći
bilo svojim radom na razvoju bilo donacijom.

</page>


text:
__author__ = 'leif'
import re
import abc
import sys
import math
import collections

class DifferenceHelper(object):
    """
    Abstract difference class.
    Contains helper methods for setting up - the difference() method is abstract.
    """
    def __init__(self, stopword_file=None, vocab_file=None):
        self.vocab = self.__read_vocab_dict(vocab_file)
        self.stopwords = self.__read_stopwords_list(stopword_file)

        if not self.stopwords:
            self.stopwords = ['and', 'for', 'if', 'the', 'then', 'be', 'is', 'are', 'will', 'in', 'it', 'to', 'that']

    def __read_stopwords_list(self, stopwords_file):
        """
        Given the stopwords instance variable, returns a list of stopwords to use.
        Assumes that each word to be used is on a new line.
        """
        stopwords = []
        if stopwords_file:
            f = open(stopwords_file, 'r')
            for line in f:
                line = line.strip()
                stopwords.append(line)

            f.close()
        return stopwords

    def __read_vocab_dict(self, vocab_file):
        """
        :param vocab_file: Given a file which is a list of (word (string) ,count (int)) pairs on newlines
        :return: a dictionary of the words and their counts
        """
        vocab = {}
        if vocab_file:
            f = open(vocab_file, 'r')
            for line in f:
                split_line=line.strip().split(',')
                term = split_line[0]
                count = int(split_line[1])
                vocab[term] = count
        return vocab

    def _tokeniser(self, _str, stopwords=['and', 'for', 'if', 'the', 'then', 'be', 'is', 'are', 'will', 'in', 'it', 'to', 'that']):
        """
        Given an input string and list of stopwords, returns a dictionary of frequency occurrences for terms in the given input string.
        From https://gist.github.com/mrorii/961963
        """
        tokens = collections.defaultdict(lambda: 0.)

        for m in re.finditer(r"(\w+)", _str, re.UNICODE):
            m = m.group(1).lower()

            if len(m) < 2:
                continue

            if m in stopwords:
                continue

            tokens[m] += 1

        return tokens

    @abc.abstractmethod
    def difference(self, new_text, seen_text):
        """
        Abstract method for determining the difference between previously seen and unseen text.
        """
        return NotImplementedError()

class TermOverlapDifference(DifferenceHelper):
    """
    String difference implemenattion - determines the difference between two strings by counting term overlaps.
    """
    def __init__(self, stopword_file=None, vocab_file=None):
        super(TermOverlapDifference, self).__init__(stopword_file, vocab_file)

    def difference(self, new_text, seen_text):
        """
        Concrete implementation - works out the term overlap between the two passed strings.
        """
        new_text = self._tokeniser(new_text)
        seen_text = self._tokeniser(seen_text)

        new_text_length = len(new_text)
        overlap_count = 0.0

        for term in new_text.keys():
            if term in seen_text.keys():
                overlap_count += 1

        return overlap_count / new_text_length

class KLDifference(DifferenceHelper):
    """
    Implementation of KL-Divergence for determining the difference between two texts (strings).
    """
    def __init__(self, alpha = 0.5, stopword_file=None, vocab_file=None):
        super(KLDifference, self).__init__(stopword_file, vocab_file)
        self.alpha = alpha # the mixing co-efficient

    def difference(self, new_text, seen_text):
        """
        Concrete implementation - works out the KL divergence between the two passed strings.
        """
        new_text = self._tokeniser(new_text)
        seen_text = self._tokeniser(seen_text)

        # need to mix the seen text with the background text.

        for t in seen_text:
            seen_text[t] =  seen_text[t] * self.alpha/(1-self.alpha)

        # dmax says: I don't understand this; and the results don't level off as well as the implementation below.
        # for t in self.vocab:
        #     if seen_text[t]:
        #         seen_text[t] = seen_text[t] + self.vocab[t]
        #     else:
        #         seen_text[t] = self.vocab[t]

        for t in self.vocab:
            if t in seen_text:
                seen_text[t] += 1
            else:
                seen_text[t] = 1.0

        return self.__kl_divergence(new_text,seen_text)

    def __kl_divergence(self,_s, _t):
        """
        An implementation of Kullback-Leibler divergence for comparing two strings (documents).
        From https://gist.github.com/mrorii/961963
        """
        stopwords = self.stopwords

        if (len(_s) == 0):
            return 1e33

        if (len(_t) == 0):
            return 1e33

        ssum = 0. + sum(_s.values())
        slen = len(_s)

        tsum = 0. + sum(_t.values())
        tlen = len(_t)

        vocabdiff = set(_s.keys()).difference(set(_t.keys()))
        lenvocabdiff = len(vocabdiff)

        """ epsilon """
        epsilon = min(min(_s.values())/ssum, min(_t.values())/tsum) * 0.001

        """ gamma """
        gamma = 1 - lenvocabdiff * epsilon

        # print "_s: %s" % _s
        # print "_t: %s" % _t

        """ Check if distribution probabilities sum to 1"""
        sc = sum([v/ssum for v in _s.itervalues()])
        st = sum([v/tsum for v in _t.itervalues()])

        if sc < 9e-6:
            print "Sum P: %e, Sum Q: %e" % (sc, st)
            print "*** ERROR: sc does not sum up to 1. Bailing out .."
            sys.exit(2)
        if st < 9e-6:
            print "Sum P: %e, Sum Q: %e" % (sc, st)
            print "*** ERROR: st does not sum up to 1. Bailing out .."
            sys.exit(2)

        div = 0.
        for t, v in _s.iteritems():
            pts = v / ssum

            ptt = epsilon
            if t in _t:
                ptt = gamma * (_t[t] / tsum)

            ckl = (pts - ptt) * math.log(pts / ptt)

            div +=  ckl

        return div


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Formatting;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudio.Utilities;

namespace Microsoft.VisualStudio.LanguageServices.Implementation.InheritanceMargin
{
    internal class InheritanceMarginViewMargin : ForegroundThreadAffinitizedObject, IWpfTextViewMargin
    {
        // 16 (width of the crisp image) + 2 * 1 (width of the border) = 18
        private const double HeightAndWidthOfMargin = 18;
        private readonly IWpfTextView _textView;
        private readonly ITagAggregator<InheritanceMarginTag> _tagAggregator;
        private readonly IGlobalOptionService _globalOptions;
        private readonly InheritanceGlyphManager _glyphManager;
        private readonly string _languageName;
        private readonly Canvas _mainCanvas;

        /// <summary>
        /// A flag indicates all the glyphs in this margin needs be refreshed when the Layout of the TextView changes.
        /// Should only be read or written to by the UI thread.
        /// </summary>
        private bool _refreshAllGlyphs;
        private bool _disposed;

        public InheritanceMarginViewMargin(
            Workspace workspace,
            IWpfTextView textView,
            IThreadingContext threadingContext,
            IStreamingFindUsagesPresenter streamingFindUsagesPresenter,
            IUIThreadOperationExecutor operationExecutor,
            IClassificationFormatMap classificationFormatMap,
            ClassificationTypeMap classificationTypeMap,
            ITagAggregator<InheritanceMarginTag> tagAggregator,
            IEditorFormatMap editorFormatMap,
            IGlobalOptionService globalOptions,
            IAsynchronousOperationListener listener,
            string languageName) : base(threadingContext)
        {
            _textView = textView;
            _tagAggregator = tagAggregator;
            _globalOptions = globalOptions;
            _languageName = languageName;
            _mainCanvas = new Canvas { ClipToBounds = true, Width = HeightAndWidthOfMargin };
            _glyphManager = new InheritanceGlyphManager(
                workspace,
                textView,
                threadingContext,
                streamingFindUsagesPresenter,
                classificationFormatMap,
                classificationTypeMap,
                operationExecutor,
                editorFormatMap,
                listener,
                _mainCanvas,
                HeightAndWidthOfMargin);
            _refreshAllGlyphs = true;
            _disposed = false;

            _tagAggregator.BatchedTagsChanged += OnTagsChanged;
            _textView.LayoutChanged += OnLayoutChanged;
            _textView.ZoomLevelChanged += OnZoomLevelChanged;
            _globalOptions.OptionChanged += OnGlobalOptionChanged;

            UpdateMarginVisibility();
        }

        void IDisposable.Dispose()
        {
            AssertIsForeground();
            if (!_disposed)
            {
                _disposed = true;
                _tagAggregator.BatchedTagsChanged -= OnTagsChanged;
                _textView.LayoutChanged -= OnLayoutChanged;
                _textView.ZoomLevelChanged -= OnZoomLevelChanged;
                _globalOptions.OptionChanged -= OnGlobalOptionChanged;
                _tagAggregator.Dispose();
                ((IDisposable)_glyphManager).Dispose();
            }
        }

        private void OnZoomLevelChanged(object sender, ZoomLevelChangedEventArgs e)
        {
            _refreshAllGlyphs = true;
        }

        private void OnLayoutChanged(object sender, TextViewLayoutChangedEventArgs e)
        {
            _glyphManager.SetSnapshotAndUpdate(
                _textView.TextSnapshot,
                e.NewOrReformattedLines,
                e.VerticalTranslation ? _textView.TextViewLines : e.TranslatedLines);

            IList<ITextViewLine> lines = _refreshAllGlyphs ? _textView.TextViewLines : e.NewOrReformattedLines;
            foreach (var line in lines)
            {
                _glyphManager.RemoveGlyphs(line.Extent);
                RefreshGlyphsOver(line);
            }

            _refreshAllGlyphs = false;
        }

        private void OnGlobalOptionChanged(object sender, OptionChangedEventArgs e)
        {
            if (e.Option.Equals(FeatureOnOffOptions.ShowInheritanceMargin) ||
                e.Option.Equals(FeatureOnOffOptions.InheritanceMarginCombinedWithIndicatorMargin))
            {
                UpdateMarginVisibility();
            }
        }

        private void UpdateMarginVisibility()
        {
            _mainCanvas.Visibility =
                (_globalOptions.GetOption(FeatureOnOffOptions.ShowInheritanceMargin, _languageName) ?? true) &&
                !_globalOptions.GetOption(FeatureOnOffOptions.InheritanceMarginCombinedWithIndicatorMargin) ? Visibility.Visible : Visibility.Collapsed;
        }

        private void OnTagsChanged(object sender, BatchedTagsChangedEventArgs e)
        {
            if (_textView.IsClosed)
            {
                return;
            }

            using var _ = CodeAnalysis.PooledObjects.ArrayBuilder<SnapshotSpan>.GetInstance(out var builder);
            foreach (var mappingSpan in e.Spans)
            {
                var normalizedSpan = mappingSpan.GetSpans(_textView.TextSnapshot);
                builder.AddRange(normalizedSpan);
            }

            var changedSnapshotSpans = builder.ToImmutable();
            if (changedSnapshotSpans.Length == 0)
            {
                return;
            }

            var startOfChangedSpan = changedSnapshotSpans.Min(span => span.Start);
            var endOfChangedSpan = changedSnapshotSpans.Max(span => span.End);
            var changedSpan = new SnapshotSpan(startOfChangedSpan, endOfChangedSpan);

            _glyphManager.RemoveGlyphs(changedSpan);

            foreach (var line in _textView.TextViewLines.GetTextViewLinesIntersectingSpan(changedSpan))
            {
                if (line.IsValid)
                {
                    RefreshGlyphsOver(line);
                }
            }
        }

        private void RefreshGlyphsOver(ITextViewLine textViewLine)
        {
            if (!_globalOptions.GetOption(FeatureOnOffOptions.InheritanceMarginCombinedWithIndicatorMargin))
            {
                foreach (var mappingTagSpan in _tagAggregator.GetTags(textViewLine.ExtentAsMappingSpan))
                {
                    // Only take tag spans with a visible start point and that map to something
                    // in the edit buffer and *start* on this line
                    if (mappingTagSpan.Span.Start.GetPoint(_textView.VisualSnapshot.TextBuffer, PositionAffinity.Predecessor) != null)
                    {
                        var tagSpans = mappingTagSpan.Span.GetSpans(_textView.TextSnapshot);
                        if (tagSpans.Count > 0)
                        {
                            _glyphManager.AddGlyph(mappingTagSpan.Tag, tagSpans[0]);
                        }
                    }
                }
            }
        }

        private void ThrowIfDisposed()
        {
            if (_disposed)
            {
                throw new ObjectDisposedException(nameof(InheritanceMarginViewMargin));
            }
        }

        FrameworkElement IWpfTextViewMargin.VisualElement
        {
            get
            {
                ThrowIfDisposed();
                return _mainCanvas;
            }
        }

        double ITextViewMargin.MarginSize
        {
            get
            {
                ThrowIfDisposed();
                return _mainCanvas.ActualWidth;
            }
        }

        bool ITextViewMargin.Enabled
        {
            get
            {
                ThrowIfDisposed();
                return true;
            }
        }

        ITextViewMargin? ITextViewMargin.GetTextViewMargin(string marginName)
            => marginName == nameof(InheritanceMarginViewMargin) ? this : null;
    }
}


text: export * from './condensed-header-example';


text:
* API based on https requests to Ubisoft servers. It's just proof of concept.

* If you will login too often, google captcha will be forced. There's no support of it

* Last Update: 1st Mar 2017

* Use this only as reference, this code is not well designed and outdated (it'll probably work)!

### Downloading

To use this API you'll just need to copy ticket_file and uAPI.php

### Examples

First of all, you'll need to include api
```php
<?php
include("uAPI.php");
?>
```

Login and update Ticket in ticket_file
```php
<?php
include("uAPI.php");
$uapi = new ubiapi("email","password",null);
$apianswer=$uapi->login(1); //1 for raw, 2 for decoded raw
print $apianswer["error"]; //when 0 - everything is good!
?>
```

Update Ticket (no need to login everytime, without this function you can get banned)
```php
<?php
...
//include api and define it as $uapi
$rt = $uapi->refreshTicket("bynick","v.m.r_ipa");
if($rt["error"]){
	die( "Error: ".$rt["content"]);
}
else{
	print "No Error: ".$rt["content"];
}
```

Get friendlist
```php
<?php
...
//include api, define it as $uapi and update ticket
$fl = $uapi->getFriends();
if($fl["error"] != true){ //small check if api response is vaild
	print $fl["raw"];
}
```

Get Nickname using profileId
```php
<?php
...
//include api, define it as $uapi (and update ticket [refreshTicket])
$su = $uapi->searchUser("byid","01e84770-c50e-402b-8132-b94016f93b77");
if($su["error"] != true){
	print "profileid is: ".$su["nick"]; //you can use 'json' to get array with all info
}
```

Get profileId using Nickname
```php
<?php
...
//include api, define it as $uapi (and update ticket [refreshTicket])
$su = $uapi->searchUser("bynick","v.m.r_ipa");
if($su["error"] != true){
	print "profileid is: ".$su["uid"]; //you can use 'json' to get array with all info
}
```
## Disabling Debug Messages

To disable debug messages you'll need to change line 14 in uAPI.php

from
```
public $debug=true;
```

to
```
public $debug=false;
```
## License

This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details


text:
package com.testin;

import javax.sql.DataSource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

/**
 * ClassName:DataSourceConfigure

 * Function:

 * Date: 2016年12月16日 下午6:27:39

 * @author xushjie
 * @version
 * @since JDK 1.8
 * @see
 */
@Configuration
public class DataSourceConfigure {

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource("jdbc:mysql://10.10.32.32:3306/demo?useUnicode=true&characterEncoding=UTF-8",
                                                                         "root",
                                                                         "testin");
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        return dataSource;
    }

}


text:
package org.unitils.mock.mockbehavior.impl;

import org.unitils.mock.core.DummyFactory;
import org.unitils.mock.core.proxy.ProxyInvocation;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.lang.reflect.Modifier.isFinal;

/**
 * Mock behavior that returns a default value. The default value for an object will be a proxy object with the same behaviour. When doing
 * the same call multiple times the same 'proxy' object will be returned each time. Doing the same method call with other parameters will
 * however result a new object returned.
 *

 * Following defaults are used:
 *

 *
Number values: 0

 *
String values: ""

 *
Object values: DummyObject

 *
Collection: empty list

 *
Arrays: empty array

 *

 *

 *
 * @author Tim Ducheyne
 * @author Jeroen Horemans
 */
public class DummyValueReturningMockBehavior extends DefaultValueReturningMockBehavior {

    protected DummyFactory dummyFactory;
    /* Keeps track of what object we have returned, so that we return the "same" instance on each invocation */
    protected Map<MethodKey, Object> returnValues = new HashMap<MethodKey, Object>();

    public DummyValueReturningMockBehavior(DummyFactory dummyFactory) {
        this.dummyFactory = dummyFactory;
    }

    /**
     * Executes the mock behavior.
     *
     * @param proxyInvocation The proxy method invocation, not null
     * @return The default value defined by this behavior
     */
    public Object execute(ProxyInvocation proxyInvocation) {
        Method method = proxyInvocation.getMethod();
        Class<?> returnType = method.getReturnType();
        List<?> argumentValues = proxyInvocation.getArgumentValues();
        MethodKey key = new MethodKey(method.getName(), argumentValues);

        if (returnValues.containsKey(key)) {
            return returnValues.get(key);
        }
        Object result = getReturnValue(proxyInvocation, returnType);
        returnValues.put(key, result);
        return result;
    }

    protected Object getReturnValue(ProxyInvocation proxyInvocation, Class<?> returnType) {
        Object result = super.execute(proxyInvocation);
        if (result != null) {
            return result;
        }
        if (String.class.equals(returnType)) {
            return "";
        }
        if (cannotCreateDummy(returnType)) {
            return null;
        }
        return dummyFactory.createDummy(null, returnType);
    }

    protected boolean cannotCreateDummy(Class<?> returnType) {
        return returnType == Void.TYPE || isFinal(returnType.getModifiers());
    }

    protected static class MethodKey {

        protected String methodName;
        protected List<?> arguments;

        public MethodKey(String methodName, List<?> arguments) {
            this.methodName = methodName;
            this.arguments = arguments;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }

            MethodKey methodKey = (MethodKey) o;
            if (arguments != null ? !arguments.equals(methodKey.arguments) : methodKey.arguments != null) {
                return false;
            }
            if (methodName != null ? !methodName.equals(methodKey.methodName) : methodKey.methodName != null) {
                return false;
            }
            return true;
        }

        @Override
        public int hashCode() {
            int result = methodName != null ? methodName.hashCode() : 0;
            result = 31 * result + (arguments != null ? arguments.hashCode() : 0);
            return result;
        }
    }
}


text:
FloatingView

  FloatingView can make the target view  floating above the anchor view with cool animation

Links
-----
- [中文版 README](https://github.com/UFreedom/FloatingView/blob/master/README_CN.md)
- [Blog about FloatingView](http://www.jianshu.com/p/6aaa258d77f1)
- [demo.apk](http://oeapkptbn.bkt.clouddn.com/FloatingView-demo-v1.0.1.apk)

Usage
-----

### Step 1

Add dependencies in build.gradle.

```groovy
    dependencies {
        compile 'com.ufreedom.uikit:FloatingViewLib:1.0.2'
    }

```

### Step 2

Use FloatingBuilder to create a FloatingElement

```java

    FloatingElement builder = new FloatingBuilder()
                            .anchorView(View)
                            .targetView(View)
                            .offsetX(int)
                            .offsetY(int)
                            .floatingTransition(FloatingTransition)
                            .build();

```

The use of FloatingBuilder can be configured to have:

* anchorView :Anchor, is you want to float animation in which View above
* target:Target, The view which you want to float
* offsetX:X direction of offset, unit PX
* offsetY: Y direction of offset, unit PX
* floatingTransition : Floating effect, the default is ScaleFloatingTransition

### Step 3

Create a Floating as a FloatingElement container, and then let your View fly up

```java
    Floating floating = new Floating(getActivity());
    floating.startFloating(builder);
```

Customisation
-------------

####1.Coordinates

####2.Class Diagram

####3.Floating Animation

Implementation of floating animation is very simple, you only need to implement the [FloatingTransition][4] interface.

```java

    public interface FloatingTransition {
        public void applyFloating(YumFloating yumFloating);
    }

```

In the `applyFloating` method, you can use Android Animation to do the animation, and then use the [YumFloating][6] to do Alpha  , Scale, Translate, Rotate and other transformations.
If you want to add the [Facebook Rebound][5]  animation effect, you can use the [SpringHelper][7], for example, [ScaleFloatingTransition][8]:

```java
    public class ScaleFloatingTransition implements FloatingTransition {

    ...

    @Override
    public void applyFloating(final YumFloating yumFloating) {

        ValueAnimator alphaAnimator = ObjectAnimator.ofFloat(1.0f, 0.0f);
        alphaAnimator.setDuration(duration);
        alphaAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                yumFloating.setAlpha((Float) valueAnimator.getAnimatedValue());
            }
        });
        alphaAnimator.start();

        SpringHelper.createWithBouncinessAndSpeed(0.0f, 1.0f,bounciness, speed)
                .reboundListener(new SimpleReboundListener(){
                    @Override
                    public void onReboundUpdate(double currentValue) {
                        yumFloating.setScaleX((float) currentValue);
                        yumFloating.setScaleY((float) currentValue);
                    }
                }).start(yumFloating);
    }

}

```

If [SpringHelper][7] can not meet your needs, you can directly use the `createSpringByBouncinessAndSpeed(double bounciness, double speed)` or
`createSpringByTensionAndFriction(double tension, double friction)` to create the Spring, and then use `transition (Progress double, startValue float, endValue float)` for numerical conversion

####4.Floating Path Animation
The floating path animation is also very simple, such as [CurveFloatingPathTransition][9], first you need to inherit from the [BaseFloatingPathTransition][10] class ,The difference is, you need to implement a `getFloatingPath (`) method.
Use `Path` in the `getFloatingPath () `method to create the path you want to float, and then call `FloatingPath.create (path, false)` to return. For example, [CurveFloatingPathTransition][9] implementation:

```java
    public class CurveFloatingPathTransition extends BaseFloatingPathTransition {

        ...

        @Override
        public FloatingPath getFloatingPath() {
            if (path == null){
                path = new Path();
                path.moveTo(0, 0);
                path.quadTo(-100, -200, 0, -300);
                path.quadTo(200, -400, 0, -500);
            }
            return FloatingPath.create(path, false);
        }

        @Override
        public void applyFloating(final YumFloating yumFloating) {
            ValueAnimator translateAnimator;
            ValueAnimator alphaAnimator;

            translateAnimator = ObjectAnimator.ofFloat(getStartPathPosition(), getEndPathPosition());
            translateAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator valueAnimator) {
                    float value = (float) valueAnimator.getAnimatedValue();
                    PathPosition floatingPosition = getFloatingPosition(value);
                    yumFloating.setTranslationX(floatingPosition.x);
                    yumFloating.setTranslationY(floatingPosition.y);

                }
            });

           ...
        }

}
```

Use Path to describe the path you want to float, and then in `applyFloating (YumFloating yumFloating)`:

* Use `getStartPathPosition () ` method to obtain the starting position of the path
* Use `getEndPathPosition () ` method to obtain the end position of the path
* Use `getFloatingPosition(float progress)` to get the position of the current progress

`getFloatingPosition(float progress)`method will return a `PathPosition` object, its properties x an y representing the current path animation x coordinates and Y coordinates.

Release Log
-----------

#### v1.0.2
[Fix bug](https://github.com/UFreedom/FloatingView/pull/6)

#### v1.0.1
First Version

License
--------

    Copyright 2015 UFreedom

    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.

[1]:https://github.com/UFreedom/FloatingView/blob/master/FloatingViewLib/src/main/java/com/ufreedom/floatingview/FloatingBuilder.java
[2]:https://github.com/UFreedom/FloatingView/blob/master/FloatingViewLib/src/main/java/com/ufreedom/floatingview/FloatingElement.java
[3]:https://github.com/UFreedom/FloatingView/blob/master/FloatingViewLib/src/main/java/com/ufreedom/floatingview/Floating.java
[4]:https://github.com/UFreedom/FloatingView/blob/master/FloatingViewLib/src/main/java/com/ufreedom/floatingview/transition/FloatingTransition.java
[5]:http://facebook.github.io/rebound/
[6]:https://github.com/UFreedom/FloatingView/blob/master/FloatingViewLib/src/main/java/com/ufreedom/floatingview/transition/YumFloating.java
[7]:https://github.com/UFreedom/FloatingView/blob/master/FloatingViewLib/src/main/java/com/ufreedom/floatingview/spring/SpringHelper.java
[8]:https://github.com/UFreedom/FloatingView/blob/master/FloatingViewLib/src/main/java/com/ufreedom/floatingview/effect/ScaleFloatingTransition.java
[9]:https://github.com/UFreedom/FloatingView/blob/master/FloatingViewLib/src/main/java/com/ufreedom/floatingview/effect/CurveFloatingPathTransition.java
[10]:https://github.com/UFreedom/FloatingView/blob/master/FloatingViewLib/src/main/java/com/ufreedom/floatingview/transition/BaseFloatingPathTransition.java


text:
<?php
/**
 * Created by PhpStorm.
 * User: hp
 * Date: 19/12/2014
 * Time: 17:12
 */

namespace Sise\Bundle\UserBundle\Controller;

use Symfony\Component\HttpFoundation\RedirectResponse;
use FOS\UserBundle\Controller\RegistrationController as BaseController;
use Symfony\Component\HttpFoundation\Request;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;

use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\Event\GetResponseUserEvent;
use FOS\UserBundle\Event\FilterUserResponseEvent;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use FOS\UserBundle\Model\UserInterface;

class RegistrationController extends BaseController
{

    /**
     * @Security("has_role('A')")
     */

    public function registerAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        /** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
        $formFactory = $this->get('fos_user.registration.form.factory');
        /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
        $userManager = $this->get('fos_user.user_manager');
        /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
        $dispatcher = $this->get('event_dispatcher');

        $user = $userManager->createUser();
        $user->setEnabled(true);

        $event = new GetResponseUserEvent($user, $request);
        $dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);

        if (null !== $event->getResponse()) {
            return $event->getResponse();
        }

        $form = $formFactory->createForm();
        if ($request->isMethod('POST')) {
            $form->setData($user);
            $form->handleRequest($request);
            $event = new FormEvent($form, $request);
            $dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);
            $params = $request->request->get($form->getName());
            if($params["codedele"]){
                $del = $em->getRepository('SiseCoreBundle:NomenclatureDelegation')->find($params["codedele"]);
                if($del){
                    $user->setCodedele($del);
                }
            }
            if($params["codetypeetab"]){
                $typeetab = $em->getRepository('SiseCoreBundle:NomenclatureTypeetablissement')->find($params["codetypeetab"]);
                if($typeetab){
                    $user->setCodetypeetab($typeetab);
                }
            }
            if($params["codeetab"]){
                $etab = $em->getRepository('SiseCoreBundle:NomenclatureEtablissement')->findOneBy(array('codeetab'=>$params["codeetab"], 'codetypeetab'=>$typeetab));
                if($typeetab and $etab){
                    $user->setCodeetab($etab);
                }
            }
            if ($form->isValid()) {
                $userManager->updateUser($user);
                if (null === $response = $event->getResponse()) {
                    //  $url = $this->generateUrl('fos_user_registration_confirmed');
                    $url = $this->generateUrl('sise_user_list');
                    $response = new RedirectResponse($url);
                }
                // $dispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response));
                return $response;

            }
        }
        return $this->render('FOSUserBundle:Registration:register.html.twig', array(
            'form' => $form->createView(),
        ));
    }

    /**
     * @Security("has_role('A')")
     */

    public function editAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();
        $user = $em->getRepository('SiseUserBundle:User')->find($id);
        if (!$user) {
            throw new AccessDeniedException('This user does not have access to this section.');
        }
        /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
        $dispatcher = $this->get('event_dispatcher');
        $event = new GetResponseUserEvent($user, $request);
        $dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_INITIALIZE, $event);
        if (null !== $event->getResponse()) {
            return $event->getResponse();
        }
        /** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
       // $formFactory = $this->get('sise_user.profile.form.factory');
        $formFactory = $this->container->get('sise_user.profile.form.factory');

        $form = $formFactory->createForm();
        $form->setData($user);
        $form->handleRequest($request);
        $params = $request->request->get($form->getName());
        if($params["codedele"]){
            $del = $em->getRepository('SiseCoreBundle:NomenclatureDelegation')->find($params["codedele"]);
            if($del){
                $user->setCodedele($del);
            }
        }
        if($params["codetypeetab"]){
            $typeetab = $em->getRepository('SiseCoreBundle:NomenclatureTypeetablissement')->find($params["codetypeetab"]);
            if($typeetab){
                $user->setCodetypeetab($typeetab);
            }
        }
        if($params["codeetab"]){
            $etab = $em->getRepository('SiseCoreBundle:NomenclatureEtablissement')->findOneBy(array('codeetab'=>$params["codeetab"], 'codetypeetab'=>$typeetab));
            if($typeetab and $etab){
                $user->setCodeetab($etab);
            }
        }
        if ($form->isValid()) {
            /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
            $userManager = $this->get('fos_user.user_manager');
            $event = new FormEvent($form, $request);
            $dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_SUCCESS, $event);
            $userManager->updateUser($user);
            if (null === $response = $event->getResponse()) {
                $url = $this->generateUrl('sise_user_list');
                $response = new RedirectResponse($url);
            }

            $dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_COMPLETED, new FilterUserResponseEvent($user, $request, $response));

            return $response;
        }
        return $this->render('FOSUserBundle:Registration:edit.html.twig', array(
            'form' => $form->createView(),
            'user'=>$user
        ));
    }

    /**
     * Tell the user to check his email provider
     */
    public function checkEmailAction()
    {
        $email = $this->get('session')->get('fos_user_send_confirmation_email/email');
        $this->get('session')->remove('fos_user_send_confirmation_email/email');
        $user = $this->get('fos_user.user_manager')->findUserByEmail($email);

        if (null === $user) {
            throw new NotFoundHttpException(sprintf('The user with email "%s" does not exist', $email));
        }

        return $this->render('FOSUserBundle:Registration:checkEmail.html.twig', array(
            'user' => $user,
        ));
    }

    /**
     * Receive the confirmation token from user email provider, login the user
     */
    public function confirmAction(Request $request, $token)
    {
        /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
        $userManager = $this->get('fos_user.user_manager');

        $user = $userManager->findUserByConfirmationToken($token);

        if (null === $user) {
            throw new NotFoundHttpException(sprintf('The user with confirmation token "%s" does not exist', $token));
        }

        /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
        $dispatcher = $this->get('event_dispatcher');

        $user->setConfirmationToken(null);
        $user->setEnabled(true);

        $event = new GetResponseUserEvent($user, $request);
        $dispatcher->dispatch(FOSUserEvents::REGISTRATION_CONFIRM, $event);

        $userManager->updateUser($user);

        if (null === $response = $event->getResponse()) {
           // $url = $this->generateUrl('fos_user_registration_confirmed');
            $url = $this->generateUrl('sise_user_list');
            $response = new RedirectResponse($url);
        }

        $dispatcher->dispatch(FOSUserEvents::REGISTRATION_CONFIRMED, new FilterUserResponseEvent($user, $request, $response));

        return $response;
    }

    /**
     * Tell the user his account is now confirmed
     */
    public function confirmedAction()
    {
        $user = $this->getUser();
        if (!is_object($user) || !$user instanceof UserInterface) {
            throw new AccessDeniedException('This user does not have access to this section.');
        }

        return $this->render('FOSUserBundle:Registration:confirmed.html.twig', array(
            'user' => $user,
        ));
    }
}


text:
from tests.fixtures import *
from servi.utils import *
from servi.command import process_and_run_command_line as servi_run
from servi.template_mgr import TemplateManager

ROLETEST_PLAYBOOK = '''
---
-   hosts: all
    vars_files:
      - ../Servifile.yml
    sudo: yes
    tasks:
    roles:
        # - baseUbuntu
        #mainAccount
        - hardenedUbuntu
        - hardenedApache
        - projectSpecific
'''

def test_role_handling(setup_init):
    # Role in master, not in template directory -- ignored

    # Role commented in master and also in template:
    # 1) don't copy
    # 2) Do warn
    with open(pathfor('ansible_config/playbook.yml', c.MASTER), 'w') as fp:
        fp.write(ROLETEST_PLAYBOOK)
    modify_file(pathfor('ansible_config/roles/baseUbuntu/tasks/main.yml',
                c.TEMPLATE))
    modify_file(pathfor('ansible_config/roles/mainAccount/tasks/main.yml',
                c.TEMPLATE))

    assert servi_run('update')

    tmgr = TemplateManager(raw_template_playbook=ROLETEST_PLAYBOOK)
    assert tmgr.possible_roles == {'baseUbuntu', 'mainAccount'}
    assert tmgr.modified_possible_roles == {'baseUbuntu', 'mainAccount'}
    assert 'ansible_config/playbook.yml' in tmgr.t_mod_but_ignored

    # TODO - make sure a new role file is also caught


text:
package com.fsck.k9.message;

import com.fsck.k9.mail.Body;
import com.fsck.k9.mail.BodyPart;
import com.fsck.k9.mail.Message;
import com.fsck.k9.mail.MessagingException;
import com.fsck.k9.mail.internet.MimeBodyPart;
import com.fsck.k9.mail.internet.MimeHeader;
import com.fsck.k9.mail.internet.MimeMessage;
import com.fsck.k9.mail.internet.MimeMultipart;
import com.fsck.k9.mail.internet.TextBody;
import com.fsck.k9.mailstore.BinaryMemoryBody;

public class MessageCreationHelper {
    public static BodyPart createTextPart(String mimeType) throws MessagingException {
        return createTextPart(mimeType, "");
    }

    public static BodyPart createTextPart(String mimeType, String text) throws MessagingException {
        TextBody body = new TextBody(text);
        return new MimeBodyPart(body, mimeType);
    }

    public static BodyPart createEmptyPart(String mimeType) throws MessagingException {
        return new MimeBodyPart(null, mimeType);
    }

    public static BodyPart createPart(String mimeType) throws MessagingException {
        BinaryMemoryBody body = new BinaryMemoryBody(new byte[0], "utf-8");
        return new MimeBodyPart(body, mimeType);
    }

    public static BodyPart createMultipart(String mimeType, BodyPart... parts) throws MessagingException {
        MimeMultipart multipart = createMultipartBody(mimeType, parts);
        return new MimeBodyPart(multipart, mimeType);
    }

    public static Message createTextMessage(String mimeType, String text) throws MessagingException {
        TextBody body = new TextBody(text);
        return createMessage(mimeType, body);
    }

    public static Message createMultipartMessage(String mimeType, BodyPart... parts) throws MessagingException {
        MimeMultipart body = createMultipartBody(mimeType, parts);
        return createMessage(mimeType, body);
    }

    public static Message createMessage(String mimeType) throws MessagingException {
        return createMessage(mimeType, null);
    }

    private static Message createMessage(String mimeType, Body body) {
        MimeMessage message = new MimeMessage();
        message.setBody(body);
        message.setHeader(MimeHeader.HEADER_CONTENT_TYPE, mimeType);

        return message;
    }

    private static MimeMultipart createMultipartBody(String mimeType, BodyPart[] parts) {
        MimeMultipart multipart = new MimeMultipart(mimeType, "boundary");
        for (BodyPart part : parts) {
            multipart.addBodyPart(part);
        }
        return multipart;
    }
}


text:
namespace codegen {
class CParCodeGen : public CCodeGen {
public:
    CParCodeGen(parser::Driver &Drv);
    void visit(common::Program &Node);

private:
    void visit(common::Function &Node);
    void visit(common::Case &Node);
    void visit(common::CallExpr &Node);

    const std::string GPar = "par";
    const std::string GSeq = "call";
    const std::string GTask = GGenerated + "task";

    unsigned int TaskCount = 0;

    std::string CurrentArg;
    bool GenerateParallel;

    unsigned int CallDepth;
    std::vector<std::vector<ctree::Statement*>> ParallelCalls;
    std::vector<ctree::Statement*> SequentialCall;

    std::string generateSignature(common::Type &Ty);
    std::string getArgType(common::Type &Ty);
    std::string getArgName(common::Type &Ty);
    void outputParallel();
    void generateStd();
};
}


text:
/**
  @module ember-flexberry
*/

import Ember from 'ember';
import { Query } from 'ember-flexberry-data';
const { SimplePredicate, StringPredicate, DatePredicate, NotPredicate } = Query;

/**
  Builds predicate for filter

  @example
    ```javascript
    import { predicateForFilter } from 'ember-flexberry/utils/filter'
    predicateForFilter(filter)
    ```

  @method predicateForFilter
  @param {Object} filter Object (`{ name, condition, pattern }`) with parameters for filter.
  @return {BasePredicate|null} Predicate to filter through.
*/
let predicateForFilter = function (filter) {
  if (filter.condition) {
    switch (filter.type) {
      case 'string':
        switch (filter.condition) {
          case 'like':
            return new StringPredicate(filter.name).contains(filter.pattern || '');
          case 'nlike':
            return new NotPredicate(new StringPredicate(filter.name).contains(filter.pattern || ''));
          default:
            return new SimplePredicate(filter.name, filter.condition, filter.pattern || null);
        }

        break;
      case 'boolean':
        switch (filter.condition) {
          case 'empty':
            return new SimplePredicate(filter.name, 'eq', null);
          case 'nempty':
            return new SimplePredicate(filter.name, 'neq', null);
          default:
            return new SimplePredicate(filter.name, filter.condition, filter.pattern);
        }

        break;
      case 'number':
        if (filter.condition === 'between') {
          if (!filter.pattern) {
            return new SimplePredicate(filter.name, filter.condition, null);
          } else {
            let [from, to] = filter.pattern.split('|');
            let isNumber = (s) => Number(s) === Number(s) && s;
            if (isNumber(from) && isNumber(to)) {
              return new SimplePredicate(filter.name, 'geq', Number(from)).and(
                new SimplePredicate(filter.name, 'leq', Number(to))
              );
            } else if (isNumber(from)) {
              return new SimplePredicate(filter.name, 'leq', Number(to));
            } else if (isNumber(to)) {
              return new SimplePredicate(filter.name, 'geq', Number(from));
            } else {
              return null;
            }
          }
        } else {
          return new SimplePredicate(filter.name, filter.condition, filter.pattern ? Number(filter.pattern) : null);
        }

        break;
      case 'date':
        return filter.pattern ?
          new DatePredicate(filter.name, filter.condition, filter.pattern, true) :
          new SimplePredicate(filter.name, filter.condition, null);
      default:
        return null;
    }
  } else if (filter.pattern) {
    switch (filter.type) {
      case 'string':
        Ember.set(filter, 'condition', 'like');
        return new StringPredicate(filter.name).contains(filter.pattern);
      case 'date':
        Ember.set(filter, 'condition', 'eq');
        return new DatePredicate(filter.name, filter.condition, filter.pattern, true);
      default:
        return null;
    }
  }

  return null;
};

export {
  predicateForFilter
};


text:
layout: doc
title: "Index"
---

{% capture build %}

{% assign result = '' %}
{% assign basePath = page.basePath %}

{% assign outEndList = false %}
{% assign sortedPages = site.pages | sort: "title" %}
{% assign result = result | append: '
' %}

{% for page in sortedPages %}
	{% if page.path contains basePath %}
		{% assign titleSize = page.title | size %}

		{% if titleSize > 0 %}
			{% capture titleSymbol %}{{ page.title | split: "" | first }}{% endcapture %}

			{% if titleSymbol != titleSymbolNext %}
				{% assign result = result | append: '
' | append: titleSymbol | append: '
' %}
				{% capture titleSymbolNext %}{{ titleSymbol }}{% endcapture %}
			{% endif %}
		{% endif %}
	{% endif %}
{% endfor %}

{% assign result = result | append: '
' %}

{% for page in sortedPages %}
	{% if page.path contains basePath %}
		{% assign titleSize = page.title | size %}

		{% if titleSize > 0 %}
			{% capture titleSymbol %}{{ page.title | split: "" | first }}{% endcapture %}

			{% if titleSymbol != titleSymbolNext %}
				{% if outEndList %}
					{% assign result = result | append: '
' %}
				{% endif %}

				{% assign outEndList = true %}
				{% assign result = result | append: '
' | append: titleSymbol | append: '
' %}
				{% assign result = result | append: '
' %}
				{% capture titleSymbolNext %}{{ titleSymbol }}{% endcapture %}
			{% endif %}

			{% assign result = result | append: '
' | append: page.title | append: '
' %}
		{% endif %}
	{% endif %}
{% endfor %}

{% endcapture %}

{{result}}


text:
package com.eaglesakura.andriders.serialize;

import com.eaglesakura.util.RandomUtil;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import java.util.Random;

/**
 * セッション情報を格納する
 */
public class RawSessionData {
    /**
     * 現在の状態が"自走"である
     */
    public static final int FLAG_ACTIVE = 0x1 << 0;

    /**
     * セッションを一意に識別するID
     *
     * 一日のトータル情報等、複数のSessionが含まれる場合はnullが指定される
     */
    @Nullable
    public Long sessionId;

    /**
     * このセッションでのフィットネス情報
     */
    @NonNull
    public RawFitnessStatus fitness;

    /**
     * 開始時刻
     */
    public long startTime;

    /**
     * 走行距離(km)
     * <p>
     * 検出不可能な場合は0kmとなる
     */
    public float distanceKm;

    /**
     * セッション中に自走した時間
     */
    public int activeTimeMs;

    /**
     * セッション中に自走した時間
     */
    public float activeDistanceKm;

    /**
     * 状態フラグ
     */
    public int flags;

    /**
     * セッションの継続時間(ミリ秒)
     */
    public int durationTimeMs;

    /**
     * 合計獲得標高
     */
    public float sumAltitudeMeter;

    public RawSessionData() {
    }

    public RawSessionData(Long sessionId) {
        this.sessionId = sessionId;
    }

    @Deprecated
    public RawSessionData(Class<Random> dummy) {
        sessionId = RandomUtil.randInt64();
        fitness = new RawFitnessStatus(dummy);
        startTime = RandomUtil.randUInt64();
        durationTimeMs = RandomUtil.randUInt32();
        distanceKm = RandomUtil.randFloat();
        activeTimeMs = RandomUtil.randUInt32();
        activeDistanceKm = RandomUtil.randFloat();
        flags = RandomUtil.randInt32();
        sumAltitudeMeter = RandomUtil.randFloat();
    }

    public boolean isActiveMoving() {
        return (flags & FLAG_ACTIVE) != 0;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        RawSessionData that = (RawSessionData) o;

        if (startTime != that.startTime) return false;
        if (Float.compare(that.distanceKm, distanceKm) != 0) return false;
        if (activeTimeMs != that.activeTimeMs) return false;
        if (Float.compare(that.activeDistanceKm, activeDistanceKm) != 0) return false;
        if (flags != that.flags) return false;
        if (durationTimeMs != that.durationTimeMs) return false;
        if (Float.compare(that.sumAltitudeMeter, sumAltitudeMeter) != 0) return false;
        if (sessionId != null ? !sessionId.equals(that.sessionId) : that.sessionId != null)
            return false;
        return fitness.equals(that.fitness);

    }

    @Override
    public int hashCode() {
        int result = sessionId != null ? sessionId.hashCode() : 0;
        result = 31 * result + fitness.hashCode();
        result = 31 * result + (int) (startTime ^ (startTime >>> 32));
        result = 31 * result + (distanceKm != +0.0f ? Float.floatToIntBits(distanceKm) : 0);
        result = 31 * result + activeTimeMs;
        result = 31 * result + (activeDistanceKm != +0.0f ? Float.floatToIntBits(activeDistanceKm) : 0);
        result = 31 * result + flags;
        result = 31 * result + durationTimeMs;
        result = 31 * result + (sumAltitudeMeter != +0.0f ? Float.floatToIntBits(sumAltitudeMeter) : 0);
        return result;
    }

    /**
     * 現在のフィットネス状態
     */
    public static class RawFitnessStatus {
        /**
         * 現在のMETs値
         *
         * 一日トータルでは0.0が指定される
         */

        public float mets;

        /**
         * 消費カロリー
         */

        public float calorie;

        /**
         * エクササイズ値
         */

        public float exercise;

        public RawFitnessStatus() {
        }

        public RawFitnessStatus(Class<Random> dummy) {
            mets = RandomUtil.randFloat();
            calorie = RandomUtil.randFloat();
            exercise = RandomUtil.randFloat();
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            RawFitnessStatus that = (RawFitnessStatus) o;

            if (Float.compare(that.mets, mets) != 0) return false;
            if (Float.compare(that.calorie, calorie) != 0) return false;
            return Float.compare(that.exercise, exercise) == 0;

        }

        @Override
        public int hashCode() {
            int result = (mets != +0.0f ? Float.floatToIntBits(mets) : 0);
            result = 31 * result + (calorie != +0.0f ? Float.floatToIntBits(calorie) : 0);
            result = 31 * result + (exercise != +0.0f ? Float.floatToIntBits(exercise) : 0);
            return result;
        }
    }
}


text:
using namespace Tiny;

PipelineRunNodeedges::PipelineRunNodeedges()
{
	id = std::string();
	_class = std::string();
}

PipelineRunNodeedges::PipelineRunNodeedges(std::string jsonString)
{
	this->fromJson(jsonString);
}

PipelineRunNodeedges::~PipelineRunNodeedges()
{

}

void
PipelineRunNodeedges::fromJson(std::string jsonObj)
{
    bourne::json object = bourne::json::parse(jsonObj);

    const char *idKey = "id";

    if(object.has_key(idKey))
    {
        bourne::json value = object[idKey];

        jsonToValue(&id, value, "std::string");

    }

    const char *_classKey = "_class";

    if(object.has_key(_classKey))
    {
        bourne::json value = object[_classKey];

        jsonToValue(&_class, value, "std::string");

    }

}

bourne::json
PipelineRunNodeedges::toJson()
{
    bourne::json object = bourne::json::object();

    object["id"] = getId();

    object["_class"] = getClass();

    return object;

}

std::string
PipelineRunNodeedges::getId()
{
	return id;
}

void
PipelineRunNodeedges::setId(std::string  id)
{
	this->id = id;
}

std::string
PipelineRunNodeedges::getClass()
{
	return _class;
}

void
PipelineRunNodeedges::setClass(std::string  _class)
{
	this->_class = _class;
}


text:
'use strict';

var expect = require('chai').expect;
var mongoose = require('mongoose');
var Promise = require('bluebird');

// Mocks
var Payload = require('../mocks/payload-schema');
var Helper = require('./helper.js');

// Class under test
var MongooseQueue = require('../index').MongooseQueue;

var JobSchema = require('../index').JobSchema;
var Job = JobSchema('queue', mongoose.Schema.Types.ObjectId);

describe('MongooseQueue', function()
{
	describe('constructor', function()
	{
		it('should set default options', function(done)
		{
			var queue = new MongooseQueue('payload', '123456789');

			expect(queue.options.queueCollection).to.equal('queue');
			expect(queue.options.payloadRefType).to.equal(mongoose.Schema.Types.ObjectId);
			expect(queue.options.blockDuration).to.equal(30000);
			expect(queue.options.maxRetries).to.equal(5);

			done();
		});
	});

	describe('add', function()
	{
		var mongooseQueue = null;

		before(function(done)
		{
			mongooseQueue = new MongooseQueue('payload', '123456789');

			done();
		});

		after(function(done)
		{
			// remove all elements from queue
			Job.remove({}, function(err)
			{
				done();
			});
		});

		it('should accept a mongoose documents as payload', function(done)
		{
			// create a sample payload object
			var samplePayload = new Payload({
				first: 'First element',
				second: 'Second element'
			}).save().then(function(samplePayload)
			{
				// add document to queue
				mongooseQueue.add(samplePayload, function(err, jobId)
				{
					expect(jobId).to.not.be.null;

					Job.findById(jobId, function(err, queuedJob)
					{
						expect(queuedJob.payload.toString()).to.equal(samplePayload._id.toString());
						done();
					});
				});
			});
		});

		it('should fail if no payload is provided', function(done)
		{
			mongooseQueue.add(null, function(err, jobId)
			{
				expect(jobId).to.be.null;
				expect(err).to.not.be.null;
				expect(err.message).to.equal('Payload missing.');

				done();
			});
		});

		it('should fail when payload is no Mongoose document', function(done)
		{
			mongooseQueue.add({invalid: 'object'}, function(err, jobId)
			{
				expect(jobId).to.be.null;
				expect(err).to.not.be.null;
				expect(err.message).to.equal('Payload is no valid Mongoose document.');

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

	describe('clean', function()
	{
		var jobs = [];

		var mongooseQueue = null;
		var payload = null;

		var maxRetries = 5;

		before(function(done)
		{
			mongooseQueue = new MongooseQueue('payload', '1234567890',
				{
					maxRetries: maxRetries
				}
			);

			// create some sample payloads
			payload = Helper.randomPayload()
			.save()
			.then(function(saved) {
				payload = saved;

				jobs.push(new Job({
					payload: payload._id
				}).save());
				jobs.push(new Job({
					payload: payload._id,
					done: true
				}).save());
				jobs.push(new Job({
					payload: payload._id,
					error: "Error message",
					done: true
				}).save());
				jobs.push(new Job({
					payload: payload._id,
					retries: maxRetries+1
				}).save());

				Promise.all(jobs).then(function(allJobs)
				{
					// overwrite promise array
					jobs = allJobs;
					done();
				});
			});
		});

		after(function(done)
		{
			Job.remove({}).then(function(err) {
				done();
			});
		});

		it('should remove all jobs marked as done/error or where the retry count is maxed out', function(done)
		{
			mongooseQueue.clean(function(err)
			{
				Job.find({
				}).then(function(jobs)
				{
					expect(jobs.length).to.equal(1);
					expect(jobs[0].done).to.be.false;
					expect(jobs[0].retries).to.be.below(maxRetries);

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

	describe('reset', function()
	{
		var jobs = [];

		var mongooseQueue = null;
		var payload = null;

		var maxRetries = 5;

		before(function(done)
		{
			mongooseQueue = new MongooseQueue('payload', '1234567890',
				{
					maxRetries: maxRetries
				}
			);

			// create some sample payloads
			payload = Helper.randomPayload()
			.save()
			.then(function(saved) {
				payload = saved;

				jobs.push(new Job({
					payload: payload._id
				}).save());
				jobs.push(new Job({
					payload: payload._id,
					done: true
				}).save());
				jobs.push(new Job({
					payload: payload._id,
					error: "Error message",
					done: true
				}).save());
				jobs.push(new Job({
					payload: payload._id,
					retries: maxRetries+1
				}).save());

				Promise.all(jobs).then(function(allJobs)
				{
					// overwrite promise array
					jobs = allJobs;
					done();
				});
			});
		});

		after(function(done)
		{
			Job.remove({}).then(function(err) {
				done();
			});
		});

		it('should remove all jobs no matter what', function(done)
		{
			mongooseQueue.reset(function(err)
			{
				Job.find({
				}).then(function(jobs)
				{
					expect(jobs.length).to.equal(0);

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

	describe('get', function()
	{
		var mongooseQueue = null;
		var payload = null;

		var maxRetries = 5;

		before(function(done)
		{
			mongooseQueue = new MongooseQueue('payload', '1234567890',
				{
					maxRetries: maxRetries
				}
			);

			// create some sample payloads
			payload = Helper.randomPayload()
			.save()
			.then(function(saved) {
				payload = saved;

				done();
			});
		});

		describe('retries', function()
		{
			var job = null;

			before(function(done)
			{
				job = new Job({
					payload: payload._id
				})
				.save()
				.then(function(insertedJob)
				{
					job = insertedJob;
					done();
				});
			});

			after(function(done)
			{
				Job.remove({}).then(function(err) {
					done();
				});
			});

			it('should increment retry count on get', function(done)
			{
				mongooseQueue.get(function(err, job)
				{
					expect(err).to.be.null;
					expect(job).to.not.be.null;

					Job.findOne({
						_id: job.id
					}).then(function(retryJob)
					{
						expect(retryJob).to.not.be.null;
						expect(retryJob.retries).to.equal(1);

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

			it('should not return job with maxed out retries', function(done)
			{
				// manually set job retry count to max and unblock it from previous test
				job.blockedUntil = Date.now();
				job.retries = maxRetries+1;
				job.save().then(function(maxedOutJob)
				{
					mongooseQueue.get(function(err, noJob)
					{
						expect(err).to.be.null;
						expect(noJob).to.be.null;

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

		describe('order', function()
		{
			var jobs = [];

			before(function(done)
			{
				for(var i = 0; i<2; ++i)
				{
					jobs.push(new Job({
						payload: payload._id
					}).save());
				}
				Promise.all(jobs).then(function(allJobs)
				{
					// overwrite promise array
					jobs = allJobs;
					done();
				});
			});

			after(function(done)
			{
				Job.remove({}).then(function(err) {
					done();
				});
			});

			it('should return the oldest job for processing', function(done)
			{
				mongooseQueue.get(function(err, job)
				{
					expect(err).to.be.null;
					expect(job).to.not.be.null;

					Job.find({$lt: {createdAt: job.createdAt}}, function(err, olderJob)
					{
						expect(olderJob).to.be.undefined;
						done();
					});
				});
			});
		});

		describe('blocking', function()
		{
			var jobs = [];

			before(function(done)
			{
				jobs.push(new Job({
					blockedUntil: Date.now() + 100000000,
					payload: payload._id
				}).save());
				jobs.push(new Job({
					payload: payload._id
				}).save());

				Promise.all(jobs).then(function(allJobs)
				{
					// overwrite promise array
					jobs = allJobs;
					done();
				});
			});

			after(function(done)
			{
				Job.remove({}).then(function(err) {
					done();
				});
			});

			it('should return the oldest job that is not currently blocked and block it for the time set in the options', function(done)
			{
				mongooseQueue.get(function(err, job)
				{
					expect(err).to.be.null;
					expect(job.blockedUntil.getTime()).to.be.above(Date.now());

					done();
				});
			});

			it('should not return a job since all are currently blocked', function(done)
			{
				// this call should not return a job since all are taken from the previous call
				mongooseQueue.get(function(err, failJob)
				{
					expect(err).to.be.null;
					expect(failJob).to.be.null;

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

		describe('ack/done and error', function()
		{
			var jobs = [];

			before(function(done)
			{
				jobs.push(new Job({
					payload: payload._id,
					done: true
				}).save());
				// this job is used to test that only undone jobs are fetched
				jobs.push(new Job({
					payload: payload._id
				}).save());
				// this job is used to test that ack works
				jobs.push(new Job({
					payload: payload._id
				}).save());
				// this job is used to test that error works
				jobs.push(new Job({
					payload: payload._id
				}).save());

				Promise.all(jobs).then(function(allJobs)
				{
					// overwrite promise array
					jobs = allJobs;

					done();
				});
			});

			after(function(done)
			{
				Job.remove({}).then(function(err) {
					done();
				});
			});

			it('should return the oldest job that is not marked as done', function(done)
			{
				mongooseQueue.get(function(err, job)
				{
					expect(err).to.be.null;
					expect(job).to.not.be.null;
					expect(job.id.equals(jobs[1]._id)).to.be.true;

					done();
				});
			});

			it('ack() should mark the job as done when ack was called', function(done)
			{
				// this is to a certain extent not a valid unit test. I know...
				mongooseQueue.get(function(err, job)
				{
					expect(err).to.be.null;
					expect(job).to.not.be.null;
					expect(jobs[2]._id.equals(job.id)).to.be.true;

					// here is the meat of the test
					mongooseQueue.ack(job.id, function(err, ackJob)
					{
						expect(err).to.be.null;
						expect(ackJob).to.not.be.null;
						expect(jobs[2]._id.equals(ackJob.id)).to.be.true;
						expect(ackJob.done).to.be.true;

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

			it('ack() should fail when jobId is invalid', function(done)
			{
				mongooseQueue.ack('57a9a8c526f9c3c114f00000', function(err, ackJob)
				{
					expect(ackJob).to.be.null;
					expect(err).to.not.be.null;
					expect(err.message).to.equal('Job id invalid, job not found.');

					done();
				});
			});

			it('error() should save the job as failed and mark it as done', function(done)
			{
				// this is to a certain extent not a valid unit test. I know...
				mongooseQueue.get(function(err,job)
				{
					expect(err).to.be.null;
					expect(job).to.not.be.null;
					expect(jobs[3]._id.equals(job.id)).to.be.true;

					// here is the meat of the test
					mongooseQueue.error(job.id, 'Job failed', function(err, errorJob)
					{
						expect(err).to.be.null;
						expect(errorJob).to.not.be.null;
						expect(jobs[3]._id.equals(errorJob.id)).to.be.true;
						expect(errorJob.done).to.be.true;
						expect(errorJob.error).to.equal('Job failed');

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

			it('error() should fail when jobId is invalid', function(done)
			{
				mongooseQueue.error('57a9a8c526f9c3c114f00000', 'failed', function(err, errorJob)
				{
					expect(errorJob).to.be.null;
					expect(err).to.not.be.null;
					expect(err.message).to.equal('Job id invalid, job not found.');

					done();
				});
			});

			it('should return null, when no undone job is found', function(done)
			{
				// manually mark all jobs as done
				Job.update({
				},{
					$set: {
						done: true
					}
				}, function(err, jobs)
				{
					mongooseQueue.get(function(err, noJob)
					{
						expect(err).to.be.null;
						expect(noJob).to.be.null;

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


text:
package org.apache.servicecomb.demo.edge.model;

import org.apache.servicecomb.registry.RegistrationManager;

public class ResultWithInstance {
  private int result;

  private String serviceId;

  private String instanceId;

  private String version;

  public static ResultWithInstance create(int value) {
    ResultWithInstance result = new ResultWithInstance();
    result.setResult(value);
    result.setInstanceId(RegistrationManager.INSTANCE.getMicroserviceInstance().getInstanceId());
    result.setServiceId(RegistrationManager.INSTANCE.getMicroservice().getServiceId());
    result.setVersion(RegistrationManager.INSTANCE.getMicroservice().getVersion());

    return result;
  }

  public int getResult() {
    return result;
  }

  public void setResult(int result) {
    this.result = result;
  }

  public String getServiceId() {
    return serviceId;
  }

  public void setServiceId(String serviceId) {
    this.serviceId = serviceId;
  }

  public String getInstanceId() {
    return instanceId;
  }

  public void setInstanceId(String instanceId) {
    this.instanceId = instanceId;
  }

  public String getVersion() {
    return version;
  }

  public void setVersion(String version) {
    this.version = version;
  }

  @Override
  public String toString() {
    return "ResultWithInstance [result=" + result + ", serviceId=" + serviceId + ", instanceId=" + instanceId
        + ", version=" + version + "]";
  }
}


text:
package entities

import ()

type UserMsg struct {
	Id          int      `json:"id" xorm:"not null pk INT(11)"`
	SendUid     int      `json:"send_uid" xorm:"not null index INT(11)"`
	RecvUid     int      `json:"recv_uid" xorm:"not null index INT(11)"`
	Msg         string   `json:"msg" xorm:"not null VARCHAR(1023)"`
	DeletedTime int      `json:"deleted_time" xorm:"not null INT(11)"`
	CreatedTime JsonTime `json:"created_time" xorm:"not null default 'CURRENT_TIMESTAMP' TIMESTAMP"`
	UpdatedTime JsonTime `json:"updated_time" xorm:"not null default 'CURRENT_TIMESTAMP' TIMESTAMP"`
}


text:
//
// "$Id: Fl_GIF_Image.H 7903 2010-11-28 21:06:39Z matt $"
//
// GIF image header file for the Fast Light Tool Kit (FLTK).
//
// Copyright 1998-2010 by Bill Spitzak and others.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Library General Public
// License as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
// USA.
//
// Please report all bugs and problems on the following page:
//
//     http://www.fltk.org/str.php
//

/* \file
   Fl_GIF_Image widget . */

#ifndef Fl_GIF_Image_H
#define Fl_GIF_Image_H
#  include "Fl_Pixmap.H"

/**
  The Fl_GIF_Image class supports loading, caching,
  and drawing of Compuserve GIFSM images. The class
  loads the first image and supports transparency.
*/
class FL_EXPORT Fl_GIF_Image : public Fl_Pixmap {

  public:

  Fl_GIF_Image(const char* filename);
};

#endif

//
// End of "$Id: Fl_GIF_Image.H 7903 2010-11-28 21:06:39Z matt $".
//


text:
package org.apache.spark.sql.catalyst.analysis

import org.apache.spark.sql.AnalysisException
import org.apache.spark.sql.catalyst.expressions.SubqueryExpression
import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan, With}
import org.apache.spark.sql.catalyst.rules.Rule
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.internal.SQLConf.LEGACY_CTE_PRECEDENCE_ENABLED

/**
 * Analyze WITH nodes and substitute child plan with CTE definitions.
 */
object CTESubstitution extends Rule[LogicalPlan] {
  def apply(plan: LogicalPlan): LogicalPlan = {
    val isLegacy = SQLConf.get.getConf(LEGACY_CTE_PRECEDENCE_ENABLED)
    if (isLegacy.isEmpty) {
      assertNoNameConflictsInCTE(plan, inTraverse = false)
      traverseAndSubstituteCTE(plan, inTraverse = false)
    } else if (isLegacy.get) {
      legacyTraverseAndSubstituteCTE(plan)
    } else {
      traverseAndSubstituteCTE(plan, inTraverse = false)
    }
  }

  /**
   * Check the plan to be traversed has naming conflicts in nested CTE or not, traverse through
   * child, innerChildren and subquery for the current plan.
   */
  private def assertNoNameConflictsInCTE(
      plan: LogicalPlan,
      inTraverse: Boolean,
      cteNames: Set[String] = Set.empty): Unit = {
    plan.foreach {
      case w @ With(child, relations) =>
        val newNames = relations.map {
          case (cteName, _) =>
            if (cteNames.contains(cteName)) {
              throw new AnalysisException(s"Name $cteName is ambiguous in nested CTE. " +
                s"Please set ${LEGACY_CTE_PRECEDENCE_ENABLED.key} to false so that name defined " +
                "in inner CTE takes precedence. See more details in SPARK-28228.")
            } else {
              cteName
            }
        }.toSet
        child.transformExpressions {
          case e: SubqueryExpression =>
            assertNoNameConflictsInCTE(e.plan, inTraverse = true, cteNames ++ newNames)
            e
        }
        w.innerChildren.foreach { p =>
          assertNoNameConflictsInCTE(p, inTraverse = true, cteNames ++ newNames)
        }

      case other if inTraverse =>
        other.transformExpressions {
          case e: SubqueryExpression =>
            assertNoNameConflictsInCTE(e.plan, inTraverse = true, cteNames)
            e
        }

      case _ =>
    }
  }

  private def legacyTraverseAndSubstituteCTE(plan: LogicalPlan): LogicalPlan = {
    plan.resolveOperatorsUp {
      case With(child, relations) =>
        // substitute CTE expressions right-to-left to resolve references to previous CTEs:
        // with a as (select * from t), b as (select * from a) select * from b
        relations.foldRight(child) {
          case ((cteName, ctePlan), currentPlan) => substituteCTE(currentPlan, cteName, ctePlan)
        }
    }
  }

  /**
   * Traverse the plan and expression nodes as a tree and replace matching references to CTE
   * definitions.
   * - If the rule encounters a WITH node then it substitutes the child of the node with CTE
   *   definitions of the node right-to-left order as a definition can reference to a previous
   *   one.
   *   For example the following query is valid:
   *   WITH
   *     t AS (SELECT 1),
   *     t2 AS (SELECT * FROM t)
   *   SELECT * FROM t2
   * - If a CTE definition contains an inner WITH node then substitution of inner should take
   *   precedence because it can shadow an outer CTE definition.
   *   For example the following query should return 2:
   *   WITH
   *     t AS (SELECT 1),
   *     t2 AS (
   *       WITH t AS (SELECT 2)
   *       SELECT * FROM t
   *     )
   *   SELECT * FROM t2
   * - If a CTE definition contains a subquery that contains an inner WITH node then substitution
   *   of inner should take precedence because it can shadow an outer CTE definition.
   *   For example the following query should return 2:
   *   WITH t AS (SELECT 1 AS c)
   *   SELECT max(c) FROM (
   *     WITH t AS (SELECT 2 AS c)
   *     SELECT * FROM t
   *   )
   * - If a CTE definition contains a subquery expression that contains an inner WITH node then
   *   substitution of inner should take precedence because it can shadow an outer CTE
   *   definition.
   *   For example the following query should return 2:
   *   WITH t AS (SELECT 1)
   *   SELECT (
   *     WITH t AS (SELECT 2)
   *     SELECT * FROM t
   *   )
   * @param plan the plan to be traversed
   * @param inTraverse whether the current traverse is called from another traverse, only in this
   *                   case name collision can occur
   * @return the plan where CTE substitution is applied
   */
  private def traverseAndSubstituteCTE(plan: LogicalPlan, inTraverse: Boolean): LogicalPlan = {
    plan.resolveOperatorsUp {
      case With(child: LogicalPlan, relations) =>
        // child might contain an inner CTE that has priority so traverse and substitute inner CTEs
        // in child first
        val traversedChild: LogicalPlan = child transformExpressions {
          case e: SubqueryExpression => e.withNewPlan(traverseAndSubstituteCTE(e.plan, true))
        }

        // Substitute CTE definitions from last to first as a CTE definition can reference a
        // previous one
        relations.foldRight(traversedChild) {
          case ((cteName, ctePlan), currentPlan) =>
            // A CTE definition might contain an inner CTE that has priority, so traverse and
            // substitute CTE defined in ctePlan.
            // A CTE definition might not be used at all or might be used multiple times. To avoid
            // computation if it is not used and to avoid multiple recomputation if it is used
            // multiple times we use a lazy construct with call-by-name parameter passing.
            lazy val substitutedCTEPlan = traverseAndSubstituteCTE(ctePlan, true)
            substituteCTE(currentPlan, cteName, substitutedCTEPlan)
        }

      // CTE name collision can occur only when inTraverse is true, it helps to avoid eager CTE
      // substitution in a subquery expression.
      case other if inTraverse =>
        other.transformExpressions {
          case e: SubqueryExpression => e.withNewPlan(traverseAndSubstituteCTE(e.plan, true))
        }
    }
  }

  private def substituteCTE(
      plan: LogicalPlan,
      cteName: String,
      ctePlan: => LogicalPlan): LogicalPlan =
    plan resolveOperatorsUp {
      case UnresolvedRelation(Seq(table)) if plan.conf.resolver(cteName, table) => ctePlan

      case other =>
        // This cannot be done in ResolveSubquery because ResolveSubquery does not know the CTE.
        other transformExpressions {
          case e: SubqueryExpression => e.withNewPlan(substituteCTE(e.plan, cteName, ctePlan))
        }
    }
}


text:
            Orders

Order History

Awaiting Approval

Favorite Orders

    <form name="OrdersSearchForm" pretty-submit>
        <fieldset class="form-group">

                <input type="search" ng-change="orders.search()" ng-model-options="{debounce:1000}" placeholder="Search orders..." ng-model="orders.parameters.search" class="form-control">

                    <button class="btn btn-default" type="button" aria-label="Clear Search" ng-click="orders.clearSearch()"> Clear Search</button>

        </fieldset>
    </form>

    <form name="OrdersFiltersForm">

                Status
                <select id="Status" class="form-control" ng-model="orders.parameters.status" ng-options="status.Value as status.Name for status in orders.orderStatuses" ng-change="orders.filter(true)">
                    <option value="">All</option>
                </select>

                From Date
                <input ng-if="application.isTouchDevice" type="date" class="form-control" ng-model="orders.parameters.fromDate" ng-blur="orders.filter(true)">
                <input id="FromDate" ng-if="!application.isTouchDevice" type="text" class="form-control" ng-model="orders.parameters.fromDate" uib-datepicker-popup datepicker-options="{maxDate:orders.parameters.toDate}" is-open="fromDate.open" ng-change="orders.filter(true)" ng-click="fromDate.open = !fromDate.open">

                To Date
                <input ng-if="application.isTouchDevice" type="date" class="form-control" ng-model="orders.parameters.toDate" ng-blur="orders.filter(true)">
                <input id="ToDate" type="text" class="form-control" ng-model="orders.parameters.toDate" uib-datepicker-popup datepicker-options="{minDate:orders.parameters.fromDate, maxDate: orders.today}" is-open="toDate.open" ng-change="orders.filter(true)" ng-click="toDate.open = !toDate.open">

    </form>

                {{orders.filtersApplied || orders.searchResults ? 'No matches found' : 'No orders'}}

                {{orders.filtersApplied || orders.searchResults ? 'No matches found' : 'No orders awaiting your approval'}}

                {{orders.filtersApplied || orders.searchResults ? 'No matches found' : 'No orders have been favorited'}}

{{(application.$ocMedia('min-width:768px') ? orders.list.Meta.ItemRange[0] : '1') + ' - ' +
                    orders.list.Meta.ItemRange[1] + ' of ' + orders.list.Meta.TotalCount + ' results'}}

                    <colgroup>
                        <col>
                        <col>
                        <col>
                        <col>
                        <col>
                        <col>
                        <col>
                    </colgroup>

                            Reorder

                                ID

                                Status

                                Submitted

                                Submitted By

                                Subtotal

                            <ordercloud-repeat-order original-order-id="order.ID"></ordercloud-repeat-order>
                            {{order.ID}}
                            {{order.Status | humanize}}
                            {{(order.DateSubmitted || order.DateCreated) | date:'short'}}
                            {{order.FromUser.FirstName + ' ' + order.FromUser.LastName}}
                            {{order.Subtotal | currency}}

 1"
                total-items="orders.list.Meta.TotalCount"
                items-per-page="orders.list.Meta.PageSize"
                max-size="5"
                boundary-links="orders.list.Meta.TotalPages > 5"
                ng-model="orders.list.Meta.Page"
                ng-change="orders.pageChanged()">

            <button type="button"
                    class="btn btn-default btn-block btn-lg visible-xs"
                    ng-show="orders.list.Meta.Page < orders.list.Meta.TotalPages"
                    ng-click="orders.loadMore()">Load More</button>


text:
import unittest

from pythonwarrior.units.thick_sludge import ThickSludge

class TestThickSludge(unittest.TestCase):
    def setUp(self):
        self.sludge = ThickSludge()

    def test_should_have_24_max_health(self):
        self.assertEqual(24, self.sludge.max_health)

    def test_should_appear_as_S_on_map(self):
        self.assertEqual("S", self.sludge.character)

    def test_should_have_the_name_Thick_Sludge(self):
        self.assertEqual("ThickSludge", self.sludge.name())


text:
const { List } = require('immutable');
const ACTION_TYPES = require('../actions/TYPES');

function reduceComponents(state, action) {
    state = state || List();
    switch (action.type) {

    case ACTION_TYPES.REGISTER_COMPONENT:
        return state.push({
            Component: action.Component,
            descriptor: action.descriptor
        });

    default:
        return state;

    }
}

module.exports = reduceComponents;


text:
package exp

type (
	TruncateClauses interface {
		HasTable() bool
		clone() *truncateClauses

		Table() ColumnListExpression
		SetTable(tables ColumnListExpression) TruncateClauses

		Options() TruncateOptions
		SetOptions(opts TruncateOptions) TruncateClauses
	}
	truncateClauses struct {
		tables  ColumnListExpression
		options TruncateOptions
	}
)

func NewTruncateClauses() TruncateClauses {
	return &truncateClauses{}
}

func (tc *truncateClauses) HasTable() bool {
	return tc.tables != nil
}

func (tc *truncateClauses) clone() *truncateClauses {
	return &truncateClauses{
		tables: tc.tables,
	}
}

func (tc *truncateClauses) Table() ColumnListExpression {
	return tc.tables
}
func (tc *truncateClauses) SetTable(tables ColumnListExpression) TruncateClauses {
	ret := tc.clone()
	ret.tables = tables
	return ret
}

func (tc *truncateClauses) Options() TruncateOptions {
	return tc.options
}
func (tc *truncateClauses) SetOptions(opts TruncateOptions) TruncateClauses {
	ret := tc.clone()
	ret.options = opts
	return ret
}