text:
/******************************************************************/
/**
	@file	SkeletonFrame.h
	@brief	Skeleton frame and skeleton data for kinect video/ depth camera
	@note
	@todo
	@bug
	@see		https://github.com/sadmb/kinect_sdk_sandbox/tree/master/kinect_cpp_wrapper

	@author	kaorun55
	@author	sadmb
	@date	Oct. 26, 2011 modified
*/
/******************************************************************/
#ifndef KINECT_NUI_SKELETON_FRAME_H
#define KINECT_NUI_SKELETON_FRAME_H

#include <memory>
#include <tuple>

#include <Windows.h>
#include <NuiApi.h>

namespace kinect {
	namespace nui {
		//////////////////////////////////////////////////////
		//				forward declaration					//
		//////////////////////////////////////////////////////
		// implemented
		class SkeletonFrame;
		class SkeletonData;

		// required
		class SkeletonEngine;

		//////////////////////////////////////////////////////
		//				class declarations					//
		//////////////////////////////////////////////////////
		/****************************************/
		/**
			@class	SkeletonData
			@brief	Skeleton data for kinect video/ depth camera
			@note
			@date	Oct. 26, 2011
		*/
		/****************************************/
		class SkeletonData
		{
			friend class SkeletonFrame;

		public:
			struct SkeletonPoint {
				LONG   x;		///<	X position of skeleton joint
				LONG   y;		///<	Y position of skeleton joint
				USHORT  depth;	///<	depth data of skeleton joint

				SkeletonPoint() : x( 0 ), y( 0 ), depth( 0 ) {}
			};

			static const int POSITION_COUNT = NUI_SKELETON_POSITION_COUNT; ///< number of skeleton joints

			//////////////////////////////////////////////////////
			//				inline implementation				//
			//////////////////////////////////////////////////////
			//----------------------------------------------------------
			/**
				@brief transform skeleton data to Point struct
			*/
			SkeletonPoint TransformSkeletonToDepthImage( int index )
			{
				SkeletonPoint p;
				NuiTransformSkeletonToDepthImage( skeletonData_.SkeletonPositions[index], &p.x, &p.y, &p.depth );
				return p;
			}

			//----------------------------------------------------------
			/**
				@brief Get tracking state
			*/
			NUI_SKELETON_TRACKING_STATE TrackingState() const { return skeletonData_.eTrackingState; }

			//----------------------------------------------------------
			Vector4 operator [] ( int index )
			{
				return skeletonData_.SkeletonPositions[index];
			}

			//----------------------------------------------------------
			/**
				@brief Get user index
			*/
			DWORD GetUserIndex() const { return skeletonData_.dwUserIndex; }

		private:
			//----------------------------------------------------------
			/**
				@brief Constructor
			*/
			SkeletonData( NUI_SKELETON_DATA& skeletonData )
				: skeletonData_( skeletonData )
			{
			}

		private:

			NUI_SKELETON_DATA&   skeletonData_; ///< skeleton data
		};

		//////////////////////////////////////////////////////
		//				class declarations					//
		//////////////////////////////////////////////////////
		/****************************************/
		/**
			@class	SkeletonFrame
			@brief	Skeleton frame for kinect video/ depth camera
			@note
			@date	Nov. 21, 2011
		*/
		/****************************************/
		class SkeletonFrame
		{
			friend class SkeletonEngine;

		public:

			static const int SKELETON_COUNT = NUI_SKELETON_COUNT; ///< number of skeletons
			virtual ~SkeletonFrame();

			void TransformSmooth( const NUI_TRANSFORM_SMOOTH_PARAMETERS *pSmoothingParams = 0 );

			bool IsFoundSkeleton() const;
			bool IsFoundPosition() const;

			SkeletonData operator [] ( int index ) { return SkeletonData( skeletonFrame_.SkeletonData[index] ); }

		private:
			SkeletonFrame( INuiSensor* sensor, DWORD dwMillisecondsToWait = 0 );

			void GetNextFrame( DWORD dwMillisecondsToWait = 0 );

		protected:

			INuiSensor* sensor_; ///< kinect sensor

			NUI_SKELETON_FRAME skeletonFrame_; ///< skeleton frame
		};
	} // namespace nui
} // namespace kinect
#endif // KINECT_NUI_SKELETON_FRAME_H


text:
layout: default
title: Sitespeed.io - Release notes 1.8.2
description: Sitespeed.io 1.8.2 release let you export the pages info as CSV, better error logging and some bug fixes.
author: Peter Hedenskog
keywords: sitespeed.io, release, release-notes, 1.8.2
nav:
image: http://sitespeed.io/img/sitespeed-1.5-twitter.jpg
twitterdescription: This release let you export the pages info as CSV, better error logging and some bug fixes.
---

Sitespeed.io 1.8.2 release notes

The 1.8.2 release contains some new small features, cleanup & bug fixes.

New features/enhancements

CSV export - you can now export the pages data to a CSV file (added it again) with the switch "-o csv"

Content type percentage - the detailed page now show percentage of requests & size per content type

Better error reporting - a URL that fails e.g. breaks the test, now logs the exact URL, the error message and add the URL to the error list. Also if a cookie is wrongly set, the URL that sets the cookie is logged. Also the Java & PhantomJS version is always shown

Content categories - Favicon and the document are now own categorizes in the detailed page summary

Cleanup - before two different Javascript column sorters was used (on different pages), now one is used

Cleanup - the output is cleaner if you run a test with a list of URLs from a file

Bug fixes

If a page was redirected, the gzipped size was before fetched as 0

For some sites (example www.bike.se) the total weight was fetched wrong by YSlow, now the weight is calculated from each assets on the pages info page

URLs containing & broke some tests

In very rare cases, YSlow reports a larger cache weight than the page weight. The bug is not fixed but when it happens, an error message is displayed

See the changelog for changes done in the past.

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<efi:FlexibilityRevoke efi:efiVersion="2.0" xmlns:efi="http://www.flexiblepower.org/efi-2"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.flexiblepower.org/efi-2 ../schema/efi-2.0.xsd ">
  <efi:header>
    <efi:efiResourceId>device-001</efi:efiResourceId>
    <efi:timestamp>2001-12-31T12:00:00</efi:timestamp>
  </efi:header>
</efi:FlexibilityRevoke>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using XenAdmin.Network;
using XenAdmin.Actions;
using XenAdmin.Core;
using XenAPI;
using System.Text;

namespace XenAdmin.Alerts
{
    public class XenServerPatchAlert : XenServerUpdateAlert
    {
        public XenServerPatch Patch;
        public XenServerVersion NewServerVersion;

        /// <summary>
        /// Can we apply this alert. Calling this sets the CannotApplyReason where applicable
        /// </summary>
        public bool CanApply
        {
            get
            {
                var distinctHosts = DistinctHosts;

                if (distinctHosts != null)
                {
                    if (distinctHosts.All(IsHostLicenseRestricted))
                    {
                        CannotApplyReason = Messages.MANUAL_CHECK_FOR_UPDATES_UNLICENSED_INFO;
                        return false;
                    }

                    if (distinctHosts.Any(IsHostLicenseRestricted))
                    {
                        CannotApplyReason = Messages.MANUAL_CHECK_FOR_UPDATES_PARTIAL_UNLICENSED_INFO;
                        return true;
                    }
                }

                CannotApplyReason = null;
                return true;
            }
        }

        public string CannotApplyReason { get; set; }

        private bool IsHostLicenseRestricted(Host host)
        {
            if(host == null)
                return false;

            return !host.CanApplyHotfixes();
        }

        /// <summary>
        /// Creates a patch alert
        ///  </summary>
        /// <param name="patch">The patch</param>
        /// <param name="newServerVersion">The version that the patch installs, or null if the patch doesn't update the server version</param>
        public XenServerPatchAlert(XenServerPatch patch, XenServerVersion newServerVersion = null)
        {
            Patch = patch;
            NewServerVersion = newServerVersion;
            if (NewServerVersion != null)
                RequiredXenCenterVersion = Updates.GetRequiredXenCenterVersion(NewServerVersion);
            _priority = patch.Priority;
            _timestamp = Patch.TimeStamp;
        }

        public override string WebPageLabel
        {
            get
            {
                return Patch.Url;
            }
        }

        public override AlertPriority Priority
        {
            get
            {
                if (Enum.IsDefined(typeof(AlertPriority), _priority))
                    return (AlertPriority)_priority;

                return AlertPriority.Priority2;
            }
        }

        public override string Description
        {
            get
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(Patch.Description);
                if (Patch.InstallationSize != 0)
                {
                    sb.AppendLine();
                    sb.AppendFormat(Messages.PATCH_INSTALLATION_SIZE, Util.DiskSizeString(Patch.InstallationSize));
                }
                if (RequiredXenCenterVersion != null)
                {
                    sb.AppendLine();
                    sb.AppendFormat(Messages.PATCH_NEEDS_NEW_XENCENTER, RequiredXenCenterVersion.Version);
                }
                return sb.ToString();
            }
        }

        public override string Name
        {
            get
            {
                if (ShowAsNewVersion)
                    return NewServerVersion.Name;
                return Patch.Name;
            }
        }

        public override Action FixLinkAction
        {
            get { return () => Program.OpenURL(Patch.Url); }
        }

        public override string FixLinkText
        {
            get
            {
                return Messages.ALERT_NEW_PATCH_DOWNLOAD;
            }
        }

        public override string HelpID
        {
            get
            {
                return "XenServerPatchAlert";
            }
        }

        public override string Title
        {
            get
            {
                if (ShowAsNewVersion)
                    return string.Format(Messages.DOWLOAD_LATEST_XS_TITLE, NewServerVersion.Name);
                return string.Format(Messages.NEW_UPDATE_AVAILABLE, Patch.Name);
            }
        }

        protected override bool IsDismissed(IXenConnection connection)
        {
            Pool pool = Helpers.GetPoolOfOne(connection);
            if (pool == null)
                return false;

            Dictionary<string, string> other_config = pool.other_config;

            if (other_config.ContainsKey(Updates.IgnorePatchKey))
            {
                List<string> current = new List<string>(other_config[Updates.IgnorePatchKey].Split(','));
                if (current.Contains(Patch.Uuid, StringComparer.OrdinalIgnoreCase))
                    return true;
            }
            return false;
        }

        public override bool Equals(Alert other)
        {
            if (other is XenServerPatchAlert)
            {
                return string.Equals(Patch.Uuid, ((XenServerPatchAlert)other).Patch.Uuid, StringComparison.OrdinalIgnoreCase);
            }
            return base.Equals(other);
        }

        public bool ShowAsNewVersion
        {
            get
            {
                return NewServerVersion != null && !NewServerVersion.PresentAsUpdate;
            }
        }
    }
}


text:
package oic.simulator.clientcontroller.view.dialogs;

import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.TrayDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Shell;

import java.util.ArrayList;
import java.util.Map;
import java.util.Set;

import oic.simulator.clientcontroller.utils.Constants;

/**
 * Dialog for starting and stopping the automatic verifications.
 */
public class VerificationDialog extends TrayDialog {
    private Map<String, Boolean> automationStatus;

    public VerificationDialog(Shell shell, Map<String, Boolean> automationStatus) {
        super(shell);
        this.automationStatus = automationStatus;
    }

    @Override
    protected void configureShell(Shell shell) {
        super.configureShell(shell);
    }

    @Override
    protected Control createDialogArea(Composite parent) {
        Composite composite = (Composite) super.createDialogArea(parent);
        createAutomationGroup(composite);
        getShell().setText("Automation Settings");
        return composite;
    }

    /**
     * Dynamically creates a check-box list for enabling/disabling different
     * types of automation
     */
    private void createAutomationGroup(Composite parent) {
        Group group = new Group(parent, SWT.NONE);
        group.setLayout(new GridLayout());
        GridData gd = new GridData(GridData.FILL_HORIZONTAL);
        gd.widthHint = 275;
        group.setLayoutData(gd);
        group.setText("Automation Levels");

        Set<String> keySet = automationStatus.keySet();
        if (null == keySet) {
            return;
        }
        ArrayList<String> list = new ArrayList<String>(
                automationStatus.keySet());
        for (final String str : list) {
            final Button checkbox = new Button(group, SWT.CHECK);
            checkbox.setText(str);
            checkbox.setSelection(automationStatus.get(str));
            checkbox.addSelectionListener(new SelectionAdapter() {

                @Override
                public void widgetSelected(SelectionEvent e) {
                    Button btn = (Button) e.getSource();
                    if (null == btn) {
                        return;
                    }
                    String btnText = btn.getText();
                    if (btnText.equalsIgnoreCase(Constants.GET)) {
                        automationStatus.put(Constants.GET, btn.getSelection());
                    } else if (btnText.equalsIgnoreCase(Constants.PUT)) {
                        automationStatus.put(Constants.PUT, btn.getSelection());
                    } else if (btnText.equalsIgnoreCase(Constants.POST)) {
                        automationStatus.put(Constants.POST, btn.getSelection());
                    }
                }
            });
        }
    }

    @Override
    protected Button createButton(Composite parent, int id, String label,
            boolean defaultButton) {
        if (id == IDialogConstants.CANCEL_ID) {
            return null;
        }
        return super.createButton(parent, id, label, defaultButton);
    }

    @Override
    public boolean isHelpAvailable() {
        return false;
    }

    public Map<String, Boolean> getAutomationStatus() {
        return automationStatus;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OVHApi.Parser
{
	public class Program
	{
		public static void Main(string[] args)
		{
			HttpFileLoader loader = new HttpFileLoader();
			var apis = loader.Load();

			ModelGenerator generator = new ModelGenerator();
			generator.CreateModels(apis);
		}
	}
}


text:
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
          Toggle navigation

      </button>

    <gcse:search></gcse:search>

Rancher Documentation

How to use the API

What are API keys

API Resources

Common Resource Fields

            Account

Account

Activate

Deactivate

            AddOutputsInput

AddOutputsInput

            Amazonec2Config

Amazonec2Config

Create

            ApiKey

ApiKey

Create

Update

Delete

Activate

Deactivate

            AuditLog

AuditLog

            AzureConfig

AzureConfig

Create

            Certificate

Certificate

Create

Update

Delete

            Container

Container

Create

Update

Delete

Console

Execute

Logs

Proxy

Restart

Start

Stop

            ContainerExec

ContainerExec

Create

            DigitaloceanConfig

DigitaloceanConfig

Create

            DnsService

DnsService

Create

Update

Delete

Activate

Deactivate

Removeservicelink

Rollback

Setservicelinks

Upgrade

            DockerBuild

DockerBuild

Create

            Environment

Environment

Create

Update

Delete

Activateservices

Cancelrollback

Cancelupgrade

Deactivateservices

Exportconfig

Finishupgrade

Rollback

            EnvironmentUpgrade

EnvironmentUpgrade

Create

            ExoscaleConfig

ExoscaleConfig

Create

            ExternalService

ExternalService

Create

Update

Delete

Activate

Cancelrollback

Cancelupgrade

Deactivate

Finishupgrade

Rollback

Upgrade

            GenericConfig

GenericConfig

Create

            GoogleConfig

GoogleConfig

Create

            HealthcheckInstanceHostMap

HealthcheckInstanceHostMap

            Host

Host

Update

Delete

Activate

Deactivate

Dockersocket

            HostAccess

HostAccess

            HypervConfig

HypervConfig

Create

            Identity

Identity

            LoadBalancerConfig

LoadBalancerConfig

Create

Update

Delete

            LoadBalancerService

LoadBalancerService

Create

Update

Delete

Activate

Addservicelink

Cancelrollback

Cancelupgrade

Deactivate

Finishupgrade

Removeservicelink

Rollback

Setservicelinks

Upgrade

            Machine

Machine

Create

Delete

            OpenstackConfig

OpenstackConfig

Create

            PacketConfig

PacketConfig

Create

            Project

Project

Activate

Deactivate

Setmembers

            ProjectMember

ProjectMember

Activate

Deactivate

            PullTask

PullTask

Create

            RackspaceConfig

RackspaceConfig

Create

            RegistrationToken

RegistrationToken

Create

            Registry

Registry

Create

Update

Delete

Activate

Deactivate

            RegistryCredential

RegistryCredential

Create

Update

Delete

Activate

Deactivate

            Service

Service

Create

Update

Delete

Activate

Addservicelink

Cancelrollback

Cancelupgrade

Deactivate

Finishupgrade

Removeservicelink

Restart

Rollback

Setservicelinks

            ServiceConsumeMap

ServiceConsumeMap

            ServiceExposeMap

ServiceExposeMap

            Setting

Setting

            SoftlayerConfig

SoftlayerConfig

Create

            StatsAccess

StatsAccess

            Subscribe

Subscribe

Create

            UbiquityConfig

UbiquityConfig

Create

            VirtualboxConfig

VirtualboxConfig

Create

            VmwarefusionConfig

VmwarefusionConfig

Create

            VmwarevcloudairConfig

VmwarevcloudairConfig

Create

            VmwarevsphereConfig

VmwarevsphereConfig

Create

            Volume

Volume

Create

Delete


text:
#import "NSNotificationCenter.h"

@interface NSNotificationCenter (DVTNSNotificationCenterAdditions)
- (id)dvt_addObserverForName:(id)arg1 object:(id)arg2 queue:(id)arg3 usingBlock:(id)arg4;
- (id)dvt_addObserver:(id)arg1 selector:(SEL)arg2 name:(id)arg3 object:(id)arg4;
@end


text:
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
/*==============================================================*/
/* DBMS name:      MySQL 5.0                                    */
/* Created on:     2016/12/9 13:49:28                           */
/*==============================================================*/

drop table if exists gis_fmaprelationalspace;

drop table if exists gis_mainspaceinfo;

drop table if exists gis_product;

drop table if exists gis_relationalproductshow;

drop table if exists gis_spacedetails;

drop table if exists gis_spacerealinfo;

drop table if exists gis_spacetype;

/*==============================================================*/
/* Table: gis_fmaprelationalspace                               */
/*==============================================================*/
create table gis_fmaprelationalspace
(
   id                   int not null auto_increment,
   fmap_id              varchar(50),
   space_id             int,
   primary key (id)
);

alter table gis_fmaprelationalspace comment '蜂鸟地图id与空间id关联';

/*==============================================================*/
/* Table: gis_mainspaceinfo                                     */
/*==============================================================*/
create table gis_mainspaceinfo
(
   id                   int not null auto_increment comment '主键Id',
   mainspacecode        varchar(50),
   mainspacename        varchar(250),
   mainspacedesc        varchar(250),
   note                 varchar(250),
   primary key (id)
);

alter table gis_mainspaceinfo comment '主空间';

/*==============================================================*/
/* Table: gis_product                                           */
/*==============================================================*/
create table gis_product
(
   id                   int not null auto_increment,
   productCode          varchar(50),
   productPhotoUrl      varchar(250),
   note                 varchar(250),
   primary key (id)
);

alter table gis_product comment '显示产品定义字典';

/*==============================================================*/
/* Table: gis_relationalproductshow                             */
/*==============================================================*/
create table gis_relationalproductshow
(
   id                   int not null auto_increment,
   photourl             varchar(250),
   spacerealinfo_id     int,
   product_id           int,
   note                 varchar(250),
   primary key (id)
);

alter table gis_relationalproductshow comment '关联空间产品秀';

/*==============================================================*/
/* Table: gis_spacedetails                                      */
/*==============================================================*/
create table gis_spacedetails
(
   id                   int not null auto_increment,
   parentid             int,
   spacecode            varchar(50),
   spacename            varchar(100),
   mainspace_id         int,
   spacetype_id         int,
   isend                int,
   note                 varchar(250),
   primary key (id)
);

alter table gis_spacedetails comment '空间细节定义';

/*==============================================================*/
/* Table: gis_spacerealinfo                                     */
/*==============================================================*/
create table gis_spacerealinfo
(
   id                   int not null auto_increment,
   photourl             varchar(250),
   space_id             int,
   isRemarkPoint        int,
   note                 varchar(250),
   primary key (id)
);

alter table gis_spacerealinfo comment '空间实景信息';

/*==============================================================*/
/* Table: gis_spacetype                                         */
/*==============================================================*/
create table gis_spacetype
(
   id                   int not null auto_increment,
   typecode             varchar(50),
   typename             varchar(100),
   note                 varchar(250),
   primary key (id)
);

alter table gis_spacetype comment '空间类型表';


text:
"""Utilities for downloading data from WMT, tokenizing, vocabularies."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import gzip
import os
import re
import tarfile

from tensorflow.python.platform import gfile

# Special vocabulary symbols - we always put them at the start.
_PAD = b"_PAD"
_GO = b"_GO"
_EOS = b"_EOS"
_UNK = b"_UNK"
_START_VOCAB = [_PAD, _GO, _EOS, _UNK]

PAD_ID = 0
GO_ID = 1
EOS_ID = 2
UNK_ID = 3

# Regular expressions used to tokenize.
_DIGIT_RE = re.compile(br"\d")

def basic_tokenizer(sentence, lower=True):
    """Very basic tokenizer: split the sentence into a list of tokens."""
    words = sentence.strip().split()
    if lower:
        words = [w.lower() for w in words if w]
    else:
        words = [w for w in words if w]
    return words

def create_vocabulary(vocabulary_path, data_path, max_vocabulary_size,
                      tokenizer=None, normalize_digits=True):
    """Create vocabulary file (if it does not exist yet) from data file.

    Data file is assumed to contain one sentence per line. Each sentence is
    tokenized and digits are normalized (if normalize_digits is set).
    Vocabulary contains the most-frequent tokens up to max_vocabulary_size.
    We write it to vocabulary_path in a one-token-per-line format, so that later
    token in the first line gets id=0, second line gets id=1, and so on.

    Args:
      vocabulary_path: path where the vocabulary will be created.
      data_path: data file that will be used to create vocabulary.
      max_vocabulary_size: limit on the size of the created vocabulary.
      tokenizer: a function to use to tokenize each data sentence;
        if None, basic_tokenizer will be used.
      normalize_digits: Boolean; if true, all digits are replaced by 0s.
    """
    if not gfile.Exists(vocabulary_path):
        print("Creating vocabulary %s from data %s" % (vocabulary_path, data_path))
        vocab = {}
        with gfile.GFile(data_path, mode="rb") as f:
            counter = 0
            for line in f:
                counter += 1
                if counter % 100000 == 0:
                    print("  processing line %d" % counter)
                tokens = tokenizer(line) if tokenizer else basic_tokenizer(line)
                for w in tokens:
                    word = re.sub(_DIGIT_RE, b"0", w) if normalize_digits else w
                    if word in vocab:
                        vocab[word] += 1
                    else:
                        vocab[word] = 1
            vocab_list = _START_VOCAB + sorted(vocab, key=vocab.get, reverse=True)
            if len(vocab_list) > max_vocabulary_size:
                vocab_list = vocab_list[:max_vocabulary_size]
            with gfile.GFile(vocabulary_path, mode="wb") as vocab_file:
                for w in vocab_list:
                    vocab_file.write(w + b"\n")

def initialize_vocabulary(vocabulary_path):
    """Initialize vocabulary from file.

    Args:
      vocabulary_path: path to the file containing the vocabulary.

    Returns:
      a pair: the vocabulary (a dictionary mapping string to integers), and
      the reversed vocabulary (a list, which reverses the vocabulary mapping).

    Raises:
      ValueError: if the provided vocabulary_path does not exist.
    """
    if gfile.Exists(vocabulary_path):
        rev_vocab = []
        with gfile.GFile(vocabulary_path, mode="rb") as f:
            rev_vocab.extend(f.readlines())
        rev_vocab = [line.strip() for line in rev_vocab]
        vocab = dict([(x, y) for (y, x) in enumerate(rev_vocab)])
        return vocab, rev_vocab
    else:
        raise ValueError("Vocabulary file %s not found.", vocabulary_path)

def sentence_to_token_ids(sentence, vocabulary,
                          tokenizer=None, normalize_digits=True):
    """Convert a string to list of integers representing token-ids.

    For example, a sentence "I have a dog" may become tokenized into
    ["I", "have", "a", "dog"] and with vocabulary {"I": 1, "have": 2,
    "a": 4, "dog": 7"} this function will return [1, 2, 4, 7].

    Args:
      sentence: the sentence in bytes format to convert to token-ids.
      vocabulary: a dictionary mapping tokens to integers.
      tokenizer: a function to use to tokenize each sentence;
        if None, basic_tokenizer will be used.
      normalize_digits: Boolean; if true, all digits are replaced by 0s.

    Returns:
      a list of integers, the token-ids for the sentence.
    """

    if tokenizer:
        words = tokenizer(sentence)
    else:
        words = basic_tokenizer(sentence)
    if not normalize_digits:
        return [vocabulary.get(w, UNK_ID) for w in words]
    # Normalize digits by 0 before looking words up in the vocabulary.
    return [vocabulary.get(re.sub(_DIGIT_RE, b"0", w), UNK_ID) for w in words]

def data_to_token_ids(data_path, target_path, vocabulary_path,
                      tokenizer=None, normalize_digits=True):
    """Tokenize data file and turn into token-ids using given vocabulary file.

    This function loads data line-by-line from data_path, calls the above
    sentence_to_token_ids, and saves the result to target_path. See comment
    for sentence_to_token_ids on the details of token-ids format.

    Args:
      data_path: path to the data file in one-sentence-per-line format.
      target_path: path where the file with token-ids will be created.
      vocabulary_path: path to the vocabulary file.
      tokenizer: a function to use to tokenize each sentence;
        if None, basic_tokenizer will be used.
      normalize_digits: Boolean; if true, all digits are replaced by 0s.
    """
    if not gfile.Exists(target_path):
        print("Tokenizing data in %s" % data_path)
        vocab, _ = initialize_vocabulary(vocabulary_path)
        with gfile.GFile(data_path, mode="rb") as data_file:
            with gfile.GFile(target_path, mode="w") as tokens_file:
                counter = 0
                for line in data_file:
                    counter += 1
                    if counter % 100000 == 0:
                        print("  tokenizing line %d" % counter)
                    token_ids = sentence_to_token_ids(line, vocab, tokenizer,
                                                      normalize_digits)
                    tokens_file.write(" ".join([str(tok) for tok in token_ids]) + "\n")

def prepare_data(data_dir, src_vocabulary_size, trg_vocabulary_size, tokenizer=None):
    """prepare data from data_dir, create vocabularies and tokenize data.

    Args:
      data_dir: directory in which the data sets will be stored.
      src_vocabulary_size: size of the source vocabulary to create and use.
      trg_vocabulary_size: size of the target vocabulary to create and use.
      tokenizer: a function to use to tokenize each data sentence;
        if None, basic_tokenizer will be used.

    Returns:
      A tuple of 6 elements:
        (1) path to the token-ids for source training data-set,
        (2) path to the token-ids for target training data-set,
        (3) path to the token-ids for source development data-set,
        (4) path to the token-ids for target development data-set,
        (5) path to the source vocabulary file,
        (6) path to the target vocabulary file.
    """
    # Get data from the specified directory.
    train_path = os.path.join(data_dir, "train")
    dev_path = os.path.join(data_dir, "dev")

    # Create vocabularies of the appropriate sizes.
    trg_vocab_path = os.path.join(data_dir, "vocab%d.trg" % trg_vocabulary_size)
    src_vocab_path = os.path.join(data_dir, "vocab%d.src" % src_vocabulary_size)
    create_vocabulary(trg_vocab_path, train_path + ".trg", trg_vocabulary_size, tokenizer)
    create_vocabulary(src_vocab_path, train_path + ".src", src_vocabulary_size, tokenizer)

    # Create token ids for the training data.
    trg_train_ids_path = train_path + (".ids%d.trg" % trg_vocabulary_size)
    src_train_ids_path = train_path + (".ids%d.src" % src_vocabulary_size)
    data_to_token_ids(train_path + ".trg", trg_train_ids_path, trg_vocab_path, tokenizer)
    data_to_token_ids(train_path + ".src", src_train_ids_path, src_vocab_path, tokenizer)

    # Create token ids for the development data.
    trg_dev_ids_path = dev_path + (".ids%d.trg" % trg_vocabulary_size)
    src_dev_ids_path = dev_path + (".ids%d.src" % src_vocabulary_size)
    data_to_token_ids(dev_path + ".trg", trg_dev_ids_path, trg_vocab_path, tokenizer)
    data_to_token_ids(dev_path + ".src", src_dev_ids_path, src_vocab_path, tokenizer)

    return (src_train_ids_path, trg_train_ids_path,
            src_dev_ids_path, trg_dev_ids_path,
            src_vocab_path, trg_vocab_path)

if __name__ == '__main__':
    prepare_data("data", 30000, 30000)


text:
<!-- markdownlint-disable MD002 MD041 -->

## Modify the Backend API

For this tutorial, let's modify the API to include a new endpoint that expects an Access Token to be supplied.

::: note
In a real scenario, this work would be done by the external API that is to be called from the frontend. This new endpoint is simply a convenience to serve as a learning exercise.
:::

Open `server.js` and add a new Express route to serve as the API endpoint, right underneath the existing one:

```js
// server.js

// ... other code

// This is the existing endpoint for sample 2
app.get("/api/private", checkJwt, (req, res) => {
  res.send({
    msg: "Your ID Token was successfully validated!"
  });
});

// Add the new endpoint here:
app.get("/api/external", checkJwt, (req, res) => {
  res.send({
    msg: "Your Access Token was successfully validated!"
  });
});
```

Notice that it continues to use the same `checkJwt` middleware in order to validate the Access Token. The difference here is that the Access Token must be validated using the API identifier, rather than the client ID that we used for the ID Token.

::: note
The API identifier is the identifier that was specified when the API was created in the [Auth0 dashboard](${manage_url}/#/apis).
:::

Therefore, modify the `checkJwt` function to include the API identifier value in the `audience` setting:

```js
const checkJwt = jwt({
  secret: jwksRsa.expressJwtSecret({
    cache: true,
    rateLimit: true,
    jwksRequestsPerMinute: 5,
    jwksUri: `https://<%= "${authConfig.domain}" %>/.well-known/jwks.json`
  }),

  // Modify the audience to include both the client ID and the audience from configuration in an array
  audience: [authConfig.clientID, authConfig.audience],
  issuer: `https://<%= "${authConfig.domain}" %>/`,
  algorithms: ["RS256"]
});
```

::: note
As the `audience` property accepts an array of values, both the client ID and the API identifier can be given, allowing both the ID Token and the Access Token to be verified using the same middleware.
:::

Finally, modify the `authConfig` object to include your `audience` value:

```js
const authConfig = {
  domain: "${account.namespace}",
  clientID: "${account.clientId}",
  audience: "${apiIdentifier}"
};
```


text:
package licensetype

import "strings"

// https://github.com/elastic/elasticsearch-specification/blob/4ca0cc05d3ae3fa06c2cd7be91905b656a474334/specification/license/_types/License.ts#L23-L33
type LicenseType struct {
	Name string
}

var (
	Missing = LicenseType{"missing"}

	Trial = LicenseType{"trial"}

	Basic = LicenseType{"basic"}

	Standard = LicenseType{"standard"}

	Dev = LicenseType{"dev"}

	Silver = LicenseType{"silver"}

	Gold = LicenseType{"gold"}

	Platinum = LicenseType{"platinum"}

	Enterprise = LicenseType{"enterprise"}
)

func (l LicenseType) MarshalText() (text []byte, err error) {
	return []byte(l.String()), nil
}

func (l *LicenseType) UnmarshalText(text []byte) error {
	switch strings.ToLower(string(text)) {

	case "missing":
		*l = Missing
	case "trial":
		*l = Trial
	case "basic":
		*l = Basic
	case "standard":
		*l = Standard
	case "dev":
		*l = Dev
	case "silver":
		*l = Silver
	case "gold":
		*l = Gold
	case "platinum":
		*l = Platinum
	case "enterprise":
		*l = Enterprise
	default:
		*l = LicenseType{string(text)}
	}

	return nil
}

func (l LicenseType) String() string {
	return l.Name
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>net.sourceforge.pmd.cpd (PMD 5.0.4 Test API)</title>
<meta name="date" content="2013-05-01">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package net.sourceforge.pmd.cpd

Class Summary

Class
Description

AnyTokenizerTest

CPDTest

Unit test for CPD

CPPTokenizerTest

CsTokenizerTest

EcmascriptTokenizerTest

FileReporterTest

FortranTokenizerTest

JavaTokensTokenizerTest

LanguageFactoryTest

MatchAlgorithmTest

MatchTest

RubyTokenizerTest

SourceCodeTest

TokenEntryTest

XMLRendererTest

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Copyright © 2002-2013 InfoEther. All Rights Reserved.


text:
module ActionView::Helpers
  module ChartrHelpers
    # easy way to include Chartr assets
    def chartr_includes
      return "<!--[if IE]>\n" +
        javascript_include_tag('chartr/excanvas.js', 'chartr/base64.js') +
        "\n<![endif]-->" +
        javascript_include_tag("chartr/canvas2image.js", "chartr/canvastext.js", "chartr/flotr-min")
    end
  end
end


text:
package sshchat

import (
	"bytes"

	"github.com/alexcesaro/log"
	"github.com/alexcesaro/log/golog"
)

var logger *golog.Logger

func SetLogger(l *golog.Logger) {
	logger = l
}

func init() {
	// Set a default null logger
	var b bytes.Buffer
	SetLogger(golog.New(&b, log.Debug))
}


text:
<?xml version='1.0' encoding='utf-8'?>
<widget id="io.cordova.hellocordova" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>IBeaconPluginTester</name>
    <description>
        Tests the Cordova iBeacon Plugin.
    </description>
    <author email="dev@cordova.apache.org" href="http://cordova.io">
        Apache Cordova Team
    </author>
    <content src="index.html" />
    <access origin="*" />
</widget>


text:
var app = {
    // Application Constructor
    initialize: function () {
        document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
    },

    // deviceready Event Handler
    //
    // Bind any cordova events here. Common events are:
    // 'pause', 'resume', etc.
    onDeviceReady: function () {
        this.receivedEvent('deviceready');
    },

    // Update DOM on a Received Event
    receivedEvent: function (id) {
        var parentElement = document.getElementById(id);
        // var listeningElement = parentElement.querySelector('.listening');
        // var receivedElement = parentElement.querySelector('.received');

        // listeningElement.setAttribute('style', 'display:none;');
        // receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
        // document.getElementById("cameraButton").addEventListener("click", this.openCamera);
    },

    cameraPressed: function () {
        console.log("Camera Pressed");

        navigator.camera.getPicture(onSuccess, onFail, {
            quality: 50,
            destinationType: Camera.DestinationType.FILE_URI
        });

        function onSuccess(imageURI) {
            var image = document.getElementById('myImage');
            image.src = imageURI;
        }

        function onFail(message) {
            alert('Failed because: ' + message);
        }

        //navigator.camera.getPicture(onSuccess, onFail, { quality: 25,
        //    destinationType: Camera.DestinationType.DATA_URL
        //});
        //
        //function onSuccess(imageData) {
        //    var image = document.getElementById('myImage');
        //    image.src = "data:image/jpeg;base64," + imageData;
        //}
        //
        //function onFail(message) {
        //    alert('Failed because: ' + message);
        //}
    },

    setOptions: function (srcType) {
        var options = {
            // Some common settings are 20, 50, and 100
            quality: 100,
            destinationType: Camera.DestinationType.FILE_URI,
            // In this app, dynamically set the picture source, Camera or photo gallery
            sourceType: srcType,
            encodingType: Camera.EncodingType.JPEG,
            mediaType: Camera.MediaType.PICTURE,
            allowEdit: true,
            correctOrientation: true  //Corrects Android orientation quirks
        }
        return options;
    },

    openCamera: function (selection) {

        var srcType = Camera.PictureSourceType.CAMERA;
        var options = app.setOptions(srcType);
        var func = app.createNewFileEntry;

        navigator.camera.getPicture(function cameraSuccess(imageUri) {

            app.displayImage(imageUri);
            // You may choose to copy the picture, save it somewhere, or upload.
            func(imageUri);

        }, function cameraError(error) {
            console.debug("Unable to obtain picture: " + error, "app");

        }, options);
    },
    displayImage: function (imgUri) {

        var elem = document.getElementById('imageFile');
        elem.src = "data:image/jpeg;base64," + imgUri;
    },

    createNewFileEntry: function (imgUri) {
        window.resolveLocalFileSystemURL(cordova.file.cacheDirectory, function success(dirEntry) {

            // JPEG file
            dirEntry.getFile("tempFile.jpeg", {create: true, exclusive: false}, function (fileEntry) {

                // Do something with it, like write to it, upload it, etc.
                // writeFile(fileEntry, imgUri);
                console.log("got file: " + fileEntry.fullPath);
                // displayFileData(fileEntry.fullPath, "File copied to");

            }, onErrorCreateFile);

        }, onErrorResolveUrl);
    }
};

app.initialize();


text:
package atto

import atto.Atto._
import atto.syntax.refined._
import eu.timepit.refined.string.MatchesRegex
import eu.timepit.refined.W
import cats.implicits._
import org.scalacheck._

@SuppressWarnings(Array("org.wartremover.warts.NonUnitStatements", "org.wartremover.warts.Any"))
object RefinedTest extends Properties("Refined") {
  import Prop._

  property("refined success") = forAll { (n: Long) =>
    type Hex = MatchesRegex[W.`"[0-9a-fA-F]+"`.T]
    val hexStr = n.toHexString
    stringOf(hexDigit).refined[Hex].parseOnly(hexStr).option.map(_.value) === Some(hexStr)
  }

  property("refined error") = forAll { (n: Long) =>
    type Alpha = MatchesRegex[W.`"[e-z]+"`.T]
    stringOf(anyChar).refined[Alpha].parseOnly(n.toString).either.swap.toOption ===
      Some(s"""Predicate failed: "$n".matches("[e-z]+").""")
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SpecialNumbers
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());
            for (int i = 1; i <= n; i++)
            {
                int sum = 0;
                int digits = i;
                while (digits > 0)
                {
                    sum += digits % 10;
                    digits = digits / 10;
                }
                bool special = (sum == 5 || sum == 7 || sum == 11);
                Console.WriteLine("{0} -> {1}", i, special);
            }
        }
    }
}


text:
.class public Lcom/fasterxml/jackson/databind/jsontype/impl/StdSubtypeResolver;
.super Lcom/fasterxml/jackson/databind/jsontype/SubtypeResolver;
.source ""

# interfaces
.implements Ljava/io/Serializable;

# static fields
.field private static final serialVersionUID:J = 0x1L

# instance fields
.field protected _registeredSubtypes:Ljava/util/LinkedHashSet;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/LinkedHashSet<Lcom/fasterxml/jackson/databind/jsontype/NamedType;>;"
        }
    .end annotation
.end field

# direct methods
.method public constructor <init>()V
    .locals 0

    .line 23
    invoke-direct {p0}, Lcom/fasterxml/jackson/databind/jsontype/SubtypeResolver;-><init>()V

    return-void
.end method

# virtual methods
.method protected _collectAndResolve(Lcom/fasterxml/jackson/databind/introspect/AnnotatedClass;Lcom/fasterxml/jackson/databind/jsontype/NamedType;Lcom/fasterxml/jackson/databind/cfg/MapperConfig;Lcom/fasterxml/jackson/databind/AnnotationIntrospector;Ljava/util/HashMap;)V
    .locals 7
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(Lcom/fasterxml/jackson/databind/introspect/AnnotatedClass;Lcom/fasterxml/jackson/databind/jsontype/NamedType;Lcom/fasterxml/jackson/databind/cfg/MapperConfig<*>;Lcom/fasterxml/jackson/databind/AnnotationIntrospector;Ljava/util/HashMap<Lcom/fasterxml/jackson/databind/jsontype/NamedType;Lcom/fasterxml/jackson/databind/jsontype/NamedType;>;)V"
        }
    .end annotation

    .line 141
    invoke-virtual {p2}, Lcom/fasterxml/jackson/databind/jsontype/NamedType;->hasName()Z

    move-result v0

    if-nez v0, :cond_0

    .line 142
    invoke-virtual {p4, p1}, Lcom/fasterxml/jackson/databind/AnnotationIntrospector;->findTypeName(Lcom/fasterxml/jackson/databind/introspect/AnnotatedClass;)Ljava/lang/String;

    move-result-object v0

    .line 143
    move-object v6, v0

    if-eqz v0, :cond_0

    .line 144
    new-instance v0, Lcom/fasterxml/jackson/databind/jsontype/NamedType;

    invoke-virtual {p2}, Lcom/fasterxml/jackson/databind/jsontype/NamedType;->getType()Ljava/lang/Class;

    move-result-object v1

    invoke-direct {v0, v1, v6}, Lcom/fasterxml/jackson/databind/jsontype/NamedType;-><init>(Ljava/lang/Class;Ljava/lang/String;)V

    move-object p2, v0

    .line 149
    :cond_0
    invoke-virtual {p5, p2}, Ljava/util/HashMap;->containsKey(Ljava/lang/Object;)Z

    move-result v0

    if-eqz v0, :cond_2

    .line 151
    invoke-virtual {p2}, Lcom/fasterxml/jackson/databind/jsontype/NamedType;->hasName()Z

    move-result v0

    if-eqz v0, :cond_1

    .line 152
    invoke-virtual {p5, p2}, Ljava/util/HashMap;->get(Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Lcom/fasterxml/jackson/databind/jsontype/NamedType;

    .line 153
    invoke-virtual {v0}, Lcom/fasterxml/jackson/databind/jsontype/NamedType;->hasName()Z

    move-result v0

    if-nez v0, :cond_1

    .line 154
    invoke-virtual {p5, p2, p2}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;

    .line 157
    :cond_1
    return-void

    .line 160
    :cond_2
    invoke-virtual {p5, p2, p2}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;

    .line 161
    invoke-virtual {p4, p1}, Lcom/fasterxml/jackson/databind/AnnotationIntrospector;->findSubtypes(Lcom/fasterxml/jackson/databind/introspect/Annotated;)Ljava/util/List;

    move-result-object v0

    .line 162
    move-object v6, v0

    if-eqz v0, :cond_4

    invoke-interface {v6}, Ljava/util/Collection;->isEmpty()Z

    move-result v0

    if-nez v0, :cond_4

    .line 163
    invoke-interface {v6}, Ljava/util/Collection;->iterator()Ljava/util/Iterator;

    move-result-object p1

    :goto_0
    invoke-interface {p1}, Ljava/util/Iterator;->hasNext()Z

    move-result v0

    if-eqz v0, :cond_4

    invoke-interface {p1}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Lcom/fasterxml/jackson/databind/jsontype/NamedType;

    .line 164
    move-object p2, v0

    invoke-virtual {v0}, Lcom/fasterxml/jackson/databind/jsontype/NamedType;->getType()Ljava/lang/Class;

    move-result-object v0

    invoke-static {v0, p4, p3}, Lcom/fasterxml/jackson/databind/introspect/AnnotatedClass;->constructWithoutSuperTypes(Ljava/lang/Class;Lcom/fasterxml/jackson/databind/AnnotationIntrospector;Lcom/fasterxml/jackson/databind/introspect/ClassIntrospector$MixInResolver;)Lcom/fasterxml/jackson/databind/introspect/AnnotatedClass;

    move-result-object v6

    .line 166
    invoke-virtual {p2}, Lcom/fasterxml/jackson/databind/jsontype/NamedType;->hasName()Z

    move-result v0

    if-nez v0, :cond_3

    .line 167
    new-instance v0, Lcom/fasterxml/jackson/databind/jsontype/NamedType;

    invoke-virtual {p2}, Lcom/fasterxml/jackson/databind/jsontype/NamedType;->getType()Ljava/lang/Class;

    move-result-object v1

    invoke-virtual {p4, v6}, Lcom/fasterxml/jackson/databind/AnnotationIntrospector;->findTypeName(Lcom/fasterxml/jackson/databind/introspect/AnnotatedClass;)Ljava/lang/String;

    move-result-object v2

    invoke-direct {v0, v1, v2}, Lcom/fasterxml/jackson/databind/jsontype/NamedType;-><init>(Ljava/lang/Class;Ljava/lang/String;)V

    move-object p2, v0

    .line 169
    :cond_3
    move-object v0, p0

    move-object v1, v6

    move-object v2, p2

    move-object v3, p3

    move-object v4, p4

    move-object v5, p5

    invoke-virtual/range {v0 .. v5}, Lcom/fasterxml/jackson/databind/jsontype/impl/StdSubtypeResolver;->_collectAndResolve(Lcom/fasterxml/jackson/databind/introspect/AnnotatedClass;Lcom/fasterxml/jackson/databind/jsontype/NamedType;Lcom/fasterxml/jackson/databind/cfg/MapperConfig;Lcom/fasterxml/jackson/databind/AnnotationIntrospector;Ljava/util/HashMap;)V

    .line 170
    goto :goto_0

    .line 172
    :cond_4
    return-void
.end method

.method public collectAndResolveSubtypes(Lcom/fasterxml/jackson/databind/introspect/AnnotatedClass;Lcom/fasterxml/jackson/databind/cfg/MapperConfig;Lcom/fasterxml/jackson/databind/AnnotationIntrospector;)Ljava/util/Collection;
    .locals 11
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(Lcom/fasterxml/jackson/databind/introspect/AnnotatedClass;Lcom/fasterxml/jackson/databind/cfg/MapperConfig<*>;Lcom/fasterxml/jackson/databind/AnnotationIntrospector;)Ljava/util/Collection<Lcom/fasterxml/jackson/databind/jsontype/NamedType;>;"
        }
    .end annotation

    .line 110
    new-instance v6, Ljava/util/HashMap;

    invoke-direct {v6}, Ljava/util/HashMap;-><init>()V

    .line 112
    iget-object v0, p0, Lcom/fasterxml/jackson/databind/jsontype/impl/StdSubtypeResolver;->_registeredSubtypes:Ljava/util/LinkedHashSet;

    if-eqz v0, :cond_1

    .line 113
    invoke-virtual {p1}, Lcom/fasterxml/jackson/databind/introspect/AnnotatedClass;->getRawType()Ljava/lang/Class;

    move-result-object v7

    .line 114
    iget-object v0, p0, Lcom/fasterxml/jackson/databind/jsontype/impl/StdSubtypeResolver;->_registeredSubtypes:Ljava/util/LinkedHashSet;

    invoke-virtual {v0}, Ljava/util/LinkedHashSet;->iterator()Ljava/util/Iterator;

    move-result-object v8

    :goto_0
    invoke-interface {v8}, Ljava/util/Iterator;->hasNext()Z

    move-result v0

    if-eqz v0, :cond_1

    invoke-interface {v8}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Lcom/fasterxml/jackson/databind/jsontype/NamedType;

    move-object v9, v0

    .line 116
    invoke-virtual {v9}, Lcom/fasterxml/jackson/databind/jsontype/NamedType;->getType()Ljava/lang/Class;

    move-result-object v0

    invoke-virtual {v7, v0}, Ljava/lang/Class;->isAssignableFrom(Ljava/lang/Class;)Z

    move-result v0

    if-eqz v0, :cond_0

    .line 117
    invoke-virtual {v9}, Lcom/fasterxml/jackson/databind/jsontype/NamedType;->getType()Ljava/lang/Class;

    move-result-object v0

    invoke-static {v0, p3, p2}, Lcom/fasterxml/jackson/databind/introspect/AnnotatedClass;->constructWithoutSuperTypes(Ljava/lang/Class;Lcom/fasterxml/jackson/databind/AnnotationIntrospector;Lcom/fasterxml/jackson/databind/introspect/ClassIntrospector$MixInResolver;)Lcom/fasterxml/jackson/databind/introspect/AnnotatedClass;

    move-result-object v10

    .line 118
    move-object v0, p0

    move-object v1, v10

    move-object v2, v9

    move-object v3, p2

    move-object v4, p3

    move-object v5, v6

    invoke-virtual/range {v0 .. v5}, Lcom/fasterxml/jackson/databind/jsontype/impl/StdSubtypeResolver;->_collectAndResolve(Lcom/fasterxml/jackson/databind/introspect/AnnotatedClass;Lcom/fasterxml/jackson/databind/jsontype/NamedType;Lcom/fasterxml/jackson/databind/cfg/MapperConfig;Lcom/fasterxml/jackson/databind/AnnotationIntrospector;Ljava/util/HashMap;)V

    .line 120
    :cond_0
    goto :goto_0

    .line 123
    :cond_1
    new-instance v7, Lcom/fasterxml/jackson/databind/jsontype/NamedType;

    invoke-virtual {p1}, Lcom/fasterxml/jackson/databind/introspect/AnnotatedClass;->getRawType()Ljava/lang/Class;

    move-result-object v0

    const/4 v1, 0x0

    invoke-direct {v7, v0, v1}, Lcom/fasterxml/jackson/databind/jsontype/NamedType;-><init>(Ljava/lang/Class;Ljava/lang/String;)V

    .line 124
    move-object v0, p0

    move-object v1, p1

    move-object v2, v7

    move-object v3, p2

    move-object v4, p3

    move-object v5, v6

    invoke-virtual/range {v0 .. v5}, Lcom/fasterxml/jackson/databind/jsontype/impl/StdSubtypeResolver;->_collectAndResolve(Lcom/fasterxml/jackson/databind/introspect/AnnotatedClass;Lcom/fasterxml/jackson/databind/jsontype/NamedType;Lcom/fasterxml/jackson/databind/cfg/MapperConfig;Lcom/fasterxml/jackson/databind/AnnotationIntrospector;Ljava/util/HashMap;)V

    .line 125
    new-instance v0, Ljava/util/ArrayList;

    invoke-virtual {v6}, Ljava/util/HashMap;->values()Ljava/util/Collection;

    move-result-object v1

    invoke-direct {v0, v1}, Ljava/util/ArrayList;-><init>(Ljava/util/Collection;)V

    return-object v0
.end method

.method public collectAndResolveSubtypes(Lcom/fasterxml/jackson/databind/introspect/AnnotatedMember;Lcom/fasterxml/jackson/databind/cfg/MapperConfig;Lcom/fasterxml/jackson/databind/AnnotationIntrospector;)Ljava/util/Collection;
    .locals 1
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(Lcom/fasterxml/jackson/databind/introspect/AnnotatedMember;Lcom/fasterxml/jackson/databind/cfg/MapperConfig<*>;Lcom/fasterxml/jackson/databind/AnnotationIntrospector;)Ljava/util/Collection<Lcom/fasterxml/jackson/databind/jsontype/NamedType;>;"
        }
    .end annotation

    .annotation runtime Ljava/lang/Deprecated;
    .end annotation

    .line 60
    const/4 v0, 0x0

    invoke-virtual {p0, p1, p2, p3, v0}, Lcom/fasterxml/jackson/databind/jsontype/impl/StdSubtypeResolver;->collectAndResolveSubtypes(Lcom/fasterxml/jackson/databind/introspect/AnnotatedMember;Lcom/fasterxml/jackson/databind/cfg/MapperConfig;Lcom/fasterxml/jackson/databind/AnnotationIntrospector;Lcom/fasterxml/jackson/databind/JavaType;)Ljava/util/Collection;

    move-result-object v0

    return-object v0
.end method

.method public collectAndResolveSubtypes(Lcom/fasterxml/jackson/databind/introspect/AnnotatedMember;Lcom/fasterxml/jackson/databind/cfg/MapperConfig;Lcom/fasterxml/jackson/databind/AnnotationIntrospector;Lcom/fasterxml/jackson/databind/JavaType;)Ljava/util/Collection;
    .locals 10
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(Lcom/fasterxml/jackson/databind/introspect/AnnotatedMember;Lcom/fasterxml/jackson/databind/cfg/MapperConfig<*>;Lcom/fasterxml/jackson/databind/AnnotationIntrospector;Lcom/fasterxml/jackson/databind/JavaType;)Ljava/util/Collection<Lcom/fasterxml/jackson/databind/jsontype/NamedType;>;"
        }
    .end annotation

    .line 75
    if-nez p4, :cond_0

    invoke-virtual {p1}, Lcom/fasterxml/jackson/databind/introspect/AnnotatedMember;->getRawType()Ljava/lang/Class;

    move-result-object p4

    goto :goto_0

    :cond_0
    invoke-virtual {p4}, Lcom/fasterxml/jackson/databind/JavaType;->getRawClass()Ljava/lang/Class;

    move-result-object p4

    .line 77
    :goto_0
    new-instance v6, Ljava/util/HashMap;

    invoke-direct {v6}, Ljava/util/HashMap;-><init>()V

    .line 79
    iget-object v0, p0, Lcom/fasterxml/jackson/databind/jsontype/impl/StdSubtypeResolver;->_registeredSubtypes:Ljava/util/LinkedHashSet;

    if-eqz v0, :cond_2

    .line 80
    iget-object v0, p0, Lcom/fasterxml/jackson/databind/jsontype/impl/StdSubtypeResolver;->_registeredSubtypes:Ljava/util/LinkedHashSet;

    invoke-virtual {v0}, Ljava/util/LinkedHashSet;->iterator()Ljava/util/Iterator;

    move-result-object v7

    :goto_1
    invoke-interface {v7}, Ljava/util/Iterator;->hasNext()Z

    move-result v0

    if-eqz v0, :cond_2

    invoke-interface {v7}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Lcom/fasterxml/jackson/databind/jsontype/NamedType;

    move-object v8, v0

    .line 82
    invoke-virtual {v8}, Lcom/fasterxml/jackson/databind/jsontype/NamedType;->getType()Ljava/lang/Class;

    move-result-object v0

    invoke-virtual {p4, v0}, Ljava/lang/Class;->isAssignableFrom(Ljava/lang/Class;)Z

    move-result v0

    if-eqz v0, :cond_1

    .line 83
    invoke-virtual {v8}, Lcom/fasterxml/jackson/databind/jsontype/NamedType;->getType()Ljava/lang/Class;

    move-result-object v0

    invoke-static {v0, p3, p2}, Lcom/fasterxml/jackson/databind/introspect/AnnotatedClass;->constructWithoutSuperTypes(Ljava/lang/Class;Lcom/fasterxml/jackson/databind/AnnotationIntrospector;Lcom/fasterxml/jackson/databind/introspect/ClassIntrospector$MixInResolver;)Lcom/fasterxml/jackson/databind/introspect/AnnotatedClass;

    move-result-object v9

    .line 84
    move-object v0, p0

    move-object v1, v9

    move-object v2, v8

    move-object v3, p2

    move-object v4, p3

    move-object v5, v6

    invoke-virtual/range {v0 .. v5}, Lcom/fasterxml/jackson/databind/jsontype/impl/StdSubtypeResolver;->_collectAndResolve(Lcom/fasterxml/jackson/databind/introspect/AnnotatedClass;Lcom/fasterxml/jackson/databind/jsontype/NamedType;Lcom/fasterxml/jackson/databind/cfg/MapperConfig;Lcom/fasterxml/jackson/databind/AnnotationIntrospector;Ljava/util/HashMap;)V

    .line 86
    :cond_1
    goto :goto_1

    .line 90
    :cond_2
    invoke-virtual {p3, p1}, Lcom/fasterxml/jackson/databind/AnnotationIntrospector;->findSubtypes(Lcom/fasterxml/jackson/databind/introspect/Annotated;)Ljava/util/List;

    move-result-object v0

    .line 91
    move-object v7, v0

    if-eqz v0, :cond_3

    .line 92
    invoke-interface {v7}, Ljava/util/Collection;->iterator()Ljava/util/Iterator;

    move-result-object v8

    :goto_2
    invoke-interface {v8}, Ljava/util/Iterator;->hasNext()Z

    move-result v0

    if-eqz v0, :cond_3

    invoke-interface {v8}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Lcom/fasterxml/jackson/databind/jsontype/NamedType;

    .line 93
    move-object v9, v0

    invoke-virtual {v0}, Lcom/fasterxml/jackson/databind/jsontype/NamedType;->getType()Ljava/lang/Class;

    move-result-object v0

    invoke-static {v0, p3, p2}, Lcom/fasterxml/jackson/databind/introspect/AnnotatedClass;->constructWithoutSuperTypes(Ljava/lang/Class;Lcom/fasterxml/jackson/databind/AnnotationIntrospector;Lcom/fasterxml/jackson/databind/introspect/ClassIntrospector$MixInResolver;)Lcom/fasterxml/jackson/databind/introspect/AnnotatedClass;

    move-result-object p1

    .line 94
    move-object v0, p0

    move-object v1, p1

    move-object v2, v9

    move-object v3, p2

    move-object v4, p3

    move-object v5, v6

    invoke-virtual/range {v0 .. v5}, Lcom/fasterxml/jackson/databind/jsontype/impl/StdSubtypeResolver;->_collectAndResolve(Lcom/fasterxml/jackson/databind/introspect/AnnotatedClass;Lcom/fasterxml/jackson/databind/jsontype/NamedType;Lcom/fasterxml/jackson/databind/cfg/MapperConfig;Lcom/fasterxml/jackson/databind/AnnotationIntrospector;Ljava/util/HashMap;)V

    .line 95
    goto :goto_2

    .line 98
    :cond_3
    new-instance v8, Lcom/fasterxml/jackson/databind/jsontype/NamedType;

    const/4 v0, 0x0

    invoke-direct {v8, p4, v0}, Lcom/fasterxml/jackson/databind/jsontype/NamedType;-><init>(Ljava/lang/Class;Ljava/lang/String;)V

    .line 99
    invoke-static {p4, p3, p2}, Lcom/fasterxml/jackson/databind/introspect/AnnotatedClass;->constructWithoutSuperTypes(Ljava/lang/Class;Lcom/fasterxml/jackson/databind/AnnotationIntrospector;Lcom/fasterxml/jackson/databind/introspect/ClassIntrospector$MixInResolver;)Lcom/fasterxml/jackson/databind/introspect/AnnotatedClass;

    move-result-object v9

    .line 102
    move-object v0, p0

    move-object v1, v9

    move-object v2, v8

    move-object v3, p2

    move-object v4, p3

    move-object v5, v6

    invoke-virtual/range {v0 .. v5}, Lcom/fasterxml/jackson/databind/jsontype/impl/StdSubtypeResolver;->_collectAndResolve(Lcom/fasterxml/jackson/databind/introspect/AnnotatedClass;Lcom/fasterxml/jackson/databind/jsontype/NamedType;Lcom/fasterxml/jackson/databind/cfg/MapperConfig;Lcom/fasterxml/jackson/databind/AnnotationIntrospector;Ljava/util/HashMap;)V

    .line 103
    new-instance v0, Ljava/util/ArrayList;

    invoke-virtual {v6}, Ljava/util/HashMap;->values()Ljava/util/Collection;

    move-result-object v1

    invoke-direct {v0, v1}, Ljava/util/ArrayList;-><init>(Ljava/util/Collection;)V

    return-object v0
.end method

.method public varargs registerSubtypes([Lcom/fasterxml/jackson/databind/jsontype/NamedType;)V
    .locals 4

    .line 34
    iget-object v0, p0, Lcom/fasterxml/jackson/databind/jsontype/impl/StdSubtypeResolver;->_registeredSubtypes:Ljava/util/LinkedHashSet;

    if-nez v0, :cond_0

    .line 35
    new-instance v0, Ljava/util/LinkedHashSet;

    invoke-direct {v0}, Ljava/util/LinkedHashSet;-><init>()V

    iput-object v0, p0, Lcom/fasterxml/jackson/databind/jsontype/impl/StdSubtypeResolver;->_registeredSubtypes:Ljava/util/LinkedHashSet;

    .line 37
    :cond_0
    move-object v0, p1

    move-object p1, v0

    array-length v1, v0

    const/4 v2, 0x0

    :goto_0
    if-ge v2, v1, :cond_1

    aget-object v3, p1, v2

    .line 38
    iget-object v0, p0, Lcom/fasterxml/jackson/databind/jsontype/impl/StdSubtypeResolver;->_registeredSubtypes:Ljava/util/LinkedHashSet;

    invoke-virtual {v0, v3}, Ljava/util/LinkedHashSet;->add(Ljava/lang/Object;)Z

    .line 37
    add-int/lit8 v2, v2, 0x1

    goto :goto_0

    .line 40
    :cond_1
    return-void
.end method

.method public varargs registerSubtypes([Ljava/lang/Class;)V
    .locals 5
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "([Ljava/lang/Class<*>;)V"
        }
    .end annotation

    .line 45
    array-length v0, p1

    new-array v2, v0, [Lcom/fasterxml/jackson/databind/jsontype/NamedType;

    .line 46
    const/4 v3, 0x0

    array-length v4, p1

    :goto_0
    if-ge v3, v4, :cond_0

    .line 47
    new-instance v0, Lcom/fasterxml/jackson/databind/jsontype/NamedType;

    aget-object v1, p1, v3

    invoke-direct {v0, v1}, Lcom/fasterxml/jackson/databind/jsontype/NamedType;-><init>(Ljava/lang/Class;)V

    aput-object v0, v2, v3

    .line 46
    add-int/lit8 v3, v3, 0x1

    goto :goto_0

    .line 49
    :cond_0
    invoke-virtual {p0, v2}, Lcom/fasterxml/jackson/databind/jsontype/impl/StdSubtypeResolver;->registerSubtypes([Lcom/fasterxml/jackson/databind/jsontype/NamedType;)V

    .line 50
    return-void
.end method


text:
package it.unibz.inf.ontop.spec.ontology;

/**
 * Represents DataPropertyExpression in OWL 2 QL specification.
 *
 * DataPropertyExpression := DataProperty
 *
 * where
 * 		DataProperty := IRI
 *
 * @author roman
 *
 */

import java.util.Collection;

import org.apache.commons.rdf.api.IRI;

/**
 * Represents DataPropertyExpression from the OWL 2 QL Specification
 *
 * DataPropertyExpression := DataProperty
 *
 * Support for owl:topDataProperty and owl:bottomDataProperty
 *
 * @author Roman Kontchakov
 *
 */

public interface DataPropertyExpression extends DescriptionBT {

	IRI getIRI();

	/**
	 * returns the DataSomeValuesFrom for the domain of the data property
	 *
	 * @return
	 */

	DataSomeValuesFrom getDomainRestriction(Datatype datatype);

	Collection<DataSomeValuesFrom> getAllDomainRestrictions();

	/**
	 * returns the DataPropertyRangeExpression for the range of the data property
	 *
	 * @return
	 */
	DataPropertyRangeExpression getRange();
}


text:
import React, {Component} from "react";
import { addAnimationClass, removeAnimationClass } from './modules/animationFunctions.js'

export default class MobileSlideNav extends Component {
  componentDidMount () {
    addAnimationClass('.slide-nav', 'slide-out-nav')
  }

  handleCloseSlideNav = () => {
    removeAnimationClass('.slide-nav', 'slide-out-nav')
    addAnimationClass('.slide-nav', 'slide-in-nav')
    setTimeout(() => this.props.closeSlideNav(), 500)
  }

  handleSlideNavScroll = (element) => {
    this.handleCloseSlideNav()
    this.props.scrollToComponent(element)
  }

  render () {
    return (

 this.handleSlideNavScroll('header') }>HOME

 this.handleSlideNavScroll('about') }>ABOUT

 this.handleSlideNavScroll('resume') }>RESUME

 this.handleSlideNavScroll('portfolio') }>PORTFOLIO

 this.handleSlideNavScroll('footer') }>CONTACT

    )
  }
}


text:
<?php defined('SYSPATH') OR die('No direct script access.');

abstract class Model_Database extends Kohana_Model_Database
{
    public function execute_for_object($query)
    {
        return $query->execute_for_object($this->_db);
    }

    public function execute_for_objects_array($query)
    {
        return $query->execute_for_objects_array($this->_db);
    }

    public function execute($query)
    {
        return $query->execute($this->_db);
    }
}


text:
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric      #-}
{-# LANGUAGE EmptyDataDecls     #-}
{-# LANGUAGE FlexibleContexts   #-}
{-# LANGUAGE OverloadedStrings  #-}
{-# LANGUAGE TemplateHaskell    #-}
{-# LANGUAGE TupleSections      #-}

-- | Resolving a build plan for a set of packages in a given Stackage
-- snapshot.

module Stack.BuildPlan
    ( BuildPlanException (..)
    , MiniBuildPlan(..)
    , MiniPackageInfo(..)
    , Snapshots (..)
    , getSnapshots
    , loadMiniBuildPlan
    , resolveBuildPlan
    , findBuildPlan
    , ToolMap
    , getToolMap
    , shadowMiniBuildPlan
    , parseCustomMiniBuildPlan
    ) where

import           Control.Applicative
import           Control.Exception (assert)
import           Control.Monad (liftM, forM)
import           Control.Monad.Catch
import           Control.Monad.IO.Class
import           Control.Monad.Logger
import           Control.Monad.Reader (asks)
import           Control.Monad.State.Strict      (State, execState, get, modify,
                                                  put)
import           Control.Monad.Trans.Control (MonadBaseControl)
import qualified Crypto.Hash.SHA256 as SHA256
import           Data.Aeson.Extended (FromJSON (..), withObject, withText, (.:), (.:?), (.!=))
import           Data.Binary.VersionTagged (taggedDecodeOrLoad)
import           Data.ByteString (ByteString)
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString as S
import qualified Data.ByteString.Char8 as S8
import           Data.Either (partitionEithers)
import qualified Data.Foldable as F
import qualified Data.HashMap.Strict as HM
import           Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import           Data.List (intercalate)
import           Data.Map (Map)
import qualified Data.Map as Map
import           Data.Maybe (fromMaybe, mapMaybe)
import           Data.Monoid
import           Data.Set (Set)
import qualified Data.Set as Set
import qualified Data.Text as T
import           Data.Text.Encoding (encodeUtf8)
import           Data.Time (Day)
import qualified Data.Traversable as Tr
import           Data.Typeable (Typeable)
import           Data.Yaml (decodeEither', decodeFileEither)
import           Distribution.PackageDescription (GenericPackageDescription,
                                                  flagDefault, flagManual,
                                                  flagName, genPackageFlags,
                                                  executables, exeName, library, libBuildInfo, buildable)
import qualified Distribution.Package as C
import qualified Distribution.PackageDescription as C
import qualified Distribution.Version as C
import           Distribution.Text (display)
import           Network.HTTP.Download
import           Network.HTTP.Types (Status(..))
import           Network.HTTP.Client (checkStatus)
import           Path
import           Path.IO
import           Prelude -- Fix AMP warning
import           Stack.Constants
import           Stack.Fetch
import           Stack.Package
import           Stack.Types
import           Stack.Types.StackT
import           System.Directory (canonicalizePath)
import qualified System.FilePath as FP

data BuildPlanException
    = UnknownPackages
        (Path Abs File) -- stack.yaml file
        (Map PackageName (Maybe Version, (Set PackageName))) -- truly unknown
        (Map PackageName (Set PackageIdentifier)) -- shadowed
    | SnapshotNotFound SnapName
    deriving (Typeable)
instance Exception BuildPlanException
instance Show BuildPlanException where
    show (SnapshotNotFound snapName) = unlines
        [ "SnapshotNotFound " ++ snapName'
        , "Non existing resolver: " ++ snapName' ++ "."
        , "For a complete list of available snapshots see https://www.stackage.org/snapshots"
        ]
        where snapName' = show $ renderSnapName snapName
    show (UnknownPackages stackYaml unknown shadowed) =
        unlines $ unknown' ++ shadowed'
      where
        unknown' :: [String]
        unknown'
            | Map.null unknown = []
            | otherwise = concat
                [ ["The following packages do not exist in the build plan:"]
                , map go (Map.toList unknown)
                , case mapMaybe goRecommend $ Map.toList unknown of
                    [] -> []
                    rec ->
                        ("Recommended action: modify the extra-deps field of " ++
                        toFilePath stackYaml ++
                        " to include the following:")
                        : (rec
                        ++ ["Note: further dependencies may need to be added"])
                , case mapMaybe getNoKnown $ Map.toList unknown of
                    [] -> []
                    noKnown ->
                        [ "There are no known versions of the following packages:"
                        , intercalate ", " $ map packageNameString noKnown
                        ]
                ]
          where
            go (dep, (_, users)) | Set.null users = packageNameString dep
            go (dep, (_, users)) = concat
                [ packageNameString dep
                , " (used by "
                , intercalate ", " $ map packageNameString $ Set.toList users
                , ")"
                ]

            goRecommend (name, (Just version, _)) =
                Just $ "- " ++ packageIdentifierString (PackageIdentifier name version)
            goRecommend (_, (Nothing, _)) = Nothing

            getNoKnown (name, (Nothing, _)) = Just name
            getNoKnown (_, (Just _, _)) = Nothing

        shadowed' :: [String]
        shadowed'
            | Map.null shadowed = []
            | otherwise = concat
                [ ["The following packages are shadowed by local packages:"]
                , map go (Map.toList shadowed)
                , ["Recommended action: modify the extra-deps field of " ++
                   toFilePath stackYaml ++
                   " to include the following:"]
                , extraDeps
                , ["Note: further dependencies may need to be added"]
                ]
          where
            go (dep, users) | Set.null users = concat
                [ packageNameString dep
                , " (internal stack error: this should never be null)"
                ]
            go (dep, users) = concat
                [ packageNameString dep
                , " (used by "
                , intercalate ", "
                    $ map (packageNameString . packageIdentifierName)
                    $ Set.toList users
                , ")"
                ]

            extraDeps = map (\ident -> "- " ++ packageIdentifierString ident)
                      $ Set.toList
                      $ Set.unions
                      $ Map.elems shadowed

-- | Determine the necessary packages to install to have the given set of
-- packages available.
--
-- This function will not provide test suite and benchmark dependencies.
--
-- This may fail if a target package is not present in the @BuildPlan@.
resolveBuildPlan :: (MonadThrow m, MonadIO m, MonadReader env m, HasBuildConfig env, MonadLogger m, HasHttpManager env, MonadBaseControl IO m,MonadCatch m)
                 => MiniBuildPlan
                 -> (PackageName -> Bool) -- ^ is it shadowed by a local package?
                 -> Map PackageName (Set PackageName) -- ^ required packages, and users of it
                 -> m ( Map PackageName (Version, Map FlagName Bool)
                      , Map PackageName (Set PackageName)
                      )
resolveBuildPlan mbp isShadowed packages
    | Map.null (rsUnknown rs) && Map.null (rsShadowed rs) = return (rsToInstall rs, rsUsedBy rs)
    | otherwise = do
        bconfig <- asks getBuildConfig
        let maxVer =
                Map.fromListWith max $
                map toTuple $
                Map.keys (bcPackageCaches bconfig)
            unknown = flip Map.mapWithKey (rsUnknown rs) $ \ident x ->
                (Map.lookup ident maxVer, x)
        throwM $ UnknownPackages
            (bcStackYaml bconfig)
            unknown
            (rsShadowed rs)
  where
    rs = getDeps mbp isShadowed packages

data ResolveState = ResolveState
    { rsVisited   :: Map PackageName (Set PackageName) -- ^ set of shadowed dependencies
    , rsUnknown   :: Map PackageName (Set PackageName)
    , rsShadowed  :: Map PackageName (Set PackageIdentifier)
    , rsToInstall :: Map PackageName (Version, Map FlagName Bool)
    , rsUsedBy    :: Map PackageName (Set PackageName)
    }

toMiniBuildPlan :: (MonadIO m, MonadLogger m, MonadReader env m, HasHttpManager env, MonadThrow m, HasConfig env, MonadBaseControl IO m, MonadCatch m)
                => CompilerVersion -- ^ Compiler version
                -> Map PackageName Version -- ^ cores
                -> Map PackageName (Version, Map FlagName Bool) -- ^ non-core packages
                -> m MiniBuildPlan
toMiniBuildPlan compilerVersion corePackages packages = do
    $logInfo "Caching build plan"

    -- Determine the dependencies of all of the packages in the build plan. We
    -- handle core packages specially, because some of them will not be in the
    -- package index. For those, we allow missing packages to exist, and then
    -- remove those from the list of dependencies, since there's no way we'll
    -- ever reinstall them anyway.
    (cores, missingCores) <- addDeps True compilerVersion
        $ fmap (, Map.empty) corePackages

    (extras, missing) <- addDeps False compilerVersion packages

    assert (Set.null missing) $ return MiniBuildPlan
        { mbpCompilerVersion = compilerVersion
        , mbpPackages = Map.unions
            [ fmap (removeMissingDeps (Map.keysSet cores)) cores
            , extras
            , Map.fromList $ map goCore $ Set.toList missingCores
            ]
        }
  where
    goCore (PackageIdentifier name version) = (name, MiniPackageInfo
                { mpiVersion = version
                , mpiFlags = Map.empty
                , mpiPackageDeps = Set.empty
                , mpiToolDeps = Set.empty
                , mpiExes = Set.empty
                , mpiHasLibrary = True
                })

    removeMissingDeps cores mpi = mpi
        { mpiPackageDeps = Set.intersection cores (mpiPackageDeps mpi)
        }

-- | Add in the resolved dependencies from the package index
addDeps :: (MonadIO m, MonadLogger m, MonadReader env m, HasHttpManager env, MonadThrow m, HasConfig env, MonadBaseControl IO m, MonadCatch m)
        => Bool -- ^ allow missing
        -> CompilerVersion -- ^ Compiler version
        -> Map PackageName (Version, Map FlagName Bool)
        -> m (Map PackageName MiniPackageInfo, Set PackageIdentifier)
addDeps allowMissing compilerVersion toCalc = do
    menv <- getMinimalEnvOverride
    platform <- asks $ configPlatform . getConfig
    (resolvedMap, missingIdents) <-
        if allowMissing
            then do
                (missingNames, missingIdents, m) <-
                    resolvePackagesAllowMissing menv (Map.keysSet idents0) Set.empty
                assert (Set.null missingNames)
                    $ return (m, missingIdents)
            else do
                m <- resolvePackages menv (Map.keysSet idents0) Set.empty
                return (m, Set.empty)
    let byIndex = Map.fromListWith (++) $ flip map (Map.toList resolvedMap)
            $ \(ident, rp) ->
                (indexName $ rpIndex rp,
                    [( ident
                    , rpCache rp
                    , maybe Map.empty snd $ Map.lookup (packageIdentifierName ident) toCalc
                    )])
    res <- forM (Map.toList byIndex) $ \(indexName', pkgs) -> withCabalFiles indexName' pkgs
        $ \ident flags cabalBS -> do
            (_warnings,gpd) <- readPackageUnresolvedBS Nothing cabalBS
            let packageConfig = PackageConfig
                    { packageConfigEnableTests = False
                    , packageConfigEnableBenchmarks = False
                    , packageConfigFlags = flags
                    , packageConfigCompilerVersion = compilerVersion
                    , packageConfigPlatform = platform
                    }
                name = packageIdentifierName ident
                pd = resolvePackageDescription packageConfig gpd
                exes = Set.fromList $ map (ExeName . S8.pack . exeName) $ executables pd
                notMe = Set.filter (/= name) . Map.keysSet
            return (name, MiniPackageInfo
                { mpiVersion = packageIdentifierVersion ident
                , mpiFlags = flags
                , mpiPackageDeps = notMe $ packageDependencies pd
                , mpiToolDeps = Map.keysSet $ packageToolDependencies pd
                , mpiExes = exes
                , mpiHasLibrary = maybe
                    False
                    (buildable . libBuildInfo)
                    (library pd)
                })
    return (Map.fromList $ concat res, missingIdents)
  where
    idents0 = Map.fromList
        $ map (\(n, (v, f)) -> (PackageIdentifier n v, Left f))
        $ Map.toList toCalc

-- | Resolve all packages necessary to install for
getDeps :: MiniBuildPlan
        -> (PackageName -> Bool) -- ^ is it shadowed by a local package?
        -> Map PackageName (Set PackageName)
        -> ResolveState
getDeps mbp isShadowed packages =
    execState (mapM_ (uncurry goName) $ Map.toList packages) ResolveState
        { rsVisited = Map.empty
        , rsUnknown = Map.empty
        , rsShadowed = Map.empty
        , rsToInstall = Map.empty
        , rsUsedBy = Map.empty
        }
  where
    toolMap = getToolMap mbp

    -- | Returns a set of shadowed packages we depend on.
    goName :: PackageName -> Set PackageName -> State ResolveState (Set PackageName)
    goName name users = do
        -- Even though we could check rsVisited first and short-circuit things
        -- earlier, lookup in mbpPackages first so that we can produce more
        -- usable error information on missing dependencies
        rs <- get
        put rs
            { rsUsedBy = Map.insertWith Set.union name users $ rsUsedBy rs
            }
        case Map.lookup name $ mbpPackages mbp of
            Nothing -> do
                modify $ \rs' -> rs'
                    { rsUnknown = Map.insertWith Set.union name users $ rsUnknown rs'
                    }
                return Set.empty
            Just mpi -> case Map.lookup name (rsVisited rs) of
              Just shadowed -> return shadowed
              Nothing -> do
                put rs { rsVisited = Map.insert name Set.empty $ rsVisited rs }
                let depsForTools = Set.unions $ mapMaybe (flip Map.lookup toolMap) (Set.toList $ mpiToolDeps mpi)
                let deps = Set.filter (/= name) (mpiPackageDeps mpi <> depsForTools)
                shadowed <- fmap F.fold $ Tr.forM (Set.toList deps) $ \dep ->
                    if isShadowed dep
                        then do
                            modify $ \rs' -> rs'
                                { rsShadowed = Map.insertWith
                                    Set.union
                                    dep
                                    (Set.singleton $ PackageIdentifier name (mpiVersion mpi))
                                    (rsShadowed rs')
                                }
                            return $ Set.singleton dep
                        else do
                            shadowed <- goName dep (Set.singleton name)
                            let m = Map.fromSet (\_ -> Set.singleton $ PackageIdentifier name (mpiVersion mpi)) shadowed
                            modify $ \rs' -> rs'
                                { rsShadowed = Map.unionWith Set.union m $ rsShadowed rs'
                                }
                            return shadowed
                modify $ \rs' -> rs'
                    { rsToInstall = Map.insert name (mpiVersion mpi, mpiFlags mpi) $ rsToInstall rs'
                    , rsVisited = Map.insert name shadowed $ rsVisited rs'
                    }
                return shadowed

-- | Look up with packages provide which tools.
type ToolMap = Map ByteString (Set PackageName)

-- | Map from tool name to package providing it
getToolMap :: MiniBuildPlan -> Map ByteString (Set PackageName)
getToolMap mbp =
      Map.unionsWith Set.union

    {- We no longer do this, following discussion at:

        https://github.com/commercialhaskell/stack/issues/308#issuecomment-112076704

    -- First grab all of the package names, for times where a build tool is
    -- identified by package name
    $ Map.fromList (map (packageNameByteString &&& Set.singleton) (Map.keys ps))
    -}

    -- And then get all of the explicit executable names
    $ concatMap goPair (Map.toList ps)
  where
    ps = mbpPackages mbp

    goPair (pname, mpi) =
        map (flip Map.singleton (Set.singleton pname) . unExeName)
      $ Set.toList
      $ mpiExes mpi

-- | Download the 'Snapshots' value from stackage.org.
getSnapshots :: (MonadThrow m, MonadIO m, MonadReader env m, HasHttpManager env, HasStackRoot env, HasConfig env)
             => m Snapshots
getSnapshots = askLatestSnapshotUrl >>= parseUrl . T.unpack >>= downloadJSON

-- | Most recent Nightly and newest LTS version per major release.
data Snapshots = Snapshots
    { snapshotsNightly :: !Day
    , snapshotsLts     :: !(IntMap Int)
    }
    deriving Show
instance FromJSON Snapshots where
    parseJSON = withObject "Snapshots" $ \o -> Snapshots
        <$> (o .: "nightly" >>= parseNightly)
        <*> (fmap IntMap.unions
                $ mapM parseLTS
                $ map snd
                $ filter (isLTS . fst)
                $ HM.toList o)
      where
        parseNightly t =
            case parseSnapName t of
                Left e -> fail $ show e
                Right (LTS _ _) -> fail "Unexpected LTS value"
                Right (Nightly d) -> return d

        isLTS = ("lts-" `T.isPrefixOf`)

        parseLTS = withText "LTS" $ \t ->
            case parseSnapName t of
                Left e -> fail $ show e
                Right (LTS x y) -> return $ IntMap.singleton x y
                Right (Nightly _) -> fail "Unexpected nightly value"

-- | Load up a 'MiniBuildPlan', preferably from cache
loadMiniBuildPlan
    :: (MonadIO m, MonadThrow m, MonadLogger m, MonadReader env m, HasHttpManager env, HasConfig env, HasGHCVariant env, MonadBaseControl IO m, MonadCatch m)
    => SnapName
    -> m MiniBuildPlan
loadMiniBuildPlan name = do
    path <- configMiniBuildPlanCache name
    taggedDecodeOrLoad path $ liftM buildPlanFixes $ do
        bp <- loadBuildPlan name
        toMiniBuildPlan
            (siCompilerVersion $ bpSystemInfo bp)
            (siCorePackages $ bpSystemInfo bp)
            (fmap goPP $ bpPackages bp)
  where
    goPP pp =
        ( ppVersion pp
        , pcFlagOverrides $ ppConstraints pp
        )

-- | Some hard-coded fixes for build plans, hopefully to be irrelevant over
-- time.
buildPlanFixes :: MiniBuildPlan -> MiniBuildPlan
buildPlanFixes mbp = mbp
    { mbpPackages = Map.fromList $ map go $ Map.toList $ mbpPackages mbp
    }
  where
    go (name, mpi) =
        (name, mpi
            { mpiFlags = goF (packageNameString name) (mpiFlags mpi)
            })

    goF "persistent-sqlite" = Map.insert $(mkFlagName "systemlib") False
    goF "yaml" = Map.insert $(mkFlagName "system-libyaml") False
    goF _ = id

-- | Load the 'BuildPlan' for the given snapshot. Will load from a local copy
-- if available, otherwise downloading from Github.
loadBuildPlan :: (MonadIO m, MonadThrow m, MonadLogger m, MonadReader env m, HasHttpManager env, HasStackRoot env)
              => SnapName
              -> m BuildPlan
loadBuildPlan name = do
    env <- ask
    let stackage = getStackRoot env
    file' <- parseRelFile $ T.unpack file
    let fp = buildPlanDir stackage </> file'
    $logDebug $ "Decoding build plan from: " <> T.pack (toFilePath fp)
    eres <- liftIO $ decodeFileEither $ toFilePath fp
    case eres of
        Right bp -> return bp
        Left e -> do
            $logDebug $ "Decoding build plan from file failed: " <> T.pack (show e)
            createTree (parent fp)
            req <- parseUrl $ T.unpack url
            $logSticky $ "Downloading " <> renderSnapName name <> " build plan ..."
            $logDebug $ "Downloading build plan from: " <> url
            _ <- download req { checkStatus = handle404 } fp
            $logStickyDone $ "Downloaded " <> renderSnapName name <> " build plan."
            liftIO (decodeFileEither $ toFilePath fp) >>= either throwM return

  where
    file = renderSnapName name <> ".yaml"
    reponame =
        case name of
            LTS _ _ -> "lts-haskell"
            Nightly _ -> "stackage-nightly"
    url = rawGithubUrl "fpco" reponame "master" file
    handle404 (Status 404 _) _ _ = Just $ SomeException $ SnapshotNotFound name
    handle404 _ _ _              = Nothing

-- | Find the set of @FlagName@s necessary to get the given
-- @GenericPackageDescription@ to compile against the given @BuildPlan@. Will
-- only modify non-manual flags, and will prefer default values for flags.
-- Returns @Nothing@ if no combination exists.
checkBuildPlan :: (MonadLogger m, MonadThrow m, MonadIO m, MonadReader env m, HasConfig env, MonadCatch m)
               => Map PackageName Version -- ^ locally available packages
               -> MiniBuildPlan
               -> GenericPackageDescription
               -> m (Either DepErrors (Map PackageName (Map FlagName Bool)))
checkBuildPlan locals mbp gpd = do
    platform <- asks (configPlatform . getConfig)
    return $ loop platform flagOptions
  where
    packages = Map.union locals $ fmap mpiVersion $ mbpPackages mbp
    loop _ [] = assert False $ Left Map.empty
    loop platform (flags:rest)
        | Map.null errs = Right $
            if Map.null flags
                then Map.empty
                else Map.singleton (packageName pkg) flags
        | null rest = Left errs
        | otherwise = loop platform rest
      where
        errs = checkDeps (packageName pkg) (packageDeps pkg) packages
        pkg = resolvePackage pkgConfig gpd
        pkgConfig = PackageConfig
            { packageConfigEnableTests = True
            , packageConfigEnableBenchmarks = True
            , packageConfigFlags = flags
            , packageConfigCompilerVersion = compilerVersion
            , packageConfigPlatform = platform
            }

    compilerVersion = mbpCompilerVersion mbp

    flagName' = fromCabalFlagName . flagName

    -- Avoid exponential complexity in flag combinations making us sad pandas.
    -- See: https://github.com/commercialhaskell/stack/issues/543
    maxFlagOptions = 128

    flagOptions = take maxFlagOptions $ map Map.fromList $ mapM getOptions $ genPackageFlags gpd
    getOptions f
        | flagManual f = [(flagName' f, flagDefault f)]
        | flagDefault f =
            [ (flagName' f, True)
            , (flagName' f, False)
            ]
        | otherwise =
            [ (flagName' f, False)
            , (flagName' f, True)
            ]

-- | Checks if the given package dependencies can be satisfied by the given set
-- of packages. Will fail if a package is either missing or has a version
-- outside of the version range.
checkDeps :: PackageName -- ^ package using dependencies, for constructing DepErrors
          -> Map PackageName VersionRange
          -> Map PackageName Version
          -> DepErrors
checkDeps myName deps packages =
    Map.unionsWith mappend $ map go $ Map.toList deps
  where
    go :: (PackageName, VersionRange) -> DepErrors
    go (name, range) =
        case Map.lookup name packages of
            Nothing -> Map.singleton name DepError
                { deVersion = Nothing
                , deNeededBy = Map.singleton myName range
                }
            Just v
                | withinRange v range -> Map.empty
                | otherwise -> Map.singleton name DepError
                    { deVersion = Just v
                    , deNeededBy = Map.singleton myName range
                    }

type DepErrors = Map PackageName DepError
data DepError = DepError
    { deVersion :: !(Maybe Version)
    , deNeededBy :: !(Map PackageName VersionRange)
    }
instance Monoid DepError where
    mempty = DepError Nothing Map.empty
    mappend (DepError a x) (DepError b y) = DepError
        (maybe a Just b)
        (Map.unionWith C.intersectVersionRanges x y)

-- | Find a snapshot and set of flags that is compatible with the given
-- 'GenericPackageDescription'. Returns 'Nothing' if no such snapshot is found.
findBuildPlan :: (MonadIO m, MonadCatch m, MonadLogger m, MonadReader env m, HasHttpManager env, HasConfig env, HasGHCVariant env, MonadBaseControl IO m)
              => [GenericPackageDescription]
              -> [SnapName]
              -> m (Maybe (SnapName, Map PackageName (Map FlagName Bool)))
findBuildPlan gpds0 =
    loop
  where
    loop [] = return Nothing
    loop (name:names') = do
        mbp <- loadMiniBuildPlan name
        $logInfo $ "Checking against build plan " <> renderSnapName name
        res <- mapM (checkBuildPlan localNames mbp) gpds0
        case partitionEithers res of
            ([], flags) -> return $ Just (name, Map.unions flags)
            (errs, _) -> do
                $logInfo ""
                $logInfo "* Build plan did not match your requirements:"
                displayDepErrors $ Map.unionsWith mappend errs
                $logInfo ""
                loop names'

    localNames = Map.fromList $ map (fromCabalIdent . C.package . C.packageDescription) gpds0

    fromCabalIdent (C.PackageIdentifier name version) =
        (fromCabalPackageName name, fromCabalVersion version)

displayDepErrors :: MonadLogger m => DepErrors -> m ()
displayDepErrors errs =
    F.forM_ (Map.toList errs) $ \(depName, DepError mversion neededBy) -> do
        $logInfo $ T.concat
            [ "    "
            , T.pack $ packageNameString depName
            , case mversion of
                Nothing -> " not found"
                Just version -> T.concat
                    [ " version "
                    , T.pack $ versionString version
                    , " found"
                    ]
            ]
        F.forM_ (Map.toList neededBy) $ \(user, range) -> $logInfo $ T.concat
            [ "    - "
            , T.pack $ packageNameString user
            , " requires "
            , T.pack $ display range
            ]
        $logInfo ""

shadowMiniBuildPlan :: MiniBuildPlan
                    -> Set PackageName
                    -> (MiniBuildPlan, Map PackageName MiniPackageInfo)
shadowMiniBuildPlan (MiniBuildPlan cv pkgs0) shadowed =
    (MiniBuildPlan cv $ Map.fromList met, Map.fromList unmet)
  where
    pkgs1 = Map.difference pkgs0 $ Map.fromSet (\_ -> ()) shadowed

    depsMet = flip execState Map.empty $ mapM_ (check Set.empty) (Map.keys pkgs1)

    check visited name
        | name `Set.member` visited =
            error $ "shadowMiniBuildPlan: cycle detected, your MiniBuildPlan is broken: " ++ show (visited, name)
        | otherwise = do
            m <- get
            case Map.lookup name m of
                Just x -> return x
                Nothing ->
                    case Map.lookup name pkgs1 of
                        Nothing
                            | name `Set.member` shadowed -> return False

                            -- In this case, we have to assume that we're
                            -- constructing a build plan on a different OS or
                            -- architecture, and therefore different packages
                            -- are being chosen. The common example of this is
                            -- the Win32 package.
                            | otherwise -> return True
                        Just mpi -> do
                            let visited' = Set.insert name visited
                            ress <- mapM (check visited') (Set.toList $ mpiPackageDeps mpi)
                            let res = and ress
                            modify $ \m' -> Map.insert name res m'
                            return res

    (met, unmet) = partitionEithers $ map toEither $ Map.toList pkgs1

    toEither pair@(name, _) =
        wrapper pair
      where
        wrapper =
            case Map.lookup name depsMet of
                Just True -> Left
                Just False -> Right
                Nothing -> assert False Right

parseCustomMiniBuildPlan :: (MonadIO m, MonadCatch m, MonadLogger m, MonadReader env m, HasHttpManager env, HasConfig env, MonadBaseControl IO m)
                         => Path Abs File -- ^ stack.yaml file location
                         -> T.Text -> m MiniBuildPlan
parseCustomMiniBuildPlan stackYamlFP url0 = do
    yamlFP <- getYamlFP url0

    yamlBS <- liftIO $ S.readFile $ toFilePath yamlFP
    let yamlHash = S8.unpack $ B16.encode $ SHA256.hash yamlBS
    binaryFilename <- parseRelFile $ yamlHash ++ ".bin"
    customPlanDir <- getCustomPlanDir
    let binaryFP = customPlanDir </> $(mkRelDir "bin") </> binaryFilename

    taggedDecodeOrLoad binaryFP $ do
        cs <- either throwM return $ decodeEither' yamlBS
        let addFlags :: PackageIdentifier -> (PackageName, (Version, Map FlagName Bool))
            addFlags (PackageIdentifier name ver) =
                (name, (ver, fromMaybe Map.empty $ Map.lookup name $ csFlags cs))
        toMiniBuildPlan
            (csCompilerVersion cs)
            Map.empty
            (Map.fromList $ map addFlags $ Set.toList $ csPackages cs)
  where
    getCustomPlanDir = do
        root <- asks $ configStackRoot . getConfig
        return $ root </> $(mkRelDir "custom-plan")

    -- Get the path to the YAML file
    getYamlFP url =
        case parseUrl $ T.unpack url of
            Just req -> getYamlFPFromReq url req
            Nothing -> getYamlFPFromFile url

    getYamlFPFromReq url req = do
        let hashStr = S8.unpack $ B16.encode $ SHA256.hash $ encodeUtf8 url
        hashFP <- parseRelFile $ hashStr ++ ".yaml"
        customPlanDir <- getCustomPlanDir

        let cacheFP = customPlanDir </> $(mkRelDir "yaml") </> hashFP
        _ <- download req cacheFP
        return cacheFP

    getYamlFPFromFile url = do
        fp <- liftIO $ canonicalizePath $ toFilePath (parent stackYamlFP) FP.</> T.unpack (fromMaybe url $
            T.stripPrefix "file://" url <|> T.stripPrefix "file:" url)
        parseAbsFile fp

data CustomSnapshot = CustomSnapshot
    { csCompilerVersion :: !CompilerVersion
    , csPackages :: !(Set PackageIdentifier)
    , csFlags :: !(Map PackageName (Map FlagName Bool))
    }
instance FromJSON CustomSnapshot where
    parseJSON = withObject "CustomSnapshot" $ \o -> CustomSnapshot
        <$> ((o .: "compiler") >>= \t ->
                case parseCompilerVersion t of
                    Nothing -> fail $ "Invalid compiler: " ++ T.unpack t
                    Just compilerVersion -> return compilerVersion)
        <*> o .: "packages"
        <*> o .:? "flags" .!= Map.empty