text:
package com.microsoft.azure.management.network.v2020_06_01;

import java.util.Collection;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.microsoft.rest.ExpandableStringEnum;

/**
 * Defines values for PublicIPPrefixSkuName.
 */
public final class PublicIPPrefixSkuName extends ExpandableStringEnum<PublicIPPrefixSkuName> {
    /** Static value Standard for PublicIPPrefixSkuName. */
    public static final PublicIPPrefixSkuName STANDARD = fromString("Standard");

    /**
     * Creates or finds a PublicIPPrefixSkuName from its string representation.
     * @param name a name to look for
     * @return the corresponding PublicIPPrefixSkuName
     */
    @JsonCreator
    public static PublicIPPrefixSkuName fromString(String name) {
        return fromString(name, PublicIPPrefixSkuName.class);
    }

    /**
     * @return known PublicIPPrefixSkuName values
     */
    public static Collection<PublicIPPrefixSkuName> values() {
        return values(PublicIPPrefixSkuName.class);
    }
}


text:
using System.Data.Entity;
using System.Linq;

namespace NuGetGallery
{
    public interface IPackageRegistrationByIdQuery
    {
        PackageRegistration Execute(
            string id,
            bool includePackages,
            bool includeOwners = true);
    }

    public class PackageRegistrationByIdQuery : IPackageRegistrationByIdQuery
    {
        private readonly IEntitiesContext _entities;

        public PackageRegistrationByIdQuery(IEntitiesContext entities)
        {
            _entities = entities;
        }

        public PackageRegistration Execute(
            string id,
            bool includePackages,
            bool includeOwners = true)
        {
            IQueryable<PackageRegistration> query = _entities.PackageRegistrations;

            if (includePackages)
            {
                query = query.Include(packageRegistration => packageRegistration.Packages);
            }

            if (includeOwners)
            {
                query = query.Include(packageRegistration => packageRegistration.Owners);
            }

            return query.SingleOrDefault(pr => pr.Id == id);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
// MvxWindowsPhoneGeoLocationWatcher.cs
// (c) Copyright Cirrious Ltd. http://www.cirrious.com
// MvvmCross is licensed using Microsoft Public License (Ms-PL)
// Contributions and inspirations noted in readme.md and license.txt
//
// Project Lead - Stuart Lodge, @slodge, me@slodge.com

using System;
using System.Device.Location;
using Cirrious.CrossCore.Exceptions;

namespace MvvmCross.Plugins.Location.WindowsPhone
{
    [Obsolete("Use MvxWindowsPhoneLocationWatcher instead")]
    public sealed class MvxWindowsPhoneGeoLocationWatcher : MvxGeoLocationWatcher
    {
        private GeoCoordinateWatcher _geoWatcher;

        public MvxWindowsPhoneGeoLocationWatcher()
        {
            EnsureStopped();
        }

        protected override void PlatformSpecificStart(MvxGeoLocationOptions options)
        {
            if (_geoWatcher != null)
                throw new MvxException("You cannot start the MvxLocation service more than once");

            _geoWatcher =
                new GeoCoordinateWatcher(options.EnableHighAccuracy
                                             ? GeoPositionAccuracy.High
                                             : GeoPositionAccuracy.Default);

            // see https://github.com/slodge/MvvmCross/issues/90 re: _geoWatcher.MovementThreshold
            _geoWatcher.StatusChanged += OnStatusChanged;
            _geoWatcher.PositionChanged += OnPositionChanged;
            _geoWatcher.Start();
        }

        protected override void PlatformSpecificStop()
        {
            EnsureStopped();
        }

        private void EnsureStopped()
        {
            if (_geoWatcher != null)
            {
                _geoWatcher.Stop();
                _geoWatcher.StatusChanged -= OnStatusChanged;
                _geoWatcher.PositionChanged -= OnPositionChanged;
                _geoWatcher = null;
            }
        }

        private void OnPositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            var location = CreateLocation(e.Position.Location, e.Position.Timestamp);
            SendLocation(location);
        }

        private void OnStatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
        {
            switch (e.Status)
            {
                case GeoPositionStatus.NoData:
                case GeoPositionStatus.Disabled:
                    var errorCode = _geoWatcher.Permission == GeoPositionPermission.Denied
                                        ? MvxLocationErrorCode.PermissionDenied
                                        : MvxLocationErrorCode.PositionUnavailable;
                    SendError(errorCode);
                    break;
                case GeoPositionStatus.Initializing:
                case GeoPositionStatus.Ready:
                    // not an error - so ignored
                    break;
                default:
                    // other codes ignored
                    break;
            }
        }

        private static MvxGeoLocation CreateLocation(GeoCoordinate coordinate, DateTimeOffset timestamp)
        {
            var position = new MvxGeoLocation {Timestamp = timestamp};
            var coords = position.Coordinates;

            coords.Altitude = coordinate.Altitude;
            coords.Latitude = coordinate.Latitude;
            coords.Longitude = coordinate.Longitude;
            coords.Speed = coordinate.Speed;
            coords.Accuracy = coordinate.HorizontalAccuracy;
            coords.AltitudeAccuracy = coordinate.VerticalAccuracy;

#warning Heading needed?

            return position;
        }
    }
}


text:
package java.math.test;

import org.bouncycastle.util.test.Test;
import org.bouncycastle.util.test.TestResult;

public class RegressionTest
{
    public static Test[]    tests = {
        new BigIntegerTest()
    };

    public static void main(
        String[]    args)
    {
        for (int i = 0; i != tests.length; i++)
        {
            TestResult  result = tests[i].perform();
            System.out.println(result);
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Created by ModBuddy on 8/22/2013 8:06:59 PM -->
<GameData>
	<!-- Adding a new CityState entry. -->
	<MinorCivilizations>
		<Row>
			<Type>MINOR_CIV_MALI</Type>
			<Description>TXT_KEY_CITYSTATE_MALI</Description>
			<ShortDescription>TXT_KEY_CITYSTATE_MALI</ShortDescription>
			<Adjective>TXT_KEY_CITYSTATE_MALI_ADJ</Adjective>
			<Civilopedia>TXT_KEY_CITYSTATE_MALI_PEDIA</Civilopedia>
			<DefaultPlayerColor>PLAYERCOLOR_MINOR_YELLOW</DefaultPlayerColor>
			<ArtDefineTag>ART_DEF_CIVILIZATION_MINOR</ArtDefineTag>
			<ArtStyleType>ARTSTYLE_MIDDLE_EAST</ArtStyleType>
			<ArtStyleSuffix>_AFRI</ArtStyleSuffix>
			<ArtStylePrefix>AFRICAN</ArtStylePrefix>
			<MinorCivTrait>MINOR_TRAIT_CULTURED</MinorCivTrait>
		</Row>
	</MinorCivilizations>
	<MinorCivilization_CityNames>
		<Row>
			<MinorCivType>MINOR_CIV_MALI</MinorCivType>
			<CityName>TXT_KEY_CITYSTATE_MALI</CityName>
		</Row>
	</MinorCivilization_CityNames>
	<MinorCivilization_Flavors>
		<Row>
			<MinorCivType>MINOR_CIV_MALI</MinorCivType>
			<FlavorType>FLAVOR_EXPANSION</FlavorType>
			<Flavor>9</Flavor>
		</Row>
		<Row>
			<MinorCivType>MINOR_CIV_MALI</MinorCivType>
			<FlavorType>FLAVOR_CITY_DEFENSE</FlavorType>
			<Flavor>4</Flavor>
		</Row>
		<Row>
			<MinorCivType>MINOR_CIV_MALI</MinorCivType>
			<FlavorType>FLAVOR_DEFENSE</FlavorType>
			<Flavor>9</Flavor>
		</Row>
		<Row>
			<MinorCivType>MINOR_CIV_MALI</MinorCivType>
			<FlavorType>FLAVOR_WONDER</FlavorType>
			<Flavor>9</Flavor>
		</Row>
	</MinorCivilization_Flavors>
	<Language_en_US>

		<Row Tag="TXT_KEY_CITYSTATE_MALI_ADJ">
			<Text>Mali</Text>
		</Row>
		<Row Tag="TXT_KEY_CITYSTATE_MALI_PEDIA">
			<Text>No entry available! Sorry.</Text>
		</Row>
	</Language_en_US>
</GameData>


text:
import fs from 'fs-extra';
import path from 'path';
import md5 from 'md5';
import request from 'request-promise';

const readFile = (file: string, start: number, end: number): Promise<Buffer> =>
  new Promise((resolve, reject) => {
    let data;
    const readStream = fs.createReadStream(file, { start, end });
    readStream
      .on('data', (chunk: Buffer) => {
        if (!data) {
          data = chunk;
        } else {
          data = Buffer.concat([data, chunk]);
        }
      })
      .on('end', (): Buffer => resolve(data))
      .on('error', (error: Error) => {
        reject(error);
      });
  });

const getHash = (file: string): Promise<string> =>
  new Promise((resolve, reject) => {
    const readSize = 64 * 1024;
    const contentLength = fs.statSync(file).size;
    readFile(file, 0, readSize - 1)
      .then((start: Buffer) => {
        readFile(file, contentLength - readSize, contentLength)
          .then((end: Buffer) => {
            resolve(md5(Buffer.concat([start, end])));
          })
          .catch((error) => {
            reject(error);
          });
      })
      .catch((error) => {
        reject(error);
      });
  });

const availLan = (file: string): Promise<Array<string>> =>
  new Promise((resolve, reject) => {
    getHash(path.resolve(__dirname, file)).then((hash: string) => {
      const options = {
        url: `http://api.thesubdb.com/?action=search&hash=${hash}`,
        headers: {
          'User-Agent': 'SubDB/1.0 (thesubdb/0.1; https://github.com/MaartenRimaux/thesubdb)',
        },
      };
      request(options)
        .then((result: string) => {
          resolve(result.split(','));
        })
        .catch(reject);
    });
  });

const downSub = (lang: string, file: string): Promise<string> =>
  new Promise((resolve, reject) => {
    getHash(path.resolve(__dirname, file)).then((hash: string) => {
      const options = {
        url: `http://api.thesubdb.com/?action=download&hash=${hash}&language=${lang}`,
        headers: {
          'User-Agent': 'SubDB/1.0 (thesubdb/0.1; https://github.com/MaartenRimaux/thesubdb)',
        },
      };
      request(options)
        .then((result: string) => {
          fs
            .writeFile(
              path.resolve(
                __dirname,
                path.dirname(file),
                `${path.basename(file, path.extname(file))}.srt`,
              ),
              result,
            )
            .then(resolve)
            .catch(reject);
        })
        .catch(reject);
    });
  });

module.exports = {
  downSub,
  availLan,
};


text:
function increasingSequence(sequence){

    var startSequence = 0, length = sequence.length, tempCounter = 1, maxCounter = 1;

    for(var i = 0; i < length; i+=1){
        if(sequence[i] < sequence[i + 1]){
            tempCounter += 1;
        }
        else{
            if(tempCounter > maxCounter){
                maxCounter = tempCounter;
                startSequence = i - maxCounter;
            }

            tempCounter = 1;
        }

    }

    if(maxCounter < 2){
        console.log('There is no increasing sequence');
    }

    else{
        console.log('The max increasing sequence is: ');
        console.log(sequence.slice(startSequence + 1, maxCounter + startSequence + 1));
    }
}

var sequence = [3, 2, 3, 4, 2, 2, 4];

increasingSequence(sequence);


text:
package org.motechproject.mds.util;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.motechproject.mds.helper.MdsBundleHelper;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;

import java.util.Dictionary;
import java.util.Hashtable;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class MdsBundleHelperTest {

    @Mock
    private Bundle entitiesBundle;

    @Mock
    private Bundle mdsBundle;

    @Mock
    private Bundle frameworkBundle;

    @Mock
    private Bundle nullSymNameBundle;

    @Mock
    private Bundle importsMdsBundle;

    @Mock
    private Bundle dynamicImportBundle;

    @Mock
    private Bundle nonMdsBundle;

    @Before
    public void setUp() {
        setUpBundleMock(frameworkBundle, "framework", 0);
        setUpBundleMock(entitiesBundle, Constants.BundleNames.MDS_ENTITIES_SYMBOLIC_NAME, 1);
        setUpBundleMock(mdsBundle, Constants.BundleNames.MDS_BUNDLE_SYMBOLIC_NAME, 2);
        setUpBundleMock(nullSymNameBundle, null, 3);
        setUpBundleMock(importsMdsBundle, "imports", 4, "org.something;org.motechproject.mds");
        setUpBundleMock(dynamicImportBundle, "dynImports", 5, "nonMds.package", "*");
        setUpBundleMock(nonMdsBundle, "nonMds", 6, "nonMds.package");

        when(bundleContext.getBundles()).thenReturn(new Bundle[] {nullSymNameBundle, frameworkBundle, entitiesBundle,
                mdsBundle, importsMdsBundle, dynamicImportBundle, nonMdsBundle});
    }

    @Mock
    private BundleContext bundleContext;

    @Test
    public void shouldReturnAndRecognizeEntitiesBundle() {
        assertEquals(entitiesBundle, MdsBundleHelper.findMdsEntitiesBundle(bundleContext));

        assertTrue(MdsBundleHelper.isMdsEntitiesBundle(entitiesBundle));

        assertFalse(MdsBundleHelper.isMdsEntitiesBundle(mdsBundle));
        assertFalse(MdsBundleHelper.isMdsEntitiesBundle(nullSymNameBundle));
        assertFalse(MdsBundleHelper.isMdsEntitiesBundle(importsMdsBundle));
    }

    @Test
    public void shouldReturnAndRecognizeMdsBundle() {
        assertEquals(mdsBundle, MdsBundleHelper.findMdsBundle(bundleContext));

        assertTrue(MdsBundleHelper.isMdsBundle(mdsBundle));

        assertFalse(MdsBundleHelper.isMdsBundle(entitiesBundle));
        assertFalse(MdsBundleHelper.isMdsBundle(nullSymNameBundle));
        assertFalse(MdsBundleHelper.isMdsBundle(importsMdsBundle));
    }

    @Test
    public void shouldRecognizeTheFrameworkBundle() {
        assertTrue(MdsBundleHelper.isFrameworkBundle(frameworkBundle));

        assertFalse(MdsBundleHelper.isFrameworkBundle(nullSymNameBundle));
        assertFalse(MdsBundleHelper.isFrameworkBundle(mdsBundle));
        assertFalse(MdsBundleHelper.isFrameworkBundle(importsMdsBundle));
    }

    @Test
    public void shouldRecognizeMdsDependentBundles() {
        assertTrue(MdsBundleHelper.isBundleMdsDependent(importsMdsBundle));
        assertTrue(MdsBundleHelper.isBundleMdsDependent(dynamicImportBundle));

        assertFalse(MdsBundleHelper.isBundleMdsDependent(frameworkBundle));
        assertFalse(MdsBundleHelper.isBundleMdsDependent(nullSymNameBundle));
        assertFalse(MdsBundleHelper.isBundleMdsDependent(nonMdsBundle));
    }

    private void setUpBundleMock(Bundle bundle, String symbolicName, long bundleId) {
        setUpBundleMock(bundle, symbolicName, bundleId, null, null);
    }

    private void setUpBundleMock(Bundle bundle, String symbolicName, long bundleId, String imports) {
        setUpBundleMock(bundle, symbolicName, bundleId, imports, null);
    }

    private void setUpBundleMock(Bundle bundle, String symbolicName, long bundleId, String imports, String dynamicImports) {
        when(bundle.getSymbolicName()).thenReturn(symbolicName);
        when(bundle.getBundleId()).thenReturn(bundleId);

        Dictionary<String, String> headers = new Hashtable<>();
        if (imports != null) {
            headers.put(org.osgi.framework.Constants.IMPORT_PACKAGE, imports);
        }
        if (dynamicImports != null) {
            headers.put(org.osgi.framework.Constants.DYNAMICIMPORT_PACKAGE, dynamicImports);
        }

        when(bundle.getHeaders()).thenReturn(headers);
    }
}


text:
using System;
using System.IO;
using ArgData.Entities;

namespace ArgData.Internals
{
    internal static class TrackSectionHeaderReader
    {
        public static InternalTrackSectionHeader Read(BinaryReader reader, int offset)
        {
            reader.BaseStream.Position = offset + 18;
            byte kerbTypeByte = reader.ReadByte();

            reader.BaseStream.Position = offset;

            var header = new InternalTrackSectionHeader
            {
                FirstSectionAngle = reader.ReadUInt16(),
                FirstSectionHeight = reader.ReadInt16(),
                TrackCenterX = reader.ReadInt16(),
                TrackCenterZ = reader.ReadInt16(),
                TrackCenterY = reader.ReadInt16(),
                StartWidth = reader.ReadInt16(),
                PoleSide = reader.ReadInt16() == -768 ? TrackSide.Left : TrackSide.Right,
                PitsSide = reader.ReadByte() == 0 ? TrackSide.Right : TrackSide.Left,
                SurroundingArea = (SurroundingArea)Enum.Parse(typeof(SurroundingArea), reader.ReadByte().ToString()),
                RightVergeStartWidth = reader.ReadByte(),
                LeftVergeStartWidth = reader.ReadByte()
            };

            header.KerbType = GetKerbType(kerbTypeByte);
            reader.BaseStream.Position = offset + 22;
            header.KerbUpperColor = reader.ReadByte();
            reader.BaseStream.Position = offset + 24;
            header.KerbLowerColor = reader.ReadByte();

            if (header.KerbType == KerbType.TripleColor)
            {
                reader.BaseStream.Position = offset + 28;
                header.KerbUpperColor2 = reader.ReadByte();
                reader.BaseStream.Position = offset + 30;
                header.KerbLowerColor2 = reader.ReadByte();
            }

            return header;
        }

        private static KerbType GetKerbType(byte kerbTypeByte)
        {
            return kerbTypeByte == 4 ? KerbType.TripleColor : KerbType.DualColor;
        }
    }
}


text:
package com.senla.rakickaya.courseplanner.ui.actions.students;

import com.senla.rakickaya.courseplanner.api.data_exchange.IRequest;
import com.senla.rakickaya.courseplanner.api.data_exchange.IResponse;
import com.senla.rakickaya.courseplanner.api.data_exchange.enums.TagsRequest;
import com.senla.rakickaya.courseplanner.api.data_exchange.enums.TagsResponse;
import com.senla.rakickaya.courseplanner.api.facade.IFacade;
import com.senla.rakickaya.courseplanner.di.ServiceDI;
import com.senla.rakickaya.courseplanner.facade.dataExchange.RequestBuilder;
import com.senla.rakickaya.courseplanner.ui.api.actions.IAction;
import com.senla.rakickaya.courseplanner.ui.util.input.Input;
import com.senla.rakickaya.courseplanner.ui.util.printer.Printer;

public class StudentAddition implements IAction {
	private ServiceDI service = ServiceDI.getInstance();
	private IFacade facade = (IFacade) service.getObject(IFacade.class);

	@Override
	public void execute() {
		Printer.show("Input student's name : ");
		String name = Input.getInstance().getString();

		IRequest request = new RequestBuilder().setHead(TagsRequest.STUDENT_NAME, name).build();
		IResponse response = facade.addStudent(request);
		Printer.show(response.getObject(TagsResponse.MESSAGE).toString());
	}

}


text:
package ai.subut.kurjun.model.identity;

import java.util.Date;

/**
 *
 */
public interface UserToken
{
    //***********************************
    String getHeader();

    //***********************************
    String getClaims();

    //***********************************
    String getFullToken();

    String getToken();

    void setToken( String token );

    String getSecret();

    void setSecret( String secret );

    String getHashAlgorithm();

    void setHashAlgorithm( String hashAlgorithm );

    String getIssuer();

    void setIssuer( String issuer );

    Date getValidDate();

    void setValidDate( Date validDate );
}


text:
require "test_helper"

class AdobeAirTest < Minitest::Test
  test "detects adobe air" do
    @browser = Browser.new ua: $ua["ADOBE_AIR"]

    assert @browser.adobe_air?
    assert @browser.webkit?
    assert_equal @browser.version, "13"
    assert_equal @browser.full_version, "13.0"
    assert_equal @browser.name, "Other"
  end
end


text:
module lookup
where
import Data.List

myLookup :: Eq a => a -> [(a, b)] -> Maybe b
myLookup _ [] = Nothing
myLookup key ((thiskey, thisval):rest) =
    if key == thiskey
       then Just thisval
       else myLookup key rest


text:
package org.apache.ignite.ml.clustering.gmm;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.DoubleStream;
import java.util.stream.Stream;
import org.apache.ignite.internal.util.typedef.internal.A;
import org.apache.ignite.ml.dataset.Dataset;
import org.apache.ignite.ml.dataset.DatasetBuilder;
import org.apache.ignite.ml.dataset.primitive.builder.context.EmptyContextBuilder;
import org.apache.ignite.ml.dataset.primitive.context.EmptyContext;
import org.apache.ignite.ml.environment.LearningEnvironment;
import org.apache.ignite.ml.environment.logging.MLLogger;
import org.apache.ignite.ml.math.exceptions.math.SingularMatrixException;
import org.apache.ignite.ml.math.functions.IgniteBiFunction;
import org.apache.ignite.ml.math.primitives.matrix.Matrix;
import org.apache.ignite.ml.math.primitives.vector.Vector;
import org.apache.ignite.ml.math.primitives.vector.VectorUtils;
import org.apache.ignite.ml.math.stat.MultivariateGaussianDistribution;
import org.apache.ignite.ml.preprocessing.Preprocessor;
import org.apache.ignite.ml.structures.DatasetRow;
import org.apache.ignite.ml.trainers.SingleLabelDatasetTrainer;
import org.jetbrains.annotations.NotNull;

/**
 * Traner for GMM model.
 */
public class GmmTrainer extends SingleLabelDatasetTrainer<GmmModel> {
    /** Min divergence of mean vectors beween iterations. If divergence will less then trainer stops. */
    private double eps = 1e-3;

    /** Count of components. */
    private int countOfComponents = 2;

    /** Max count of iterations. */
    private int maxCountOfIterations = 10;

    /** Initial means. */
    private Vector[] initialMeans;

    /** Maximum initialization tries count. */
    private int maxCountOfInitTries = 3;

    /**
     * Maximum count of clusters that can be achieved.
     */
    private int maxCountOfClusters = 2;

    /** Maximum divergence between maximum of likelihood of vector in dataset and other for anomalies identification. */
    private double maxLikelihoodDivergence = 5;

    /** Minimum required anomalies in terms of maxLikelihoodDivergence for creating new cluster. */
    private double minElementsForNewCluster = 300;

    /** Min cluster probability. */
    private double minClusterProbability = 0.05;

    /**
     * Creates an instance of GmmTrainer.
     */
    public GmmTrainer() {
    }

    /**
     * Creates an instance of GmmTrainer.
     *
     * @param countOfComponents Count of components.
     * @param maxCountOfIterations Max count of iterations.
     */
    public GmmTrainer(int countOfComponents, int maxCountOfIterations) {
        this.countOfComponents = countOfComponents;
        this.maxCountOfIterations = maxCountOfIterations;
    }

    /**
     * Creates an instance of GmmTrainer.
     *
     * @param countOfComponents Count of components.
     */
    public GmmTrainer(int countOfComponents) {
        this.countOfComponents = countOfComponents;
    }

    /** {@inheritDoc} */
    @Override public <K, V> GmmModel fitWithInitializedDeployingContext(DatasetBuilder<K, V> datasetBuilder,
        Preprocessor<K, V> extractor) {
        return updateModel(null, datasetBuilder, extractor);
    }

    /**
     * Returns mapper for initial means selection.
     *
     * @param n Number of components.
     * @return Mapper.
     */
    private static IgniteBiFunction<GmmPartitionData, LearningEnvironment, Vector[][]> selectNRandomXsMapper(int n) {
        return (data, env) -> {
            Vector[] result;

            if (data.size() <= n) {
                result = data.getAllXs().stream()
                    .map(DatasetRow::features)
                    .toArray(Vector[]::new);
            }
            else {
                result = env.randomNumbersGenerator().ints(0, data.size())
                    .distinct().mapToObj(data::getX).limit(n)
                    .toArray(Vector[]::new);
            }

            return new Vector[][] {result};
        };
    }

    /**
     * Reducer for means selection.
     *
     * @return Reducer.
     */
    private static Vector[][] selectNRandomXsReducer(Vector[][] l, Vector[][] r) {
        A.ensure(l != null || r != null, "l != null || r != null");

        if (l == null)
            return r;
        if (r == null)
            return l;

        Vector[][] res = new Vector[l.length + r.length][];
        System.arraycopy(l, 0, res, 0, l.length);
        System.arraycopy(r, 0, res, l.length, r.length);

        return res;
    }

    /**
     * Sets numberOfComponents.
     *
     * @param numberOfComponents Number of components.
     * @return Trainer.
     */
    public GmmTrainer withInitialCountOfComponents(int numberOfComponents) {
        A.ensure(numberOfComponents > 0, "Number of components in GMM cannot equal 0");

        this.countOfComponents = numberOfComponents;
        initialMeans = null;
        if (countOfComponents > maxCountOfClusters)
            maxCountOfClusters = countOfComponents;
        return this;
    }

    /**
     * Sets initial means.
     *
     * @param means Initial means for clusters.
     * @return Trainer.
     */
    public GmmTrainer withInitialMeans(List<Vector> means) {
        A.notEmpty(means, "GMM should start with non empty initial components list");

        this.initialMeans = means.toArray(new Vector[means.size()]);
        this.countOfComponents = means.size();
        if (countOfComponents > maxCountOfClusters)
            maxCountOfClusters = countOfComponents;
        return this;
    }

    /**
     * Sets max count of iterations
     *
     * @param maxCountOfIterations Max count of iterations.
     * @return Trainer.
     */
    public GmmTrainer withMaxCountIterations(int maxCountOfIterations) {
        A.ensure(maxCountOfIterations > 0, "Max count iterations cannot be less or equal zero or negative");

        this.maxCountOfIterations = maxCountOfIterations;
        return this;
    }

    /**
     * Sets min divergence beween iterations.
     *
     * @param eps Eps.
     * @return Trainer.
     */
    public GmmTrainer withEps(double eps) {
        A.ensure(eps > 0 && eps < 1.0, "Min divergence beween iterations should be between 0.0 and 1.0");

        this.eps = eps;
        return this;
    }

    /**
     * Sets MaxCountOfInitTries parameter. If means initialization were unsuccessful then algorithm try to reinitialize
     * means randomly MaxCountOfInitTries times.
     *
     * @param maxCountOfInitTries Max count of init tries.
     * @return Trainer.
     */
    public GmmTrainer withMaxCountOfInitTries(int maxCountOfInitTries) {
        A.ensure(maxCountOfInitTries > 0, "Max initialization count should be great than zero.");

        this.maxCountOfInitTries = maxCountOfInitTries;
        return this;
    }

    /**
     * Sets maximum number of clusters in GMM.
     *
     * @param maxCountOfClusters Max count of clusters.
     * @return Trainer.
     */
    public GmmTrainer withMaxCountOfClusters(int maxCountOfClusters) {
        A.ensure(maxCountOfClusters >= countOfComponents, "Max count of components should be greater than " +
            "initial count of components or equal to it");

        this.maxCountOfClusters = maxCountOfClusters;
        return this;
    }

    /**
     * Sets maximum divergence between maximum of likelihood of vector in dataset and other for anomalies
     * identification.
     *
     * @param maxLikelihoodDivergence Max likelihood divergence.
     * @return Trainer.
     */
    public GmmTrainer withMaxLikelihoodDivergence(double maxLikelihoodDivergence) {
        A.ensure(maxLikelihoodDivergence > 0, "Max likelihood divergence should be > 0");

        this.maxLikelihoodDivergence = maxLikelihoodDivergence;
        return this;
    }

    /**
     * Trains model based on the specified data.
     *
     * @param dataset Dataset.
     * @return GMM model.
     */
    private Optional<GmmModel> fit(Dataset<EmptyContext, GmmPartitionData> dataset) {
        return init(dataset).map(model -> {
            GmmModel currentModel = model;

            do {
                UpdateResult updateResult = updateModel(dataset, currentModel);
                currentModel = updateResult.model;

                double minCompProb = currentModel.componentsProbs().minElement().get();
                if (countOfComponents >= maxCountOfClusters || minCompProb < minClusterProbability)
                    break;

                double maxXProb = updateResult.maxProbInDataset;
                NewComponentStatisticsAggregator newMeanAdder = NewComponentStatisticsAggregator.computeNewMean(dataset,
                    maxXProb, maxLikelihoodDivergence, currentModel);

                Vector newMean = newMeanAdder.mean();
                if (newMeanAdder.rowCountForNewCluster() < minElementsForNewCluster)
                    break;

                countOfComponents += 1;
                Vector[] newMeans = new Vector[countOfComponents];
                for (int i = 0; i < currentModel.countOfComponents(); i++)
                    newMeans[i] = currentModel.distributions().get(i).mean();
                newMeans[countOfComponents - 1] = newMean;

                initialMeans = newMeans;

                Optional<GmmModel> newModelOpt = init(dataset);
                if (newModelOpt.isPresent())
                    currentModel = newModelOpt.get();
                else
                    break;
            }
            while (true);

            return filterModel(currentModel);
        });
    }

    /**
     * Sets minimum required anomalies in terms of maxLikelihoodDivergence for creating new cluster.
     *
     * @param minElementsForNewCluster Min elements for new cluster.
     * @return Trainer.
     */
    public GmmTrainer withMinElementsForNewCluster(int minElementsForNewCluster) {
        A.ensure(minElementsForNewCluster > 0, "Min elements for new cluster should be > 0");

        this.minElementsForNewCluster = minElementsForNewCluster;
        return this;
    }

    /**
     * Sets minimum requred probability for cluster. If cluster has probability value less than this value then this
     * cluster will be eliminated.
     *
     * @param minClusterProbability Min cluster probability.
     * @return Trainer.
     */
    public GmmTrainer withMinClusterProbability(double minClusterProbability) {
        this.minClusterProbability = minClusterProbability;
        return this;
    }

    /**
     * Result of current model update by EM-algorithm.
     */
    private static class UpdateResult {
        /** Model. */
        private final GmmModel model;

        /** Max likelihood in dataset. */
        private final double maxProbInDataset;

        /**
         * @param model Model.
         * @param maxProbInDataset Max likelihood in dataset.
         */
        public UpdateResult(GmmModel model, double maxProbInDataset) {
            this.model = model;
            this.maxProbInDataset = maxProbInDataset;
        }
    }

    /**
     * Remove clusters with probability value < minClusterProbability
     *
     * @param model Model.
     * @return Filtered model.
     */
    private GmmModel filterModel(GmmModel model) {
        List<Double> componentProbs = new ArrayList<>();
        List<MultivariateGaussianDistribution> distributions = new ArrayList<>();

        Vector originalComponentProbs = model.componentsProbs();
        List<MultivariateGaussianDistribution> originalDistr = model.distributions();
        for (int i = 0; i < model.countOfComponents(); i++) {
            double prob = originalComponentProbs.get(i);
            if (prob > minClusterProbability) {
                componentProbs.add(prob);
                distributions.add(originalDistr.get(i));
            }
        }

        return new GmmModel(
            VectorUtils.of(componentProbs.toArray(new Double[0])),
            distributions
        );
    }

    /**
     * Gets older model and returns updated model on given data.
     *
     * @param dataset Dataset.
     * @param model Model.
     * @return Updated model.
     */
    @NotNull private UpdateResult updateModel(Dataset<EmptyContext, GmmPartitionData> dataset, GmmModel model) {
        boolean isConverged = false;
        int countOfIterations = 0;
        double maxProbInDataset = Double.NEGATIVE_INFINITY;
        while (!isConverged) {
            MeanWithClusterProbAggregator.AggregatedStats stats = MeanWithClusterProbAggregator.aggreateStats(dataset, countOfComponents);
            Vector clusterProbs = stats.clusterProbabilities();
            Vector[] newMeans = stats.means().toArray(new Vector[countOfComponents]);

            A.ensure(newMeans.length == model.countOfComponents(), "newMeans.size() == count of components");
            A.ensure(newMeans[0].size() == initialMeans[0].size(), "newMeans[0].size() == initialMeans[0].size()");
            List<Matrix> newCovs = CovarianceMatricesAggregator.computeCovariances(dataset, clusterProbs, newMeans);

            try {
                List<MultivariateGaussianDistribution> components = buildComponents(newMeans, newCovs);
                GmmModel newModel = new GmmModel(clusterProbs, components);

                countOfIterations += 1;
                isConverged = isConverged(model, newModel) || countOfIterations > maxCountOfIterations;
                model = newModel;
                maxProbInDataset = GmmPartitionData.updatePcxiAndComputeLikelihood(dataset, clusterProbs, components);
            }
            catch (SingularMatrixException | IllegalArgumentException e) {
                String msg = "Cannot construct non-singular covariance matrix by data. " +
                    "Try to select other initial means or other model trainer. Iterations will stop.";
                environment.logger().log(MLLogger.VerboseLevel.HIGH, msg);
                isConverged = true;
            }
        }

        return new UpdateResult(model, maxProbInDataset);
    }

    /**
     * Init means and covariances.
     *
     * @param dataset Dataset.
     * @return Initial model.
     */
    private Optional<GmmModel> init(Dataset<EmptyContext, GmmPartitionData> dataset) {
        int cntOfTries = 0;

        while (true) {
            try {
                if (initialMeans == null) {
                    List<Vector> randomMeansSets = Stream.of(dataset.compute(
                        selectNRandomXsMapper(countOfComponents),
                        GmmTrainer::selectNRandomXsReducer))
                        .flatMap(Stream::of)
                        .sorted(Comparator.comparingDouble(Vector::getLengthSquared)).collect(Collectors.toList());

                    Collections.shuffle(randomMeansSets, environment.randomNumbersGenerator());

                    A.ensure(
                        randomMeansSets.size() >= countOfComponents,
                        "There is not enough data in dataset for select N random means"
                    );

                    initialMeans = randomMeansSets.subList(0, countOfComponents)
                        .toArray(new Vector[countOfComponents]);
                }

                dataset.compute(data -> GmmPartitionData.estimateLikelihoodClusters(data, initialMeans));

                List<Matrix> initialCovs = CovarianceMatricesAggregator.computeCovariances(
                    dataset,
                    VectorUtils.fill(1. / countOfComponents, countOfComponents),
                    initialMeans
                );

                if (initialCovs.isEmpty())
                    return Optional.empty();

                List<MultivariateGaussianDistribution> distributions = new ArrayList<>();
                for (int i = 0; i < countOfComponents; i++)
                    distributions.add(new MultivariateGaussianDistribution(initialMeans[i], initialCovs.get(i)));

                return Optional.of(new GmmModel(
                    VectorUtils.of(DoubleStream.generate(() -> 1. / countOfComponents).limit(countOfComponents).toArray()),
                    distributions
                ));
            }
            catch (SingularMatrixException | IllegalArgumentException e) {
                String msg = "Cannot construct non-singular covariance matrix by data. " +
                    "Try to select other initial means or other model trainer [number of tries = " + cntOfTries + "]";
                environment.logger().log(MLLogger.VerboseLevel.HIGH, msg);
                cntOfTries += 1;
                initialMeans = null;
                if (cntOfTries >= maxCountOfInitTries)
                    throw new RuntimeException(msg, e);
            }
        }
    }

    /** {@inheritDoc} */
    @Override public boolean isUpdateable(GmmModel mdl) {
        return mdl.countOfComponents() == countOfComponents;
    }

    /** {@inheritDoc} */
    @Override protected <K, V> GmmModel updateModel(GmmModel mdl, DatasetBuilder<K, V> datasetBuilder,
        Preprocessor<K, V> extractor) {

        try (Dataset<EmptyContext, GmmPartitionData> dataset = datasetBuilder.build(envBuilder,
            new EmptyContextBuilder<>(),
            new GmmPartitionData.Builder<>(extractor, maxCountOfClusters),
            learningEnvironment()
        )) {
            if (mdl != null) {
                if (initialMeans != null)
                    environment.logger().log(MLLogger.VerboseLevel.HIGH, "Initial means will be replaced by model from update");
                initialMeans = mdl.distributions().stream()
                    .map(MultivariateGaussianDistribution::mean)
                    .toArray(Vector[]::new);
            }

            Optional<GmmModel> model = fit(dataset);
            if (model.isPresent())
                return model.get();
            else if (mdl != null)
                return mdl;
            else
                throw new IllegalArgumentException("Cannot learn model on empty dataset.");
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Create new model components with provided means and covariances.
     *
     * @param means Means.
     * @param covs Covariances.
     * @return Gmm components.
     */
    private List<MultivariateGaussianDistribution> buildComponents(Vector[] means, List<Matrix> covs) {
        A.ensure(means.length == covs.size(), "means.size() == covs.size()");

        List<MultivariateGaussianDistribution> res = new ArrayList<>();
        for (int i = 0; i < means.length; i++)
            res.add(new MultivariateGaussianDistribution(means[i], covs.get(i)));

        return res;
    }

    /**
     * Check algorithm covergency. If it's true then algorithm stops.
     *
     * @param oldModel Old model.
     * @param newModel New model.
     * @return True if algorithm gonverged.
     */
    private boolean isConverged(GmmModel oldModel, GmmModel newModel) {
        A.ensure(oldModel.countOfComponents() == newModel.countOfComponents(),
            "oldModel.countOfComponents() == newModel.countOfComponents()");

        for (int i = 0; i < oldModel.countOfComponents(); i++) {
            MultivariateGaussianDistribution d1 = oldModel.distributions().get(i);
            MultivariateGaussianDistribution d2 = newModel.distributions().get(i);

            if (Math.sqrt(d1.mean().getDistanceSquared(d2.mean())) >= eps)
                return false;
        }

        return true;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Authors:
* Shirayuki
-->
<resources>
  <string name="crash_dialog_title">Title of dialog to show when the app crashes</string>
  <string name="crash_dialog_comment_prompt">Prompt asking people to enter info about what they were doing when the app crashed</string>
  <string name="crash_dialog_ok_toast">Toast to be displayed once someone sends an error report thanking them.\n{{Identical|Thank you}}</string>
</resources>


text:
require 'rubygems'
require 'net/https'
#require 'httparty'

module BoxcarNotifier

  # for notifications - https://new.boxcar.io/api/notifications
  class Notifier
    attr_accessor :access_token

    def initialize(access_token=nil)
      @access_token = access_token
      @boxcarurl = URI.parse('https://new.boxcar.io/api/notifications')
      @https = Net::HTTP.new(@boxcarurl.host, @boxcarurl.port)
      @https.use_ssl = true
    end

    def notify(title, message, options = {:sound => "bird-1", :source_name => nil})
      request = Net::HTTP::Post.new(@boxcarurl.path)
      request.set_form_data(
        {
          "user_credentials" => @access_token,
          "notification[title]" => title,
          "notification[long_message]" => message,
          "notification[sound]" => options[:sound],
          "notification[source_name]" => options[:source_name]
        }
      )
      res = @https.request(request)
    end
  end
end


text:
/**
 */
package io.yaktor.conversation.impl;

import io.yaktor.conversation.ConversationPackage;
import io.yaktor.conversation.TypeImport;
import io.yaktor.types.Projection;

import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;

/**
 *
 * An implementation of the model object 'Type Import'.
 *
 *

 * The following features are implemented:
 *

 *
{@link io.yaktor.conversation.impl.TypeImportImpl#getType Type}

 *

 *

 *
 * @generated
 */
public class TypeImportImpl extends ImportImpl implements TypeImport {
	/**
	 * The cached value of the '{@link #getType() Type}' reference.
	 *
	 *
	 * @see #getType()
	 * @generated
	 * @ordered
	 */
	protected Projection type;

	/**
	 *
	 *
	 * @generated
	 */
	protected TypeImportImpl() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	protected EClass eStaticClass() {
		return ConversationPackage.Literals.TYPE_IMPORT;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public Projection getType() {
		if (type != null && type.eIsProxy()) {
			InternalEObject oldType = (InternalEObject)type;
			type = (Projection)eResolveProxy(oldType);
			if (type != oldType) {
				if (eNotificationRequired())
					eNotify(new ENotificationImpl(this, Notification.RESOLVE, ConversationPackage.TYPE_IMPORT__TYPE, oldType, type));
			}
		}
		return type;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public Projection basicGetType() {
		return type;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setType(Projection newType) {
		Projection oldType = type;
		type = newType;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, ConversationPackage.TYPE_IMPORT__TYPE, oldType, type));
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public Object eGet(int featureID, boolean resolve, boolean coreType) {
		switch (featureID) {
			case ConversationPackage.TYPE_IMPORT__TYPE:
				if (resolve) return getType();
				return basicGetType();
		}
		return super.eGet(featureID, resolve, coreType);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
			case ConversationPackage.TYPE_IMPORT__TYPE:
				setType((Projection)newValue);
				return;
		}
		super.eSet(featureID, newValue);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eUnset(int featureID) {
		switch (featureID) {
			case ConversationPackage.TYPE_IMPORT__TYPE:
				setType((Projection)null);
				return;
		}
		super.eUnset(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case ConversationPackage.TYPE_IMPORT__TYPE:
				return type != null;
		}
		return super.eIsSet(featureID);
	}

} //TypeImportImpl


text:
<?php
// Call Zend_Form_Decorator_ImageTest::main() if this source file is executed directly.
if (!defined("PHPUnit_MAIN_METHOD")) {
    define("PHPUnit_MAIN_METHOD", "Zend_Form_Decorator_ImageTest::main");
}

require_once dirname(__FILE__) . '/../../../TestHelper.php';
require_once "PHPUnit/Framework/TestCase.php";
require_once "PHPUnit/Framework/TestSuite.php";

require_once 'Zend/Form/Decorator/Image.php';

require_once 'Zend/Form.php';
require_once 'Zend/Form/Element.php';
require_once 'Zend/Form/Element/Image.php';
require_once 'Zend/View.php';

/**
 * Test class for Zend_Form_Decorator_Image
 */
class Zend_Form_Decorator_ImageTest extends PHPUnit_Framework_TestCase
{
    /**
     * Runs the test methods of this class.
     *
     * @return void
     */
    public static function main()
    {
        require_once "PHPUnit/TextUI/TestRunner.php";

        $suite  = new PHPUnit_Framework_TestSuite("Zend_Form_Decorator_ImageTest");
        $result = PHPUnit_TextUI_TestRunner::run($suite);
    }

    /**
     * Sets up the fixture, for example, open a network connection.
     * This method is called before a test is executed.
     *
     * @return void
     */
    public function setUp()
    {
        $this->decorator = new Zend_Form_Decorator_Image();
    }

    /**
     * Tears down the fixture, for example, close a network connection.
     * This method is called after a test is executed.
     *
     * @return void
     */
    public function tearDown()
    {
    }

    public function getView()
    {
        $view = new Zend_View();
        $view->addHelperPath(dirname(__FILE__) . '/../../../../library/Zend/View/Helper');
        return $view;
    }

    public function testPlacementInitiallyAppends()
    {
        $this->assertEquals(Zend_Form_Decorator_Abstract::APPEND, $this->decorator->getPlacement());
    }

    public function testRenderReturnsOriginalContentWhenNoViewPresentInElement()
    {
        $element = new Zend_Form_Element('foo');
        $this->decorator->setElement($element);
        $content = 'test content';
        $this->assertSame($content, $this->decorator->render($content));
    }

    public function testTagInitiallyNull()
    {
        $this->assertNull($this->decorator->getTag());
    }

    public function testCanSetTag()
    {
        $this->testTagInitiallyNull();
        $this->decorator->setTag('div');
        $this->assertEquals('div', $this->decorator->getTag());
    }

    public function testCanSetTagViaOptions()
    {
        $this->testTagInitiallyNull();
        $this->decorator->setOption('tag', 'div');
        $this->assertEquals('div', $this->decorator->getTag());
    }

    public function testRendersXhtmlImageTag()
    {
        $element = new Zend_Form_Element_Image('foo');
        $element->setImage('foobar')
                ->setView($this->getView());
        $this->decorator->setElement($element);

        $image = $this->decorator->render('');
        $this->assertContains('<input', $image, $image);
        $this->assertContains('src="foobar"', $image);
        $this->assertContains('name="foo"', $image);
        $this->assertContains('type="image"', $image);
    }

    public function testCanRenderImageWithinAdditionalTag()
    {
        $element = new Zend_Form_Element_Image('foo');
        $element->setValue('foobar')
                ->setView($this->getView());
        $this->decorator->setElement($element)
                        ->setOption('tag', 'div');

        $image = $this->decorator->render('');
        $this->assertRegexp('#<div>.*?<input[^>]*>.*?</div>#s', $image, $image);
    }

    public function testCanPrependImageToContent()
    {
        $element = new Zend_Form_Element_Image('foo');
        $element->setValue('foobar')
                ->setView($this->getView());
        $this->decorator->setElement($element)
                        ->setOption('placement', 'prepend');

        $image = $this->decorator->render('content');
        $this->assertRegexp('#<input[^>]*>.*?(content)#s', $image, $image);
    }

    /**
     * @see ZF-2714
     */
    public function testImageElementAttributesPassedWithDecoratorOptionsToViewHelper()
    {
        $element = new Zend_Form_Element_Image('foo');
        $element->setValue('foobar')
                ->setAttrib('onClick', 'foo()')
                ->setAttrib('id', 'foo-element')
                ->setView($this->getView());
        $this->decorator->setElement($element)
                        ->setOption('class', 'imageclass');

        $image = $this->decorator->render('');
        $this->assertContains('class="imageclass"', $image);
        $this->assertContains('onClick="foo()"', $image);
        $this->assertContains('id="foo-element"', $image);
    }
}

// Call Zend_Form_Decorator_ImageTest::main() if this source file is executed directly.
if (PHPUnit_MAIN_METHOD == "Zend_Form_Decorator_ImageTest::main") {
    Zend_Form_Decorator_ImageTest::main();
}


text:
/**
 * Adjusts request paths for JS and CSS assets such that an asset requested via
 * a path '/v1.2.3/js/foo.js' will be changed to '/js/foo.js' before the static
 * file serving middleware gets a chance to handle it. This enables aggressive
 * cache settings for static assets as long as the frontend code is able to
 * update its paths with the current app version.
 */

module.exports = staticVersioning;

var types = ['js','css'];

function* staticVersioning (next) {
    if ( this.method != 'GET' && this.method != 'HEAD' ) {
        yield next;
        return;
    }
    var ext = this.path.split('.').pop();
    if ( types.indexOf(ext) == -1 ) {
        yield next;
        return;
    }
    this.path = this.path.replace(/\/v\d+.\d+.\d+/,'');
    yield next;
}


text:
import numpy
from PIL import Image
import argparse
import cv2
import os
import timeit
from UpdatedImageProcessing import *

image_path = (os.path.expanduser("~/Desktop/2.jpg"))
print SingleTargetMapDetector.detect_single_target_map(image_path)

#Run IntegratedImageProcessing
"""
target_map_path = os.path.expanduser("~/Desktop/Synthetic_Dataset/Answers/modular_target_maps")
autonomous_image_processing_save_path = os.path.expanduser("~/Desktop/Save_Path")

_processing(target_map_path, autonomous_image_processing_save_path)
"""

#Find average color of an image
'''
target_map_image = Image.open("/Users/zyin/Desktop/Synthetic_Dataset/Backgrounds/06150460.jpg")

total_r = 0
total_g = 0
total_b = 0
area = 0
pixel_access_target_map_image = target_map_image.load()

for x in range(target_map_image.width):
    for y in range(target_map_image.height):
        area += 1
        total_r += pixel_access_target_map_image[x, y][0]
        total_g += pixel_access_target_map_image[x, y][1]
        total_b += pixel_access_target_map_image[x, y][2]

average_r = total_r / area
average_g = total_g / area
average_b = total_b / area
average_color = (average_r, average_g, average_b)

print average_color
print ColorOperations.find_percentage_difference((38, 37, 19), average_color)
'''


text:
ag(1) -- The Silver Searcher. Like ack, but faster.
=============================================

## SYNOPSIS

`ag` [_options_] _pattern_ [_path ..._]

## DESCRIPTION

Recursively search for PATTERN in PATH. Like grep or ack, but faster.

## OPTIONS

  * `--ackmate`:
    Output results in a format parseable by [AckMate](https://github.com/protocool/AckMate).

  * `--[no]affinity`:
    Set thread affinity (if platform supports it). Default is true.

  * `-a --all-types`:
    Search all files. This doesn't include hidden files, and doesn't respect any ignore files.

  * `-A --after [LINES]`:
    Print lines after match. If not provided, LINES defaults to 2.

  * `-B --before [LINES]`:
    Print lines before match. If not provided, LINES defaults to 2.

  * `--[no]break`:
    Print a newline between matches in different files. Enabled by default.

  * `-c --count`:
    Only print the number of matches in each file.
    Note: This is the number of matches, **not** the number of matching lines.
    Pipe output to `wc -l` if you want the number of matching lines.

  * `--[no]color`:
    Print color codes in results. Enabled by default.

  * `--color-line-number`:
    Color codes for line numbers. Default is 1;33.

  * `--color-match`:
    Color codes for result match numbers. Default is 30;43.

  * `--color-path`:
    Color codes for path names. Default is 1;32.

  * `--column`:
    Print column numbers in results.

  * `-C --context [LINES]`:
    Print lines before and after matches. Default is 2.

  * `-D --debug`:
    Output ridiculous amounts of debugging info. Not useful unless you're actually debugging.

  * `--depth NUM`:
    Search up to NUM directories deep, -1 for unlimited. Default is 25.

  * `--[no]filename`:
    Print file names. Enabled by default, except when searching a single file.

  * `-f --[no]follow`:
    Follow symlinks. Default is false.

  * `-F --fixed-strings`:
    Alias for --literal for compatibility with grep.

  * `--[no]group`:
    The default, `--group`, lumps multiple matches in the same file
    together, and presents them under a single occurrence of the
    filename. `--nogroup` refrains from this, and instead places the
    filename at the start of each match line.

  * `-g PATTERN`:
    Print filenames matching PATTERN.

  * `-G --file-search-regex PATTERN`:
    Only search files whose names match PATTERN.

  * `-H --[no]heading`:
    Print filenames above matching contents.

  * `--hidden`:
    Search hidden files. This option obeys ignored files.

  * `--ignore PATTERN`:
    Ignore files/directories whose names match this pattern. Literal
    file and directory names are also allowed.

  * `--ignore-dir NAME`:
    Alias for --ignore for compatibility with ack.

  * `-i --ignore-case`:
    Match case-insensitively.

  * `-l --files-with-matches`:
    Only print the names of files containing matches, not the matching
    lines. An empty query will print all files that would be searched.

  * `-L --files-without-matches`:
    Only print the names of files that don't contain matches.

  * `--list-file-types`:
    See `FILE TYPES` below.

  * `-m --max-count NUM`:
    Skip the rest of a file after NUM matches. Default is 0, which never skips.

  * `--[no]mmap`:
    Toggle use of memory-mapped I/O. Defaults to true.

  * `--[no]multiline`:
    Match regexes across newlines. Enabled by default.

  * `-n --norecurse`:
    Don't recurse into directories.

  * `--[no]numbers`:
    Print line numbers. Default is to omit line numbers when searching streams.

  * `-o --only-matching`:
    Print only the matching part of the lines.

  * `--one-device`:
    When recursing directories, don't scan dirs that reside on other storage
    devices. This lets you avoid scanning slow network mounts.
    This feature is not supported on all platforms.

  * `-p --path-to-ignore STRING`:
    Provide a path to a specific .ignore file.

  * `--pager COMMAND`:
    Use a pager such as `less`. Use `--nopager` to override. This option
    is also ignored if output is piped to another program.

  * `--parallel`:
    Parse the input stream as a search term, not data to search. This is meant
    to be used with tools such as GNU parallel. For example:
    `echo "foo\nbar\nbaz" | parallel "ag {} ."` will run 3 instances of ag,
    searching the current directory for "foo", "bar", and "baz".

  * `--print-long-lines`:
    Print matches on very long lines (> 2k characters by default).

  * `--passthrough --passthru`:
    When searching a stream, print all lines even if they don't match.

  * `-Q --literal`:
    Do not parse PATTERN as a regular expression. Try to match it literally.

  * `-r --recurse`:
    Recurse into directories when seacrhing. Default is true.

  * `-s --case-sensitive`:
    Match case-sensitively.

  * `-S --smart-case`:
    Match case-sensitively if there are any uppercase letters in PATTERN,
    case-insensitively otherwise. Enabled by default.

  * `--search-binary`:
    Search binary files for matches.

  * `--silent`:
    Suppress all log messages, including errors.

  * `--stats`:
    Print stats (files scanned, time taken, etc).

  * `--stats-only`:
    Print stats (files scanned, time taken, etc) and nothing else.

  * `-t --all-text`:
    Search all text files. This doesn't include hidden files.

  * `-u --unrestricted`:
    Search *all* files. This ignores .ignore, .gitignore, etc. It searches
    binary and hidden files as well.

  * `-U --skip-vcs-ignores`:
    Ignore VCS ignore files (.gitignore, .hgignore, svn:ignore), but still
    use .ignore.

  * `-v --invert-match`:
    Match every line *not* containing the specified pattern.

  * `-V --version`:
    Print version info.

  * `--vimgrep`:
    Output results in the same form as Vim's `:vimgrep /pattern/g`

    Here is a ~/.vimrc configuration example:

    `set grepprg=ag\ --vimgrep\ $*`
    `set grepformat=%f:%l:%c:%m`

    Then use `:grep` to grep for something.
    Then use `:copen`, `:cn`, `:cp`, etc. to navigate through the matches.

  * `-w --word-regexp`:
    Only match whole words.

  * `--workers NUM`:
    Use NUM worker threads. Default is the number of CPU cores, with a max of 8.

  * `-z --search-zip`:
    Search contents of compressed files. Currently, gz and xz are supported.
    This option requires that ag is built with lzma and zlib.

  * `-0 --null --print0`:
    Separate the filenames with `\0`, rather than `\n`:
    this allows `xargs -0 <command>` to correctly process filenames containing
    spaces or newlines.

## FILE TYPES

It is possible to restrict the types of files searched. For example, passing
`--html` will search only files with the extensions `htm`, `html`, `shtml`
or `xhtml`. For a list of supported types, run `ag --list-file-types`.

## IGNORING FILES

By default, ag will ignore files whose names match patterns in .gitignore,
.hgignore, or .ignore. These files can be anywhere in the directories being
searched. Ag also ignores files matched by the svn:ignore property if `svn
--version` is 1.6 or older.  Finally, ag looks in $HOME/.agignore for ignore
patterns. Binary files are ignored by default as well.

If you want to ignore .gitignore, .hgignore, and svn:ignore, but still take
.ignore into account, use `-U`.

Use the `-t` option to search all text files; `-a` to search all files; and `-u`
to search all, including hidden files.

## EXAMPLES

`ag printf`:
  Find matches for "printf" in the current directory.

`ag foo /bar/`:
  Find matches for "foo" in path /bar/.

`ag -- --foo`:
  Find matches for "--foo" in the current directory. (As with most UNIX command
  line utilities, "--" is used to signify that the remaining arguments should
  not be treated as options.)

## SEE ALSO

grep(1)


text:
package xdroid.widget;

import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.database.Cursor;
import android.net.Uri;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Adapter;
import android.widget.ListView;
import android.widget.WrapperListAdapter;

import java.io.Serializable;

import xdroid.adapter.AdapterExt;
import xdroid.adapter.CursorAdapterExt;
import xdroid.adapter.IAdapter;
import xdroid.adapter.ViewBinder;
import xdroid.adapter.ViewTypeResolver;
import xdroid.collections.Indexed;
import xdroid.collections.Prototypes;
import xdroid.core.ParcelUtils;
import xdroid.core.ReflectUtils;

import static xdroid.core.ObjectUtils.isEmpty;
import static xdroid.core.ObjectUtils.isNotEmpty;

public class ListViewExt extends ListView {
    public static final int ADAPTER_DATA_NONE = 0;
    public static final int ADAPTER_DATA_ARRAY_LIST = 1;
    public static final int ADAPTER_DATA_LINKED_LIST = 2;
    public static final int ADAPTER_DATA_CURSOR = 3;

    private boolean mKeepData;

    public boolean isKeepData() {
        return mKeepData;
    }

    public void setKeepData(boolean keepData) {
        mKeepData = keepData;
    }

    public ListViewExt(Context context) {
        super(context);
        init(context, null, 0);
    }

    public ListViewExt(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs, 0);
    }

    public ListViewExt(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs, defStyle);
    }

    private void init(Context context, AttributeSet attrs, @SuppressWarnings("unused") int defStyle) {
        if (isInEditMode()) {
            return;
        }

        mKeepData = true;

        if (attrs == null) {
            return;
        }

        if (context == null) {
            return;
        }

        Resources resources = context.getResources();
        if (resources == null) {
            return;
        }

        TypedArray a = resources.obtainAttributes(attrs, R.styleable.ListViewExt);
        if (a == null) {
            return;
        }

        try {
            switch (a.getInt(R.styleable.ListViewExt_adapterData, ADAPTER_DATA_NONE)) {
                case ADAPTER_DATA_ARRAY_LIST:
                    initAdapter(context, a, new AdapterExt(), Prototypes.newArrayList());
                    break;
                case ADAPTER_DATA_LINKED_LIST:
                    initAdapter(context, a, new AdapterExt(), Prototypes.newLinkedList());
                    break;
                case ADAPTER_DATA_CURSOR:
                    initCursorAdapter(context, a);
                    break;
            }
        } finally {
            a.recycle();
        }
    }

    private void initAdapter(Context context, TypedArray a, IAdapter adapter) {
        int layoutId = a.getResourceId(R.styleable.ListViewExt_adapterLayoutId, 0);
        if (layoutId != 0) {
            adapter.setLayoutId(layoutId);
        }

        int layoutIdsArray = a.getResourceId(R.styleable.ListViewExt_adapterLayoutIdsArray, 0);
        if (layoutIdsArray != 0) {
            TypedArray layouts = context.getResources().obtainTypedArray(layoutIdsArray);
            try {
                int count = layouts.length();
                for (int i = 0; i < count; ++i) {
                    adapter.putLayoutId(i, layouts.getResourceId(i, 0));
                }
            } finally {
                layouts.recycle();
            }
        }

        String binderClass = a.getString(R.styleable.ListViewExt_adapterBinderClass);
        if (isNotEmpty(binderClass)) {
            //noinspection unchecked
            adapter.setBinder(ReflectUtils.<ViewBinder>newInstanceByClassName(ReflectUtils.fullClassName(context, binderClass)));
        }

        String viewTypeResolverClass = a.getString(R.styleable.ListViewExt_adapterViewTypeResolverClass);
        if (isNotEmpty(viewTypeResolverClass)) {
            //noinspection unchecked
            adapter.setViewTypeResolver(ReflectUtils.<ViewTypeResolver>newInstanceByClassName(ReflectUtils.fullClassName(context, viewTypeResolverClass)));
        }
    }

    @SuppressWarnings("unchecked")
    private void initAdapter(Context context, TypedArray a, AdapterExt adapter, Indexed data) {
        adapter.setData(data);

        initAdapter(context, a, adapter);
        setAdapter(adapter);
    }

    @SuppressWarnings("unchecked")
    private void initCursorAdapter(Context context, TypedArray a) {
        String uri = a.getString(R.styleable.ListViewExt_adapterCursorQuery);
        if (isEmpty(uri)) {
            return;
        }

        Cursor cursor = context.getContentResolver().query(Uri.parse(uri), null, null, null, null);
        if (cursor == null) {
            return;
        }

        CursorAdapterExt adapter = new CursorAdapterExt(context, cursor, a.getBoolean(R.styleable.ListViewExt_adapterCursorAutoRequery, true));
        initAdapter(context, a, adapter);
        setAdapter(adapter);
    }

    @Override
    public Parcelable onSaveInstanceState() {
        return new SavedState(super.onSaveInstanceState(), this);
    }

    @Override
    public void onRestoreInstanceState(Parcelable state) {
        SavedState ss = (SavedState) state;
        super.onRestoreInstanceState(ss.getSuperState());
        ss.onRestoreInstanceState(this);
    }

    public AdapterExt getRawAdapter() {
        Adapter adapter = getAdapter();
        if (adapter instanceof WrapperListAdapter) {
            adapter = ((WrapperListAdapter) adapter).getWrappedAdapter();
        }

        if (adapter instanceof AdapterExt) {
            return (AdapterExt) adapter;
        }

        return null;
    }

    static class SavedState extends BaseSavedState {
        final int firstVisiblePosition;
        final int topItemPosition;
        final boolean keepData;
        final Object data;

        public static int getTopItemPosition(ListView listView) {
            View topItem = listView.getChildAt(listView.getHeaderViewsCount());
            return topItem == null ? 0 : topItem.getTop();
        }

        public static Object getData(ListViewExt listView) {
            AdapterExt adapter = listView.getRawAdapter();
            if (adapter != null) {
                Indexed data = adapter.getData();
                if (data instanceof Parcelable || data instanceof Serializable) {
                    return data;
                }
            }

            return null;
        }

        public SavedState(Parcelable superState, ListViewExt listView) {
            super(superState);
            firstVisiblePosition = listView.getFirstVisiblePosition();
            topItemPosition = getTopItemPosition(listView);
            keepData = listView.isKeepData();
            data = keepData ? getData(listView) : null;
        }

        @SuppressWarnings("unchecked")
        public void onRestoreInstanceState(ListViewExt listView) {
            listView.setSelectionFromTop(firstVisiblePosition, topItemPosition);
            listView.setKeepData(keepData);

            AdapterExt adapter = listView.getRawAdapter();
            if (adapter != null && data instanceof Indexed) {
                adapter.setData((Indexed) data);
            }
        }

        @Override
        public void writeToParcel(@SuppressWarnings("NullableProblems") Parcel out, int flags) {
            super.writeToParcel(out, flags);

            out.writeInt(firstVisiblePosition);
            out.writeInt(topItemPosition);
            out.writeInt(keepData ? 1 : 0);
            ParcelUtils.writeParcelableOrSerializable(out, flags, data);
        }

        public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {
            @Override
            public SavedState createFromParcel(Parcel in) {
                return new SavedState(in);
            }

            @Override
            public SavedState[] newArray(int size) {
                return new SavedState[size];
            }
        };

        private SavedState(Parcel in) {
            super(in);

            ClassLoader cl = ((Object) this).getClass().getClassLoader();

            firstVisiblePosition = in.readInt();
            topItemPosition = in.readInt();
            keepData = in.readInt() == 1;
            data = ParcelUtils.readParcelableOrSerializable(in, cl);
        }
    }
}


text:
package org.wikipedia.page;

import org.wikipedia.R;
import org.wikipedia.Site;
import org.wikipedia.WikipediaApp;
import org.wikipedia.analytics.ToCInteractionFunnel;
import org.wikipedia.bridge.CommunicationBridge;
import org.wikipedia.tooltip.ToolTipUtil;
import org.wikipedia.util.DimenUtil;
import org.wikipedia.views.ConfigurableListView;
import org.wikipedia.views.WikiDrawerLayout;
import org.json.JSONException;
import org.json.JSONObject;

import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.appenguin.onboarding.ToolTip;

import java.util.ArrayList;

import static org.wikipedia.util.L10nUtil.getStringForArticleLanguage;
import static org.wikipedia.util.DimenUtil.getContentTopOffsetPx;
import static org.wikipedia.util.ResourceUtil.getThemedAttributeId;

public class ToCHandler {
    private static final int MAX_LEVELS = 3;
    private static final int INDENTATION_WIDTH_DP = 16;
    private static final int READ_MORE_SECTION_ID = -1;
    private final ConfigurableListView tocList;
    private final ProgressBar tocProgress;
    private final CommunicationBridge bridge;
    private final WikiDrawerLayout slidingPane;
    private final TextView headerView;
    private final AppCompatActivity parentActivity;
    private ToCInteractionFunnel funnel;

    /**
     * Flag to track if the drawer is closing because a link was clicked.
     * Used to make sure that we don't track closes that are caused by
     * the user clicking on a section.
     */
    private boolean wasClicked = false;

    public ToCHandler(final AppCompatActivity activity, final WikiDrawerLayout slidingPane,
                      final CommunicationBridge bridge) {
        this.parentActivity = activity;
        this.bridge = bridge;
        this.slidingPane = slidingPane;

        this.tocList = (ConfigurableListView) slidingPane.findViewById(R.id.page_toc_list);
        ((FrameLayout.LayoutParams) tocList.getLayoutParams()).setMargins(0, getContentTopOffsetPx(activity), 0, 0);
        this.tocProgress = (ProgressBar) slidingPane.findViewById(R.id.page_toc_in_progress);

        bridge.addListener("currentSectionResponse", new CommunicationBridge.JSEventListener() {
            @Override
            public void onMessage(String messageType, JSONObject messagePayload) {
                int sectionID = messagePayload.optInt("sectionID");
                Log.d("Wikipedia", "current section is " + sectionID);
                if (tocList.getAdapter() == null) {
                    return;
                }
                int itemToSelect = 0;
                // Find the list item that corresponds to the returned sectionID.
                // Start with index 1 of the list adapter, since index 0 is the header view,
                // and won't have a Section object associated with it.
                // And end with the second-to-last section, since the last section is the
                // artificial Read More section, and unknown to the WebView.
                // The lead section (id 0) will automatically fall through the loop.
                for (int i = 1; i < tocList.getAdapter().getCount() - 1; i++) {
                    if (((Section) tocList.getAdapter().getItem(i)).getId() <= sectionID) {
                        itemToSelect = i;
                    } else {
                        break;
                    }
                }
                tocList.setItemChecked(itemToSelect, true);
                tocList.smoothScrollToPosition(itemToSelect);
            }
        });

        headerView = (TextView) LayoutInflater.from(tocList.getContext()).inflate(R.layout.header_toc_list, null, false);
        tocList.addHeaderView(headerView);

        // create a dummy funnel, in case the drawer is pulled out before a page is loaded.
        funnel = new ToCInteractionFunnel(WikipediaApp.getInstance(),
                WikipediaApp.getInstance().getSite(), 0, 0);

        slidingPane.setDrawerListener(new DrawerLayout.SimpleDrawerListener() {
            private boolean sectionRequested = false;

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                parentActivity.supportInvalidateOptionsMenu();
                funnel.logOpen();
                wasClicked = false;
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                parentActivity.supportInvalidateOptionsMenu();
                if (!wasClicked) {
                    funnel.logClose();
                }
                sectionRequested = false;
            }

            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                super.onDrawerSlide(drawerView, slideOffset);
                // make sure the ActionBar is showing
                ((PageActivity) parentActivity).showToolbar();
                ((PageActivity) parentActivity).getSearchBarHideHandler().setForceNoFade(slideOffset != 0);
                // request the current section to highlight, if we haven't yet
                if (!sectionRequested) {
                    bridge.sendMessage("requestCurrentSection", new JSONObject());
                    sectionRequested = true;
                }
            }
        });
    }

    public void scrollToSection(String sectionAnchor) {
        JSONObject payload = new JSONObject();
        try {
            payload.put("anchor", sectionAnchor);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        bridge.sendMessage("scrollToSection", payload);
    }

    public void scrollToSection(Section section) {
        if (section != null) {
            // is it the bottom (read more) section?
            if (section.getId() == READ_MORE_SECTION_ID) {
                bridge.sendMessage("scrollToBottom", new JSONObject());
            } else {
                scrollToSection(
                        section.isLead() ? "heading_" + section.getId() : section.getAnchor());
            }
        }
    }

    public void setupToC(final Page page, Site site, boolean firstPage) {
        tocProgress.setVisibility(View.GONE);
        tocList.setVisibility(View.VISIBLE);

        headerView.setText(Html.fromHtml(page.getDisplayTitle()));
        headerView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scrollToSection(page.getSections().get(0));
                wasClicked = true;
                funnel.logClick(0, page.getTitle().getDisplayText());
                hide();
            }
        });

        tocList.setAdapter(new ToCAdapter(page), site.languageCode());
        tocList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Section section = (Section) parent.getAdapter().getItem(position);
                scrollToSection(section);
                wasClicked = true;
                funnel.logClick(position, section.getHeading());
                hide();
            }
        });

        funnel = new ToCInteractionFunnel(WikipediaApp.getInstance(), site,
                page.getPageProperties().getPageId(), tocList.getAdapter().getCount());

        if (!page.isMainPage() && !firstPage) {
            if (WikipediaApp.getInstance().getOnboardingStateMachine().isTocTutorialEnabled()) {
                showTocOnboarding();
            }
        }
    }

    public void show() {
        if (slidingPane.getSlidingEnabled(Gravity.END)) {
            slidingPane.openDrawer(GravityCompat.END);
        }
    }

    public void hide() {
        slidingPane.closeDrawer(GravityCompat.END);
    }

    public boolean isVisible() {
        return slidingPane.isDrawerOpen(GravityCompat.END);
    }

    public void setEnabled(boolean enabled) {
        slidingPane.setSlidingEnabled(enabled);
    }

    private final class ToCAdapter extends BaseAdapter {
        private final ArrayList<Section> sections;

        private ToCAdapter(Page page) {
            sections = new ArrayList<>();
            for (Section s : page.getSections()) {
                if (s.getLevel() < MAX_LEVELS && !s.isLead()) {
                    sections.add(s);
                }
            }
            if (page.couldHaveReadMoreSection()) {
                // add a fake section at the end to represent the "read more" contents at the bottom:
                sections.add(new Section(READ_MORE_SECTION_ID, 0,
                        getStringForArticleLanguage(page.getTitle(), R.string.read_more_section), "", ""));
            }
        }

        @Override
        public int getCount() {
            return sections.size();
        }

        @Override
        public Object getItem(int position) {
            return sections.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_toc_entry, parent, false);
            }
            Section section = (Section) getItem(position);
            TextView sectionHeading = (TextView) convertView.findViewById(R.id.page_toc_item_text);
            View sectionFiller = convertView.findViewById(R.id.page_toc_filler);

            LinearLayout.LayoutParams indentLayoutParameters = new LinearLayout.LayoutParams(sectionFiller.getLayoutParams());
            indentLayoutParameters.width = (section.getLevel() - 1) * (int) (INDENTATION_WIDTH_DP * DimenUtil.getDensityScalar());
            sectionFiller.setLayoutParams(indentLayoutParameters);

            sectionHeading.setText(Html.fromHtml(section.getHeading()));

            if (section.getLevel() > 1) {
                sectionHeading.setTextColor(
                        WikipediaApp.getInstance().getResources().getColor(getThemedAttributeId(parentActivity, R.attr.toc_subsection_text_color)));
            } else {
                sectionHeading.setTextColor(
                        WikipediaApp.getInstance().getResources().getColor(getThemedAttributeId(parentActivity, R.attr.toc_section_text_color)));
            }
            return convertView;
        }
    }

    private void showTocOnboarding() {
        View tocButton = parentActivity.findViewById(R.id.floating_toc_button);
        ToolTipUtil.showToolTip(parentActivity,
                                tocButton,
                                R.layout.inflate_tool_tip_toc_button,
                                ToolTip.Position.CENTER);
        WikipediaApp.getInstance().getOnboardingStateMachine().setTocTutorial();
    }
}


text:
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Ads.GoogleAds.V11.Enums {

  /// Holder for reflection information generated from google/ads/googleads/v11/enums/feed_item_target_type.proto
  public static partial class FeedItemTargetTypeReflection {

    #region Descriptor
    /// File descriptor for google/ads/googleads/v11/enums/feed_item_target_type.proto
    public static pbr::FileDescriptor Descriptor {
      get { return descriptor; }
    }
    private static pbr::FileDescriptor descriptor;

    static FeedItemTargetTypeReflection() {
      byte[] descriptorData = global::System.Convert.FromBase64String(
          string.Concat(
            "Cjpnb29nbGUvYWRzL2dvb2dsZWFkcy92MTEvZW51bXMvZmVlZF9pdGVtX3Rh",
            "cmdldF90eXBlLnByb3RvEh5nb29nbGUuYWRzLmdvb2dsZWFkcy52MTEuZW51",
            "bXMidwoWRmVlZEl0ZW1UYXJnZXRUeXBlRW51bSJdChJGZWVkSXRlbVRhcmdl",
            "dFR5cGUSDwoLVU5TUEVDSUZJRUQQABILCgdVTktOT1dOEAESDAoIQ0FNUEFJ",
            "R04QAhIMCghBRF9HUk9VUBADEg0KCUNSSVRFUklPThAEQvEBCiJjb20uZ29v",
            "Z2xlLmFkcy5nb29nbGVhZHMudjExLmVudW1zQhdGZWVkSXRlbVRhcmdldFR5",
            "cGVQcm90b1ABWkNnb29nbGUuZ29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVh",
            "cGlzL2Fkcy9nb29nbGVhZHMvdjExL2VudW1zO2VudW1zogIDR0FBqgIeR29v",
            "Z2xlLkFkcy5Hb29nbGVBZHMuVjExLkVudW1zygIeR29vZ2xlXEFkc1xHb29n",
            "bGVBZHNcVjExXEVudW1z6gIiR29vZ2xlOjpBZHM6Okdvb2dsZUFkczo6VjEx",
            "OjpFbnVtc2IGcHJvdG8z"));
      descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
          new pbr::FileDescriptor[] { },
          new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
            new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V11.Enums.FeedItemTargetTypeEnum), global::Google.Ads.GoogleAds.V11.Enums.FeedItemTargetTypeEnum.Parser, null, null, new[]{ typeof(global::Google.Ads.GoogleAds.V11.Enums.FeedItemTargetTypeEnum.Types.FeedItemTargetType) }, null, null)
          }));
    }
    #endregion

  }
  #region Messages
  ///
  /// Container for enum describing possible types of a feed item target.
  ///
  public sealed partial class FeedItemTargetTypeEnum : pb::IMessage<FeedItemTargetTypeEnum>
  #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
      , pb::IBufferMessage
  #endif
  {
    private static readonly pb::MessageParser<FeedItemTargetTypeEnum> _parser = new pb::MessageParser<FeedItemTargetTypeEnum>(() => new FeedItemTargetTypeEnum());
    private pb::UnknownFieldSet _unknownFields;
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public static pb::MessageParser<FeedItemTargetTypeEnum> Parser { get { return _parser; } }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public static pbr::MessageDescriptor Descriptor {
      get { return global::Google.Ads.GoogleAds.V11.Enums.FeedItemTargetTypeReflection.Descriptor.MessageTypes[0]; }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    pbr::MessageDescriptor pb::IMessage.Descriptor {
      get { return Descriptor; }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public FeedItemTargetTypeEnum() {
      OnConstruction();
    }

    partial void OnConstruction();

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public FeedItemTargetTypeEnum(FeedItemTargetTypeEnum other) : this() {
      _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public FeedItemTargetTypeEnum Clone() {
      return new FeedItemTargetTypeEnum(this);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public override bool Equals(object other) {
      return Equals(other as FeedItemTargetTypeEnum);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public bool Equals(FeedItemTargetTypeEnum other) {
      if (ReferenceEquals(other, null)) {
        return false;
      }
      if (ReferenceEquals(other, this)) {
        return true;
      }
      return Equals(_unknownFields, other._unknownFields);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public override int GetHashCode() {
      int hash = 1;
      if (_unknownFields != null) {
        hash ^= _unknownFields.GetHashCode();
      }
      return hash;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public override string ToString() {
      return pb::JsonFormatter.ToDiagnosticString(this);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public void WriteTo(pb::CodedOutputStream output) {
    #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
      output.WriteRawMessage(this);
    #else
      if (_unknownFields != null) {
        _unknownFields.WriteTo(output);
      }
    #endif
    }

    #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
      if (_unknownFields != null) {
        _unknownFields.WriteTo(ref output);
      }
    }
    #endif

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public int CalculateSize() {
      int size = 0;
      if (_unknownFields != null) {
        size += _unknownFields.CalculateSize();
      }
      return size;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public void MergeFrom(FeedItemTargetTypeEnum other) {
      if (other == null) {
        return;
      }
      _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public void MergeFrom(pb::CodedInputStream input) {
    #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
      input.ReadRawMessage(this);
    #else
      uint tag;
      while ((tag = input.ReadTag()) != 0) {
        switch(tag) {
          default:
            _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
            break;
        }
      }
    #endif
    }

    #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
      uint tag;
      while ((tag = input.ReadTag()) != 0) {
        switch(tag) {
          default:
            _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
            break;
        }
      }
    }
    #endif

    #region Nested types
    /// Container for nested types declared in the FeedItemTargetTypeEnum message type.
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public static partial class Types {
      ///
      /// Possible type of a feed item target.
      ///
      public enum FeedItemTargetType {
        ///
        /// Not specified.
        ///
        [pbr::OriginalName("UNSPECIFIED")] Unspecified = 0,
        ///
        /// Used for return value only. Represents value unknown in this version.
        ///
        [pbr::OriginalName("UNKNOWN")] Unknown = 1,
        ///
        /// Feed item targets a campaign.
        ///
        [pbr::OriginalName("CAMPAIGN")] Campaign = 2,
        ///
        /// Feed item targets an ad group.
        ///
        [pbr::OriginalName("AD_GROUP")] AdGroup = 3,
        ///
        /// Feed item targets a criterion.
        ///
        [pbr::OriginalName("CRITERION")] Criterion = 4,
      }

    }
    #endregion

  }

  #endregion

}

#endregion Designer generated code


text:
"""
WSGI config for letscelebratepride project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "letscelebratepride.settings")

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()


text:
package Sisimai::MDA;
use feature ':5.10';
use strict;
use warnings;

my $Re0 = {
    'from' => qr/\A(?:Mail Delivery Subsystem|MAILER-DAEMON|postmaster)/i,
};
my $Re1 = {
    # dovecot/src/deliver/deliver.c
    # 11: #define DEFAULT_MAIL_REJECTION_HUMAN_REASON \
    # 12: "Your message to <%t> was automatically rejected:%n%r"
    'dovecot'    => qr/\AYour message to .+ was automatically rejected:\z/,
    'mail.local' => qr/\Amail[.]local: /,
    'procmail'   => qr/\Aprocmail: /,
    'maildrop'   => qr/\Amaildrop: /,
    'vpopmail'   => qr/\Avdelivermail: /,
    'vmailmgr'   => qr/\Avdeliver: /,
};
my $Re2 = qr{\A(?>
             Your[ ]message[ ]to[ ].+[ ]was[ ]automatically[ ]rejected:\z
            |(?:mail[.]local|procmail|maildrop|vdelivermail|vdeliver):[ ]
            )
          }x;

# dovecot/src/deliver/mail-send.c:94
my $ReFailure = {
    'dovecot' => {
        'userunknown' => qr/\AMailbox doesn't exist: /i,
        'mailboxfull' => qr{\A(?:
             Quota[ ]exceeded # Dovecot 1.2 dovecot/src/plugins/quota/quota.c
            |Quota[ ]exceeded[ ][(]mailbox[ ]for[ ]user[ ]is[ ]full[)]  # dovecot/src/plugins/quota/quota.c
            |Not[ ]enough[ ]disk[ ]space
            )
        }xi,
    },
    'mail.local' => {
        'userunknown' => qr{[:][ ](?:
             unknown[ ]user[:]
            |User[ ]unknown
            |Invalid[ ]mailbox[ ]path
            |User[ ]missing[ ]home[ ]directory
            )
        }xi,
        'mailboxfull' => qr{(?:
             Disc[ ]quota[ ]exceeded
            |Mailbox[ ]full[ ]or[ ]quota[ ]exceeded
            )
        }xi,
        'systemerror' => qr/Temporary file write error/i,
    },
    'procmail' => {
        'mailboxfull' => qr/Quota exceeded while writing/i,
        'systemfull'  => qr/No space left to finish writing/i,
    },
    'maildrop' => {
        'userunknown' => qr{(?:
             Invalid[ ]user[ ]specified[.]
            |Cannot[ ]find[ ]system[ ]user
            )
        }xi,
        'mailboxfull' => qr/maildir over quota[.]\z/i,
    },
    'vpopmail' => {
        'userunknown' => qr/Sorry, no mailbox here by that name[.]/i,
        'filtered'    => qr{(?:
             account[ ]is[ ]locked[ ]email[ ]bounced
            |user[ ]does[ ]not[ ]exist,[ ]but[ ]will[ ]deliver[ ]to[ ]
            )
        }xi,
        'mailboxfull' => qr/(?:domain|user) is over quota/i,
    },
    'vmailmgr' => {
        'userunknown' => qr{(?>
             Invalid[ ]or[ ]unknown[ ](?:base[ ]user[ ]or[ ]domain|virtual[ ]user)
            |User[ ]name[ ]does[ ]not[ ]refer[ ]to[ ]a[ ]virtual[ ]user/
            )
        }ix,
        'mailboxfull' => qr/Delivery failed due to system quota violation/i,
    },
};

sub scan {
    # Parse message body and return reason and text
    # @param         [Hash] mhead       Message header of a bounce email
    # @options mhead [String] from      From header
    # @options mhead [String] date      Date header
    # @options mhead [String] subject   Subject header
    # @options mhead [Array]  received  Received headers
    # @options mhead [String] others    Other required headers
    # @param         [String] mbody     Message body of a bounce email
    # @return        [Hash, Undef]      Bounce data list and message/rfc822 part
    #                                   or Undef if it failed to parse or the
    #                                   arguments are missing
    my $class = shift;
    my $mhead = shift // return undef;
    my $mbody = shift // return undef;

    return undef unless ref( $mhead ) eq 'HASH';
    return undef unless $mhead->{'from'} =~ $Re0->{'from'};
    return undef unless ref( $mbody ) eq 'SCALAR';
    return undef unless length $$mbody;

    my $agentname0 = '';    # [String] MDA name
    my $reasonname = '';    # [String] Error reason
    my $bouncemesg = '';    # [String] Error message
    my @hasdivided = split( "\n", $$mbody );
    my @linebuffer = ();

    for my $e ( @hasdivided ) {
        # Check each line with each MDA's symbol regular expression.
        if( $agentname0 eq '' ) {
            # Try to match with each regular expression
            next unless $e;
            next unless $e =~ $Re2;

            for my $f ( keys %$Re1 ) {
                # Detect the agent name from the line
                next unless $e =~ $Re1->{ $f };
                $agentname0 = $f;
                last;
            }
        }

        # Append error message lines to @linebuffer
        push @linebuffer, $e;
        last unless length $e;
    }
    return undef unless $agentname0;
    return undef unless scalar @linebuffer;

    for my $e ( keys %{ $ReFailure->{ $agentname0 } } ) {
        # Detect an error reason from message patterns of the MDA.
        for my $f ( @linebuffer ) {
            # Try to match with each regular expression
            next unless $f =~ $ReFailure->{ $agentname0 }->{ $e };
            $reasonname = $e;
            $bouncemesg = $f;
            last;
        }
        last if $bouncemesg && $reasonname;
    }

    return {
        'mda'     => $agentname0,
        'reason'  => $reasonname // '',
        'message' => $bouncemesg // '',
    };
}

1;
__END__

=encoding utf-8

=head1 NAME

Sisimai::MDA - Error message parser for MDA

=head1 SYNOPSIS

    use Sisimai::MDA;
    my $header = { 'from' => 'mailer-daemon@example.jp' };
    my $string = 'mail.local: Disc quota exceeded';
    my $return = Sisimai::MDA->scan( $header, \$string );

=head1 DESCRIPTION

Sisimai::MDA parse bounced email which created by some MDA, such as C<dovecot>,
C<mail.local>, C<procmail>, and so on.
This class is called from Sisimai::Message only.

=head1 CLASS METHODS

=head2 C<B<scan( I<Header>, I<Reference to message body> )>>

C<scan()> is a parser for detecting an error from mail delivery agent.

    my $header = { 'from' => 'mailer-daemon@example.jp' };
    my $string = 'mail.local: Disc quota exceeded';
    my $return = Sisimai::MDA->scan( $header, \$string );
    warn Dumper $return;
    $VAR1 = {
        'mda' => 'mail.local',
        'reason' => 'mailboxfull',
        'message' => 'mail.local: Disc quota exceeded'
    }

=head1 AUTHOR

azumakuniyuki

=head1 COPYRIGHT

Copyright (C) 2014-2016 azumakuniyuki, All rights reserved.

=head1 LICENSE

This software is distributed under The BSD 2-Clause License.

=cut


text:
Ocr::Ocr()
  : src_image_(nullptr),
    classifier_(Options::is_knn() ?
		static_cast<IClassifier*>(new ClassifierKNN) :
		static_cast<IClassifier*>(new ClassifierANN))
{
  classifier_->train();
  if (Options::run_test())
    {
      std::streamsize ss = std::cout.precision();
      std::cout << ANSI_GREEN
		<< "test result: " << std::setprecision(2) << std::fixed
		<< (1.00 - classifier_->test()) * 100 << "% accurate"
		<< std::setprecision(ss) << ANSI_RESET << std::endl;
    }
}

char	Ocr::classify(void* image)
{
  src_image_ = reinterpret_cast<cv::Mat*>(image);
  return classifier_->classify(src_image_);
}

std::string	Ocr::digitize(void* image)
{
  src_image_ = reinterpret_cast<cv::Mat*>(image);
  return classifier_->digitize(src_image_);
}