text:
using namespace gl;
using namespace globjects;

RigAnimatedObject::RigAnimatedObject(gloperate::Scene *animated, gloperate::Scene *animations)
{

    for(gloperate::PolygonalGeometry* curDrawable : animated->meshes())
    {
        m_animated.push_back(std::shared_ptr<RiggedDrawable>{new RiggedDrawable(*curDrawable)});
    }
    m_animations = std::shared_ptr<gloperate::Scene>(animations);

    m_program = new Program{};
    m_program->attach(
        Shader::fromFile(GL_VERTEX_SHADER, "data/animationexample/rigAnim.vert"),
        Shader::fromFile(GL_FRAGMENT_SHADER, "data/animationexample/rigAnim.frag"));

    m_transformLocation = m_program->getUniformLocation("transform");
    m_bonesUniform = new globjects::Uniform<std::vector<glm::mat4>>{"bones"};
    m_program->addUniform(m_bonesUniform);
}

void RigAnimatedObject::draw(float time, const glm::mat4 &viewProjection)
{

    for(auto& curDrawable : m_animated)
    {
        std::vector<glm::mat4> current = interpolate(time, curDrawable);

        m_program->use();
        m_program->setUniform(m_transformLocation,  viewProjection);

        m_bonesUniform->set(current);

        curDrawable->draw();
    }

    m_program->release();
}

std::vector<glm::mat4> RigAnimatedObject::interpolate(float t, std::shared_ptr<RiggedDrawable> curAnimated)
{
    std::vector<glm::mat4> boneTransforms{curAnimated->m_bindTransforms.size()};

    interpolateRecursively(*(m_animations->boneHierarchy()), t, boneTransforms,
                           glm::mat4(), curAnimated);

    return boneTransforms;
}

void RigAnimatedObject::interpolateRecursively(const BoneNode& Bone,
                                               float t,
                                               std::vector<glm::mat4> &into,
                                               glm::mat4 parentTransform,
                                               std::shared_ptr<RiggedDrawable> curAnimated)

{

    //Of course sometimes the model and the animation have different views about the start of the hierarchy
    //if(Bone.boneName == "<MD5_Hierarchy>")
    //{
    //    interpolateRecursively(Bone.children[0],t,into,parentTransform,curAnimated);
    //    return;
    //}
    gloperate::RigAnimationTrack* Animation = m_animations->animations()[0];
    gloperate::Channel* BoneChannel = nullptr;
    for(size_t i = 0; i < Animation->boneChannels.size(); i++)
    {
        if(Animation->boneChannels.at(i).boneName == Bone.boneName)
        {
            BoneChannel = &(Animation->boneChannels[i]);
        }
    }
    if(!BoneChannel)
    {
        interpolateRecursively(Bone.children[0],t,into,parentTransform,curAnimated);
        return;
    }

    float ticks = t * Animation->ticksPerSecond;

    //Find the corresponding Translate key and interpolate
    glm::vec3 translation;
    if(BoneChannel->translation.size() > 1)
    {
        gloperate::TranslationKey first,second;
        for(size_t i = 0; i < BoneChannel->translation.size(); i++)
        {
            if(ticks < BoneChannel->translation[i].time)
            {
                second = BoneChannel->translation[i];
            }
            else
            {
                first = BoneChannel->translation[i];
            }
        }
        float dist = second.time - first.time;
        float pos = t - first.time; // The distance to the first frame
        float normPos = pos/dist;	// Normalized position between 0 an 1
        normPos = normPos < 0 ? 0 : normPos;
        normPos = normPos > 1 ? 1 : normPos;
        translation = glm::mix(first.translation,second.translation,normPos);
    }
    else
    {
         if(BoneChannel->translation.size() != 0)
         {
            translation = BoneChannel->translation[0].translation;
         }
    }

    glm::quat rotation;
    if(BoneChannel->rotation.size() > 1)
    {
        gloperate::RotationKey first,second;
        for(size_t i = 0; i < BoneChannel->rotation.size(); i++)
        {
            if(ticks < BoneChannel->rotation[i].time)
            {
                second = BoneChannel->rotation[i];
            }
            else
            {
                first = BoneChannel->rotation[i];
            }
        }
        float dist = second.time - first.time;
        float pos = t - first.time; // The distance to the first frame
        float normPos = pos/dist;	// Normalized position between 0 an 1
        normPos = normPos < 0 ? 0 : normPos;
        normPos = normPos > 1 ? 1 : normPos;
        rotation = glm::mix(first.rotation,second.rotation,normPos);
    }
    else
    {
         if(BoneChannel->rotation.size() != 0)
         {
            rotation = BoneChannel->rotation[0].rotation;
         }
    }

    glm::vec3 scale;
    if(BoneChannel->scale.size() > 1)
    {
        gloperate::ScaleKey first,second;
        for(size_t i = 0; i < BoneChannel->scale.size(); i++)
        {
            if(ticks < BoneChannel->scale[i].time)
            {
                second = BoneChannel->scale[i];
            }
            else
            {
                first = BoneChannel->scale[i];
            }
        }
        float dist = second.time - first.time;
        float pos = t - first.time; // The distance to the first frame
        float normPos = pos/dist;	// Normalized position between 0 an 1
        normPos = normPos < 0 ? 0 : normPos;
        normPos = normPos > 1 ? 1 : normPos;
        scale = glm::mix(first.scale,second.scale,normPos);
    }
    else
    {
         if(BoneChannel->scale.size() != 0)
         {
            scale = BoneChannel->scale[0].scale;
         }
    }

    glm::mat4 transform;
    transform = glm::translate(transform, translation);
    transform = glm::scale(transform, scale);
    transform = transform * glm::mat4_cast(rotation);
    transform = parentTransform * transform;

    if(curAnimated->m_boneMapping.count(BoneChannel->boneName) == 1)
    {
        auto boneIndex = curAnimated->m_boneMapping.at(BoneChannel->boneName);
        into[boneIndex] = transform * curAnimated->m_bindTransforms[boneIndex];
    }

    for (auto& child : Bone.children) {

        interpolateRecursively(child, t, into, transform, curAnimated);
    }
}


text:
<?php
/**
 * @file
 * Contains \Drupal\bootstrap\Plugin\Prerender\Operations.
 */

namespace Drupal\bootstrap\Plugin\Prerender;

use Drupal\bootstrap\Annotation\BootstrapPrerender;

/**
 * Pre-render callback for the "operations" element type.
 *
 * @ingroup plugins_prerender
 *
 * @BootstrapPrerender("operations",
 *   replace = "Drupal\Core\Render\Element\Operations::preRenderDropbutton"
 * )
 *
 * @see \Drupal\bootstrap\Plugin\Prerender\Dropbutton
 * @see \Drupal\Core\Render\Element\Operations::preRenderDropbutton()
 */
class Operations extends Dropbutton {}

redpajama_set_name: RedPajamaGithub


text:
import java.applet.Applet;
import java.awt.Color;
import java.awt.Event;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.TextField;

public class HelloWorldApplet extends Applet {

    private TextField text1;
    private TextField text2;
    private TextField text3;
    private int p,r,t;
    private int interest;
    private Image image;

    @Override
    public void init(){
        setBackground(Color.blue);
       text1 = new TextField();
       text2 = new TextField();
       text3 = new TextField();
       text1.setText("0");
       text2.setText("0");
       text3.setText("0");
       image = getImage(getDocumentBase(),"p5.jpg");
       add(text1);
       add(text2);
       add(text3);

    }

    @Override
    public void paint(Graphics g){
       g.drawString("Enter P,R,t", 25, 25);
       g.drawLine(15,10,100,10);
       p=Integer.parseInt(text1.getText());
       r=Integer.parseInt(text2.getText());
       t=Integer.parseInt(text3.getText());
       interest = (p*r*t)/100;
       String str = "Interest is " + String.valueOf(interest);
       g.drawString(str, 25, 100);
       g.drawImage(image,200,200,this);
        showStatus("Status here");
    }

    @Override
    public boolean action(Event ev,Object obj){
        repaint();
        return true;
    }
}


text:
/**
 * box.test.js
 * Andrea Tino - 2017
 */

import * as components from "../../src/box.js";

describe("TestSuite for Box", function() {

    let box = new components.Box();

    it("Random id generation", function() {
        // Check not null or undefined
        expect(box.id).not.toBeNull();
        expect(box.id).not.toBeUndefined();
        expect(box.id).toBeTruthy();

        // Check length
        expect(box.id.length).toBeTruthy();
        expect(box.id.length).toEqual(10);
    });

    it("Construct with id", function() {
        let namedBox = new components.Box("box-000000");

        expect(namedBox.id).toBeTruthy();
        expect(namedBox.id).toEqual("box-000000");
    });

    it("Multiple random id generation", function() {
        for (let i = 0; i < 100; i++) {
            let box = new components.Box();

            // Check not null or undefined
            expect(box.id).toBeTruthy();

            // Check length
            expect(box.id.length).toBeTruthy();
            expect(box.id.length).toEqual(10);
        }
    });

    it("Id assignment", function() {
        let box = new components.Box();
        expect(box.id).toBeTruthy();

        box.id = "box-000000";
        expect(box.id).toEqual("box-000000");
    });

    it("Assign falsy id", function() {
        let box = new components.Box();
        expect(box.id).toBeTruthy();

        let assignNull = function() {
            box.id = null;
        };
        let assignUndefined = function() {
            box.id = undefined;
        };
        let assignProper = function() {
            box.id = "box-000000";
        };

        expect(assignNull).toThrow();
        expect(assignUndefined).toThrow();
        expect(assignProper).not.toThrow();
    });

});


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Exidia polytricha Mont., 1834

### Remarks
null


text:
package commandwrappers;

import java.nio.ByteBuffer;
import java.util.Arrays;

/**
 * Created by Felipe Herranz(felhr85@gmail.com) on 4/12/14.
 */
public class CommandStatusWrapper extends CommandWrapper
{
    private int dCSWSignature;
    private int dCSWTag;
    private int dCSWDataResidue;
    private byte bCSWStatus;

    public CommandStatusWrapper(int dCSWSignature, int dCSWTag, int dCSWDataResidue,
                                byte bCSWStatus)
    {
        this.dCSWSignature = dCSWSignature;
        this.dCSWTag = dCSWTag;
        this.dCSWDataResidue = dCSWDataResidue;
        this.bCSWStatus = bCSWStatus;
    }

    public static CommandStatusWrapper getCWStatus(byte[] buffer)
    {
        int signature = convertToInt(Arrays.copyOfRange(buffer, 0, 4));
        int tag = convertToInt(Arrays.copyOfRange(buffer, 4, 8));
        int residue = convertToInt(Arrays.copyOfRange(buffer, 8, 12));
        byte status = buffer[12];
        return new CommandStatusWrapper(signature, tag, residue, status);
    }

    private static int convertToInt(byte[] buffer)
    {
        int result;
        result = buffer[0] & 0xff;
        result = result + ((buffer[1] & 0xff) << 8);
        result = result + ((buffer[2] & 0xff) << 16);
        return result + ((buffer[3] & 0xff) << 24);
    }

    @Override
    public byte[] getCWBuffer()
    {
        ByteBuffer buffer = ByteBuffer.allocate(CBS_SIZE);
        buffer.putInt(dCSWSignature);
        buffer.putInt(dCSWTag);
        buffer.putInt(dCSWDataResidue);
        buffer.put(bCSWStatus);
        return buffer.array();
    }

    public int getdCSWSignature()
    {
        return dCSWSignature;
    }

    public void setdCSWSignature(int dCSWSignature)
    {
        this.dCSWSignature = dCSWSignature;
    }

    public int getdCSWTag()
    {
        return dCSWTag;
    }

    public void setdCSWTag(int dCSWTag)
    {
        this.dCSWTag = dCSWTag;
    }

    public int getdCSWDataResidue()
    {
        return dCSWDataResidue;
    }

    public void setdCSWDataResidue(int dCSWDataResidue)
    {
        this.dCSWDataResidue = dCSWDataResidue;
    }

    public byte getbCSWStatus()
    {
        return bCSWStatus;
    }

    public void setbCSWStatus(byte bCSWStatus)
    {
        this.bCSWStatus = bCSWStatus;
    }
}


text:
package org.apache.ignite.internal.processors.query.h2;

/**
 * Tests for H2 indexing SPI.
 */
public class GridH2IndexingInMemSelfTest extends GridIndexingSpiAbstractSelfTest {
    // No-op.
}


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

@Injectable()
export class IdkService {

  constructor() { }

}


text:
using System.Windows;
using JetBrains.ActionManagement;
using JetBrains.Application.DataContext;
using JetBrains.DotPeek.Plugins.NuPeek.Controls;
using JetBrains.DotPeek.Plugins.NuPeek.ViewModels;
using JetBrains.ProjectModel;
using JetBrains.UI.Extensions.Commands;
using NuGet;

namespace JetBrains.DotPeek.Plugins.NuPeek.Handlers
{
#if !DP13
    [ActionHandler("NuPeek.OpenFromNuget")]
    public partial class OpenFromNuGetHandler : IActionHandler { }
#else
    using JetBrains.UI.ActionsRevised;
    [Action("NuPeek.OpenFromNuget", "Open from &NuGet...", Id = 78001, Icon = typeof(NuPeekThemedIcons.NuGet),
        IdeaShortcuts = new[] { "Control+Shift+N" }, VsShortcuts = new[] { "Control+Shift+N" })]
    public partial class OpenFromNuGetHandler : IExecutableAction
      , IInsertAfter<resources.DotPeekFileActionGroup, OpenFromGac.OpenFromGacActionHandler>
      , IInsertAfter<resources.InsertIntoAssemblyExplorerActionBarAnchoredAssemblyExplorerAddFolderActionGroup, OpenFromGac.OpenFromGacActionHandler> { }
#endif

    public partial class OpenFromNuGetHandler : OpenFromNuGetHandlerBase
    {
        public bool Update(IDataContext context, ActionPresentation presentation, DelegateUpdate nextUpdate)
        {
            return context.GetData<ISolution>(JetBrains.ProjectModel.DataContext.DataConstants.SOLUTION) != null;
        }

        public void Execute(IDataContext context, DelegateExecute nextExecute)
        {
            ISolution solution = context.GetData<ISolution>(JetBrains.ProjectModel.DataContext.DataConstants.SOLUTION);
            if (solution == null)
            {
                return;
            }

            var model = new PackageSelectorViewModel();
            var window = new Window
            {
                Title = "Select Package",
                Content = new PackageSelector(model),
                Width = 520,
                Height = 520,
                WindowStartupLocation = WindowStartupLocation.CenterScreen,
                ResizeMode = ResizeMode.NoResize
            };
            model.CancelCommand = new SimpleCommand(window.Close);
            model.OpenCommand = new SimpleCommand(() =>
            {
                window.Close();

                if (model.SelectedPackage != null)
                {
                    var packagesToOpen = GetPackagesToOpen(PackageRepositoryFactory.Default.CreateRepository(model.PackageSource.ToString()), model.SelectedPackage.Id, model.SelectedPackage.Version, model.LoadDependencies);
                    OpenPackageFilesInCurrentSolution(context, packagesToOpen);
                }

            });
            window.ShowDialog();
        }
    }
}


text:
@interface AWFPrecipitationEstimate : AWFGeographicObject

@property (strong, nonatomic) NSArray *periods;

@end


text:
/**
 */
package org.tud.inf.st.mbt.test;

import org.eclipse.emf.common.util.EList;

import org.tud.inf.st.mbt.core.AbstractModelElement;

import org.tud.inf.st.mbt.core.ITopLevelElement;
import org.tud.inf.st.mbt.features.Configuration;
import org.tud.inf.st.mbt.features.ExplicitSet;

/**
 *
 * A representation of the model object 'Suite'.
 *
 *
 *

 * The following features are supported:
 *

 *
{@link org.tud.inf.st.mbt.test.TestSuite#getCases Cases}

 *
{@link org.tud.inf.st.mbt.test.TestSuite#getConfiguration Configuration}

 *
{@link org.tud.inf.st.mbt.test.TestSuite#getRiskReduction Risk Reduction}

 *

 *

 *
 * @see org.tud.inf.st.mbt.test.TestPackage#getTestSuite()
 * @model
 * @generated
 */
public interface TestSuite extends ITopLevelElement, TestExecutable {
	/**
	 * Returns the value of the 'Cases' containment reference list.
	 * The list contents are of type {@link org.tud.inf.st.mbt.test.TestCase}.
	 *
	 *

	 * If the meaning of the 'Cases' containment reference list isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Cases' containment reference list.
	 * @see org.tud.inf.st.mbt.test.TestPackage#getTestSuite_Cases()
	 * @model containment="true"
	 * @generated
	 */
	EList<TestCase> getCases();

	/**
	 * Returns the value of the 'Configuration' reference.
	 *
	 *

	 * If the meaning of the 'Configuration' containment reference isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Configuration' reference.
	 * @see #setConfiguration(Configuration)
	 * @see org.tud.inf.st.mbt.test.TestPackage#getTestSuite_Configuration()
	 * @model required="true"
	 * @generated
	 */
	Configuration getConfiguration();

	/**
	 * Sets the value of the '{@link org.tud.inf.st.mbt.test.TestSuite#getConfiguration Configuration}' reference.
	 *
	 *
	 * @param value the new value of the 'Configuration' reference.
	 * @see #getConfiguration()
	 * @generated
	 */
	void setConfiguration(Configuration value);

	/**
	 * Returns the value of the 'Risk Reduction' attribute.
	 *
	 *

	 * If the meaning of the 'Risk Reduction' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Risk Reduction' attribute.
	 * @see #setRiskReduction(double)
	 * @see org.tud.inf.st.mbt.test.TestPackage#getTestSuite_RiskReduction()
	 * @model required="true"
	 * @generated
	 */
	double getRiskReduction();

	/**
	 * Sets the value of the '{@link org.tud.inf.st.mbt.test.TestSuite#getRiskReduction Risk Reduction}' attribute.
	 *
	 *
	 * @param value the new value of the 'Risk Reduction' attribute.
	 * @see #getRiskReduction()
	 * @generated
	 */
	void setRiskReduction(double value);

} // TestSuite


text:
Linear Regression
=================

.. figure:: icons/linear-regression.png

Learns a linear function of its input data.

Signals
-------

**Inputs**:

-  **Data**

Data set

-  **Preprocessor**

Preprocesed data set.

**Outputs**:

-  **Learner**

Learning algorithm with the supplied parameters

-  **Predictor**

Trained regressor. Signal *Predictor* sends the output signal only if
signal *Data* is present.

Description
-----------

**Linear Regression** widget constructs a learner/predictor that learns
a `linear function <https://en.wikipedia.org/wiki/Linear_regression>`__
from its input data. The model can identify the relationship between a
predictor xi and the response variable y. Additionally
`Lasso <https://en.wikipedia.org/wiki/Least_squares#Lasso_method>`__
and `Ridge <https://en.wikipedia.org/wiki/Tikhonov_regularization>`__
regularization parameters can be specified. Lasso regression minimizes a
penalized version of the least squares loss function with L1-norm
penalty and Ridge regularization with L2-norm penalty.

.. figure:: images/linear-regression1-stamped.png

1. The learner/predictor name
2. Choose a model to train:

   -  an ordinary least squares (linear regression) model,
   -  a
      `Ridge <https://en.wikipedia.org/wiki/Least_squares#Lasso_method>`__
      regularization (L2-norm penalty)
   -  a
      `Lasso <https://en.wikipedia.org/wiki/Least_squares#Lasso_method>`__
      bound (L1-norm penalty)

3. Press *Apply* to commit changes.

Example
-------

Below is a simple workflow showing how to use both the *Predictor* and
the *Learner* output. For the *Predictor* we input the prediction model
into :doc:`Predictions<../evaluation/predictions>` widget and view the results in :doc:`Data Table<../data/datatable>`. For
*Learner* we can compare different learners in :doc:`Test&Score<../evaluation/testlearners>` widget.

.. figure:: images/linear-regression-example1.png


text:
This is a documentation on the metadata elements provided by the o2r meta extract.

_Last updated: 2018-03-06, work in progress!_

# Elements of the o2r metadata file

- `access_right` _String_.
- `creators` _Array of objects_.
- `creators.name` _String_.
- `creators.orcid` _String_.
- `creators.affiliation` _String_.
- `codefiles` _Array of strings_ List of all files of the recursively parsed workspace that have an extension belonging to a ("R") codefile.
- `communities` _Array of objects_ prepared zenodo MD element
- `communities[0].identifier` _String_. Indicating the collection as required in zenodo MD, default "o2r".
- `depends` _Array of objects_.
- `depends.operatingSystem` _String_.
- `depends.identifier` _String_.
- `depends.packageSystem` _String_. URL
- `description` _String_. A text representation conveying the purpose and scope of the asset (the abstract).
- `displayfile` _String_. The suggested file for viewing the text of the workspace, i.e. a rendering of the suggested mainfile.
- `displayfile_candidates` _Array of strings_. An unsorted list of candidates for displayfiles.
- `identifier` _Object_.
- `identifier.doi` _String_. The [DOI](https://www.doi.org/index.html) of the publication
- `identifier.doiurl` _String_. DEPRECATED, use `.doi`. A clickable URL based on the DOI.
- `identifier.reverseddoi` _String_. DEPRECATED (use unknown)
- `inputfiles` _Array of strings_. A compiled list of files from the extracted workspace that is called or used in the extracted code of the workspace.
- `interaction` TBD
- `keywords` _Array of strings_. Tags associated with the asset.
- `license`_Object_.  License information for the entire ERC.
- `license.code` _String_. License information for the code included.
- `license.data `_String_. License information for the data included.
- `license.md` _String_. License information for the metadata included. Should be cc0 to include in catalogues.
- `license.text`_String_. License information for the text included.
- `mainfile` _String_. The suggested main file of workspace
- `mainfile_candidates` _Array_. Unsorted list of mainfile candidates of the workspace.
- `paperLanguage` _Array of strings_. List of guessed languages for the workspace.
- `publication_date` _String_. The publication date of the paper publication as ISO8601 string.
- `publication_type` _String_.
- `related_identifier` _String_.
- `spatial` _Object_. Spatial information of the workspace.
- `spatial.files` _Array of objects_.
- `spatial.union` _Array of objects_.
- `temporal` _Object_. Aggregated information about the relevant time period of the underlying data sets.
- `temporal.begin`
- `temporal.end`
- `title` The distinguishing name of the paper publication.
- `upload_type` _String._ Zenodo preset. Defaults to "publication".


text:
# Spree SAML README

## Introduction

This code is a fork of the Spree
Social (https://github.com/spree/spree_social/) plugin for
Spree (http://spreecommerce.com/), the original plugin allows users to enrol
in Spree using OAuth services such as Twitter or Facebook via the Ruby
OmniAuth framework. This fork replaces that login behaviour allowing users to
login from a SAML identity provider such as OpenAM (http://openam.forgerock.org/) instead.

This plugin was built as material for use in a 2Keys (http://www.2keys.ca/)
client demonstration of SAML based Single Sign-On and released to GitHub in
the hopes that others in the Spree community may find it helpful.

**DISCLAIMER:** This is not production grade code, it has not been thoroughly tested, reviewed or audited, it is not supported or warrantied by 2Keys in any way.

The sections that follow outline how to build and deploy a Spree environment
that uses this plugin, they assume you have a functional OpenAM server
installation to test against.

## Configuring Spree as an OpenAM Service Provider

### Requirements

  * OpenAM Server **10.1 Xpress**
  * Spree **2.0.3** (see "Bitnami Spree Virtual Machine" section immediately below)
  * Spree SAML plugin TODO: replace with github address later

#### Installing Spree from Ruby Gem's collection

**NOTE:** This requires Ruby 1.9.3+ installed on your system. If you don't have this, it's probably easier to run the Bitnami prebuilt images (see next section)

If you are not using a prebuilt Bitnami VM, Spree 2.0.x can be installed
using:

        # Perquisite Gems
        gem install rails -v 3.2.14 # Install Rails Server into the system Gems
        gem install spree || gem install spree_cmd # Install Spree or Spree CMD (spree w/o circular deps)

        # Install
        SPREE_INSTANCE=spree_demo_store # The name of the Rails + Spree instance.
        SPREE_HOME=$(pwd)/${SPREE_INSTANCE} # Full path to where the Spree instance will be installed.
        rails _3.2.14_ new ${SPREE_INSTANCE} # Create a Rails server instance
        spree install ${SPREE_INSTANCE} -A --version=2.0.3 # Add Spree 2.0.3 metadata into Gemfile

        cd ${SPREE_HOME}
        SED=$(type -p gsed sed | head -1) # Find GNU sed
        ${SED} -ie "s/gem 'jquery-rails'/gem 'jquery-rails', '2.2.1'/" Gemfile # Patch Gemfile for JQuery needed by Spree 2.0.3
        bundle install # Install all bundles
        rails g spree:install # Set Admin Email + Password and create instance

Test the install by running the following command and opening a web browser to
[http://localhost:3000/]:

        rails server # Run Rails Server at http://localhost:3000/, use rails server -p 80 to run below port 1024

Next step: [Configure Spree to use Spree
Social|#ConfigureSpreetoUseSpreeSocial]

#### Bitnami pre-built Spree Virtual Machine

**NOTE:** This requires Virtualbox or VMWare.

This can be used to get a quickly working installation of Spree as a base to
build on:

[http://bitnami.com/stack/spree/virtual-machine]

Site Admin login: user: user@example.com &nbsp_place_holder;
&nbsp_place_holder;pw: bitnami

OS login: bitnami

**NOTE:** see [next section|#TimeSynchronization]

### Time Synchronization

{warning}It is critically important that all SAML parties have synchronized
time, this can be particularly problematic for VMs who's time can drift over
time or if VM hosts suspend/wake.{warning}

To prevent _**time mismatch problems**_, it's highly recommend that all idP
and SP servers be synced to the same NTP servers. Below is one way to do that
via _cron_ and _ntpdate_:

        sudo apt-get -y install ntpdate # Install NTP time sync utility

sudo crontab -e # Edit root crontab{code} and enter the following cronjob to
insure the server's time is accurate:

        # m h dom mon dow command
          1 *  *   *   *  /usr/sbin/ntpdate pool.ntp.org >/dev/null 2>&1 # Synchronize time once every hour

### Spree SAML Plugin

#### Clone the Spree SAML code to the server

        ### install git either port install git-core or apt-get install git
        mkdir ~/git
        cd ~/git
        git clone git://github.com/jumpkick/spree_saml
        cd spree_saml
        SPREE_SOCIAL_HOME="$(pwd)"

#### Configure Spree to Use Spree Social

        cd "${SPREE_HOME}" # Replace ${SPREE_HOME} with your Spree install directory i.e. /opt/bitnami/spree
        if [ -e "${SPREE_SOCIAL_HOME}" ]; then

          # Queue up spree SAML DB structure changes
          DB_MIGRATE_FILE="$(rails generate migration SamlConfigurations | gsed -r 's/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g' | grep rb | sed -e 's/create//' -e 's/^[ \t]*//')"
          cp "${SPREE_SOCIAL_HOME}/db/migrate/*_saml_configurations.rb" "${DB_MIGRATE_FILE}"
          DB_MIGRATE_FILE="$(rails generate migration CreateUserAuthentications | gsed -r 's/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g' | grep rb | sed -e 's/create//' -e 's/^[ \t]*//')"
          cp "${SPREE_SOCIAL_HOME}/db/migrate/*_create_user_authentications.rb" "${DB_MIGRATE_FILE}"

          # Update the Gem's and change the DB structure
          bundle update
          bundle exec rake db:migrate

          # Inject dependencies into Gemfile
          echo >> Gemfile
          echo >> Gemfile
          echo "gem 'spree_social', :path => '${SPREE_SOCIAL_HOME}'" >> Gemfile
          echo "gem 'omniauth-saml', :git => 'git://github.com/ruvr/omniauth-saml.git'" >> Gemfile

          # Activate the SAML plugin
          bundle update

          # Start the Rails server
          rvmsudo rails server -p 80 # Start the Rails server on port 80
        else
          echo "Check your SPREE_SOCIAL_HOME variable is set and that the directory
          SPREE_SOCIAL_HOME exists and then try again."
        fi

#### Configuration Steps For Creating New IDP within Spree SAML

{note}Make sure that server names are resolvable both to OpenAM and the SP
server either through /etc/hosts entries or DNS entries on each server.{note}

  * Login using a Spree Admin user
  * Go to '/admin' page and click Configuration tab
  * On the right menu, choose Saml Authentication
  * Create "New SAML Configuration". Complete following fields (many others are not being used atm):
    1. **_Assertion Consumer Service URL_**: [http://website.example.com/users/auth/saml/callback]
**NOTE:** Make sure that server names are resolvable both to OpenAM and the SP server either through /etc/hosts entries or DNS entries
    2. **_Assertion Consumer Service Binding_**: urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect
    3. **_Name Identifier Format_**: urn:oasis:names:tc:SAML:2.0:nameid-format:transient
    4. **_Issuer_**: website.example.com
    5. **_IDP SSO Target URL_**: http(s)://openamserver/openam*/SSORedirect/metaAlias/idp*
    6. **_Host_**: OpenAM (this is for display purposes only)
    7. SLO, IDP Metadata, Authentication Context, IDP Certificate Fingerprint fields are not used
    8. Set **_Active_** to "Yes"
    9. **_IDP Certificate_** (remember to add \n after every line of the cert to format into 1 long line):

        -----BEGIN CERTIFICATE-----\nMIICQDCCAakCBEeNB0swDQYJKoZIhvcNAQEEBQAwZzELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNh\nbGlmb3JuaWExFDASBgNVBAcTC1NhbnRhIENsYXJhMQwwCgYDVQQKEwNTdW4xEDAOBgNVBAsTB09w\nZW5TU08xDTALBgNVBAMTBHRlc3QwHhcNMDgwMTE1MTkxOTM5WhcNMTgwMTEyMTkxOTM5WjBnMQsw\nCQYDVQQGEwJVUzETMBEGA1UECBMKQ2FsaWZvcm5pYTEUMBIGA1UEBxMLU2FudGEgQ2xhcmExDDAK\nBgNVBAoTA1N1bjEQMA4GA1UECxMHT3BlblNTTzENMAsGA1UEAxMEdGVzdDCBnzANBgkqhkiG9w0B\nAQEFAAOBjQAwgYkCgYEArSQc/U75GB2AtKhbGS5piiLkmJzqEsp64rDxbMJ+xDrye0EN/q1U5Of+\nRkDsaN/igkAvV1cuXEgTL6RlafFPcUX7QxDhZBhsYF9pbwtMzi4A4su9hnxIhURebGEmxKW9qJNY\nJs0Vo5+IgjxuEWnjnnVgHTs1+mq5QYTA7E6ZyL8CAwEAATANBgkqhkiG9w0BAQQFAAOBgQB3Pw/U\nQzPKTPTYi9upbFXlrAKMwtFf2OW4yvGWWvlcwcNSZJmTJ8ARvVYOMEVNbsT4OFcfu2/PeYoAdiDA\ncGy/F2Zuj8XJJpuQRSE6PtQqBuDEHjjmOQJ0rV/r8mO1ZCtHRhpZ5zYRjhRC9eCbjx9VrFax0JDC\n/FfwWigmrW0Y0Q==\n-----END CERTIFICATE-----

 Your IDP certificate can be found in the X509 block of the IDP Metadata @
http(s)://openamserver/openam*/saml2/jsp/exportmetadata.jsp*

**NOTE:** Github markdown renders this line with extra breaks after BEGIN and before END CERTIFCATE lines.

* Save the configuration and logout.

### OpenAM setup using Spree SAML

**Make sure that server names are resolvable both to OpenAM and the SP server either through /etc/hosts entries or DNS entries on each server.**

  * Register Remote Service Provider using Metadata URL: [http://website.example.com/users/auth/saml/metadata]
  * Set Name ID Format: urn:oasis:names:tc:SAML:2.0:nameid-format:transient
  * Add the following attibute mappers:
    * telephone=telephoneNumber
    * address=postalAddress
    * last_name=sn
    * uid=uid
    * name=uid
    * first_name=givenName
    * mail=mail
  * Save the new SP

**NOTE:** see [Time Synchronization|#TimeSynchronization] to insure that the OpenAM server has accurate time, otherwise expired assertions may be rejected by SPs.

### Require SAML authentication for all logins

Configuration Steps for Toggling Gatekeeper:

* Open _$\{SPREE_SOCIAL_HOME\}/app/models/spree/authentication_disabler.rb_
* Changing _**return true**_ for _**def self.login_disabled**_ will force login through SAML only. Reverse this step to disable SAML logins.
* Save changes then restart rails server

### Spree SAML Development Enhancements

**This is work that is beyond the scope of our demo, but are things people
wishing to use this plugin should probably complete before using it in a
production deployment.**

  * Admin cannot login when Spree SAML is enabled -> add groups=isMemberOf to OpenAM SP's Assertion Mappings, add group for users and group for admins to spree SAML and then check the login user's group
  * Enable Single Logout in Spree SAML, so that session can be expired when user signs out of OpenAM
  * Fix translation when hitting the "X" next to SAML authentication type on User's Account screen (optionally remove this if it doesn't need to be there)
  * Have address from SAML assertion appear during checkout process as default address


text:
/////////////////////////////////////////////////////////////////////////////
// Name:        scrolling.h
// Purpose:     topic overview
// Author:      wxWidgets team
// Licence:     wxWindows licence
/////////////////////////////////////////////////////////////////////////////

/**

@page overview_scrolling Scrolled Windows

@tableofcontents

Scrollbars come in various guises in wxWidgets. All windows have the potential
to show a vertical scrollbar and/or a horizontal scrollbar: it is a basic
capability of a window. However, in practice, not all windows do make use of
scrollbars, such as a single-line wxTextCtrl.

Because any class derived from wxWindow may have scrollbars, there are
functions to manipulate the scrollbars and event handlers to intercept scroll
events. But just because a window generates a scroll event, doesn't mean that
the window necessarily handles it and physically scrolls the window. The base
class wxWindow in fact doesn't have any default functionality to handle scroll
events. If you created a wxWindow object with scrollbars, and then clicked on
the scrollbars, nothing at all would happen. This is deliberate, because the
@e interpretation of scroll events varies from one window class to another.

::wxScrolledWindow (formerly wxCanvas) is an example of a window that adds
functionality to make scrolling really work. It assumes that scrolling happens
in consistent units, not different-sized jumps, and that page size is
represented by the visible portion of the window. It is suited to drawing
applications, but perhaps not so suitable for a sophisticated editor in which
the amount scrolled may vary according to the size of text on a given line. For
this, you would derive from wxWindow and implement scrolling yourself. wxGrid
is an example of a class that implements its own scrolling, largely because
columns and rows can vary in size.

@see wxScrollBar

@section overview_scrolling_model The Scrollbar Model

The function wxWindow::SetScrollbar gives a clue about the way a scrollbar is
modeled. This function takes the following arguments:

@beginTable
@row2col{ @c orientation , Which scrollbar: wxVERTICAL or wxHORIZONTAL. }
@row2col{ @c position , The position of the scrollbar in scroll units. }
@row2col{ @c visible , The size of the visible portion of the scrollbar,
                       in scroll units. }
@row2col{ @c range , The maximum position of the scrollbar. }
@row2col{ @c refresh , Whether the scrollbar should be repainted. }
@endTable

@c orientation determines whether we're talking about the built-in horizontal
or vertical scrollbar.

@c position is simply the position of the 'thumb' (the bit you drag to scroll
around). It is given in scroll units, and so is relative to the total range of
the scrollbar.

@c visible gives the number of scroll units that represents the portion of the
window currently visible. Normally, a scrollbar is capable of indicating this
visually by showing a different length of thumb.

@c range is the maximum value of the scrollbar, where zero is the start
position. You choose the units that suit you, so if you wanted to display text
that has 100 lines, you would set this to 100. Note that this doesn't have to
correspond to the number of pixels scrolled - it is up to you how you actually
show the contents of the window.

@c refresh just indicates whether the scrollbar should be repainted immediately
or not.

@section overview_scrolling_example An Example

Let's say you wish to display 50 lines of text, using the same font. The window
is sized so that you can only see 16 lines at a time. You would use:

@code
SetScrollbar(wxVERTICAL, 0, 16, 50);
@endcode

Note that with the window at this size, the thumb position can never go above
50 minus 16, or 34. You can determine how many lines are currently visible by
dividing the current view size by the character height in pixels.

When defining your own scrollbar behaviour, you will always need to recalculate
the scrollbar settings when the window size changes. You could therefore put
your scrollbar calculations and SetScrollbar call into a function named
AdjustScrollbars, which can be called initially and also from your wxSizeEvent
handler function.

*/


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Caching;
using Umbraco.Core.Cache;
using Umbraco.Core.Logging;

namespace Umbraco.Core
{

	/// <summary>
	/// Class that is exposed by the ApplicationContext for application wide caching purposes
	/// </summary>
    public class CacheHelper
	{
	    private readonly bool _enableCache;
	    private readonly ICacheProvider _requestCache;
        private readonly ICacheProvider _nullRequestCache = new NullCacheProvider();
        private readonly ICacheProvider _staticCache;
        private readonly ICacheProvider _nullStaticCache = new NullCacheProvider();
        private readonly IRuntimeCacheProvider _httpCache;
        private readonly IRuntimeCacheProvider _nullHttpCache = new NullCacheProvider();

        /// <summary>
        /// Creates a cache helper with disabled caches
        /// </summary>
        /// <returns></returns>
        /// <remarks>
        /// Good for unit testing
        /// </remarks>
        public static CacheHelper CreateDisabledCacheHelper()
        {
            return new CacheHelper(null, null, null, false);
        }

	    /// <summary>
	    /// Initializes a new instance for use in the web
	    /// </summary>
	    public CacheHelper()
	        : this(
	            new HttpRuntimeCacheProvider(HttpRuntime.Cache),
	            new StaticCacheProvider(),
	            new HttpRequestCacheProvider(() => new HttpContextWrapper(HttpContext.Current)))
	    {
	    }

	    /// <summary>
	    /// Initializes a new instance for use in the web
	    /// </summary>
	    /// <param name="cache"></param>
	    public CacheHelper(System.Web.Caching.Cache cache)
	        : this(
	            new HttpRuntimeCacheProvider(cache),
	            new StaticCacheProvider(),
	            new HttpRequestCacheProvider(() => new HttpContextWrapper(HttpContext.Current)))
	    {
	    }

	    /// <summary>
        /// Initializes a new instance based on the provided providers
        /// </summary>
        /// <param name="httpCacheProvider"></param>
        /// <param name="staticCacheProvider"></param>
        /// <param name="requestCacheProvider"></param>
        public CacheHelper(
            IRuntimeCacheProvider httpCacheProvider,
            ICacheProvider staticCacheProvider,
            ICacheProvider requestCacheProvider)
            : this(httpCacheProvider, staticCacheProvider, requestCacheProvider, true)
        {
        }

        /// <summary>
        /// Private ctor used for creating a disabled cache helper
        /// </summary>
        /// <param name="httpCacheProvider"></param>
        /// <param name="staticCacheProvider"></param>
        /// <param name="requestCacheProvider"></param>
        /// <param name="enableCache"></param>
        private CacheHelper(
            IRuntimeCacheProvider httpCacheProvider,
            ICacheProvider staticCacheProvider,
            ICacheProvider requestCacheProvider,
            bool enableCache)
        {
            if (enableCache)
            {
                _httpCache = httpCacheProvider;
                _staticCache = staticCacheProvider;
                _requestCache = requestCacheProvider;
            }
            else
            {
                _httpCache = null;
                _staticCache = null;
                _requestCache = null;
            }

            _enableCache = enableCache;
        }

        /// <summary>
        /// Returns the current Request cache
        /// </summary>
        public ICacheProvider RequestCache
        {
            get { return _enableCache ? _requestCache : _nullRequestCache; }
        }

        /// <summary>
        /// Returns the current Runtime cache
        /// </summary>
        public ICacheProvider StaticCache
        {
            get { return _enableCache ? _staticCache : _nullStaticCache; }
        }

        /// <summary>
        /// Returns the current Runtime cache
        /// </summary>
	    public IRuntimeCacheProvider RuntimeCache
	    {
	        get { return _enableCache ? _httpCache : _nullHttpCache; }
	    }

	    #region Legacy Runtime/Http Cache accessors

        /// <summary>
        /// Clears the item in umbraco's runtime cache
        /// </summary>
        [Obsolete("Do not use this method, access the runtime cache from the RuntimeCache property")]
        public void ClearAllCache()
        {
            if (_enableCache == false)
            {
                _nullHttpCache.ClearAllCache();
            }
            else
            {
                _httpCache.ClearAllCache();
            }
        }

        /// <summary>
        /// Clears the item in umbraco's runtime cache with the given key
        /// </summary>
        /// <param name="key">Key</param>
        [Obsolete("Do not use this method, access the runtime cache from the RuntimeCache property")]
        public void ClearCacheItem(string key)
        {
            if (_enableCache == false)
            {
                _nullHttpCache.ClearCacheItem(key);
            }
            else
            {
                _httpCache.ClearCacheItem(key);
            }
        }

        /// <summary>
        /// Clears all objects in the System.Web.Cache with the System.Type name as the
        /// input parameter. (using [object].GetType())
        /// </summary>
        /// <param name="typeName">The name of the System.Type which should be cleared from cache ex "System.Xml.XmlDocument"</param>
        [Obsolete("Do not use this method, access the runtime cache from the RuntimeCache property")]
        public void ClearCacheObjectTypes(string typeName)
        {
            if (_enableCache == false)
            {
                _nullHttpCache.ClearCacheObjectTypes(typeName);
            }
            else
            {
                _httpCache.ClearCacheObjectTypes(typeName);
            }
        }

        /// <summary>
        /// Clears all objects in the System.Web.Cache with the System.Type specified
        /// </summary>
        [Obsolete("Do not use this method, access the runtime cache from the RuntimeCache property")]
        public void ClearCacheObjectTypes<T>()
        {
            if (_enableCache == false)
            {
                _nullHttpCache.ClearCacheObjectTypes<T>();
            }
            else
            {
                _httpCache.ClearCacheObjectTypes<T>();
            }
        }

        /// <summary>
        /// Clears all cache items that starts with the key passed.
        /// </summary>
        /// <param name="keyStartsWith">The start of the key</param>
        [Obsolete("Do not use this method, access the runtime cache from the RuntimeCache property")]
        public void ClearCacheByKeySearch(string keyStartsWith)
        {
            if (_enableCache == false)
            {
                _nullHttpCache.ClearCacheByKeySearch(keyStartsWith);
            }
            else
            {
                _httpCache.ClearCacheByKeySearch(keyStartsWith);
            }
        }

        /// <summary>
        /// Clears all cache items that have a key that matches the regular expression
        /// </summary>
        /// <param name="regexString"></param>
        [Obsolete("Do not use this method, access the runtime cache from the RuntimeCache property")]
        public void ClearCacheByKeyExpression(string regexString)
        {
            if (_enableCache == false)
            {
                _nullHttpCache.ClearCacheByKeyExpression(regexString);
            }
            else
            {
                _httpCache.ClearCacheByKeyExpression(regexString);
            }
        }

        [Obsolete("Do not use this method, access the runtime cache from the RuntimeCache property")]
        public IEnumerable<T> GetCacheItemsByKeySearch<T>(string keyStartsWith)
        {
            if (_enableCache == false)
            {
                return _nullHttpCache.GetCacheItemsByKeySearch<T>(keyStartsWith);
            }
            else
            {
                return _httpCache.GetCacheItemsByKeySearch<T>(keyStartsWith);
            }
        }

        /// <summary>
        /// Returns a cache item by key, does not update the cache if it isn't there.
        /// </summary>
        /// <typeparam name="TT"></typeparam>
        /// <param name="cacheKey"></param>
        /// <returns></returns>
        [Obsolete("Do not use this method, access the runtime cache from the RuntimeCache property")]
        public TT GetCacheItem<TT>(string cacheKey)
        {
            if (_enableCache == false)
            {
                return _nullHttpCache.GetCacheItem<TT>(cacheKey);
            }
            else
            {
                return _httpCache.GetCacheItem<TT>(cacheKey);
            }
        }

        /// <summary>
        /// Gets (and adds if necessary) an item from the cache with all of the default parameters
        /// </summary>
        /// <typeparam name="TT"></typeparam>
        /// <param name="cacheKey"></param>
        /// <param name="getCacheItem"></param>
        /// <returns></returns>
        [Obsolete("Do not use this method, access the runtime cache from the RuntimeCache property")]
        public TT GetCacheItem<TT>(string cacheKey, Func<TT> getCacheItem)
        {
            if (_enableCache == false)
            {
                return _nullHttpCache.GetCacheItem<TT>(cacheKey, getCacheItem);
            }
            else
            {
                return _httpCache.GetCacheItem<TT>(cacheKey, getCacheItem);
            }
        }

        /// <summary>
        /// Gets (and adds if necessary) an item from the cache with the specified absolute expiration date (from NOW)
        /// </summary>
        /// <typeparam name="TT"></typeparam>
        /// <param name="cacheKey"></param>
        /// <param name="timeout">This will set an absolute expiration from now until the timeout</param>
        /// <param name="getCacheItem"></param>
        /// <returns></returns>
        [Obsolete("Do not use this method, access the runtime cache from the RuntimeCache property")]
        public TT GetCacheItem<TT>(string cacheKey,
            TimeSpan timeout, Func<TT> getCacheItem)
        {
            if (_enableCache == false)
            {
                return _nullHttpCache.GetCacheItem<TT>(cacheKey, getCacheItem, timeout);
            }
            else
            {
                return _httpCache.GetCacheItem<TT>(cacheKey, getCacheItem, timeout);
            }
        }

        /// <summary>
        /// Gets (and adds if necessary) an item from the cache with the specified absolute expiration date (from NOW)
        /// </summary>
        /// <typeparam name="TT"></typeparam>
        /// <param name="cacheKey"></param>
        /// <param name="refreshAction"></param>
        /// <param name="timeout">This will set an absolute expiration from now until the timeout</param>
        /// <param name="getCacheItem"></param>
        /// <returns></returns>
        [Obsolete("Do not use this method, access the runtime cache from the RuntimeCache property")]
        public TT GetCacheItem<TT>(string cacheKey,
            CacheItemRemovedCallback refreshAction, TimeSpan timeout,
            Func<TT> getCacheItem)
        {
            if (!_enableCache)
            {
                return _nullHttpCache.GetCacheItem<TT>(cacheKey, getCacheItem, timeout, removedCallback: refreshAction);
            }
            else
            {
                return _httpCache.GetCacheItem<TT>(cacheKey, getCacheItem, timeout, removedCallback: refreshAction);
            }
        }

        /// <summary>
        /// Gets (and adds if necessary) an item from the cache with the specified absolute expiration date (from NOW)
        /// </summary>
        /// <typeparam name="TT"></typeparam>
        /// <param name="cacheKey"></param>
        /// <param name="priority"></param>
        /// <param name="refreshAction"></param>
        /// <param name="timeout">This will set an absolute expiration from now until the timeout</param>
        /// <param name="getCacheItem"></param>
        /// <returns></returns>
        [Obsolete("Do not use this method, access the runtime cache from the RuntimeCache property")]
        public TT GetCacheItem<TT>(string cacheKey,
            CacheItemPriority priority, CacheItemRemovedCallback refreshAction, TimeSpan timeout,
            Func<TT> getCacheItem)
        {
            if (_enableCache == false)
            {
                return _nullHttpCache.GetCacheItem<TT>(cacheKey, getCacheItem, timeout, false, priority, refreshAction);
            }
            else
            {
                return _httpCache.GetCacheItem<TT>(cacheKey, getCacheItem, timeout, false, priority, refreshAction);
            }
        }

        /// <summary>
        /// Gets (and adds if necessary) an item from the cache with the specified absolute expiration date (from NOW)
        /// </summary>
        /// <typeparam name="TT"></typeparam>
        /// <param name="cacheKey"></param>
        /// <param name="priority"></param>
        /// <param name="refreshAction"></param>
        /// <param name="cacheDependency"></param>
        /// <param name="timeout">This will set an absolute expiration from now until the timeout</param>
        /// <param name="getCacheItem"></param>
        /// <returns></returns>
        [Obsolete("Do not use this method, we no longer support the caching overloads with references to CacheDependency, use the overloads specifying a file collection instead")]
        public TT GetCacheItem<TT>(string cacheKey,
            CacheItemPriority priority,
            CacheItemRemovedCallback refreshAction,
            CacheDependency cacheDependency,
            TimeSpan timeout,
            Func<TT> getCacheItem)
        {
            if (_enableCache == false)
            {
                return _nullHttpCache.GetCacheItem<TT>(cacheKey, getCacheItem, timeout, false, priority, refreshAction, null);
            }
            else
            {
                var cache = _httpCache as HttpRuntimeCacheProvider;
                if (cache != null)
                {
                    var result = cache.GetCacheItem(cacheKey, () => getCacheItem(), timeout, false, priority, refreshAction, cacheDependency);
                    return result == null ? default(TT) : result.TryConvertTo<TT>().Result;
                }
                throw new InvalidOperationException("Cannot use this obsoleted overload when the current provider is not of type " + typeof(HttpRuntimeCacheProvider));
            }
        }

        /// <summary>
        /// Gets (and adds if necessary) an item from the cache
        /// </summary>
        /// <typeparam name="TT"></typeparam>
        /// <param name="cacheKey"></param>
        /// <param name="priority"></param>
        /// <param name="cacheDependency"></param>
        /// <param name="getCacheItem"></param>
        /// <returns></returns>
        [Obsolete("Do not use this method, we no longer support the caching overloads with references to CacheDependency, use the overloads specifying a file collection instead")]
        public TT GetCacheItem<TT>(string cacheKey,
            CacheItemPriority priority,
            CacheDependency cacheDependency,
            Func<TT> getCacheItem)
        {
            if (!_enableCache)
            {
                return _nullHttpCache.GetCacheItem<TT>(cacheKey, getCacheItem, null, false, priority, null, null);
            }
            else
            {
                var cache = _httpCache as HttpRuntimeCacheProvider;
                if (cache != null)
                {
                    var result = cache.GetCacheItem(cacheKey, () => getCacheItem(), null, false, priority, null, cacheDependency);
                    return result == null ? default(TT) : result.TryConvertTo<TT>().Result;
                }
                throw new InvalidOperationException("Cannot use this obsoleted overload when the current provider is not of type " + typeof(HttpRuntimeCacheProvider));
            }
        }

        /// <summary>
        /// Inserts an item into the cache, if it already exists in the cache it will be replaced
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cacheKey"></param>
        /// <param name="priority"></param>
        /// <param name="getCacheItem"></param>
        public void InsertCacheItem<T>(string cacheKey,
                                       CacheItemPriority priority,
                                       Func<T> getCacheItem)
        {
            if (_enableCache == false)
            {
                _nullHttpCache.InsertCacheItem<T>(cacheKey, getCacheItem, priority: priority);
            }
            else
            {
                _httpCache.InsertCacheItem<T>(cacheKey, getCacheItem, priority: priority);
            }
        }

        /// <summary>
        /// Inserts an item into the cache, if it already exists in the cache it will be replaced
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cacheKey"></param>
        /// <param name="priority"></param>
        /// <param name="timeout">This will set an absolute expiration from now until the timeout</param>
        /// <param name="getCacheItem"></param>
        public void InsertCacheItem<T>(string cacheKey,
                                       CacheItemPriority priority,
                                       TimeSpan timeout,
                                       Func<T> getCacheItem)
        {
            if (_enableCache == false)
            {
                _nullHttpCache.InsertCacheItem<T>(cacheKey, getCacheItem, timeout, priority: priority);
            }
            else
            {
                _httpCache.InsertCacheItem<T>(cacheKey, getCacheItem, timeout, priority: priority);
            }
        }

        /// <summary>
        /// Inserts an item into the cache, if it already exists in the cache it will be replaced
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cacheKey"></param>
        /// <param name="priority"></param>
        /// <param name="cacheDependency"></param>
        /// <param name="timeout">This will set an absolute expiration from now until the timeout</param>
        /// <param name="getCacheItem"></param>
        [Obsolete("Do not use this method, we no longer support the caching overloads with references to CacheDependency, use the overloads specifying a file collection instead")]
        public void InsertCacheItem<T>(string cacheKey,
                                       CacheItemPriority priority,
                                       CacheDependency cacheDependency,
                                       TimeSpan timeout,
                                       Func<T> getCacheItem)
        {
            if (_enableCache == false)
            {
                _nullHttpCache.InsertCacheItem<T>(cacheKey, getCacheItem, timeout, priority: priority, dependentFiles:null);
            }
            else
            {
                var cache = _httpCache as HttpRuntimeCacheProvider;
                if (cache != null)
                {
                    cache.InsertCacheItem(cacheKey, () => getCacheItem(), timeout, false, priority, null, cacheDependency);
                }
                throw new InvalidOperationException("Cannot use this obsoleted overload when the current provider is not of type " + typeof(HttpRuntimeCacheProvider));
            }
        }

        /// <summary>
        /// Inserts an item into the cache, if it already exists in the cache it will be replaced
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="cacheKey"></param>
        /// <param name="priority"></param>
        /// <param name="refreshAction"></param>
        /// <param name="cacheDependency"></param>
        /// <param name="timeout">This will set an absolute expiration from now until the timeout</param>
        /// <param name="getCacheItem"></param>
        [Obsolete("Do not use this method, we no longer support the caching overloads with references to CacheDependency, use the overloads specifying a file collection instead")]
        public void InsertCacheItem<T>(string cacheKey,
                                       CacheItemPriority priority,
                                       CacheItemRemovedCallback refreshAction,
                                       CacheDependency cacheDependency,
                                       TimeSpan? timeout,
                                       Func<T> getCacheItem)
        {
            if (_enableCache == false)
            {
                _nullHttpCache.InsertCacheItem<T>(cacheKey, getCacheItem, timeout, false, priority, refreshAction, null);
            }
            else
            {
                var cache = _httpCache as HttpRuntimeCacheProvider;
                if (cache != null)
                {
                    cache.InsertCacheItem(cacheKey, () => getCacheItem(), timeout, false, priority, refreshAction, cacheDependency);
                }
                throw new InvalidOperationException("Cannot use this obsoleted overload when the current provider is not of type " + typeof(HttpRuntimeCacheProvider));
            }
        }
        #endregion

	}

}


text:
import json
import os
import re
import sys

# Nasty hack to force utf-8 encoding by default:
reload(sys)
sys.setdefaultencoding('utf8')

###############################################################################
# Useful settings:
_TOP_LEVEL_DIRECTORY = "C:/Path/To/Repository/Parent"  # Path to folder above repository
_CONTENT_DIRECTORY = "./rutherford-content/content"  # Path to the "content" folder of the repo
API_IMAGE_URL = "/api/any/api/images/content"
FULL_API_IMAGE_URL = "https://isaacphysics.org/api/any/api/images/content"

ignore_biology = True
print_to_file = True
output_batch_file = True

# subdir = "/questions"
# subdir = "/concepts"
subdir = ""

# action = "COPY"
action = "MOVE"

image_src_dict = {}
html_img_regex = re.compile(r'<img src=\"(.*?)\"')

###############################################################################
# How to process each image source string:
def process_image_reference(dir_path, json_path, src):
    # Check if empty string, return "" to denote no image if so:
    if src == "":
        return ""
    # Remove any leading forward slash:
    if src.startswith("/"):
        src = src.replace("/", "", 1)
    # Get the directory in a nice format:
    # Deal with relative references to parent folders of dir_path if present.
    path = dir_path
    while "../" in src:
        src = src.replace("../", "", 1)
        path = "/".join(path.split("/")[:-1])
    # Join the image source path to the directory:
    src_path = ""
    if (("http" in src) and not ("isaacphysics" in src)):
        # Ignore external links, return "" to denote no image.
        return ""
    elif (API_IMAGE_URL in src):
        # If links go via API, rather than simply to content, deal with this:
        src_path = src.replace(FULL_API_IMAGE_URL, _CONTENT_DIRECTORY).replace(API_IMAGE_URL, _CONTENT_DIRECTORY)
    else:
        # Otherwise just as image source to directory location:
        src_path = path + "/" + src
    return src_path

# How to process each JSON object:
def process_thing(dir_path, json_path, obj):
    # Keep a list of referenced objects:
    referenced = []
    # Check if any images added using HTML <img> tags:
    if "value" in obj:
        matches = html_img_regex.finditer(obj["value"])
        for m in matches:
            src = m.group(1)
            src_path = process_image_reference(dir_path, json_path, src)
            if (src_path != ""):
                image_src_dict[src_path] = json_path
                referenced.append(str(src_path))
    # If the current object is a figure or image, add it and return (Figures shouldn't have figures inside them!)
    if ((obj["type"] == "figure") or (obj["type"] == "image")):
        src = obj["src"]
        src_path = process_image_reference(dir_path, json_path, src)
        if src_path != "":
            image_src_dict[src_path] = json_path
            referenced.append(str(src_path))
        return referenced
    # Otherwise, keep searching down the tree recursively adding any other images:
    if "answer" in obj:
        referenced.extend(process_thing(dir_path, json_path, obj["answer"]))
    if "explanation" in obj:
        referenced.extend(process_thing(dir_path, json_path, obj["explanation"]))
    if "eventThumbnail" in obj:
        referenced.extend(process_thing(dir_path, json_path, obj["eventThumbnail"]))
    if obj["type"] == "isaacFeaturedProfile":
        referenced.extend(process_thing(dir_path, json_path, obj["image"]))
    if obj["type"] == "isaacPod":
        referenced.extend(process_thing(dir_path, json_path, obj["image"]))
    if "hints" in obj:
        for h in obj["hints"]:
            referenced.extend(process_thing(dir_path, json_path, h))
    if "children" in obj:
        for c in obj["children"]:
            referenced.extend(process_thing(dir_path, json_path, c))
    if "choices" in obj:
        for c in obj["choices"]:
            referenced.extend(process_thing(dir_path, json_path, c))
    return referenced

###############################################################################
# The main function:

if __name__ == "__main__":
    """The main function, search for JSON files and run process_thing() on each."""
    os.chdir(_TOP_LEVEL_DIRECTORY)
    all_files = []
    for root, directories, files in os.walk(_CONTENT_DIRECTORY + subdir):
        for fname in files:
            all_files.append(root + "\\" + fname)

    ###########################################################################
    # Find all references to images in JSON files:
    referenced = set()

    for fpath in all_files:
        if (not ("biology" in fpath.lower()) or not ignore_biology):
            if fpath.lower().endswith(".json"):
                file_handle = open(fpath)
                try:
                    obj = json.load(file_handle)
                except UnicodeDecodeError as e:
                    print fpath
                    raise Exception(e)
                json_path = "/".join(fpath.split("\\"))
                dir_path = "/".join(json_path.split("/")[:-1])
                referenced.update(process_thing(dir_path, json_path, obj))

    ###########################################################################
    # Find all image type files:
    existing = set()

    for fpath in all_files:
        if (not ("biology" in fpath.lower()) or not ignore_biology):
            if (fpath.lower().endswith(".svg") or fpath.lower().endswith(".png") or fpath.lower().endswith(".jpg")):
                existing.add(fpath.replace("\\", "/"))

    ###########################################################################
    # Print total number found:
    print ""
    print "Found %s referenced image files." % len(referenced)
    print "Found %s existing files" % len(existing)
    # Print useful numbers:
    print ""
    print "Files which exist and are referenced: %s" % len(existing.intersection(referenced))
    print "Files which exist but are not referenced (unwanted): %s" % len(existing.difference(referenced))
    print "Files which are referenced but do not exist (nonexistent): %s" % len(referenced.difference(existing))
    print ""

    # Create strings of file names and optionally print file names to text files:
    existing_files = str(sorted(existing)).replace("['", "").replace("']", "")  # Implict conversion to list by sorted()
    existing_files = "\n".join(existing_files.split("', '"))

    referenced_files = str(sorted(referenced)).replace("['", "").replace("']", "")  # Implict conversion to list by sorted()
    referenced_files = "\n".join(referenced_files.split("', '"))

    unwanted_files = str(sorted(existing.difference(referenced))).replace("['", "").replace("']", "")
    unwanted_files = "\n".join(unwanted_files.split("', '"))

    unreal_files = sorted(referenced.difference(existing))
    problem_src_files = ""
    for f in unreal_files:
        if "http" not in f:
            problem_src_files += "Non-existent image found in %s\n     The image '%s' does not exist\n\n" % (image_src_dict[f], f)
    unreal_files = str(unreal_files).replace("['", "").replace("']", "")
    unreal_files = "\n".join(unreal_files.split("', '"))

    if print_to_file:
        with open("existing.txt", 'w') as f:
            f.write(existing_files)
        with open("referenced.txt", 'w') as f:
            f.write(referenced_files)
        with open("unwanted.txt", 'w') as f:
            f.write(unwanted_files)
        with open("nonexistent_files.txt", 'w') as f:
            f.write(unreal_files)
        with open("src_nonexistent_files.txt", 'w') as f:
            f.write(problem_src_files)

    ###########################################################################
    # Write the batch file:
    if output_batch_file:
        with open("remove_old_images.bat", 'w') as bat:
            bat.write('@ECHO OFF\nECHO WARNING: This file will remove all unreferenced images from the repository.\n')
            bat.write('ECHO It will place them to a new folder outside the repository called "BACKUP".\nECHO.\nECHO.\n')
            bat.write('ECHO This will move all unreferenced images from all subfolders of:\r\nECHO     ')
            bat.write('%s\n' % ((_TOP_LEVEL_DIRECTORY + _CONTENT_DIRECTORY + subdir).replace("/", "\\").replace(".", "")))
            bat.write('ECHO To the folder:\r\nECHO      %s\\BACKUP\r\n' % _TOP_LEVEL_DIRECTORY.replace("/", "\\"))
            bat.write('CD %s\r\n' % _TOP_LEVEL_DIRECTORY.replace("/", "\\"))
            bat.write('PAUSE\n')
            bat.write('\n')
            bat.write('IF NOT EXIST BACKUP MKDIR BACKUP\n\n')
            bat.write('REM The copy or move commands follow:\n\n')

            backup_path = _TOP_LEVEL_DIRECTORY.replace("/", "\\") + "\\BACKUP\\"
            unwanted_list = sorted(unwanted_files.split("\n"), key=lambda s: s.lower())  # To be same as Dart, sort case-insensitive

            for filepath in unwanted_list:
                # Swap to the right type of slashes
                filepath = filepath.replace("/", "\\")
                filepath = filepath.replace(".\\", _TOP_LEVEL_DIRECTORY.replace("/", "\\") + "\\")
                # In "BACKUP", preserve only directory structure below "content"
                split_to_index = filepath.split("\\").index("content") + 1
                new_filepath = "\\".join(filepath.split("\\")[split_to_index:])
                # If we're down the tree, may need to make directories:
                if len(new_filepath.split("\\")) > 1:
                    new_directory = "\\".join(new_filepath.split("\\")[:-1])
                    new_directory = backup_path + new_directory
                    bat.write('IF NOT EXIST "%s" MKDIR "%s"\n' % (new_directory, new_directory))
                # Do the move/copy from one location to the other:
                bat.write('%s "%s" "%s"\n' % (action, filepath, backup_path + new_filepath))

            bat.write("REM Pause at end in case double-clicked; allows viewing output.\nPAUSE\n")


text:
// TypeScript Version: 2.0

/// <reference types="@stdlib/types"/>

import { Complex128 } from '@stdlib/types/object';

/**
* Rounds a double-precision complex floating-point number toward positive infinity.
*
* @param z - input value
* @returns result
*
* @example
* var Complex128 = require( `@stdlib/complex/float64` );
* var real = require( `@stdlib/complex/real` );
* var imag = require( `@stdlib/complex/imag` );
*
* var v = cceil( new Complex128( -1.5, 2.5 ) );
* // returns <Complex128>
*
* var re = real( v );
* // returns -1.0
*
* var im = imag( v );
* // returns 3.0
*/
declare function cceil( z: Complex128 ): Complex128;

// EXPORTS //

export = cceil;


text:
{% load staticfiles %}

Kolibri makes high quality education technology available in low-resource communities such as rural schools, refugee camps, orphanages, non-formal school systems, and prison systems.


text:
from .charsetgroupprober import CharSetGroupProber
from .utf8prober import UTF8Prober
from .sjisprober import SJISProber
from .eucjpprober import EUCJPProber
from .gb2312prober import GB2312Prober
from .euckrprober import EUCKRProber
from .big5prober import Big5Prober
from .euctwprober import EUCTWProber

class MBCSGroupProber(CharSetGroupProber):
    def __init__(self):
        CharSetGroupProber.__init__(self)
        self._mProbers = [
            UTF8Prober(),
            SJISProber(),
            EUCJPProber(),
            GB2312Prober(),
            EUCKRProber(),
            Big5Prober(),
            EUCTWProber()
        ]
        self.reset()


text:
using namespace Eigen;

namespace DrakeShapes {
Element::Element(const Element& other)
    : T_element_to_world(other.getWorldTransform()),
      T_element_to_local(other.getLocalTransform()),
      geometry(other.getGeometry().clone()) {}

Element* Element::clone() const { return new Element(*this); }

const Isometry3d& Element::getWorldTransform() const {
  return T_element_to_world;
}

const Isometry3d& Element::getLocalTransform() const {
  return T_element_to_local;
}

Shape Element::getShape() const { return geometry->getShape(); }

void Element::setGeometry(const Geometry& geometry_in) {
  geometry = std::unique_ptr<Geometry>(geometry_in.clone());
}

const Geometry& Element::getGeometry() const { return *geometry; }

bool Element::hasGeometry() const { return geometry != nullptr; }

void Element::getTerrainContactPoints(Eigen::Matrix3Xd& local_points) const {
  if (!hasGeometry()) {
    local_points = Eigen::Matrix3Xd();
    return;
  }

  Eigen::Matrix3Xd points;
  geometry->getTerrainContactPoints(points);

  local_points = T_element_to_local * points;
}

void Element::SetLocalTransform(
    const Eigen::Isometry3d& T_element_to_local_in) {
  T_element_to_local = T_element_to_local_in;
}

void Element::updateWorldTransform(
    const Eigen::Isometry3d& T_local_to_world_in) {
  setWorldTransform(T_local_to_world_in * (T_element_to_local));
}

void Element::setWorldTransform(const Isometry3d& T_element_to_world_in) {
  T_element_to_world = T_element_to_world_in;
}
}


text:
"""Make token scopes not nullable

Revision ID: 1b7e98f581bc
Revises: 1f6738730753
Create Date: 2021-06-30 00:54:37.365288
"""

from alembic import op

# revision identifiers, used by Alembic.
revision = '1b7e98f581bc'
down_revision = '1f6738730753'
branch_labels = None
depends_on = None

def upgrade():
    op.alter_column('tokens', 'scopes', nullable=False, schema='oauth')

def downgrade():
    op.alter_column('tokens', 'scopes', nullable=True, schema='oauth')


text:
<?php namespace Octommerce\Octommerce\Updates;

use Schema;
use October\Rain\Database\Updates\Migration;

class AddIndexToCategoryProductTable extends Migration
{

    public function up()
    {
        Schema::table('octommerce_octommerce_category_product', function($table)
        {
            $table->integer('product_id')->unsigned()->index()->change();
            $table->integer('category_id')->unsigned()->index()->change();
        });
    }

    public function down()
    {
        Schema::table('octommerce_octommerce_category_product', function($table)
        {
            $table->integer('product_id')->unsigned()->change();
            $table->integer('category_id')->unsigned()->change();
        });
    }

}


text:
module SpookyCore
  class Transaction
    include XmlHelpers

    Error = Struct.new(:attribute, :type, :message)

    def self.create_from_transaction(action, token, body = {})
      options = {body: body[:transaction].to_xml(root: :transaction, skip_types: true)}
      response = Request.post("/transactions/#{token}/#{action}.xml", options)
      Transaction.new(response.body)
    end

    def self.create_from_payment_method(action, token, amount, currency = 'USD')
      params = Nokogiri::XML::Builder.new do |xml|
        xml.transaction {
          xml.transaction_type(action)
          xml.payment_method_token(token)
          xml.amount(amount)
          xml.currency_code(currency)
        }
      end

      response = Request.post("/gateways/#{Request.config[:gateway]}/#{action}.xml", :body => params.to_xml(root: :transaction, skip_types: true))
      Transaction.new(response.body)
    end

    def self.find(token)

    end

    def initialize(xml)
      create_doc('transaction', xml)
    end

    def credit
      self.class.create_from_transaction('credit', token)
    end

    def capture
      self.class.create_from_transaction('capture', token)
    end

    def void
      self.class.create_from_transaction('void', token)
    end

    def token
      at('token')
    end

    def transaction_type
      at('transaction_type')
    end

    def amount
      at('amount', :to_i)
    end

    def currency_code
      at('currency_code')
    end

    def succeeded?
      at('succeeded') == 'true'
    end

    def message
      at('message')
    end

    def error_messages
      @error_messages ||= errors.map {|k, v| v.map(&:message)}
    end

    def errors
      @errors ||= begin
        errors = Hash.new {|h, k| h[k] = []}

        # The errors elements contain information about problems that occured before the transaction was attempted.
        @doc.css('errors error').each do |e|
          attribute = e.attribute('attribute').value.to_sym
          type      = e.attribute('key').value.split('.').last.to_sym
          message   = e.inner_text
          errors[attribute] << Error.new(attribute, type, message)
        end

        #Messages elements may also contain error info returned by the gateway
        unless succeeded?
          @doc.css('message').each do |m|
            if m.attribute('key')
              attribute = m.attribute('key').value.to_sym
              type = m.attribute('key').value.split('.').last.to_sym
              message = m.inner_text
              errors[attribute] << Error.new(attribute, type, message)
            end
          end
        end

        errors
      end
    end
  end # Transaction
end # SpookyCore


text:
require 'ghaki/account/syn_opts'

############################################################################
module Ghaki module Account
  module DB_Driver
    extend SynOpts

    ######################################################################
    attr_syn_opts :db_driver, :database_driver
    attr_accessor :db_driver

    #---------------------------------------------------------------------
    def valid_db_driver?
      return false if @db_driver.nil?
      return false if @db_driver.empty?
      return true
    end

  end # helper
end end # package
############################################################################


text:
class CreateSpreeLookbooks < ActiveRecord::Migration
  def change
    create_table :spree_lookbooks do |t|
      t.string :name
      t.string :slug
      t.string :publish_date
      t.attachment :featured_image
      t.boolean :enabled, default: true

      t.timestamps null: false
    end
  end
end


text:
namespace XlsxStream
{
    public class ContentTypeOverride:SingleAttributeSettingsElement
    {
        public string PartName { get; set; }
        public string ContentType { get; set; }
    }
}


text:
- Added support for the *proxy* integration parameter.
- Updated the Docker image to: *demisto/powershell-ubuntu:7.1.4.24032*.


text:
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.customtabs;

import android.content.Context;
import android.os.IBinder;
import android.os.Process;
import android.support.customtabs.ICustomTabsCallback;
import android.test.InstrumentationTestCase;
import android.test.suitebuilder.annotation.SmallTest;

import org.chromium.base.library_loader.LibraryLoader;
import org.chromium.base.library_loader.LibraryProcessType;

/** Tests for ClientManager. */
public class ClientManagerTest extends InstrumentationTestCase {
    private static final String URL = "https://www.android.com";
    private ClientManager mClientManager;
    private ICustomTabsCallback mCallback = new CustomTabsTestUtils.DummyCallback();
    private IBinder mSession = mCallback.asBinder();
    private int mUid = Process.myUid();

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        Context context = getInstrumentation().getTargetContext().getApplicationContext();
        // UrlUtilities used in ClientManager#getPredictionOutcome() needs the native library.
        LibraryLoader.get(LibraryProcessType.PROCESS_BROWSER).ensureInitialized(context);
        RequestThrottler.purgeAllEntriesForTesting(context);
        mClientManager = new ClientManager(context);
    }

    @SmallTest
    public void testNoSessionNoWarmup() {
        assertEquals(ClientManager.NO_SESSION_NO_WARMUP, mClientManager.getWarmupState(null));
    }

    @SmallTest
    public void testNoSessionWarmup() {
        mClientManager.recordUidHasCalledWarmup(mUid);
        assertEquals(ClientManager.NO_SESSION_WARMUP, mClientManager.getWarmupState(null));
    }

    @SmallTest
    public void testInvalidSessionNoWarmup() {
        assertEquals(ClientManager.NO_SESSION_NO_WARMUP, mClientManager.getWarmupState(mSession));
    }

    @SmallTest
    public void testInvalidSessionWarmup() {
        mClientManager.recordUidHasCalledWarmup(mUid);
        assertEquals(ClientManager.NO_SESSION_WARMUP, mClientManager.getWarmupState(mSession));
    }

    @SmallTest
    public void testValidSessionNoWarmup() {
        mClientManager.newSession(mCallback, mUid, null);
        assertEquals(ClientManager.SESSION_NO_WARMUP_NOT_CALLED,
                mClientManager.getWarmupState(mSession));
    }

    @SmallTest
    public void testValidSessionOtherWarmup() {
        mClientManager.recordUidHasCalledWarmup(mUid + 1);
        mClientManager.newSession(mCallback, mUid, null);
        assertEquals(ClientManager.SESSION_NO_WARMUP_ALREADY_CALLED,
                mClientManager.getWarmupState(mSession));
    }

    @SmallTest
    public void testValidSessionWarmup() {
        mClientManager.recordUidHasCalledWarmup(mUid);
        mClientManager.newSession(mCallback, mUid, null);
        assertEquals(ClientManager.SESSION_WARMUP, mClientManager.getWarmupState(mSession));
    }

    @SmallTest
    public void testValidSessionWarmupSeveralCalls() {
        mClientManager.recordUidHasCalledWarmup(mUid);
        mClientManager.newSession(mCallback, mUid, null);
        assertEquals(ClientManager.SESSION_WARMUP, mClientManager.getWarmupState(mSession));

        ICustomTabsCallback callback = new CustomTabsTestUtils.DummyCallback();
        IBinder session = callback.asBinder();
        mClientManager.newSession(callback, mUid, null);
        assertEquals(ClientManager.SESSION_WARMUP, mClientManager.getWarmupState(session));
    }

    @SmallTest
    public void testPredictionOutcomeSuccess() {
        assertTrue(mClientManager.newSession(mCallback, mUid, null));
        assertTrue(mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, URL));
        assertEquals(
                ClientManager.GOOD_PREDICTION, mClientManager.getPredictionOutcome(mSession, URL));
    }

    @SmallTest
    public void testPredictionOutcomeNoPrediction() {
        assertTrue(mClientManager.newSession(mCallback, mUid, null));
        mClientManager.recordUidHasCalledWarmup(mUid);
        assertEquals(
                ClientManager.NO_PREDICTION, mClientManager.getPredictionOutcome(mSession, URL));
    }

    @SmallTest
    public void testPredictionOutcomeBadPrediction() {
        assertTrue(mClientManager.newSession(mCallback, mUid, null));
        assertTrue(mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, URL));
        assertEquals(
                ClientManager.BAD_PREDICTION,
                mClientManager.getPredictionOutcome(mSession, URL + "#fragment"));
    }

    @SmallTest
    public void testPredictionOutcomeIgnoreFragment() {
        assertTrue(mClientManager.newSession(mCallback, mUid, null));
        assertTrue(mClientManager.updateStatsAndReturnWhetherAllowed(mSession, mUid, URL));
        mClientManager.setIgnoreFragmentsForSession(mSession, true);
        assertEquals(
                ClientManager.GOOD_PREDICTION,
                mClientManager.getPredictionOutcome(mSession, URL + "#fragment"));
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <groupId>com.github.chencye.demo</groupId>
        <artifactId>springcloud-demo</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>_02_eureka-server</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
        </dependency>
    </dependencies>

</project>


text:
package com.example.android.sunshine.app;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.ShareActionProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.android.sunshine.app.data.WeatherContract;

/**
 * A placeholder fragment containing a simple view.
 */
public class ForecastDetailFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {

    private static final String LOG_TAG = ForecastDetailFragment.class.getSimpleName();

    private static final String FORECAST_SHARE_HASHTAG = " #SunshineApp";
    private ShareActionProvider m_ShareActionProvider;
    private String m_ForecastString;

    private static final int DETAIL_LOADER = 0;

    private static final String[] FORECAST_COLUMNS = {
            WeatherContract.WeatherEntry.TABLE_NAME + "." + WeatherContract.WeatherEntry._ID,
            WeatherContract.WeatherEntry.COLUMN_DATE,
            WeatherContract.WeatherEntry.COLUMN_SHORT_DESC,
            WeatherContract.WeatherEntry.COLUMN_MAX_TEMP,
            WeatherContract.WeatherEntry.COLUMN_MIN_TEMP,
            WeatherContract.WeatherEntry.COLUMN_HUMIDITY,
            WeatherContract.WeatherEntry.COLUMN_PRESSURE,
            WeatherContract.WeatherEntry.COLUMN_WIND_SPEED,
            WeatherContract.WeatherEntry.COLUMN_DEGREES,
            WeatherContract.WeatherEntry.COLUMN_WEATHER_ID,
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING

    };

    // these constants correspond to the projection defined above, and must change if the
    // projection changes
    private static final int COL_WEATHER_ID = 0;
    private static final int COL_WEATHER_DATE = 1;
    private static final int COL_WEATHER_DESC = 2;
    private static final int COL_WEATHER_MAX_TEMP = 3;
    private static final int COL_WEATHER_MIN_TEMP = 4;
    private static final int COL_WEATHER_HUMIDITY = 5;
    private static final int COL_WEATHER_PRESSURE = 6;
    private static final int COL_WEATHER_WIND_SPEED = 7;
    private static final int COL_WEATHER_DEGREES = 8;
    //private static final int COL_WEATHER_ID = 9;

    private ImageView mIconView;
    private TextView mFriendlyDateView;
    private TextView mDateView;
    private TextView mDescriptionView;
    private TextView mHighTempView;
    private TextView mLowTempView;
    private TextView mHumidityView;
    private TextView mWindView;
    private TextView mPressureView;

    public ForecastDetailFragment() {
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_forecast_detail, container, false);

        mIconView = (ImageView) rootView.findViewById(R.id.detail_icon);
        mDateView = (TextView) rootView.findViewById(R.id.detail_date_textview);
        mFriendlyDateView = (TextView) rootView.findViewById(R.id.detail_day_textview);
        mDescriptionView = (TextView) rootView.findViewById(R.id.detail_forecast_textview);
        mHighTempView = (TextView) rootView.findViewById(R.id.detail_high_textview);
        mLowTempView = (TextView) rootView.findViewById(R.id.detail_low_textview);
        mHumidityView = (TextView) rootView.findViewById(R.id.detail_humidity_textview);
        mWindView = (TextView) rootView.findViewById(R.id.detail_wind_textview);
        mPressureView = (TextView) rootView.findViewById(R.id.detail_pressure_textview);

        return rootView;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.detailfragment, menu);

        MenuItem item = menu.findItem(R.id.action_share);

        m_ShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(item);

        // If onLoadFinished happens before this, we can go ahead and set the share intent now.
        if (m_ForecastString != null) {
            m_ShareActionProvider.setShareIntent(createShareForecastIntent());
        }

    }

    private Intent createShareForecastIntent()  {

        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_TEXT, m_ForecastString + FORECAST_SHARE_HASHTAG);

        return shareIntent;

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        getLoaderManager().initLoader(DETAIL_LOADER, null, this);
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {

        Log.v(LOG_TAG, "In onCreateLoader");

        Intent intent = getActivity().getIntent();
        if (intent == null) {
            return null;
        }

        // Now create and return a CursorLoader that will take care of
        // creating a Cursor for the data being displayed.
        return new CursorLoader(
                getActivity(),
                intent.getData(),
                FORECAST_COLUMNS,
                null,
                null,
                null
        );
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {

        Log.v(LOG_TAG, "In onLoadFinished");

        if (!data.moveToFirst()) { return; }

        long date = data.getLong(COL_WEATHER_DATE);
        String day = Utility.getDayName(getActivity(), date);
        //TextView dayTextView = (TextView)getView().findViewById(R.id.detail_day_textview);
        mFriendlyDateView.setText(day);

        String dateStr = Utility.getFormattedMonthDay(getActivity(), date);
       // TextView dateTextView = (TextView)getView().findViewById(R.id.detail_date_textview);
        mDateView.setText(dateStr);

        String weatherDescription = data.getString(COL_WEATHER_DESC);

        boolean isMetric = Utility.isMetric(getActivity());

        String high = Utility.formatTemperature(getActivity(),
                data.getDouble(COL_WEATHER_MAX_TEMP), isMetric);

        String low = Utility.formatTemperature(getActivity(),
                data.getDouble(COL_WEATHER_MIN_TEMP), isMetric);

        //TextView highTextView = (TextView)getView().findViewById(R.id.detail_high_textview);
        mHighTempView.setText(high);

        //TextView lowTextView = (TextView)getView().findViewById(R.id.detail_low_textview);
        mLowTempView.setText(low);

        //ImageView imageView = (ImageView)getView().findViewById(R.id.detail_icon);
        mIconView.setImageResource(R.drawable.ic_launcher);

        double humidity = data.getDouble(COL_WEATHER_HUMIDITY);
        //TextView humidityTextView = (TextView)getView().findViewById(R.id.detail_humidity_textview);
        mHumidityView.setText(getString(R.string.format_humidity, humidity));

        float windSpeed = data.getFloat(COL_WEATHER_WIND_SPEED);
        float windDirection = data.getFloat(COL_WEATHER_DEGREES);
        //TextView windTextView = (TextView)getView().findViewById(R.id.detail_wind_textview);
        mWindView.setText(Utility.getFormattedWind(getActivity(), windSpeed, windDirection));

        double pressure = data.getDouble(COL_WEATHER_PRESSURE);
        //TextView pressureTextView = (TextView)getView().findViewById(R.id.detail_pressure_textview);
        mPressureView.setText(getString(R.string.format_pressure, humidity));

        // If onCreateOptionsMenu has already happened, we need to update the share intent now.
        if (m_ShareActionProvider != null) {
            m_ShareActionProvider.setShareIntent(createShareForecastIntent());
        }
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
    }

}


text:
#pragma once

UENUM(BlueprintType)		//"BlueprintType" is essential to include
enum class ESpellTypeEnum : uint8
{
	ST_Invalid 		UMETA(DisplayName = "Invalid"),
	ST_Block		UMETA(DisplayName = "Block"),
	ST_Damage 		UMETA(DisplayName = "Damage"),
	ST_Stun			UMETA(DisplayName = "Stun")
};


text:
//package com.dominicapps.dictionary.tablelab.extras;
package com.dominicapps.tablelab.lab.utils;

import com.dominicapps.tablelab.lab.labs.TableLab;

import org.joda.time.DateTime;

/**
 * Reusable class for Many to Many relationships. Speeds up classic
 * id, left_id, right_id.
 */

public class Pair {

    private int id, left, right;
    private DateTime created, updated;

    public Pair() {
    }

    public Pair(int id, int left, int right, DateTime created, DateTime updated) {
        this.id = id;
        this.left = left;
        this.right = right;
        this.created = created;
        this.updated = updated;
    }

    public Pair(int left, int right, DateTime created, DateTime updated) {
        this.left = left;
        this.right = right;
        this.created = created;
        this.updated = updated;
    }

    public Pair(int left, int right, DateTime updated) {
        this.left = left;
        this.right = right;
        this.updated = updated;
    }

    public Pair(int left, int right) {
        this.left = left;
        this.right = right;
        created = TableLab.now();
        updated = TableLab.now();
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getLeft() {
        return left;
    }

    public void setLeft(int left) {
        this.left = left;
    }

    public int getRight() {
        return right;
    }

    public void setRight(int right) {
        this.right = right;
    }

    public DateTime getCreated() {
        return created;
    }

    public void setCreated(DateTime created) {
        this.created = created;
    }

    public DateTime getUpdated() {
        return updated;
    }

    public void setUpdated(DateTime updated) {
        this.updated = updated;
    }
}


text:
using System;

namespace statsd.net.Backends
{
  using System.ComponentModel.Composition;
  using System.Threading.Tasks;
  using System.Threading.Tasks.Dataflow;
  using System.Xml.Linq;
  using statsd.net.core;
  using statsd.net.core.Backends;
  using statsd.net.core.Structures;

  [Export(typeof (IBackend))]
  public class ConsoleBackend : IBackend
  {
    public string Name => "Console";

    public void Configure(string collectorName, XElement configElement, ISystemMetricsService systemMetrics)
    {
      IsActive = true;
      Completion = new Task(() => { IsActive = false; });
    }

    public DataflowMessageStatus OfferMessage(DataflowMessageHeader messageHeader, Bucket bucket,
      ISourceBlock<Bucket> source, bool consumeToAccept)
    {
      Console.WriteLine(bucket.ToString());
      return DataflowMessageStatus.Accepted;
    }

    public void Complete()
    {
      Console.WriteLine("Done");
      Completion.Start();
    }

    public Task Completion { get; private set; }

    public void Fault(Exception exception)
    {
      throw new NotImplementedException();
    }

    public bool IsActive { get; private set; }

    public int OutputCount => 0;
  }
}


text:
<?php namespace Myna;

/**
 * A Cache stores experiment data (aka a deployment) in some kind of
 store to reduce the frequency of network accesses.
 */
interface Cache {

    /**
     * Retrieve experiment data, possibly blocking (making a network
     * request) to do son.
     *
     * @param String $key. The key for the cached data.
     * @return String The cached data.
     */
    public function get($key);

}

?>