text:
package ExtUtils::MM_Cygwin;

use strict;

use ExtUtils::MakeMaker::Config;
use File::Spec;

require ExtUtils::MM_Any;
require ExtUtils::MM_Unix;
our @ISA = qw( ExtUtils::MM_Any ExtUtils::MM_Unix );

our $VERSION = '6.44';

=head1 NAME

ExtUtils::MM_Cygwin - methods to override UN*X behaviour in ExtUtils::MakeMaker

=head1 SYNOPSIS

 use ExtUtils::MM_Cygwin; # Done internally by ExtUtils::MakeMaker if needed

=head1 DESCRIPTION

See ExtUtils::MM_Unix for a documentation of the methods provided there.

=over 4

=item os_flavor

We're Unix and Cygwin.

=cut

sub os_flavor {
    return('Unix', 'Cygwin');
}

=item cflags

if configured for dynamic loading, triggers #define EXT in EXTERN.h

=cut

sub cflags {
    my($self,$libperl)=@_;
    return $self->{CFLAGS} if $self->{CFLAGS};
    return '' unless $self->needs_linking();

    my $base = $self->SUPER::cflags($libperl);
    foreach (split /\n/, $base) {
        /^(\S*)\s*=\s*(\S*)$/ and $self->{$1} = $2;
    };
    $self->{CCFLAGS} .= " -DUSEIMPORTLIB" if ($Config{useshrplib} eq 'true');

    return $self->{CFLAGS} = qq{
CCFLAGS = $self->{CCFLAGS}
OPTIMIZE = $self->{OPTIMIZE}
PERLTYPE = $self->{PERLTYPE}
};

}

=item replace_manpage_separator

replaces strings '::' with '.' in MAN*POD man page names

=cut

sub replace_manpage_separator {
    my($self, $man) = @_;
    $man =~ s{/+}{.}g;
    return $man;
}

=item init_linker

points to libperl.a

=cut

sub init_linker {
    my $self = shift;

    if ($Config{useshrplib} eq 'true') {
        my $libperl = '$(PERL_INC)' .'/'. "$Config{libperl}";
        if( $] >= 5.006002 ) {
            $libperl =~ s/a$/dll.a/;
        }
        $self->{PERL_ARCHIVE} = $libperl;
    } else {
        $self->{PERL_ARCHIVE} =
          '$(PERL_INC)' .'/'. ("$Config{libperl}" or "libperl.a");
    }

    $self->{PERL_ARCHIVE_AFTER} ||= '';
    $self->{EXPORT_LIST}  ||= '';
}

=back

=cut

1;

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Icecave\Chrono;

use Icecave\Chrono\Format\FormattableInterface;

/**
 * Base interface for all measures of dates and/or times.
 */
interface CommonInterface extends Iso8601Interface, FormattableInterface
{
    /**
     * Convert this date/time to a different timezone.
     *
     * @param TimeZone $timeZone The target timezone
     *
     * @return ComponentInterface
     */
    public function toTimeZone(TimeZone $timeZone);

    /**
     * Convert this date/time to the UTC timezone.
     *
     * @return ComponentInterface
     */
    public function toUtc();

    /**
     * @return TimeZone The time zone of the time point.
     */
    public function timeZone();
}


text:
title: DIB training R Markdown half day workshop
text: What is robust and reproducible research? How can you make your research more robust and reproducible? You can use RMarkdown! Wait, what's RMarkdown? RMarkdown is a variant of Markdown that has embedded R code chunks to be used with knitr to make it easy to create reproducible web-based reports. Registration required.
location: Simon Fraser University, Burnaby Campus, SSB 8114
link: https://github.com/sciprog-sfu/sciprog-sfu.github.io/issues/70
date: 2016-05-11
startTime: '9:15'
endTime: '12:15'
---


text:
using SecureSocketProtocol3.Network.Headers;
using System;
using System.Collections.Generic;
using System.Text;

namespace SecureSocketProtocol3.Misc
{
    internal class PayloadInfo
    {
        public byte[] Payload { get; private set; }
        public Header Header { get; private set; }

        public PayloadInfo(byte[] payload, Header header)
        {
            this.Payload = payload;
            this.Header = header;
        }
    }
}


text:
id: 587d78b1367417b2b2512b0a
title: Use a Retina Image for Higher Resolution Displays
challengeType: 0
videoUrl: 'https://scrimba.com/p/pzrPu4/cVZ4Rfp'
forumTopicId: 301142
dashedName: use-a-retina-image-for-higher-resolution-displays
---

# --description--

With the increase of internet connected devices, their sizes and specifications vary, and the displays they use could be different externally and internally. Pixel density is an aspect that could be different on one device from others and this density is known as Pixel Per Inch(PPI) or Dots Per Inch(DPI). The most famous such display is the one known as a "Retina Display" on the latest Apple MacBook Pro notebooks, and recently iMac computers. Due to the difference in pixel density between a "Retina" and "Non-Retina" displays, some images that have not been made with a High-Resolution Display in mind could look "pixelated" when rendered on a High-Resolution display.

The simplest way to make your images properly appear on High-Resolution Displays, such as the MacBook Pros "retina display" is to define their `width` and `height` values as only half of what the original file is. Here is an example of an image that is only using half of the original height and width:

```html
<style>
  img { height: 250px; width: 250px; }
</style>
<img src="coolPic500x500" alt="A most excellent picture">
```

# --instructions--

Set the `width` and `height` of the `img` tag to half of their original values. In this case, both the original `height` and the original `width` are `200px`.

# --hints--

Your `img` tag should have a `width` of 100 pixels.

```js
assert(document.querySelector('img').width === 100);
```

Your `img` tag should have a `height` of 100 pixels.

```js
assert(document.querySelector('img').height === 100);
```

# --seed--

## --seed-contents--

```html
<style>

</style>

<img src="https://s3.amazonaws.com/freecodecamp/FCCStickers-CamperBot200x200.jpg" alt="freeCodeCamp sticker that says 'Because CamperBot Cares'">
```

# --solutions--

```html
<style>
  img {
    height: 100px;
    width: 100px;
  }
</style>

<img src="https://s3.amazonaws.com/freecodecamp/FCCStickers-CamperBot200x200.jpg" alt="freeCodeCamp sticker that says 'Because CamperBot Cares'">
```


text:
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Globalization;
using System.Linq;
using Microsoft.CodeAnalysis.Shared;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.PatternMatching
{
    /// <summary>
    /// The pattern matcher is thread-safe.  However, it maintains an internal cache of
    /// information as it is used.  Therefore, you should not keep it around forever and should get
    /// and release the matcher appropriately once you no longer need it.
    /// Also, while the pattern matcher is culture aware, it uses the culture specified in the
    /// constructor.
    /// </summary>
    internal sealed partial class PatternMatcher : IDisposable
    {
        private static readonly char[] s_dotCharacterArray = { '.' };

        private readonly object _gate = new object();

        private readonly bool _allowFuzzyMatching;
        private readonly bool _invalidPattern;
        private readonly Segment _fullPatternSegment;
        private readonly Segment[] _dotSeparatedSegments;

        private readonly Dictionary<string, StringBreaks> _stringToWordSpans = new Dictionary<string, StringBreaks>();
        private readonly Func<string, StringBreaks> _breakIntoWordSpans = StringBreaker.BreakIntoWordParts;

        // PERF: Cache the culture's compareInfo to avoid the overhead of asking for them repeatedly in inner loops
        private readonly CompareInfo _compareInfo;

        /// <summary>
        /// Construct a new PatternMatcher using the calling thread's culture for string searching and comparison.
        /// </summary>
        public PatternMatcher(
                string pattern,
                bool verbatimIdentifierPrefixIsWordCharacter = false,
                bool allowFuzzyMatching = false) :
            this(pattern, CultureInfo.CurrentCulture, verbatimIdentifierPrefixIsWordCharacter, allowFuzzyMatching)
        {
        }

        /// <summary>
        /// Construct a new PatternMatcher using the specified culture.
        /// </summary>
        /// <param name="pattern">The pattern to make the pattern matcher for.</param>
        /// <param name="culture">The culture to use for string searching and comparison.</param>
        /// <param name="verbatimIdentifierPrefixIsWordCharacter">Whether to consider "@" as a word character</param>
        /// <param name="allowFuzzyMatching">Whether or not close matches should count as matches.</param>
        public PatternMatcher(
            string pattern,
            CultureInfo culture,
            bool verbatimIdentifierPrefixIsWordCharacter,
            bool allowFuzzyMatching)
        {
            pattern = pattern.Trim();
            _compareInfo = culture.CompareInfo;
            _allowFuzzyMatching = allowFuzzyMatching;

            _fullPatternSegment = new Segment(pattern, verbatimIdentifierPrefixIsWordCharacter, allowFuzzyMatching);

            if (pattern.IndexOf('.') < 0)
            {
                // PERF: Avoid string.Split allocations when the pattern doesn't contain a dot.
                _dotSeparatedSegments = pattern.Length > 0
                    ? new Segment[1] { _fullPatternSegment }
                    : Array.Empty<Segment>();
            }
            else
            {
                _dotSeparatedSegments = pattern.Split(s_dotCharacterArray, StringSplitOptions.RemoveEmptyEntries)
                                                .Select(text => new Segment(text.Trim(), verbatimIdentifierPrefixIsWordCharacter, allowFuzzyMatching))
                                                .ToArray();
            }

            _invalidPattern = _dotSeparatedSegments.Length == 0 || _dotSeparatedSegments.Any(s => s.IsInvalid);
        }

        public void Dispose()
        {
            _fullPatternSegment.Dispose();
            foreach (var segment in _dotSeparatedSegments)
            {
                segment.Dispose();
            }
        }

        public bool IsDottedPattern => _dotSeparatedSegments.Length > 1;

        private bool SkipMatch(string candidate)
        {
            return _invalidPattern || string.IsNullOrWhiteSpace(candidate);
        }

        public ImmutableArray<PatternMatch> GetMatches(string candidate)
        {
            return GetMatches(candidate, includeMatchSpans: false);
        }

        /// <summary>
        /// Determines if a given candidate string matches under a multiple word query text, as you
        /// would find in features like Navigate To.
        /// </summary>
        /// <param name="candidate">The word being tested.</param>
        /// <param name="includeMatchSpans">Whether or not the matched spans should be included with results</param>
        /// <returns>If this was a match, a set of match types that occurred while matching the
        /// patterns. If it was not a match, it returns null.</returns>
        public ImmutableArray<PatternMatch> GetMatches(string candidate, bool includeMatchSpans)
        {
            if (SkipMatch(candidate))
            {
                return ImmutableArray<PatternMatch>.Empty;
            }

            var result = MatchSegment(candidate, includeMatchSpans, _fullPatternSegment, fuzzyMatch: true);
            if (!result.IsEmpty)
            {
                return result;
            }

            return MatchSegment(candidate, includeMatchSpans, _fullPatternSegment, fuzzyMatch: false);
        }

        public ImmutableArray<PatternMatch> GetMatchesForLastSegmentOfPattern(string candidate)
        {
            if (SkipMatch(candidate))
            {
                return ImmutableArray<PatternMatch>.Empty;
            }

            var result = MatchSegment(candidate, includeMatchSpans: false, segment: _dotSeparatedSegments.Last(), fuzzyMatch: false);
            if (!result.IsEmpty)
            {
                return result;
            }

            return MatchSegment(candidate, includeMatchSpans: false, segment: _dotSeparatedSegments.Last(), fuzzyMatch: true);
        }

        public PatternMatches GetMatches(string candidate, string dottedContainer)
        {
            return GetMatches(candidate, dottedContainer, includeMatchSpans: false);
        }

        /// <summary>
        /// Matches a pattern against a candidate, and an optional dotted container for the
        /// candidate. If the container is provided, and the pattern itself contains dots, then
        /// the pattern will be tested against the candidate and container.  Specifically,
        /// the part of the pattern after the last dot will be tested against the candidate. If
        /// a match occurs there, then the remaining dot-separated portions of the pattern will
        /// be tested against every successive portion of the container from right to left.
        ///
        /// i.e. if you have a pattern of "Con.WL" and the candidate is "WriteLine" with a
        /// dotted container of "System.Console", then "WL" will be tested against "WriteLine".
        /// With a match found there, "Con" will then be tested against "Console".
        /// </summary>
        public PatternMatches GetMatches(
            string candidate, string dottedContainer, bool includeMatchSpans)
        {
            var result = GetMatches(candidate, dottedContainer, includeMatchSpans, fuzzyMatch: false);
            if (!result.IsEmpty)
            {
                return result;
            }

            return GetMatches(candidate, dottedContainer, includeMatchSpans, fuzzyMatch: true);
        }

        private PatternMatches GetMatches(
            string candidate, string dottedContainer, bool includeMatchSpans, bool fuzzyMatch)
        {
            if (fuzzyMatch && !_allowFuzzyMatching)
            {
                return PatternMatches.Empty;
            }

            if (SkipMatch(candidate))
            {
                return PatternMatches.Empty;
            }

            // First, check that the last part of the dot separated pattern matches the name of the
            // candidate.  If not, then there's no point in proceeding and doing the more
            // expensive work.
            var candidateMatch = MatchSegment(candidate, includeMatchSpans, _dotSeparatedSegments.Last(), fuzzyMatch);
            if (candidateMatch.IsDefaultOrEmpty)
            {
                return PatternMatches.Empty;
            }

            dottedContainer = dottedContainer ?? string.Empty;
            var containerParts = dottedContainer.Split(s_dotCharacterArray, StringSplitOptions.RemoveEmptyEntries);

            // -1 because the last part was checked against the name, and only the rest
            // of the parts are checked against the container.
            var relevantDotSeparatedSegmentLength = _dotSeparatedSegments.Length - 1;
            if (relevantDotSeparatedSegmentLength > containerParts.Length)
            {
                // There weren't enough container parts to match against the pattern parts.
                // So this definitely doesn't match.
                return PatternMatches.Empty;
            }

            // So far so good.  Now break up the container for the candidate and check if all
            // the dotted parts match up correctly.
            var containerMatches = ArrayBuilder<PatternMatch>.GetInstance();

            try
            {
                // Don't need to check the last segment.  We did that as the very first bail out step.
                for (int i = 0, j = containerParts.Length - relevantDotSeparatedSegmentLength;
                     i < relevantDotSeparatedSegmentLength;
                     i++, j++)
                {
                    var segment = _dotSeparatedSegments[i];
                    var containerName = containerParts[j];
                    var containerMatch = MatchSegment(containerName, includeMatchSpans, segment, fuzzyMatch);
                    if (containerMatch.IsDefaultOrEmpty)
                    {
                        // This container didn't match the pattern piece.  So there's no match at all.
                        return PatternMatches.Empty;
                    }

                    containerMatches.AddRange(containerMatch);
                }

                // Success, this symbol's full name matched against the dotted name the user was asking
                // about.
                return new PatternMatches(candidateMatch, containerMatches.ToImmutable());
            }
            finally
            {
                containerMatches.Free();
            }
        }

        /// <summary>
        /// Determines if a given candidate string matches under a multiple word query text, as you
        /// would find in features like Navigate To.
        /// </summary>
        /// <remarks>
        /// PERF: This is slightly faster and uses less memory than <see cref="GetMatches(string, bool)"/>
        /// so, unless you need to know the full set of matches, use this version.
        /// </remarks>
        /// <param name="candidate">The word being tested.</param>
        /// <param name="inludeMatchSpans">Whether or not the matched spans should be included with results</param>
        /// <returns>If this was a match, the first element of the set of match types that occurred while matching the
        /// patterns. If it was not a match, it returns null.</returns>
        public PatternMatch? GetFirstMatch(string candidate, bool inludeMatchSpans = false)
        {
            if (SkipMatch(candidate))
            {
                return null;
            }

            return MatchSegment(candidate, inludeMatchSpans, _fullPatternSegment, wantAllMatches: false, allMatches: out var ignored, fuzzyMatch: false) ??
                   MatchSegment(candidate, inludeMatchSpans, _fullPatternSegment, wantAllMatches: false, allMatches: out ignored, fuzzyMatch: true);
        }

        private StringBreaks GetWordSpans(string word)
        {
            lock (_gate)
            {
                return _stringToWordSpans.GetOrAdd(word, _breakIntoWordSpans);
            }
        }

        internal PatternMatch? MatchSingleWordPattern_ForTestingOnly(string candidate)
        {
            return MatchTextChunk(candidate, includeMatchSpans: true,
                chunk: _fullPatternSegment.TotalTextChunk, punctuationStripped: false,
                fuzzyMatch: false);
        }

        private static bool ContainsUpperCaseLetter(string pattern)
        {
            // Expansion of "foreach(char ch in pattern)" to avoid a CharEnumerator allocation
            for (int i = 0; i < pattern.Length; i++)
            {
                if (char.IsUpper(pattern[i]))
                {
                    return true;
                }
            }

            return false;
        }

        private PatternMatch? MatchTextChunk(
            string candidate,
            bool includeMatchSpans,
            TextChunk chunk,
            bool punctuationStripped,
            bool fuzzyMatch)
        {
            int caseInsensitiveIndex = _compareInfo.IndexOf(candidate, chunk.Text, CompareOptions.IgnoreCase);
            if (caseInsensitiveIndex == 0)
            {
                if (chunk.Text.Length == candidate.Length)
                {
                    // a) Check if the part matches the candidate entirely, in an case insensitive or
                    //    sensitive manner.  If it does, return that there was an exact match.
                    return new PatternMatch(
                        PatternMatchKind.Exact, punctuationStripped, isCaseSensitive: candidate == chunk.Text,
                        matchedSpan: GetMatchedSpan(includeMatchSpans, 0, candidate.Length));
                }
                else
                {
                    // b) Check if the part is a prefix of the candidate, in a case insensitive or sensitive
                    //    manner.  If it does, return that there was a prefix match.
                    return new PatternMatch(
                        PatternMatchKind.Prefix, punctuationStripped, isCaseSensitive: _compareInfo.IsPrefix(candidate, chunk.Text),
                        matchedSpan: GetMatchedSpan(includeMatchSpans, 0, chunk.Text.Length));
                }
            }

            var isLowercase = !ContainsUpperCaseLetter(chunk.Text);
            if (isLowercase)
            {
                if (caseInsensitiveIndex > 0)
                {
                    // c) If the part is entirely lowercase, then check if it is contained anywhere in the
                    //    candidate in a case insensitive manner.  If so, return that there was a substring
                    //    match.
                    //
                    //    Note: We only have a substring match if the lowercase part is prefix match of some
                    //    word part. That way we don't match something like 'Class' when the user types 'a'.
                    //    But we would match 'FooAttribute' (since 'Attribute' starts with 'a').
                    var wordSpans = GetWordSpans(candidate);
                    for (int i = 0; i < wordSpans.Count; i++)
                    {
                        var span = wordSpans[i];
                        if (PartStartsWith(candidate, span, chunk.Text, CompareOptions.IgnoreCase))
                        {
                            return new PatternMatch(PatternMatchKind.Substring, punctuationStripped,
                                isCaseSensitive: PartStartsWith(candidate, span, chunk.Text, CompareOptions.None),
                                matchedSpan: GetMatchedSpan(includeMatchSpans, span.Start, chunk.Text.Length));
                        }
                    }
                }
            }
            else
            {
                // d) If the part was not entirely lowercase, then check if it is contained in the
                //    candidate in a case *sensitive* manner. If so, return that there was a substring
                //    match.
                var caseSensitiveIndex = _compareInfo.IndexOf(candidate, chunk.Text);
                if (caseSensitiveIndex > 0)
                {
                    return new PatternMatch(
                        PatternMatchKind.Substring, punctuationStripped, isCaseSensitive: true,
                        matchedSpan: GetMatchedSpan(includeMatchSpans, caseSensitiveIndex, chunk.Text.Length));
                }
            }

            if (!isLowercase)
            {
                // e) If the part was not entirely lowercase, then attempt a camel cased match as well.
                if (chunk.CharacterSpans.Count > 0)
                {
                    var candidateParts = GetWordSpans(candidate);
                    var camelCaseWeight = TryCamelCaseMatch(candidate, includeMatchSpans, candidateParts, chunk, CompareOptions.None, out var matchedSpans);
                    if (camelCaseWeight.HasValue)
                    {
                        return new PatternMatch(
                            PatternMatchKind.CamelCase, punctuationStripped, isCaseSensitive: true, camelCaseWeight: camelCaseWeight,
                            matchedSpans: GetMatchedSpans(includeMatchSpans, matchedSpans));
                    }

                    camelCaseWeight = TryCamelCaseMatch(candidate, includeMatchSpans, candidateParts, chunk, CompareOptions.IgnoreCase, out matchedSpans);
                    if (camelCaseWeight.HasValue)
                    {
                        return new PatternMatch(
                            PatternMatchKind.CamelCase, punctuationStripped, isCaseSensitive: false, camelCaseWeight: camelCaseWeight,
                            matchedSpans: GetMatchedSpans(includeMatchSpans, matchedSpans));
                    }
                }
            }

            if (isLowercase)
            {
                // f) Is the pattern a substring of the candidate starting on one of the candidate's word boundaries?

                // We could check every character boundary start of the candidate for the pattern. However, that's
                // an m * n operation in the worst case. Instead, find the first instance of the pattern
                // substring, and see if it starts on a capital letter. It seems unlikely that the user will try to
                // filter the list based on a substring that starts on a capital letter and also with a lowercase one.
                // (Pattern: fogbar, Candidate: quuxfogbarFogBar).
                if (chunk.Text.Length < candidate.Length)
                {
                    if (caseInsensitiveIndex != -1 && char.IsUpper(candidate[caseInsensitiveIndex]))
                    {
                        return new PatternMatch(
                            PatternMatchKind.Substring, punctuationStripped, isCaseSensitive: false,
                            matchedSpan: GetMatchedSpan(includeMatchSpans, caseInsensitiveIndex, chunk.Text.Length));
                    }
                }
            }

            if (fuzzyMatch)
            {
                if (chunk.SimilarityChecker.AreSimilar(candidate))
                {
                    return new PatternMatch(
                        PatternMatchKind.Fuzzy, punctuationStripped, isCaseSensitive: false, matchedSpan: null);
                }
            }

            return null;
        }

        private ImmutableArray<TextSpan> GetMatchedSpans(bool includeMatchSpans, List<TextSpan> matchedSpans)
        {
            return includeMatchSpans
                ? new NormalizedTextSpanCollection(matchedSpans).ToImmutableArray()
                : ImmutableArray<TextSpan>.Empty;
        }

        private static TextSpan? GetMatchedSpan(bool includeMatchSpans, int start, int length)
        {
            return includeMatchSpans ? new TextSpan(start, length) : (TextSpan?)null;
        }

        private static bool ContainsSpaceOrAsterisk(string text)
        {
            for (int i = 0; i < text.Length; i++)
            {
                char ch = text[i];
                if (ch == ' ' || ch == '*')
                {
                    return true;
                }
            }

            return false;
        }

        private ImmutableArray<PatternMatch> MatchSegment(
            string candidate, bool includeMatchSpans, Segment segment, bool fuzzyMatch)
        {
            if (fuzzyMatch && !_allowFuzzyMatching)
            {
                return ImmutableArray<PatternMatch>.Empty;
            }

            var singleMatch = MatchSegment(candidate, includeMatchSpans, segment,
                wantAllMatches: true, fuzzyMatch: fuzzyMatch, allMatches: out var matches);
            if (singleMatch.HasValue)
            {
                return ImmutableArray.Create(singleMatch.Value);
            }

            return matches;
        }

        /// <summary>
        /// Internal helper for MatchPatternInternal
        /// </summary>
        /// <remarks>
        /// PERF: Designed to minimize allocations in common cases.
        /// If there's no match, then null is returned.
        /// If there's a single match, or the caller only wants the first match, then it is returned (as a Nullable)
        /// If there are multiple matches, and the caller wants them all, then a List is allocated.
        /// </remarks>
        /// <param name="candidate">The word being tested.</param>
        /// <param name="segment">The segment of the pattern to check against the candidate.</param>
        /// <param name="wantAllMatches">Does the caller want all matches or just the first?</param>
        /// <param name="fuzzyMatch">If a fuzzy match should be performed</param>
        /// <param name="allMatches">If <paramref name="wantAllMatches"/> is true, and there's more than one match, then the list of all matches.</param>
        /// <param name="includeMatchSpans">Whether or not the matched spans should be included with results</param>
        /// <returns>If there's only one match, then the return value is that match. Otherwise it is null.</returns>
        private PatternMatch? MatchSegment(
            string candidate,
            bool includeMatchSpans,
            Segment segment,
            bool wantAllMatches,
            bool fuzzyMatch,
            out ImmutableArray<PatternMatch> allMatches)
        {
            allMatches = ImmutableArray<PatternMatch>.Empty;

            if (fuzzyMatch && !_allowFuzzyMatching)
            {
                return null;
            }

            // First check if the segment matches as is.  This is also useful if the segment contains
            // characters we would normally strip when splitting into parts that we also may want to
            // match in the candidate.  For example if the segment is "@int" and the candidate is
            // "@int", then that will show up as an exact match here.
            //
            // Note: if the segment contains a space or an asterisk then we must assume that it's a
            // multi-word segment.
            if (!ContainsSpaceOrAsterisk(segment.TotalTextChunk.Text))
            {
                var match = MatchTextChunk(candidate, includeMatchSpans,
                    segment.TotalTextChunk, punctuationStripped: false, fuzzyMatch: fuzzyMatch);
                if (match != null)
                {
                    return match;
                }
            }

            // The logic for pattern matching is now as follows:
            //
            // 1) Break the segment passed in into words.  Breaking is rather simple and a
            //    good way to think about it that if gives you all the individual alphanumeric words
            //    of the pattern.
            //
            // 2) For each word try to match the word against the candidate value.
            //
            // 3) Matching is as follows:
            //
            //   a) Check if the word matches the candidate entirely, in an case insensitive or
            //    sensitive manner.  If it does, return that there was an exact match.
            //
            //   b) Check if the word is a prefix of the candidate, in a case insensitive or
            //      sensitive manner.  If it does, return that there was a prefix match.
            //
            //   c) If the word is entirely lowercase, then check if it is contained anywhere in the
            //      candidate in a case insensitive manner.  If so, return that there was a substring
            //      match.
            //
            //      Note: We only have a substring match if the lowercase part is prefix match of
            //      some word part. That way we don't match something like 'Class' when the user
            //      types 'a'. But we would match 'FooAttribute' (since 'Attribute' starts with
            //      'a').
            //
            //   d) If the word was not entirely lowercase, then check if it is contained in the
            //      candidate in a case *sensitive* manner. If so, return that there was a substring
            //      match.
            //
            //   e) If the word was not entirely lowercase, then attempt a camel cased match as
            //      well.
            //
            //   f) The word is all lower case. Is it a case insensitive substring of the candidate starting
            //      on a part boundary of the candidate?
            //
            // Only if all words have some sort of match is the pattern considered matched.

            var subWordTextChunks = segment.SubWordTextChunks;
            var matches = ArrayBuilder<PatternMatch>.GetInstance();

            try
            {
                foreach (var subWordTextChunk in subWordTextChunks)
                {
                    // Try to match the candidate with this word
                    var result = MatchTextChunk(candidate, includeMatchSpans,
                        subWordTextChunk, punctuationStripped: true, fuzzyMatch: fuzzyMatch);
                    if (result == null)
                    {
                        return null;
                    }

                    if (!wantAllMatches || subWordTextChunks.Length == 1)
                    {
                        // Stop at the first word
                        return result;
                    }

                    matches.Add(result.Value);
                }

                allMatches = matches.ToImmutable();
                return null;
            }
            finally
            {
                matches.Free();
            }
        }

        private static bool IsWordChar(char ch, bool verbatimIdentifierPrefixIsWordCharacter)
        {
            return char.IsLetterOrDigit(ch) || ch == '_' || (verbatimIdentifierPrefixIsWordCharacter && ch == '@');
        }

        /// <summary>
        /// Do the two 'parts' match? i.e. Does the candidate part start with the pattern part?
        /// </summary>
        /// <param name="candidate">The candidate text</param>
        /// <param name="candidatePart">The span within the <paramref name="candidate"/> text</param>
        /// <param name="pattern">The pattern text</param>
        /// <param name="patternPart">The span within the <paramref name="pattern"/> text</param>
        /// <param name="compareOptions">Options for doing the comparison (case sensitive or not)</param>
        /// <returns>True if the span identified by <paramref name="candidatePart"/> within <paramref name="candidate"/> starts with
        /// the span identified by <paramref name="patternPart"/> within <paramref name="pattern"/>.</returns>
        private bool PartStartsWith(string candidate, TextSpan candidatePart, string pattern, TextSpan patternPart, CompareOptions compareOptions)
        {
            if (patternPart.Length > candidatePart.Length)
            {
                // Pattern part is longer than the candidate part. There can never be a match.
                return false;
            }

            return _compareInfo.Compare(candidate, candidatePart.Start, patternPart.Length, pattern, patternPart.Start, patternPart.Length, compareOptions) == 0;
        }

        /// <summary>
        /// Does the given part start with the given pattern?
        /// </summary>
        /// <param name="candidate">The candidate text</param>
        /// <param name="candidatePart">The span within the <paramref name="candidate"/> text</param>
        /// <param name="pattern">The pattern text</param>
        /// <param name="compareOptions">Options for doing the comparison (case sensitive or not)</param>
        /// <returns>True if the span identified by <paramref name="candidatePart"/> within <paramref name="candidate"/> starts with <paramref name="pattern"/></returns>
        private bool PartStartsWith(string candidate, TextSpan candidatePart, string pattern, CompareOptions compareOptions)
        {
            return PartStartsWith(candidate, candidatePart, pattern, new TextSpan(0, pattern.Length), compareOptions);
        }

        private int? TryCamelCaseMatch(
            string candidate,
            bool includeMatchedSpans,
            StringBreaks candidateParts,
            TextChunk chunk,
            CompareOptions compareOption,
            out List<TextSpan> matchedSpans)
        {
            matchedSpans = null;
            var chunkCharacterSpans = chunk.CharacterSpans;

            // Note: we may have more pattern parts than candidate parts.  This is because multiple
            // pattern parts may match a candidate part.  For example "SiUI" against "SimpleUI".
            // We'll have 3 pattern parts Si/U/I against two candidate parts Simple/UI.  However, U
            // and I will both match in UI.

            int currentCandidate = 0;
            int currentChunkSpan = 0;
            int? firstMatch = null;
            bool? contiguous = null;

            while (true)
            {
                // Let's consider our termination cases
                if (currentChunkSpan == chunkCharacterSpans.Count)
                {
                    Contract.Requires(firstMatch.HasValue);
                    Contract.Requires(contiguous.HasValue);

                    // We did match! We shall assign a weight to this
                    int weight = 0;

                    // Was this contiguous?
                    if (contiguous.Value)
                    {
                        weight += 1;
                    }

                    // Did we start at the beginning of the candidate?
                    if (firstMatch.Value == 0)
                    {
                        weight += 2;
                    }

                    return weight;
                }
                else if (currentCandidate == candidateParts.Count)
                {
                    // No match, since we still have more of the pattern to hit
                    matchedSpans = null;
                    return null;
                }

                var candidatePart = candidateParts[currentCandidate];
                bool gotOneMatchThisCandidate = false;

                // Consider the case of matching SiUI against SimpleUIElement. The candidate parts
                // will be Simple/UI/Element, and the pattern parts will be Si/U/I.  We'll match 'Si'
                // against 'Simple' first.  Then we'll match 'U' against 'UI'. However, we want to
                // still keep matching pattern parts against that candidate part.
                for (; currentChunkSpan < chunkCharacterSpans.Count; currentChunkSpan++)
                {
                    var chunkCharacterSpan = chunkCharacterSpans[currentChunkSpan];

                    if (gotOneMatchThisCandidate)
                    {
                        // We've already gotten one pattern part match in this candidate.  We will
                        // only continue trying to consume pattern parts if the last part and this
                        // part are both upper case.
                        if (!char.IsUpper(chunk.Text[chunkCharacterSpans[currentChunkSpan - 1].Start]) ||
                            !char.IsUpper(chunk.Text[chunkCharacterSpans[currentChunkSpan].Start]))
                        {
                            break;
                        }
                    }

                    if (!PartStartsWith(candidate, candidatePart, chunk.Text, chunkCharacterSpan, compareOption))
                    {
                        break;
                    }

                    if (includeMatchedSpans)
                    {
                        matchedSpans = matchedSpans ?? new List<TextSpan>();
                        matchedSpans.Add(new TextSpan(candidatePart.Start, chunkCharacterSpan.Length));
                    }

                    gotOneMatchThisCandidate = true;

                    firstMatch = firstMatch ?? currentCandidate;

                    // If we were contiguous, then keep that value.  If we weren't, then keep that
                    // value.  If we don't know, then set the value to 'true' as an initial match is
                    // obviously contiguous.
                    contiguous = contiguous ?? true;

                    candidatePart = new TextSpan(candidatePart.Start + chunkCharacterSpan.Length, candidatePart.Length - chunkCharacterSpan.Length);
                }

                // Check if we matched anything at all.  If we didn't, then we need to unset the
                // contiguous bit if we currently had it set.
                // If we haven't set the bit yet, then that means we haven't matched anything so
                // far, and we don't want to change that.
                if (!gotOneMatchThisCandidate && contiguous.HasValue)
                {
                    contiguous = false;
                }

                // Move onto the next candidate.
                currentCandidate++;
            }
        }
    }
}


text:
import path from 'path'
import webpack from 'webpack'

const src = path.resolve(__dirname, 'src')

export default {
  output: {
    library: 'units',
    libraryTarget: 'umd',
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        include: [src],
        loader: 'babel-loader',
      },
    ],
  },
}


text:
ENCRYPT=bin/encrypt
OMP=bin/omp
MPI=bin/mpi

FILE=tmp/file
ENCRYPTED_FILE=tmp/encrypted
METHOD=blowfish

##usage: ./decrypt [INPUT FILE] [KEY CODE] [METHOD] [OUTPUT FILE]
echo "===== Escalability Metrics ====="
echo

echo "Frase: La bersuit" > $FILE
$ENCRYPT $FILE 99999999 $METHOD $ENCRYPTED_FILE

export CANT_KEYS=500000

for I in 1 2 4 8
do
	echo "OpenMP time $I thread with 500000 keys..."
	export OMP_NUM_THREADS=$I
	time ./$OMP $ENCRYPTED_FILE
	echo
done

for I in 1 2 4 8
do
	echo "OpenMPI time with $I process with 500000 keys.."
	time mpirun -np $I $MPI $ENCRYPTED_FILE
	echo
done

echo "============================================="
echo

rm -f report key


text:
import { Injectable } from '@angular/core';

import { BehaviorSubject, Observable, Subscription } from 'rxjs';

import { ProjectorService } from 'app/core/core-services/projector.service';
import { ListOfSpeakersRepositoryService } from 'app/core/repositories/agenda/list-of-speakers-repository.service';
import { ProjectorRepositoryService } from 'app/core/repositories/projector/projector-repository.service';
import { ViewListOfSpeakers } from 'app/site/agenda/models/view-list-of-speakers';
import { isBaseViewModelWithListOfSpeakers } from 'app/site/base/base-view-model-with-list-of-speakers';
import { SlideManager } from 'app/slides/services/slide-manager.service';
import { ViewProjector } from '../models/view-projector';

/**
 * Observes the projector config for a given projector and returns a observable of the
 * current view list of speakers displayed on the projector.
 */
@Injectable({
    providedIn: 'root'
})
export class CurrentListOfSpeakersService {
    /**
     * Current clos reference projector
     */
    private closRefProjector: ViewProjector;

    /**
     * This map holds the current (number or null) los-id for the the projector.
     * It is used to check, if the reference has changed (this clos id changed for one projector).
     */
    private currentListOfSpeakersIds: { [projectorId: number]: number | null } = {};

    /**
     * Active subscriptions for the clos of each projector.
     */
    private currentListOfSpeakersSubscriptions: { [projectorId: number]: Subscription } = {};

    /**
     * All subjects for all clos of each projector.
     */
    private currentListOfSpeakers: { [projectorId: number]: BehaviorSubject<ViewListOfSpeakers | null> } = {};

    private currentListOfSpeakerSubject = new BehaviorSubject<ViewListOfSpeakers>(null);

    public currentListOfSpeakersObservable = this.currentListOfSpeakerSubject.asObservable();

    public constructor(
        private projectorService: ProjectorService,
        private projectorRepo: ProjectorRepositoryService,
        private listOfSpeakersRepo: ListOfSpeakersRepositoryService,
        private slideManager: SlideManager
    ) {
        // Watch for changes and update the current list of speakers for every projector.
        this.projectorRepo.getGeneralViewModelObservable().subscribe(projector => {
            if (projector) {
                this.setListOfSpeakersForProjector(projector);
            }
        });

        this.projectorRepo.getReferenceProjectorObservable().subscribe(clos => {
            if (clos) {
                this.closRefProjector = clos;
                this.currentListOfSpeakerSubject.next(this.getCurrentListOfSpeakers());
            }
        });
    }

    /**
     * Use the subject to get it
     */
    private getCurrentListOfSpeakers(): ViewListOfSpeakers | null {
        return this.getCurrentListOfSpeakersForProjector(this.closRefProjector);
    }

    /**
     * Returns an observable for the view list of speakers of the currently projected element on the
     * given projector.
     *
     * @param projector The projector to observe.
     * @returns An observalbe for the list of speakers. Null, if no element with an list of speakers is shown.
     */
    public getListOfSpeakersObservable(projector: ViewProjector): Observable<ViewListOfSpeakers | null> {
        if (!this.currentListOfSpeakers[projector.id]) {
            this.setListOfSpeakersForProjector(projector);
        }
        return this.currentListOfSpeakers[projector.id].asObservable();
    }

    /**
     * calld on startup and on every projector update.
     * If the reference didn't changed the clos for the projector just gets pushed.
     *
     * If it was the first call to this function for a projector or the id changed,
     * there will be a subscription to the LOS-repo to stay informed when the clos
     * of the projector is updated (if there is a current CLOS).
     */
    private setListOfSpeakersForProjector(projector: ViewProjector): void {
        const listOfSpeakers = this.getCurrentListOfSpeakersForProjector(projector);
        const listOfSpeakersId = listOfSpeakers ? listOfSpeakers.id : null;
        if (this.currentListOfSpeakersIds[projector.id] === listOfSpeakersId) {
            this.currentListOfSpeakers[projector.id].next(listOfSpeakers);
        } else {
            this.currentListOfSpeakersIds[projector.id] = listOfSpeakersId;

            if (!this.currentListOfSpeakers[projector.id]) {
                this.currentListOfSpeakers[projector.id] = new BehaviorSubject(listOfSpeakers);
            }
            // Do not send the listOfSpeakers through currentListOfSpeakers, because this will be
            // toggled by the listOfSpeakersRepo subscription below.

            if (this.currentListOfSpeakersSubscriptions[projector.id]) {
                this.currentListOfSpeakersSubscriptions[projector.id].unsubscribe();
                this.currentListOfSpeakersSubscriptions[projector.id] = null;
            }
            if (listOfSpeakersId !== null) {
                this.currentListOfSpeakersSubscriptions[projector.id] = this.listOfSpeakersRepo
                    .getViewModelObservable(listOfSpeakers.id)
                    .subscribe(los => {
                        if (los && this.currentListOfSpeakers[projector.id]) {
                            this.currentListOfSpeakers[projector.id].next(los);
                        }
                    });
            }
        }
    }

    /**
     * Tries to get the view list of speakers for one non stable element on the projector.
     *
     * @param projector The projector
     * @returns The view list of speakers or null, if there is no such projector element.
     */
    private getCurrentListOfSpeakersForProjector(projector: ViewProjector): ViewListOfSpeakers | null {
        const nonStableElements = projector.elements.filter(element => !element.stable);
        for (const nonStableElement of nonStableElements) {
            const identifiableNonStableElement = this.slideManager.getIdentifiableProjectorElement(nonStableElement);
            try {
                const viewModel =
                    this.projectorService.getViewModelFromIdentifiableProjectorElement(identifiableNonStableElement);
                if (isBaseViewModelWithListOfSpeakers(viewModel)) {
                    return viewModel.listOfSpeakers;
                }
            } catch (e) {
                // make TypeScript silent.
            }
        }
        return null;
    }
}


text:
var cp = require('child_process');

describe('CLI',function () {
	it('should thank me for downloading', function (done) {
		cp.execFile('./app.js', function (err, stdout) {
			stdout.should.equal('Thanks for downloading my app\n');
			done();
		});
	});
});


text:
package com.wangyin.common.code;

/**
 * Created by wylipengming on 2014/7/25.
 */
public enum MessageType {
    SMS(1,"短信","sms"),//短信
    EMAIL(1,"邮箱","email"),//邮箱
    WX(1,"微信","wx"),//微信
    OTHERS(1,"其他","other")//其他
    ;

    private Integer code;
    private String  desc;
    private String  msg;

    MessageType(Integer code, String msg, String desc) {
        this.code = code;
        this.desc = desc;
        this.msg = msg;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}


text:
package org.springframework.security.oauth2.client.authentication;

import java.util.Collections;

import org.junit.Before;
import org.junit.Test;

import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.springframework.security.oauth2.client.registration.TestClientRegistrations.clientRegistration;
import static org.springframework.security.oauth2.core.TestOAuth2AccessTokens.noScopes;
import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests.request;
import static org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses.success;

/**
 * Tests for {@link OAuth2AuthorizationCodeAuthenticationToken}.
 *
 * @author Joe Grandja
 */
public class OAuth2AuthorizationCodeAuthenticationTokenTests {
	private ClientRegistration clientRegistration;
	private OAuth2AuthorizationExchange authorizationExchange;
	private OAuth2AccessToken accessToken;

	@Before
	public void setUp() {
		this.clientRegistration = clientRegistration().build();
		this.authorizationExchange = new OAuth2AuthorizationExchange(request().build(),
				success().code("code").build());
		this.accessToken = noScopes();
	}

	@Test
	public void constructorAuthorizationRequestResponseWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
		assertThatThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(null, this.authorizationExchange))
				.isInstanceOf(IllegalArgumentException.class);
	}

	@Test
	public void constructorAuthorizationRequestResponseWhenAuthorizationExchangeIsNullThenThrowIllegalArgumentException() {
		assertThatThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, null))
				.isInstanceOf(IllegalArgumentException.class);
	}

	@Test
	public void constructorAuthorizationRequestResponseWhenAllParametersProvidedAndValidThenCreated() {
		OAuth2AuthorizationCodeAuthenticationToken authentication =
			new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, this.authorizationExchange);

		assertThat(authentication.getPrincipal()).isEqualTo(this.clientRegistration.getClientId());
		assertThat(authentication.getCredentials()).isEqualTo(this.authorizationExchange.getAuthorizationResponse().getCode());
		assertThat(authentication.getAuthorities()).isEqualTo(Collections.emptyList());
		assertThat(authentication.getClientRegistration()).isEqualTo(this.clientRegistration);
		assertThat(authentication.getAuthorizationExchange()).isEqualTo(this.authorizationExchange);
		assertThat(authentication.getAccessToken()).isNull();
		assertThat(authentication.isAuthenticated()).isEqualTo(false);
	}

	@Test
	public void constructorTokenRequestResponseWhenClientRegistrationIsNullThenThrowIllegalArgumentException() {
		assertThatThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(null, this.authorizationExchange, this.accessToken))
				.isInstanceOf(IllegalArgumentException.class);
	}

	@Test
	public void constructorTokenRequestResponseWhenAuthorizationExchangeIsNullThenThrowIllegalArgumentException() {
		assertThatThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, null, this.accessToken))
				.isInstanceOf(IllegalArgumentException.class);
	}

	@Test
	public void constructorTokenRequestResponseWhenAccessTokenIsNullThenThrowIllegalArgumentException() {
		assertThatThrownBy(() -> new OAuth2AuthorizationCodeAuthenticationToken(this.clientRegistration, this.authorizationExchange, null))
				.isInstanceOf(IllegalArgumentException.class);
	}

	@Test
	public void constructorTokenRequestResponseWhenAllParametersProvidedAndValidThenCreated() {
		OAuth2AuthorizationCodeAuthenticationToken authentication = new OAuth2AuthorizationCodeAuthenticationToken(
			this.clientRegistration, this.authorizationExchange, this.accessToken);

		assertThat(authentication.getPrincipal()).isEqualTo(this.clientRegistration.getClientId());
		assertThat(authentication.getCredentials()).isEqualTo(this.accessToken.getTokenValue());
		assertThat(authentication.getAuthorities()).isEqualTo(Collections.emptyList());
		assertThat(authentication.getClientRegistration()).isEqualTo(this.clientRegistration);
		assertThat(authentication.getAuthorizationExchange()).isEqualTo(this.authorizationExchange);
		assertThat(authentication.getAccessToken()).isEqualTo(this.accessToken);
		assertThat(authentication.isAuthenticated()).isEqualTo(true);
	}
}


text:
package com.oprisnik.simpleconfig;

import org.junit.Before;
import org.junit.Test;

import java.io.FileNotFoundException;

import static com.google.common.truth.Truth.assertThat;

public class ExtendedComponentTest extends BaseComponentTest {

    protected Config mConfig;

    @Before
    public void init() throws BadConfigException, FileNotFoundException {
        mConfig = getXmlConfig("/extended-component.xml");
    }

    @Test
    public void testGetName() throws Exception {
        // we only use the base class here
        SimpleComponent component = mConfig.getComponentAndInit("extended1", SimpleComponent.class);

        assertThat(component).isNotNull();
        assertThat(component.getName()).isEqualTo("Awesome component");
    }

    @Test
    public void testGetExtendedInfo() throws Exception {
        ExtendedComponent component = mConfig.getComponentAndInit("extended1", ExtendedComponent.class);

        assertThat(component).isNotNull();
        assertThat(component.getName()).isEqualTo("Awesome component");
        assertThat(component.getExtendedInfo()).isEqualTo("Extended information");
    }

    @Test
    public void testGetName2() throws Exception {
        // we only use the base class here
        SimpleComponent component = mConfig.getComponentAndInit("extended2", SimpleComponent.class);

        assertThat(component).isNotNull();
        assertThat(component.getName()).isNull();
    }

    @Test
    public void testGetExtendedInfo2() throws Exception {
        ExtendedComponent component = mConfig.getComponentAndInit("extended2", ExtendedComponent.class);

        assertThat(component).isNotNull();
        assertThat(component.getName()).isNull();
        assertThat(component.getExtendedInfo()).isNull();
    }

    @Test
    public void testGetName3() throws Exception {
        // we only use the base class here
        SimpleComponent component = mConfig.getComponentAndInit("extended3", SimpleComponent.class, ExtendedComponent.class);

        assertThat(component).isNotNull();
        assertThat(component.getName()).isEqualTo("Awesome name 3");
    }

    @Test
    public void testGetExtendedInfo3() throws Exception {
        ExtendedComponent component = mConfig.getComponentAndInit("extended3", ExtendedComponent.class, ExtendedComponent.class);

        assertThat(component).isNotNull();
        assertThat(component.getName()).isEqualTo("Awesome name 3");
        assertThat(component.getExtendedInfo()).isEqualTo("Extended information 3");
    }

    @Test
    public void testGetName4() throws Exception {
        // we only use the base class here
        SimpleComponent component = mConfig.getComponentAndInit("extended4", SimpleComponent.class, SimpleComponent.class);

        // assert that the class value specified in the config file
        // is used instead of the default value
        assertThat(component instanceof ExtendedComponent).isTrue();

        assertThat(component).isNotNull();
        assertThat(component.getName()).isEqualTo("Awesome name 4");
    }

    @Test
    public void testGetExtendedInfo4() throws Exception {
        ExtendedComponent component = mConfig.getComponentAndInit("extended4", ExtendedComponent.class, ExtendedComponent.class);

        assertThat(component).isNotNull();
        assertThat(component.getName()).isEqualTo("Awesome name 4");
        assertThat(component.getExtendedInfo()).isEqualTo("Extended information 4");
    }

}


text:
class Observable(object):
    """
    Observable pattern for parameterization.

    This Object allows for observers to register with self and a (bound!) function
    as an observer. Every time the observable changes, it sends a notification with
    self as only argument to all its observers.
    """
    def __init__(self, *args, **kwargs):
        super(Observable, self).__init__()
        from .lists_and_dicts import ObserverList
        self.observers = ObserverList()
        self._update_on = True

    def set_updates(self, on=True):
        self._update_on = on

    def add_observer(self, observer, callble, priority=0):
        """
        Add an observer `observer` with the callback `callble`
        and priority `priority` to this observers list.
        """
        self.observers.add(priority, observer, callble)

    def remove_observer(self, observer, callble=None):
        """
        Either (if callble is None) remove all callables,
        which were added alongside observer,
        or remove callable `callble` which was added alongside
        the observer `observer`.
        """
        to_remove = []
        for poc in self.observers:
            _, obs, clble = poc
            if callble is not None:
                if (obs is observer) and (callble == clble):
                    to_remove.append(poc)
            else:
                if obs is observer:
                    to_remove.append(poc)
        for r in to_remove:
            self.observers.remove(*r)

    def notify_observers(self, which=None, min_priority=None):
        """
        Notifies all observers. Which is the element, which kicked off this
        notification loop. The first argument will be self, the second `which`.

        .. note::

           notifies only observers with priority p > min_priority!

        :param min_priority: only notify observers with priority > min_priority
                             if min_priority is None, notify all observers in order
        """
        if self._update_on:
            if which is None:
                which = self
            if min_priority is None:
                [callble(self, which=which) for _, _, callble in self.observers]
            else:
                for p, _, callble in self.observers:
                    if p <= min_priority:
                        break
                    callble(self, which=which)

    def change_priority(self, observer, callble, priority):
        self.remove_observer(observer, callble)
        self.add_observer(observer, callble, priority)


text:
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

      <link rel="stylesheet" href="./../../helpwin.css">
      <title>MATLAB File Help: prtDataSetRegress/isLabeled</title>

            MATLAB File Help: prtDataSetRegress/isLabeled

prtDataSetRegress/isLabeled

 isLabeled -  Whether or not the data has target labels

Help for prtDataSetRegress/isLabeled is inherited from superclass prtDataSetBase

Property Details

            Constant
            false

            Dependent
            true

            Sealed
            false

            Transient
            false

            GetAccess
            public

            SetAccess
            public

            GetObservable
            false

            SetObservable
            false


text:
package me.kudryavka.bluecon.Consts;

/**
 * Created by seyriz on 2016. 10. 3..
 */

public class ENUMS {
    public enum SERVICE_STATES{IMMORTAL, MORTAL}
    public enum BLUETOOTH_STATES{DISCONNECTED, CONNECTED, CONNECTING, NOT_SUPPORT, DISABLED}
    public enum SERVER_MODE{SINGLE_CONNECTION, MULTIPLE_CONNECTION}
}


text:
Presentation on Introduction to jQuery using [impress.js](https://github.com/impress/impress.js)

You can view the presentation [here](https://g-akshay.github.io/Intro_To_Jquery).


text:
class VzShader {
public:
	GLuint ID;

public:
	VzShader(const char* vs_file_path, const char* fs_file_path, const char* gs_file_path = nullptr) {
		std::string vs_code;
		std::string fs_code;
		std::string gs_code;

		std::ifstream vs_file;
		std::ifstream fs_file;
		std::ifstream gs_file;

		vs_file.exceptions(std::ifstream::failbit | std::ifstream::badbit);
		fs_file.exceptions(std::ifstream::failbit | std::ifstream::badbit);
		gs_file.exceptions(std::ifstream::failbit | std::ifstream::badbit);

		try {
			vs_file.open(vs_file_path);
			fs_file.open(fs_file_path);

			std::stringstream vs_str_stream, fs_str_stream;
			vs_str_stream << vs_file.rdbuf();
			fs_str_stream << fs_file.rdbuf();

			vs_file.close();
			fs_file.close();

			vs_code = vs_str_stream.str();
			fs_code = fs_str_stream.str();

			if (gs_file_path != nullptr) {
				gs_file.open(gs_file_path);
				std::stringstream gs_str_stream;
				gs_str_stream << gs_file.rdbuf();
				gs_file.close();
				gs_code = gs_str_stream.str();
			}
		}
		catch (std::ifstream::failure e) {
			std::cout << "ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ" << std::endl;
		}

		const char* vs_code_strbuf = vs_code.c_str();
		const char* fs_code_strbuf = fs_code.c_str();
		GLuint vs, fs;

		// vertex shader
		vs = glCreateShader(GL_VERTEX_SHADER);
		glShaderSource(vs, 1, &vs_code_strbuf, NULL);
		glCompileShader(vs);
		_error_log(vs, "VERTEX");

		// fragment shader
		fs = glCreateShader(GL_FRAGMENT_SHADER);
		glShaderSource(fs, 1, &fs_code_strbuf, NULL);
		glCompileShader(fs);
		_error_log(vs, "FRAGMENT");

		// if geometry shader is given, compile geometry shader
		GLuint gs;
		if (gs_file_path != nullptr) {
			const char* gs_code_strbuf = gs_code.c_str();
			gs = glCreateShader(GL_GEOMETRY_SHADER);
			glShaderSource(gs, 1, &gs_code_strbuf, NULL);
			glCompileShader(gs);
			_error_log(vs, "GEOMETRY");
		}

		// shader program
		ID = glCreateProgram();
		glAttachShader(ID, vs);
		glAttachShader(ID, fs);
		if (gs_file_path != nullptr) {
			glAttachShader(ID, gs);
		}

		glLinkProgram(ID);
		_error_log(vs, "PROGRAM");

		glDeleteShader(vs);
		glDeleteShader(fs);
		if (gs_file_path != nullptr) {
			glDeleteShader(gs);
		}
	}

	// activate the shader
	void use() {
		glUseProgram(ID);
	}

	// ------------------------------------------------------------------------
	void set_bool(const std::string &name, bool value) const {
		glUniform1i(glGetUniformLocation(ID, name.c_str()), (int)value);
	}
	// ------------------------------------------------------------------------
	void set_int(const std::string &name, int value) const {
		glUniform1i(glGetUniformLocation(ID, name.c_str()), value);
	}
	// ------------------------------------------------------------------------
	void set_float(const std::string &name, float value) const {
		glUniform1f(glGetUniformLocation(ID, name.c_str()), value);
	}
	// ------------------------------------------------------------------------
	void set_vec2(const std::string &name, const glm::vec2 &value) const {
		glUniform2fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]);
	}
	void set_vec2(const std::string &name, float x, float y) const {
		glUniform2f(glGetUniformLocation(ID, name.c_str()), x, y);
	}
	// ------------------------------------------------------------------------
	void set_vec3(const std::string &name, const glm::vec3 &value) const {
		glUniform3fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]);
	}
	void set_vec3(const std::string &name, float x, float y, float z) const {
		glUniform3f(glGetUniformLocation(ID, name.c_str()), x, y, z);
	}
	// ------------------------------------------------------------------------
	void set_vec4(const std::string &name, const glm::vec4 &value) const {
		glUniform4fv(glGetUniformLocation(ID, name.c_str()), 1, &value[0]);
	}
	void set_vec4(const std::string &name, float x, float y, float z, float w) {
		glUniform4f(glGetUniformLocation(ID, name.c_str()), x, y, z, w);
	}
	// ------------------------------------------------------------------------
	void set_mat2(const std::string &name, const glm::mat2 &mat) const {
		glUniformMatrix2fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]);
	}
	// ------------------------------------------------------------------------
	void set_mat3(const std::string &name, const glm::mat3 &mat) const {
		glUniformMatrix3fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]);
	}
	// ------------------------------------------------------------------------
	void set_mat4(const std::string &name, const glm::mat4 &mat) const {
		glUniformMatrix4fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, &mat[0][0]);
	}

private:
	void _error_log(GLuint shader, std::string type) {
		GLint success;
		GLchar info_log[1024];

		if (type != "PROGRAM") {
			glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
			if (!success) {
				glGetShaderInfoLog(shader, 1024, NULL, info_log);
				std::cout << "ERROR:SHADER_COMPILATION_ERROR of type : " << type << "\n" << info_log << std::endl;
				std::cout << "------------------------------------------------" << std::endl;
			}
		}
		else {
			glGetProgramiv(shader, GL_LINK_STATUS, &success);
			if (!success) {
				glGetProgramInfoLog(shader, 1024, NULL, info_log);
				std::cout << "ERROR:PROGRAM_LINKING_ERROR of type : " << type << "\n" << info_log << std::endl;
				std::cout << "------------------------------------------------" << std::endl;
			}
		}
	}
};


text:
package com.deltadna.android.sdk.ads.listeners;

/**
 * Listener for ad registration events.
 */
public interface AdRegistrationListener {

    /**
     * Called when registering for interstitial ads has succeeded.
     */
    void onRegisteredForInterstitial();

    /**
     * Called when registering for interstitial ads has failed.
     *
     * @param reason the reason for the failure
     */
    void onFailedToRegisterForInterstitial(String reason);

    /**
     * Called when registering for rewarded ads has succeeded.
     */
    void onRegisteredForRewarded();

    /**
     * Called when registering for rewarded ads has failed.
     *
     * @param reason the reason for the failure
     */
    void onFailedToRegisterForRewarded(String reason);
}


text:
package com.hitsujun.core.util.kanji;

import playn.core.util.Callback;

public interface KanjiInfoLoader {
	void load (Callback<String> callback) ;
}


text:
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str

import copy
import json
import numpy
import logging
import networkx
from os import path, pardir
from collections import namedtuple

logger = logging.getLogger(__name__)

THIS_DIR = path.dirname(path.abspath(__file__))

def load_default_probs():
    json_path = path.join(THIS_DIR, pardir, 'resources',
                          'default_belief_probs.json')
    with open(json_path, 'r') as f:
        prior_probs = json.load(f)
    return prior_probs

class BeliefScorer(object):
    """Base class for a belief engine scorer, which computes the
    prior probability of a statement given its type and evidence.

    To use with the belief engine, make a subclass with methods implemented.
    """
    def score_statement(self, st, extra_evidence=None):
        """Computes the prior belief probability for an INDRA Statement.

        The Statement is assumed to be de-duplicated. In other words,
        the Statement is assumed to have
        a list of Evidence objects that supports it. The prior probability of
        the Statement is calculated based on the number of Evidences it has
        and their sources.

        Parameters
        ----------
        st : indra.statements.Statement
            An INDRA Statements whose belief scores are to
            be calculated.
        extra_evidence : list[indra.statements.Evidence]
            A list of Evidences that are supporting the Statement (that aren't
            already included in the Statement's own evidence list.

        Returns
        -------
        belief_score : float
            The computed prior probability for the statement
        """
        raise NotImplementedError('Need to subclass BeliefScorer and '
                                  'implement methods.')

    def check_prior_probs(self, statements):
        """Make sure the scorer has all the information needed to compute
        belief scores of each statement in the provided list, and raises an
        exception otherwise.

        Parameters
        ----------
        statements : list<indra.statements.Statement>
            List of statements to check
        """
        raise NotImplementedError('Need to subclass BeliefScorer and '
                                  'implement methods.')

class SimpleScorer(BeliefScorer):
    """Computes the prior probability of a statement given its type and
    evidence.

    Parameters
    ----------
    prior_probs : dict[dict]
        A dictionary of prior probabilities used to override/extend the
        default ones. There are two types of prior probabilities: rand and syst
        corresponding to random error and systematic error rate for each
        knowledge source. The prior_probs dictionary has the general structure
        {'rand': {'s1': pr1, ..., 'sn': prn},
        'syst': {'s1': ps1, ..., 'sn': psn}}
        where 's1' ... 'sn' are names of input sources and pr1 ... prn and
        ps1 ... psn are error probabilities.
        Examples: {'rand': {'some_source': 0.1}} sets the random error rate
        for some_source to 0.1; {'rand': {''}}
    subtype_probs : dict[dict]
        A dictionary of random error probabilities for knowledge sources.
        When a subtype random error probability is not specified, will just
        use the overall type prior in prior_probs. If None, will
        only use the priors for each rule.
    """
    def __init__(self, prior_probs=None, subtype_probs=None):
        self.prior_probs = load_default_probs()
        self.subtype_probs = {}
        self.update_probs(prior_probs, subtype_probs)

    def update_probs(self, prior_probs=None, subtype_probs=None):
        if prior_probs:
            for key in ('rand', 'syst'):
                self.prior_probs[key].update(prior_probs.get(key, {}))
        for err_type, source_dict in self.prior_probs.items():
            logger.debug("Prior probabilities for %s errors: %s"
                         % (err_type, source_dict))
        self.subtype_probs = subtype_probs

    def score_evidence_list(self, evidences):
        """Return belief score given a list of supporting evidences."""
        def _score(evidences):
            if not evidences:
                return 0
            # Collect all unique sources
            sources = [ev.source_api for ev in evidences]
            uniq_sources = numpy.unique(sources)
            # Calculate the systematic error factors given unique sources
            syst_factors = {s: self.prior_probs['syst'][s]
                            for s in uniq_sources}
            # Calculate the radom error factors for each source
            rand_factors = {k: [] for k in uniq_sources}
            for ev in evidences:
                rand_factors[ev.source_api].append(
                    evidence_random_noise_prior(
                        ev,
                        self.prior_probs['rand'],
                        self.subtype_probs))
            # The probability of incorrectness is the product of the
            # source-specific probabilities
            neg_prob_prior = 1
            for s in uniq_sources:
                neg_prob_prior *= (syst_factors[s] +
                                   numpy.prod(rand_factors[s]))
            # Finally, the probability of correctness is one minus incorrect
            prob_prior = 1 - neg_prob_prior
            return prob_prior
        pos_evidence = [ev for ev in evidences if
                        not ev.epistemics.get('negated')]
        neg_evidence = [ev for ev in evidences if
                        ev.epistemics.get('negated')]
        pp = _score(pos_evidence)
        np = _score(neg_evidence)
        # The basic assumption is that the positive and negative evidence
        # can't simultaneously be correct.
        # There are two cases to consider. (1) If the positive evidence is
        # incorrect then there is no Statement and the belief should be 0,
        # irrespective of the negative evidence.
        # (2) If the positive evidence is correct and the negative evidence
        # is incorrect.
        # This amounts to the following formula:
        # 0 * (1-pp) + 1 * (pp * (1-np)) which we simplify below
        score = pp * (1 - np)
        return score

    def score_statement(self, st, extra_evidence=None):
        """Computes the prior belief probability for an INDRA Statement.

        The Statement is assumed to be de-duplicated. In other words,
        the Statement is assumed to have
        a list of Evidence objects that supports it. The prior probability of
        the Statement is calculated based on the number of Evidences it has
        and their sources.

        Parameters
        ----------
        st : indra.statements.Statement
            An INDRA Statements whose belief scores are to
            be calculated.
        extra_evidence : list[indra.statements.Evidence]
            A list of Evidences that are supporting the Statement (that aren't
            already included in the Statement's own evidence list.

        Returns
        -------
        belief_score : float
            The computed prior probability for the statement
        """
        if extra_evidence is None:
            extra_evidence = []
        all_evidence = st.evidence + extra_evidence
        return self.score_evidence_list(all_evidence)

    def check_prior_probs(self, statements):
        """Throw Exception if BeliefEngine parameter is missing.

        Make sure the scorer has all the information needed to compute
        belief scores of each statement in the provided list, and raises an
        exception otherwise.

        Parameters
        ----------
        statements : list[indra.statements.Statement]
            List of statements to check
        """
        sources = set()
        for stmt in statements:
            sources |= set([ev.source_api for ev in stmt.evidence])
        for err_type in ('rand', 'syst'):
            for source in sources:
                if source not in self.prior_probs[err_type]:
                    msg = 'BeliefEngine missing probability parameter' + \
                        ' for source: %s' % source
                    raise Exception(msg)

class BayesianScorer(SimpleScorer):
    """This is a belief scorer which assumes a Beta prior and a set of prior
    counts of correct and incorrect instances for a given source. It exposes
    and interface to take additional counts and update its probability
    parameters which can then be used to calculate beliefs on a set of
    Statements.

    Parameters
    ----------
    prior_counts : dict
        A dictionary of counts of the form [pos, neg] for
        each source.
    subtype_counts : dict
        A dictionary of counts of the form [pos, neg] for
        each subtype within a source.
    """
    def __init__(self, prior_counts, subtype_counts):
        self.prior_probs = load_default_probs()
        self.subtype_probs = {}
        self.prior_counts = copy.deepcopy(prior_counts) if prior_counts else {}
        self.subtype_counts = copy.deepcopy(subtype_counts) if subtype_counts \
            else {}
        # Set the probability estimates based on the counts
        self.update_probs()

    def update_probs(self):
        """Update the internal probability values given the counts."""
        # We deal with the prior probsfirst
        # This is a fixed assumed value for systematic error
        syst_error = 0.05
        prior_probs = {'syst': {}, 'rand': {}}
        for source, (p, n) in self.prior_counts.items():
            # Skip if there are no actual counts
            if n + p == 0:
                continue
            prior_probs['syst'][source] = syst_error
            prior_probs['rand'][source] = \
                1 - min((float(p) / (n + p), 1-syst_error)) - syst_error
        # Next we deal with subtype probs based on counts
        subtype_probs = {}
        for source, entry in self.subtype_counts.items():
            for rule, (p, n) in entry.items():
                # Skip if there are no actual counts
                if n + p == 0:
                    continue
                if source not in subtype_probs:
                    subtype_probs[source] = {}
                subtype_probs[source][rule] = \
                    1 - min((float(p) / (n + p), 1-syst_error)) - syst_error
        # Finally we propagate this into the full probability
        # data structures of the parent class
        super(BayesianScorer, self).update_probs(prior_probs, subtype_probs)

    def update_counts(self, prior_counts, subtype_counts):
        """Update the internal counts based on given new counts.

        Parameters
        ----------
        prior_counts : dict
            A dictionary of counts of the form [pos, neg] for
            each source.
        subtype_counts : dict
            A dictionary of counts of the form [pos, neg] for
            each subtype within a source.
        """
        for source, (pos, neg) in prior_counts.items():
            if source not in self.prior_counts:
                self.prior_counts[source] = [0, 0]
            self.prior_counts[source][0] += pos
            self.prior_counts[source][1] += neg
        for source, subtype_dict in subtype_counts.items():
            if source not in self.subtype_counts:
                self.subtype_counts[source] = {}
            for subtype, (pos, neg) in subtype_dict.items():
                if subtype not in self.subtype_counts[source]:
                    self.subtype_counts[source][subtype] = [0, 0]
                self.subtype_counts[source][subtype][0] += pos
                self.subtype_counts[source][subtype][1] += neg
        self.update_probs()

default_scorer = SimpleScorer()

class BeliefEngine(object):
    """Assigns beliefs to INDRA Statements based on supporting evidence.

    Attributes
    ----------
    scorer : BeliefScorer
        A BeliefScorer object that computes the prior probability of a
        statement given its its statment type and evidence.
        Must implement the `score_statement` method which takes
        Statements and computes the belief score of a statement, and the
        `check_prior_probs` method which takes a list of INDRA Statements and
        verifies that the scorer has all the information it needs to score
        every statement in the list, and raises an exception if not.
    """
    def __init__(self, scorer=None, matches_fun=None):
        if scorer is None:
            scorer = default_scorer
        assert(isinstance(scorer, BeliefScorer))
        self.scorer = scorer

        self.matches_fun = matches_fun if matches_fun else \
            lambda stmt: stmt.matches_key()

    def set_prior_probs(self, statements):
        """Sets the prior belief probabilities for a list of INDRA Statements.

        The Statements are assumed to be de-duplicated. In other words,
        each Statement in the list passed to this function is assumed to have
        a list of Evidence objects that support it. The prior probability of
        each Statement is calculated based on the number of Evidences it has
        and their sources.

        Parameters
        ----------
        statements : list[indra.statements.Statement]
            A list of INDRA Statements whose belief scores are to
            be calculated. Each Statement object's belief attribute is updated
            by this function.
        """
        self.scorer.check_prior_probs(statements)
        for st in statements:
            st.belief = self.scorer.score_statement(st)

    def set_hierarchy_probs(self, statements):
        """Sets hierarchical belief probabilities for INDRA Statements.

        The Statements are assumed to be in a hierarchical relation graph with
        the supports and supported_by attribute of each Statement object having
        been set.
        The hierarchical belief probability of each Statement is calculated
        based on its prior probability and the probabilities propagated from
        Statements supporting it in the hierarchy graph.

        Parameters
        ----------
        statements : list[indra.statements.Statement]
            A list of INDRA Statements whose belief scores are to
            be calculated. Each Statement object's belief attribute is updated
            by this function.
        """
        def build_hierarchy_graph(stmts):
            """Return a DiGraph based on matches keys and Statement supports"""
            logger.debug('Building hierarchy graph')
            g = networkx.DiGraph()
            for st1 in stmts:
                g.add_node(self.matches_fun(st1), stmt=st1)
                for st2 in st1.supported_by:
                    g.add_node(self.matches_fun(st2), stmt=st2)
                    g.add_edge(self.matches_fun(st2),
                               self.matches_fun(st1))
            logger.debug('Finished building hierarchy graph')
            return g

        def get_ranked_stmts(g):
            """Return a topological sort of statement matches keys from a graph.
            """
            logger.debug('Getting ranked statements')
            node_ranks = networkx.algorithms.dag.topological_sort(g)
            node_ranks = reversed(list(node_ranks))
            stmts = [g.nodes[n]['stmt'] for n in node_ranks]
            return stmts

        def assert_no_cycle(g):
            """If the graph has cycles, throws AssertionError."""
            logger.debug('Looking for cycles in belief graph')
            try:
                cyc = networkx.algorithms.cycles.find_cycle(g)
            except networkx.exception.NetworkXNoCycle:
                return
            msg = 'Cycle found in hierarchy graph: %s' % cyc
            assert False, msg

        g = build_hierarchy_graph(statements)
        assert_no_cycle(g)
        ranked_stmts = get_ranked_stmts(g)
        logger.debug('Start belief propagation over ranked statements')
        for st in ranked_stmts:
            bps = _get_belief_package(st, self.matches_fun)
            supporting_evidences = []
            # NOTE: the last belief package in the list is this statement's own
            for bp in bps[:-1]:
                # Iterate over all the parent evidences and add only
                # non-negated ones
                for ev in bp.evidences:
                    if not ev.epistemics.get('negated'):
                        supporting_evidences.append(ev)
            # Now add the Statement's own evidence
            # Now score all the evidences
            belief = self.scorer.score_statement(st, supporting_evidences)
            st.belief = belief
        logger.debug('Finished belief propagation over ranked statements')

    def set_linked_probs(self, linked_statements):
        """Sets the belief probabilities for a list of linked INDRA Statements.

        The list of LinkedStatement objects is assumed to come from the
        MechanismLinker. The belief probability of the inferred Statement is
        assigned the joint probability of its source Statements.

        Parameters
        ----------
        linked_statements : list[indra.mechlinker.LinkedStatement]
            A list of INDRA LinkedStatements whose belief scores are to
            be calculated. The belief attribute of the inferred Statement in
            the LinkedStatement object is updated by this function.
        """
        for st in linked_statements:
            source_probs = [s.belief for s in st.source_stmts]
            st.inferred_stmt.belief = numpy.prod(source_probs)

BeliefPackage = namedtuple('BeliefPackage', 'statement_key evidences')

def _get_belief_package(stmt, matches_fun):
    """Return the belief packages of a given statement recursively."""
    # This list will contain the belief packages for the given statement
    belief_packages = []
    # Iterate over all the support parents
    for st in stmt.supports:
        # Recursively get all the belief packages of the parent
        parent_packages = _get_belief_package(st, matches_fun)
        package_stmt_keys = [pkg.statement_key for pkg in belief_packages]
        for package in parent_packages:
            # Only add this belief package if it hasn't already been added
            if package.statement_key not in package_stmt_keys:
                belief_packages.append(package)
    # Now make the Statement's own belief package and append it to the list
    belief_package = BeliefPackage(matches_fun(stmt), stmt.evidence)
    belief_packages.append(belief_package)
    return belief_packages

def sample_statements(stmts, seed=None):
    """Return statements sampled according to belief.

    Statements are sampled independently according to their
    belief scores. For instance, a Staement with a belief
    score of 0.7 will end up in the returned Statement list
    with probability 0.7.

    Parameters
    ----------
    stmts : list[indra.statements.Statement]
        A list of INDRA Statements to sample.
    seed : Optional[int]
        A seed for the random number generator used for sampling.

    Returns
    -------
    new_stmts : list[indra.statements.Statement]
        A list of INDRA Statements that were chosen by random sampling
        according to their respective belief scores.
    """
    if seed:
        numpy.random.seed(seed)
    new_stmts = []
    r = numpy.random.rand(len(stmts))
    for i, stmt in enumerate(stmts):
        if r[i] < stmt.belief:
            new_stmts.append(stmt)
    return new_stmts

def evidence_random_noise_prior(evidence, type_probs, subtype_probs):
    """Determines the random-noise prior probability for this evidence.

    If the evidence corresponds to a subtype, and that subtype has a curated
    prior noise probability, use that.

    Otherwise, gives the random-noise prior for the overall rule type.
    """
    (stype, subtype) = tag_evidence_subtype(evidence)
    # Get the subtype, if available

    # Return the subtype random noise prior, if available
    if subtype_probs is not None:
        if stype in subtype_probs:
            if subtype in subtype_probs[stype]:
                return subtype_probs[stype][subtype]

    # Fallback to just returning the overall evidence type random noise prior
    return type_probs[stype]

def tag_evidence_subtype(evidence):
    """Returns the type and subtype of an evidence object as a string,
    typically the extraction rule or database from which the statement
    was generated.

    For biopax, this is just the database name.

    Parameters
    ----------
    statement: indra.statements.Evidence
        The statement which we wish to subtype

    Returns
    -------
    types: tuple
        A tuple with (type, subtype), both strings
        Returns (type, None) if the type of statement is not yet handled in
        this function.
    """
    source_api = evidence.source_api
    annotations = evidence.annotations

    if source_api == 'biopax':
        subtype = annotations.get('source_sub_id')
    elif source_api in ('reach', 'eidos'):
        if 'found_by' in annotations:
            from indra.sources.reach.processor import determine_reach_subtype
            if source_api == 'reach':
                subtype = determine_reach_subtype(annotations['found_by'])
            elif source_api == 'eidos':
                subtype = annotations['found_by']
            else:
                subtype = None
        else:
            logger.debug('Could not find found_by attribute in reach '
                         'statement annoations')
            subtype = None
    elif source_api == 'geneways':
        subtype = annotations['actiontype']
    else:
        subtype = None

    return (source_api, subtype)


text:
package com.example.litepaldemo.model;

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

import org.litepal.crud.DataSupport;

public class NewsLitePal extends DataSupport
{
	//其中id这个字段可写可不写,因为即使不写这个字段,LitePal也会在表中自动生成一个id列,毕竟每张表都一定要有主键的嘛。
	private int id;
	private String title;
	private String content;
	private Date pulishDate;
	private int commentCount;

	//一对一加引用
	private IntroductionLitePal introduction;
	//一对多
	private List<CommentLitePal> commentList = new ArrayList<CommentLitePal>();
	//多对多
	private List<CategoryLitePal> categoryList = new ArrayList<CategoryLitePal>();
	public int getId()
	{
		return id;
	}
	public void setId(int id)
	{
		this.id = id;
	}
	public String getTitle()
	{
		return title;
	}
	public void setTitle(String title)
	{
		this.title = title;
	}
	public String getContent()
	{
		return content;
	}
	public void setContent(String content)
	{
		this.content = content;
	}
	public Date getPulishDate()
	{
		return pulishDate;
	}
	public void setPulishDate(Date pulishDate)
	{
		this.pulishDate = pulishDate;
	}
	public int getCommentCount()
	{
		return commentCount;
	}
	public void setCommentCount(int commentCount)
	{
		this.commentCount = commentCount;
	}
	public IntroductionLitePal getIntroduction()
	{
		return introduction;
	}
	public void setIntroduction(IntroductionLitePal introduction)
	{
		this.introduction = introduction;
	}
	public List<CommentLitePal> getCommentList()
	{
		return commentList;
	}
	public void setCommentList(List<CommentLitePal> commentList)
	{
		this.commentList = commentList;
	}
	public List<CategoryLitePal> getCategoryList()
	{
		return categoryList;
	}
	public void setCategoryList(List<CategoryLitePal> categoryList)
	{
		this.categoryList = categoryList;
	}

}


text:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Reflection;
using Gallio.Common.Collections;
using Gallio.Common.Reflection;
using Gallio.Runtime.Extensibility;
using Gallio.Runtime.FileTypes;

namespace Gallio.Model
{
    /// <summary>
    /// Describes traits of an <see cref="ITestFramework"/> component.
    /// </summary>
    public class TestFrameworkTraits : Traits
    {
        private readonly string name;
        private AssemblySignature[] frameworkAssemblies;
        private string[] fileTypes;

        /// <summary>
        /// Creates test framework traits.
        /// </summary>
        /// <param name="name">The framework's display name.</param>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="name"/> is null.</exception>
        public TestFrameworkTraits(string name)
        {
            if (name == null)
                throw new ArgumentNullException("name");

            this.name = name;
        }

        /// <summary>
        /// Gets the framework's display name.
        /// </summary>
        public string Name
        {
            get { return name; }
        }

        /// <summary>
        /// Gets or sets the framework's icon, or null if none.
        /// </summary>
        public Icon Icon { get; set; }

        /// <summary>
        /// The version of the test framework.
        /// </summary>
        public string Version { get; set; }

        /// <summary>
        /// Gets or sets the list of framework assembly signatures that are recognized and supported
        /// by this framework component.
        /// </summary>
        /// <remarks>
        /// <para>
        /// The framework manager consults this list to determine whether the framework component
        /// should participate in test exploration.  If none of the named framework assemblies are found
        /// among the test assembly references then the framework component will not be instantiated
        /// during test exploration in order to improve performance.
        /// </para>
        /// <para>
        /// Refer to <see cref="AssemblySignature.Parse" /> for a description of the format of an assembly signature.
        /// </para>
        /// </remarks>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception>
        public AssemblySignature[] FrameworkAssemblies
        {
            get { return frameworkAssemblies ?? EmptyArray<AssemblySignature>.Instance; }
            set
            {
                if (value == null || Array.IndexOf(value, null) >= 0)
                    throw new ArgumentNullException("value");
                frameworkAssemblies = value;
            }
        }

        /// <summary>
        /// Gets or sets the list of file types ids recognized by the framework as test files.
        /// </summary>
        /// <remarks>
        /// <para>
        /// The framework manager consults this list to determine whether the framework component
        /// should participate in test exploration.  If none of the file types match the files
        /// specified by the test source then the framework component will not be instantiated
        /// during test exploration in order to improve performance.
        /// </para>
        /// <para>
        /// For .Net-based test frameworks, the list of file types should probably include "Assembly"
        /// or one of its subtypes.
        /// </para>
        /// </remarks>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null.</exception>
        public string[] FileTypes
        {
            get { return fileTypes ?? EmptyArray<string>.Instance; }
            set
            {
                if (value == null || Array.IndexOf(value, null) >= 0)
                    throw new ArgumentNullException("value");
                fileTypes = value;
            }
        }

        /// <summary>
        /// Returns true if at least one of the assembly references is in <see cref="FrameworkAssemblies"/>.
        /// </summary>
        /// <param name="assemblyReferences">The assembly references.</param>
        /// <returns>True if the framework is compatible.</returns>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="assemblyReferences"/> is null.</exception>
        public bool IsFrameworkCompatibleWithAssemblyReferences(IEnumerable<AssemblyName> assemblyReferences)
        {
            if (assemblyReferences == null)
                throw new ArgumentNullException("assemblyReferences");

            foreach (AssemblyName referencedAssemblyName in assemblyReferences)
            {
                foreach (AssemblySignature assemblySignature in FrameworkAssemblies)
                {
                    if (assemblySignature.IsMatch(referencedAssemblyName))
                        return true;
                }
            }

            return false;
        }

        /// <summary>
        /// Returns true if the file type is the same or a subtype of one of those specified by <see cref="FileTypes"/>.
        /// </summary>
        /// <param name="fileType">The file type.</param>
        /// <param name="fileTypeManager">The file type manager used to resolve file type ids to file types.</param>
        /// <returns>True if the framework is compatible.</returns>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="fileType"/> or <paramref name="fileTypeManager"/> is null.</exception>
        public bool IsFrameworkCompatibleWithFileType(FileType fileType, IFileTypeManager fileTypeManager)
        {
            if (fileType == null)
                throw new ArgumentNullException("fileType");
            if (fileTypeManager == null)
                throw new ArgumentNullException("fileTypeManager");

            foreach (string fileTypeId in FileTypes)
            {
                FileType supportedFileType = fileTypeManager.GetFileTypeById(fileTypeId);
                if (fileType.IsSameOrSubtypeOf(supportedFileType))
                    return true;
            }

            return false;
        }
    }
}


text:
#include <string>

#include <Catch/catch.hpp>

#include <ash/optimistic_buffer.h>

TEST_CASE("optimistic buffer write", "[optimistic_buffer]")
{
    using buffer_type = ash::optimistic_buffer<std::string, 1>;
    buffer_type buf;
    buf.write("hello");
    buf.write("world");
    buf.write("other");
    std::string dest;
    REQUIRE(buf.try_read(dest));
    CHECK(dest == "other");
}


text:
using System;
using System.Linq;

namespace JsonApiDotNetCore
{
    internal static class TypeExtensions
    {
        ///
        /// Whether the specified source type implements or equals the specified interface.
        ///
        public static bool IsOrImplementsInterface(this Type source, Type interfaceType)
        {
            ArgumentGuard.NotNull(interfaceType, nameof(interfaceType));

            if (source == null)
            {
                return false;
            }

            return source == interfaceType || source.GetInterfaces().Any(type => type == interfaceType);
        }

        ///
        /// Gets the name of a type, including the names of its generic type parameters.
        /// <example>
        /// <![CDATA[
        /// KeyValuePair<TimeSpan, Nullable<DateTimeOffset>>
        /// ]]>
        /// </example>
        ///
        public static string GetFriendlyTypeName(this Type type)
        {
            ArgumentGuard.NotNull(type, nameof(type));

            // Based on https://stackoverflow.com/questions/2581642/how-do-i-get-the-type-name-of-a-generic-type-argument.

            if (type.IsGenericType)
            {
                string genericArguments = type.GetGenericArguments().Select(GetFriendlyTypeName)
                    .Aggregate((firstType, secondType) => $"{firstType}, {secondType}");

                return $"{type.Name[..type.Name.IndexOf("`", StringComparison.Ordinal)]}" + $"<{genericArguments}>";
            }

            return type.Name;
        }
    }
}


text:
#ifndef interaction_utils_h
#define interaction_utils_h

#define EXPORT __declspec(dllexport)

#ifdef __cplusplus
extern "C" {
#endif

EXPORT void wait(long millis);
EXPORT void waitWithoutMsgPump(long millis);
EXPORT HWND getChildWindow(HWND hwnd, LPCTSTR name);

#ifdef __cplusplus
}
#endif

#endif