text:
package com.hazelcast.mapreduce.aggregation.impl;

import com.hazelcast.mapreduce.Collator;
import com.hazelcast.mapreduce.Combiner;
import com.hazelcast.mapreduce.CombinerFactory;
import com.hazelcast.mapreduce.Mapper;
import com.hazelcast.mapreduce.Reducer;
import com.hazelcast.mapreduce.ReducerFactory;
import com.hazelcast.mapreduce.aggregation.Supplier;
import com.hazelcast.nio.serialization.BinaryInterface;

import java.math.BigDecimal;
import java.util.Map;

/**
 * The predefined maximum aggregation for values of type {@link java.math.BigDecimal}.
 *
 * @param <Key>   the input key type
 * @param <Value> the input value type
 */
public class BigDecimalMaxAggregation<Key, Value>
        implements AggType<Key, Value, Key, BigDecimal, BigDecimal, BigDecimal, BigDecimal> {

    @Override
    public Collator<Map.Entry<Key, BigDecimal>, BigDecimal> getCollator() {
        return new Collator<Map.Entry<Key, BigDecimal>, BigDecimal>() {
            @Override
            public BigDecimal collate(Iterable<Map.Entry<Key, BigDecimal>> values) {
                BigDecimal max = null;
                for (Map.Entry<Key, BigDecimal> entry : values) {
                    BigDecimal value = entry.getValue();
                    max = max == null ? value : value.max(max);
                }
                return max;
            }
        };
    }

    @Override
    public Mapper<Key, Value, Key, BigDecimal> getMapper(Supplier<Key, Value, BigDecimal> supplier) {
        return new SupplierConsumingMapper<Key, Value, BigDecimal>(supplier);
    }

    @Override
    public CombinerFactory<Key, BigDecimal, BigDecimal> getCombinerFactory() {
        return new BigDecimalMaxCombinerFactory<Key>();
    }

    @Override
    public ReducerFactory<Key, BigDecimal, BigDecimal> getReducerFactory() {
        return new BigDecimalMaxReducerFactory<Key>();
    }

    /**
     * Maximum CombinerFactory for type {@link java.math.BigDecimal}
     *
     * @param <Key> the key type
     */
    @BinaryInterface
    static final class BigDecimalMaxCombinerFactory<Key>
            extends AbstractAggregationCombinerFactory<Key, BigDecimal, BigDecimal> {

        @Override
        public Combiner<BigDecimal, BigDecimal> newCombiner(Key key) {
            return new BigDecimalMaxCombiner();
        }

        @Override
        public int getId() {
            return AggregationsDataSerializerHook.BIG_DECIMAL_MAX_COMBINER_FACTORY;
        }
    }

    /**
     * Maximum ReducerFactory for type {@link java.math.BigDecimal}
     *
     * @param <Key> the key type
     */
    @BinaryInterface
    static final class BigDecimalMaxReducerFactory<Key>
            extends AbstractAggregationReducerFactory<Key, BigDecimal, BigDecimal> {

        @Override
        public Reducer<BigDecimal, BigDecimal> newReducer(Key key) {
            return new BigDecimalMaxReducer();
        }

        @Override
        public int getId() {
            return AggregationsDataSerializerHook.BIG_DECIMAL_MAX_REDUCER_FACTORY;
        }
    }

    /**
     * Maximum Combiner for type {@link java.math.BigDecimal}
     */
    private static final class BigDecimalMaxCombiner
            extends Combiner<BigDecimal, BigDecimal> {

        private BigDecimal max;

        @Override
        public void combine(BigDecimal value) {
            max = max == null ? value : value.max(max);
        }

        @Override
        public BigDecimal finalizeChunk() {
            return max;
        }

        @Override
        public void reset() {
            max = null;
        }
    }

    /**
     * Maximum Reducer for type {@link java.math.BigDecimal}
     */
    private static final class BigDecimalMaxReducer
            extends Reducer<BigDecimal, BigDecimal> {

        private BigDecimal max;

        @Override
        public void reduce(BigDecimal value) {
            max = max == null ? value : value.max(max);
        }

        @Override
        public BigDecimal finalizeReduce() {
            return max;
        }
    }
}


text:
class V1::Users::SessionsController < V1::ApplicationController
  respond_to :json

  before_filter :authenticate_user!, except: [ :create ]
  before_filter :ensure_params_exist, except: [ :destroy ]

  def create
    resource = User.find_for_database_authentication(email: session_params[:email])
    return invalid_login_attempt unless resource

    if resource.valid_password?(session_params[:password])
      sign_in(:user, resource)
      resource.ensure_authentication_token!
      render json: { id: resource.uuid, auth_token: resource.authentication_token }, status: :ok
      return
    end
    invalid_login_attempt
  end

  def destroy
    resource = User.find_by_authentication_token(params[:auth_token] || header_token)
    sign_out(resource_name)
    render json: {}.to_json, status: :ok
  end

  protected

  def session_params
    params.permit(:email, :password)
  end

  def ensure_params_exist
    return unless session_params[:email].blank? && session_params[:password].blank?
    render json: { message: "email and password are required parameters" }, status: 422
  end

  def invalid_login_attempt
    render json: { message: "there was an error with your email or password" }, status: 401
  end

  def header_token
    header_token = request.headers["Authorization"]
    if header_token && header_token =~ /^token (.+)$/
      $~[1]
    end
  end

  def missing_params
    warden.custom_failure!
    return render json: {}, status: 400
  end

  def invalid_credentials
    warden.custom_failure!
    render json: {}, status: 401
  end

end

redpajama_set_name: RedPajamaGithub


text:
package io.fabric8.maven.docker;

import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Date;
import java.util.Enumeration;

import io.fabric8.maven.docker.access.DockerAccessException;
import io.fabric8.maven.docker.config.BuildImageConfiguration;
import io.fabric8.maven.docker.config.ImageConfiguration;
import io.fabric8.maven.docker.service.BuildService;
import io.fabric8.maven.docker.service.ImagePullManager;
import io.fabric8.maven.docker.service.JibBuildService;
import io.fabric8.maven.docker.service.ServiceHub;
import io.fabric8.maven.docker.util.Logger;
import io.fabric8.maven.docker.util.EnvUtil;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

/**
 * Mojo for building a data image
 *
 * @author roland
 * @since 28.07.14
 */
@Mojo(name = "build", defaultPhase = LifecyclePhase.INSTALL)
public class BuildMojo extends AbstractBuildSupportMojo {

    public static final String DMP_PLUGIN_DESCRIPTOR = "META-INF/maven/io.fabric8/dmp-plugin";
    public static final String DOCKER_EXTRA_DIR = "docker-extra";

    @Parameter(property = "docker.skip.build", defaultValue = "false")
    protected boolean skipBuild;

    @Parameter(property = "docker.name", defaultValue = "")
    protected String name;

    /**
     * Skip Sending created tarball to docker daemon
     */
    @Parameter(property = "docker.buildArchiveOnly", defaultValue = "false")
    protected String buildArchiveOnly;

    /**
     * Skip building tags
     */
    @Parameter(property = "docker.skip.tag", defaultValue = "false")
    protected boolean skipTag;

    @Override
    protected void executeInternal(ServiceHub hub) throws IOException, MojoExecutionException {
        if (skipBuild) {
            return;
        }

        // Check for build plugins
        executeBuildPlugins();

        // Iterate over all the ImageConfigurations and process one by one
        for (ImageConfiguration imageConfig : getResolvedImages()) {
            processImageConfig(hub, imageConfig);
        }
    }

    protected void buildAndTag(ServiceHub hub, ImageConfiguration imageConfig)
            throws MojoExecutionException, IOException {

        EnvUtil.storeTimestamp(getBuildTimestampFile(), getBuildTimestamp());

        BuildService.BuildContext buildContext = getBuildContext();
        ImagePullManager pullManager = getImagePullManager(determinePullPolicy(imageConfig.getBuildConfiguration()), autoPull);
        proceedWithBuildProcess(hub, buildContext, imageConfig, pullManager);
    }

    private void proceedWithBuildProcess(ServiceHub hub, BuildService.BuildContext buildContext, ImageConfiguration imageConfig, ImagePullManager pullManager) throws MojoExecutionException, IOException {
        if (Boolean.TRUE.equals(jib)) {
            proceedWithJibBuild(hub, buildContext, imageConfig);
        } else {
            proceedWithDockerBuild(hub.getBuildService(), buildContext, imageConfig, pullManager);
        }
    }

    private void proceedWithJibBuild(ServiceHub hub, BuildService.BuildContext buildContext, ImageConfiguration imageConfig) throws MojoExecutionException {
        log.info("Building Container image with [[B]]JIB(Java Image Builder)[[B]] mode");
        new JibBuildService(hub, createMojoParameters(), log).build(imageConfig, buildContext.getRegistryConfig());
    }

    private void proceedWithDockerBuild(BuildService buildService, BuildService.BuildContext buildContext, ImageConfiguration imageConfig, ImagePullManager pullManager) throws MojoExecutionException, IOException {
        File buildArchiveFile = buildService.buildArchive(imageConfig, buildContext, resolveBuildArchiveParameter());
        if (Boolean.FALSE.equals(shallBuildArchiveOnly())) {
            buildService.buildImage(imageConfig, pullManager, buildContext, buildArchiveFile);
        }
        if (!skipTag) {
            buildService.tagImage(imageConfig);
        }
    }

    // We ignore an already existing date file and always return the current date

    @Override
    protected Date getReferenceDate() {
        return new Date();
    }

    private String resolveBuildArchiveParameter() {
        if (buildArchiveOnly != null && !buildArchiveOnly.isEmpty()) {
            if (!(buildArchiveOnly.equalsIgnoreCase("false") ||
                buildArchiveOnly.equalsIgnoreCase("true"))) {
                return buildArchiveOnly;
            }
        }
        return null;
    }

    private boolean shallBuildArchiveOnly() {
        if (buildArchiveOnly != null && !buildArchiveOnly.isEmpty()) {
            if (buildArchiveOnly.equalsIgnoreCase("false") ||
                    buildArchiveOnly.equalsIgnoreCase("true")) {
                return Boolean.parseBoolean(buildArchiveOnly);
            }
        }
        return false;
    }

    private String determinePullPolicy(BuildImageConfiguration buildConfig) {
        return buildConfig != null && buildConfig.getImagePullPolicy() != null ? buildConfig.getImagePullPolicy() : imagePullPolicy;
    }

    /**
     * Helper method to process an ImageConfiguration.
     *
     * @param hub ServiceHub
     * @param aImageConfig ImageConfiguration that would be forwarded to build and tag
     * @throws DockerAccessException
     * @throws MojoExecutionException
     */
    private void processImageConfig(ServiceHub hub, ImageConfiguration aImageConfig) throws IOException, MojoExecutionException {
        BuildImageConfiguration buildConfig = aImageConfig.getBuildConfiguration();

        if (buildConfig != null) {
            if(buildConfig.skip()) {
                log.info("%s : Skipped building", aImageConfig.getDescription());
            } else {
                buildAndTag(hub, aImageConfig);
            }
        }
    }

    // check for a run-java.sh dependency an extract the script to target/ if found
    private void executeBuildPlugins() {
        try {
            Enumeration<URL> dmpPlugins = Thread.currentThread().getContextClassLoader().getResources(DMP_PLUGIN_DESCRIPTOR);
            while (dmpPlugins.hasMoreElements()) {

                URL dmpPlugin = dmpPlugins.nextElement();
                File outputDir = getAndEnsureOutputDirectory();
                processDmpPluginDescription(dmpPlugin, outputDir);
            }
        } catch (IOException e) {
            log.error("Cannot load dmp-plugins from %s", DMP_PLUGIN_DESCRIPTOR);
        }
    }

    private void processDmpPluginDescription(URL pluginDesc, File outputDir) throws IOException {
        String line = null;
        try (LineNumberReader reader =
                 new LineNumberReader(new InputStreamReader(pluginDesc.openStream(), "UTF8"))) {
            line = reader.readLine();
            while (line != null) {
                if (line.matches("^\\s*#")) {
                    // Skip comments
                    continue;
                }
                callBuildPlugin(outputDir, line);
                line = reader.readLine();
            }
        } catch (ClassNotFoundException e) {
            // Not declared as dependency, so just ignoring ...
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            log.verbose(Logger.LogVerboseCategory.BUILD,"Found dmp-plugin %s but could not be called : %s",
                     line,
                     e.getMessage());
        }
    }

    private File getAndEnsureOutputDirectory() {
        File outputDir = new File(new File(project.getBuild().getDirectory()), DOCKER_EXTRA_DIR);
        if (!outputDir.exists()) {
            outputDir.mkdirs();
        }
        return outputDir;
    }

    private void callBuildPlugin(File outputDir, String buildPluginClass) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        Class buildPlugin = Class.forName(buildPluginClass);
        try {
            Method method = buildPlugin.getMethod("addExtraFiles", File.class);
            method.invoke(null, outputDir);
            log.info("Extra files from %s extracted", buildPluginClass);
        } catch (NoSuchMethodException exp) {
            log.verbose(Logger.LogVerboseCategory.BUILD,"Build plugin %s does not support 'addExtraFiles' method", buildPluginClass);
        }
    }

}


text:
package org.atdl4j.ui.app.impl;

import org.atdl4j.config.Atdl4jConfig;
import org.atdl4j.config.Atdl4jOptions;
import org.atdl4j.fixatdl.core.StrategyT;
import org.atdl4j.ui.app.StrategyDescriptionPanel;

/**
 * Represents the base, non-GUI system-specific Strategy Description GUI component.
 *
 * Creation date: (Feb 26, 2010 11:09:19 PM)
 * @author Scott Atwell
 * @version 1.0, Mar 1, 2010
 */
public abstract class AbstractStrategyDescriptionPanel
		implements StrategyDescriptionPanel
{
	private Atdl4jOptions atdl4jOptions = null;

	abstract protected void setStrategyDescriptionText( String aText );

	/*
	 * Loads aStrategy.getDescription() if populated and if Atdl4jOptions.isShowStrategyDescription(),
	 * otherwise invokes setVisible( false ).
	 *
	 * @param aStrategy
	 */
	public void loadStrategyDescriptionVisible( StrategyT aStrategy )
	{
		setStrategyDescriptionText( "" );
		if ( ( Atdl4jConfig.getConfig().isShowStrategyDescription() )
			&& ( aStrategy != null ) && ( aStrategy.getDescription() != null )  )
		{
			setVisible( true );
		}
		else
		{
			setVisible( false );
		}
	}

	public void loadStrategyDescriptionText( StrategyT aStrategy )
	{
		if ( ( Atdl4jConfig.getConfig().isShowStrategyDescription() ) )
		{
			if ( ( aStrategy != null ) && ( aStrategy.getDescription() != null ) )
			{
				setStrategyDescriptionText( aStrategy.getDescription() );
			}
			else
			{
				setStrategyDescriptionText( "" );
			}
		}
	}

	/**
	 * @param atdl4jOptions the atdl4jOptions to set
	 */
	protected void setAtdl4jOptions(Atdl4jOptions atdl4jOptions)
	{
		this.atdl4jOptions = atdl4jOptions;
	}

	/**
	 * @return the atdl4jOptions
	 */
	public Atdl4jOptions getAtdl4jOptions()
	{
		return atdl4jOptions;
	}
}


text:
<?php

use yii\captcha\Captcha;
use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $form yii\widgets\ActiveForm */
/* @var $model frontend\models\ContactForm */

$this->title = Yii::t('frontend', 'Contact');
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <?php $form = ActiveForm::begin() ?>

        <?= $form->field($model, 'name') ?>

        <?= $form->field($model, 'email') ?>

        <?= $form->field($model, 'subject') ?>

        <?= $form->field($model, 'body')->textArea(['rows' => 6]) ?>

        <?= $form->field($model, 'verifyCode')->widget(Captcha::className(), [
            'captchaAction' => '/site/captcha',
            'template' => '

{image}

{input}

',
        ]) ?>

            <?= Html::submitButton(Yii::t('frontend', 'Send'), ['class' => 'btn btn-primary']) ?>

    <?php ActiveForm::end() ?>


text:
(function () {
    //////////////////////
    var Preloader = function () {
        this.image = h("img");
        this.cache = {};
        this.queue = [];

        this.image.addEventListener("load", this.moveQueue.bind(this));
        this.image.addEventListener("error", this.moveQueue.bind(this));
        this.moveQueue();
    };

    Preloader.prototype.add = function (src) {
        if (src in this.cache) {
            return;
        }
        this.cache[src] = true;
        this.queue.push(src);
    };

    Preloader.prototype.moveQueue = function () {
        var src = this.queue.pop();
        if (src !== undefined) {
            this.image.src = src;
        } else {
            setTimeout(this.moveQueue.bind(this), 250);
        }
    };

    //////////////////////

    var SlideShow = function () {
        this.imageStab = "/static/images/loading.gif";
        this.lightBoxImage = h("img.light-box-img", {src: this.imageStab});
        this.lightBox = h(".frf-co-light-box.first.last.hidden",
            h(".light-box-shadow",
                h(".light-box-container", this.lightBoxImage),
                h(".light-box-arrow.left"),
                h(".light-box-arrow.right")
            )
        );
        /**
         * @type {DOMTokenList}
         */
        this.cList = this.lightBox.classList;
        this.preloader = new Preloader();
        this.hidden = true;
        this.slides = [];
        this.index = 0;

        document.body.appendChild(this.lightBox);

        document.body.addEventListener("keydown", function (e) {
            if (this.hidden) {
                return;
            }

            if (e.keyCode == 27) {
                this.hide();
            } else if (e.keyCode == 39) { // →
                this.next();
                e.preventDefault();
            } else if (e.keyCode == 37) { // ←
                this.prev();
                e.preventDefault();
            } else if (e.keyCode == 36) { // Home
                this.first();
                e.preventDefault();
            } else if (e.keyCode == 35) { // End
                this.last();
                e.preventDefault();
            }
        }.bind(this), true);

        this.lightBox.addEventListener("click", function (e) {
            var arr;
            if ((arr = closestParent(e.target, ".light-box-arrow", true)) !== null) {
                e.stopPropagation();
                if (arr.classList.contains("left")) {
                    this.prev();
                } else if (arr.classList.contains("right")) {
                    this.next();
                }
            } else if (closestParent(e.target, ".light-box-shadow", true)) {
                this.hide();
            }
        }.bind(this));

        this.lightBoxImage.addEventListener("click", function () {
            window.open(this.slides[this.index].href, "_blank");
        }.bind(this));
    };

    SlideShow.prototype.isFirst = function () { return this.index === 0;};
    SlideShow.prototype.isLast = function () { return this.index === this.slides.length - 1;};

    /**
     * @param {Array<HTMLAnchorElement>} slides
     * @param {HTMLAnchorElement} currSlide
     */
    SlideShow.prototype.show = function (slides, currSlide) {
        this.slides = slides;
        slides.forEach(function (s, i) {
            if (s === currSlide) {
                this.index = i;
            } else {
                this.preloader.add(s.dataset["imageSrc"]);
            }
        }.bind(this));
        this.hidden = false;
        this.cList.remove("hidden");
        this._showCurrent();
    };

    SlideShow.prototype._showCurrent = function () {
        this.lightBoxImage.src = this.imageStab;
        this.lightBoxImage.src = this.slides[this.index].dataset["imageSrc"];
        if (this.isFirst()) this.cList.add("first"); else this.cList.remove("first");
        if (this.isLast()) this.cList.add("last"); else this.cList.remove("last");
    };

    SlideShow.prototype.hide = function () {
        if (!this.hidden) {
            this.hidden = true;
            this.cList.add("hidden");
        }
    };

    SlideShow.prototype.next = function () {
        if (this.hidden || this.isLast()) return;
        this.index++;
        this._showCurrent();
    };

    SlideShow.prototype.prev = function () {
        if (this.hidden || this.isFirst()) return;
        this.index--;
        this._showCurrent();
    };

    SlideShow.prototype.first = function () {
        if (this.hidden || this.isFirst()) return;
        this.index = 0;
        this._showCurrent();
    };

    SlideShow.prototype.last = function () {
        if (this.hidden || this.isLast()) return;
        this.index = this.slides.length - 1;
        this._showCurrent();
    };

    //////////////////////

    var OEmbedIt = function (link, url, param) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url + "?url=" + encodeURIComponent(link.href));
        xhr.responseType = "json";
        xhr.onload = function () {
            if (param in this.response) {
                link.dataset["imageSrc"] = this.response[param];
                link.classList.add("light-box-thumbnail");
            }
        };
        xhr.send();
    };

    var NoEmbedIt = function (link) { OEmbedIt(link, "https://noembed.com/embed", "media_url"); };

    registerAction(function (node) {
        if (!settings["lightBoxedImages"]) return;

        if (node === undefined) {
            // инициализация
            var slideShow = new SlideShow();

            document.body.addEventListener("click", function (e) {
                if (e.target.matches(".show-more--link")) {
                    e.target.classList.toggle("expanded");
                    var items = e.target.previousSibling;
                    if (items.style.display === "none") {
                        items.style.display = "inline";
                        if (!items.classList.contains("ready")) {
                            items.classList.add("ready");
                            selectAll(items, ".thumbnail").forEach(function (node) { node.src = node.dataset["src"]; });
                        }
                    } else {
                        items.style.display = "none";
                    }
                    return;
                }

                var th = closestParent(e.target, ".light-box-thumbnail", true);
                if (!th || e.button != 0) return;
                e.preventDefault();

                // соседи
                var slides = [th];
                var cont = closestParent(th, ".images.media");
                if (cont) {
                    slides = selectAll(cont, ".light-box-thumbnail");
                }

                slideShow.show(slides, th);
            }, false);
        }

        node = node || document.body;

        selectAll(node, ".images.media a:not(.light-box-thumbnail)").forEach(function (node) {
            var img = node.querySelector("img");
            var imgSrc = ("src" in img.dataset) ? img.dataset["src"] : img.src;

            if (node.dataset["imageSrc"]) {
                node.classList.add("light-box-thumbnail");

            } else if (/\.(jpe?g|png|gif)/i.test(node.href)) {
                node.dataset["imageSrc"] = node.href;
                node.classList.add("light-box-thumbnail");

            } else if (/^http:\/\/m\.friendfeed-media\.com\//.test(node.href)) {
                node.dataset["imageSrc"] = node.href;
                node.classList.add("light-box-thumbnail");

            } else if (/^https?:\/\/www\.flickr\.com\/photos\//.test(node.href)) {
                if (/^https?:\/\/farm\d+\.static\.?flickr\.com\//.test(imgSrc)) {
                    node.dataset["imageSrc"] = imgSrc.replace(/_.\.jpg$/, "_b.jpg");
                    node.classList.add("light-box-thumbnail");
                } else {
                    NoEmbedIt(node);
                }

            } else if (/^https?:\/\/instagram\.com\/p\//.test(node.href)) {
                NoEmbedIt(node);

            } else if (/deviantart\.com\/art\//.test(node.href)) {
                OEmbedIt(node, "https://davidmz.me/oembed/deviantart/oembed", "url");

            } else if (/^http:\/\/imgur\.com\//.test(node.href)) {
                node.dataset["imageSrc"] = "http://i.imgur.com/" + node.href.match(/^http:\/\/imgur\.com\/(gallery\/)?([^#]+)/)[2] + ".jpg";
                node.classList.add("light-box-thumbnail");

            } else if (/^http:\/\/gyazo\.com\//.test(node.href)) {
                node.dataset["imageSrc"] = "http://i.gyazo.com/" + node.href.match(/^http:\/\/gyazo\.com\/([^#]+)/)[1] + ".png";
                node.classList.add("light-box-thumbnail");

            } else if (/soup\.io\/asset/.test(imgSrc)) {
                node.dataset["imageSrc"] = imgSrc.replace(/_400(\.\w+)$/, "$1");
                node.classList.add("light-box-thumbnail");

            }
        });

        selectAll(node, "a.l_expandmedia:not(.ffco-done)").forEach(function (node) {
            node.classList.add("ffco-done");
            var entry = closestParent(node, ".entry"),
                media = closestParent(node, ".media"),
                previewCount = selectAll(media, ".thumbnail").length,
                at = document.cookie.match(/(?:^| )AT=(.*?)(?:;|$)/)[1];

            var data = "entry=" + encodeURIComponent(entry.getAttribute("eid")) + "&media=1&_nano=1&at=" + encodeURIComponent(at);
            var xhr = new XMLHttpRequest();
            xhr.open("POST", "/a/expandmedia");
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.responseType = "json";
            xhr.onload = function () {
                var items = this.response.html.match(/<a .*?<\/a>/g);
                var visibleItems = items.slice(0, previewCount);
                var invisibleItems = items.slice(previewCount)
                    .map(function (s) {
                        return s.replace(/src="(.*?)"/, 'data-src="$1" src="/static/images/loading.gif"');
                    });
                var newMedia = document.createElement("div");
                newMedia.className = "images media";
                newMedia.innerHTML = visibleItems.join("") + '' + invisibleItems.join("") + '';
                media.parentNode.insertBefore(newMedia, media);
                media.parentNode.removeChild(media);
                media.innerHTML = "";
            };
            xhr.send(data);
        });
    });
})();


text:
module Order

## notions of element ordering ##

export # not exported by Base
    Ordering, Forward, Reverse, Lexicographic,
    By, Lt, Perm,
    ReverseOrdering, ForwardOrdering, LexicographicOrdering,
    DirectOrdering,
    lt, uint_mapping, ord, ordtype

abstract Ordering

immutable ForwardOrdering <: Ordering end
immutable ReverseOrdering{Fwd<:Ordering} <: Ordering
    fwd::Fwd
end

ReverseOrdering(rev::ReverseOrdering) = rev.fwd
ReverseOrdering{Fwd}(fwd::Fwd) = ReverseOrdering{Fwd}(fwd)

typealias DirectOrdering Union(ForwardOrdering,ReverseOrdering{ForwardOrdering})

const Forward = ForwardOrdering()
const Reverse = ReverseOrdering(Forward)

immutable LexicographicOrdering <: Ordering end
const Lexicographic = LexicographicOrdering()

immutable By <: Ordering
    by::Function
end

immutable Lt <: Ordering
    lt::Function
end

immutable Perm{O<:Ordering,V<:AbstractVector} <: Ordering
    order::O
    data::V
end
Perm{O<:Ordering,V<:AbstractVector}(o::O,v::V) = Perm{O,V}(o,v)

lt(o::ForwardOrdering,       a, b) = isless(a,b)
lt(o::ReverseOrdering,       a, b) = lt(o.fwd,b,a)
lt(o::By,                    a, b) = isless(o.by(a),o.by(b))
lt(o::Lt,                    a, b) = o.lt(a,b)
lt(o::LexicographicOrdering, a, b) = lexcmp(a,b) < 0

function lt(p::Perm, a::Int, b::Int)
    da = p.data[a]
    db = p.data[b]
    lt(p.order, da, db) | (!lt(p.order, db, da) & (a < b))
end
function lt(p::Perm{LexicographicOrdering}, a::Int, b::Int)
    c = lexcmp(p.data[a], p.data[b])
    c != 0 ? c < 0 : a < b
end

# Map a bits-type to an unsigned int, maintaining sort order
uint_mapping(::ForwardOrdering, x::Unsigned) = x
uint_mapping(::ForwardOrdering, x::Int8)     = uint8  (x $ typemin(Int8))
uint_mapping(::ForwardOrdering, x::Int16)    = uint16 (x $ typemin(Int16))
uint_mapping(::ForwardOrdering, x::Int32)    = uint32 (x $ typemin(Int32))
uint_mapping(::ForwardOrdering, x::Int64)    = uint64 (x $ typemin(Int64))
uint_mapping(::ForwardOrdering, x::Int128)   = uint128(x $ typemin(Int128))
uint_mapping(::ForwardOrdering, x::Float32)  = (y = reinterpret(Int32, x); uint32(y < 0 ? ~y : (y $ typemin(Int32))))
uint_mapping(::ForwardOrdering, x::Float64)  = (y = reinterpret(Int64, x); uint64(y < 0 ? ~y : (y $ typemin(Int64))))

uint_mapping{Fwd}(::ReverseOrdering{Fwd}, x) = ~uint_mapping(Fwd, x)
#uint_mapping{T<:Real}(::ReverseOrdering{ForwardOrdering}, x::T) = ~uint_mapping(Forward, x)  ## Manually inlined
uint_mapping(::ReverseOrdering{ForwardOrdering}, x::Unsigned) = ~x
uint_mapping(::ReverseOrdering{ForwardOrdering}, x::Int8)     = ~uint8  (x $ typemin(Int8))
uint_mapping(::ReverseOrdering{ForwardOrdering}, x::Int16)    = ~uint16 (x $ typemin(Int16))
uint_mapping(::ReverseOrdering{ForwardOrdering}, x::Int32)    = ~uint32 (x $ typemin(Int32))
uint_mapping(::ReverseOrdering{ForwardOrdering}, x::Int64)    = ~uint64 (x $ typemin(Int64))
uint_mapping(::ReverseOrdering{ForwardOrdering}, x::Int128)   = ~uint128(x $ typemin(Int128))
uint_mapping(::ReverseOrdering{ForwardOrdering}, x::Float32)  = (y = reinterpret(Int32, x); uint32(y < 0 ? y : ~(y $ typemin(Int32))))
uint_mapping(::ReverseOrdering{ForwardOrdering}, x::Float64)  = (y = reinterpret(Int64, x); uint64(y < 0 ? y : ~(y $ typemin(Int64))))

uint_mapping(o::By,   x     ) = uint_mapping(Forward, o.by(x))
uint_mapping(o::Perm, i::Int) = uint_mapping(o.order, o.data[i])
uint_mapping(o::Lt,   x     ) = error("uint_mapping does not work with general Lt Orderings")

ordtype(o::ReverseOrdering, vs::AbstractArray) = ordtype(o.fwd, vs)
ordtype(o::Perm,            vs::AbstractArray) = ordtype(o.order, o.data)
# TODO: here, we really want the return type of o.by, without calling it
ordtype(o::By,              vs::AbstractArray) = try typeof(o.by(vs[1])) catch; Any end
ordtype(o::Ordering,        vs::AbstractArray) = eltype(vs)

function ord(lt::Function, by::Function, rev::Bool, order::Ordering=Forward)
    o = (lt===isless) & (by===identity) ? order  :
        (lt===isless) & (by!==identity) ? By(by) :
        (lt!==isless) & (by===identity) ? Lt(lt) :
                                          Lt((x,y)->lt(by(x),by(y)))
    rev ? ReverseOrdering(o) : o
end

end


text:
package org.apache.guacamole.auth.jdbc.permission;

/**
 * Mapper for connection group permissions.
 */
public interface ConnectionGroupPermissionMapper extends ObjectPermissionMapper {}


text:
<?php
/**
 * TextFilter.php
 *
 * @since 19/01/17
 * @author gseidel
 */

namespace Enhavo\Bundle\AppBundle\Filter\Type;

use Enhavo\Bundle\AppBundle\Filter\AbstractFilterType;
use Enhavo\Bundle\AppBundle\Filter\FilterQuery;
use Symfony\Component\OptionsResolver\OptionsResolver;

class TextType extends AbstractFilterType
{
    public function createViewData($options, $name)
    {
        $data = [
            'type' => $this->getType(),
            'key' => $name,
            'value' => null,
            'initialValue' => null,
            'component' => $options['component'],
            'label' => $this->getLabel($options),
        ];

        return $data;
    }

    public function buildQuery(FilterQuery $query, $options, $value)
    {
        $propertyPath = explode('.', $options['property']);
        $property = array_pop($propertyPath);

        $operator = $options['operator'];
        if($value !== null && trim($value) !== '') {
            $query->addWhere($property, $operator, $value, $propertyPath);
        }
    }

    public function configureOptions(OptionsResolver $optionsResolver)
    {
        parent::configureOptions($optionsResolver);
        $optionsResolver->setDefaults([
            'operator' => FilterQuery::OPERATOR_LIKE,
            'component' => 'filter-text'
        ]);
    }

    public function getType()
    {
        return 'text';
    }
}


text:
Welcome to the "FinesSE" project where FitNesse meets Selenium.

As Selenium is a widespread standard for web browser automation and Fitnesse is a low-threshold integration platform for automated testing, there is a motivation to take benefit from both solutions by making an easy-fitting and easy extensible plugin that allows to write quite normal FitNesse tables in order to call and control Selenium webdrivers.

The long-term vision is to provide a .NET based fixtures library that would cover essentials of Selenium webdrivers and broaden automated testing capabilites (e.g. with visual regression testing, workflow expressions, generating reports).

## Download

[Get the latest version 1.4.0](https://github.com/MirekVales/FinesSE/releases)

## Features

See [Wiki documentation](https://github.com/MirekVales/FinesSE/wiki) for more details.

### Selenium Webdrivers Essentials
- Locators
- Actions
- Assertions

#### Supported Webdrivers

- ✔ Chrome
- ✔ Edge
- ✔ Firefox
- ✔ Internet Explorer
- ✔ Opera
- ✔ PhantomJS
- ✔ Safari

### Workflow Expressions
- If *to conditionally execute only a branch of commands*
- Run *command to start an external process*

### Visual Regression
- Screenshots comparison (using ImageMagick and a great wrapper [Magick.NET](https://github.com/dlemstra/Magick.NET))
- Screenshots storage
- Simple css validation (using [ExCSS](https://github.com/TylerBrinks/ExCSS), a simple CSS parser)

### Generating Automation Reports
- Allows to take all evaluated assertions and aggregate results into a pretty test report (using [ExtentReports](https://github.com/anshooarora/extentreports-csharp), an HTML test report generator)

### Soap Client Suite
- An easy way to invoke Soap endpoints and make assertions on a response

### SoapUI Suites Runner
- Execute SoapUI test suite

## Use Cases

See [Wiki documentation](https://github.com/MirekVales/FinesSE/wiki) for more details.

### Stand-alone invocation
Tests may be executed directly from a file using a console application - FinesSE.Launcher. In this case, FitNesse is not needed and FinesSE plays a role of a stand-alone processor of Selenium/FitNesse test definition files.
> Check the launcher application to find out arguments needed to execute a script

### As FitNesse plug-in
FinesSE may be involved as a FitNesse extension that invokes fixtures over FitSharp runner.
> Use import command to load namespace FinesSE.Bootstrapper
>
> Use !path command to load FinesSE assemblies (e.g. !path FinesSE\*.dll)


text:
# uonome
Uonome is inverted converter for fish eye photo.
You can convert from fish eye photo to ultra wide-angle photo.

For Processing 3.xx (Processing 3.0.1 is recommended)

# Screen shot

# sample photo

## fisheye photo

## converted photo

# Creating iconset (only for MAC user)

If you want to create iconset, execute below command.

~~~~
$ iconutil -c icns sketch.iconset
~~~~

# Related Site
http://blog.lovepenta.xyz/entry/レンズの歪みを一発補正できる「uonome」でPENTAX_Q_03Lensが蘇る

http://blog.lovepenta.xyz/entry/2016/01/10/032656

http://moognyk.hateblo.jp/entry/2015/12/31/180000

http://lil.la/technology/technology-tools/post-2203

http://history.hatenablog.com/entry/2016/01/10/190000

http://lab.hendigi.com/uonome/

# License
This software is released under the MIT License, see LICENSE.


text:
<!--
  ~ Copyright (C) 2016-2021 Sandip Vaghela
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~         http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24.0"
    android:viewportHeight="24.0">
    <path
        android:fillColor="#FF000000"
        android:pathData="M12,22c1.1,0 2,-0.9 2,-2h-4c0,1.1 0.89,2 2,2zM18,16v-5c0,-3.07 -1.64,-5.64 -4.5,-6.32L13.5,4c0,-0.83 -0.67,-1.5 -1.5,-1.5s-1.5,0.67 -1.5,1.5v0.68C7.63,5.36 6,7.92 6,11v5l-2,2v1h16v-1l-2,-2z" />
</vector>


text:
module Dota
  class Team
    attr_reader :raw_team

    def initialize(raw_team)
      @raw_team = raw_team
    end

    def id
      raw_team['team_id']
    end
  end
end


text:
<?php

namespace Functional;

use Functional\Exceptions\InvalidArgumentException;
use Traversable;

/**
 * Returns an array with the specified keys omitted from the array
 *
 * @param Traversable|array $collection
 * @param array $keys
 * @return array
 * @no-named-arguments
 */
function omit_keys($collection, array $keys)
{
    InvalidArgumentException::assertCollection($collection, __FUNCTION__, 1);

    if ($collection instanceof Traversable) {
        $array = \iterator_to_array($collection);
    } else {
        $array = $collection;
    }

    return \array_diff_key($array, \array_flip($keys));
}


text:
package org.hibernate.test.interceptor;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.hibernate.EmptyInterceptor;
import org.hibernate.Session;
import org.hibernate.type.Type;

public class StatefulInterceptor extends EmptyInterceptor {

	private Session session;

	private List list = new ArrayList();

	public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) {
		if ( !(entity instanceof Log) ) {
			list.add( new Log( "insert", (String) id, entity.getClass().getName() ) );
		}
		return false;
	}

	public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
		if ( !(entity instanceof Log) ) {
			list.add( new Log( "update", (String) id, entity.getClass().getName() ) );
		}
		return false;
	}

	public void postFlush(Iterator entities) {
		if ( list.size()>0 ) {
			for ( Iterator iter = list.iterator(); iter.hasNext(); ) {
				session.persist( iter.next() );
			}
			list.clear();
			session.flush();
		}
	}

	public void setSession(Session s) {
		session = s;
	}

}


text:
Symphony scripts
================

The database load process for this reporting solution consists of a series of database scripts to pull data out of the Symphony database and store in it text files (1 text file per database table).  These text files are then used in the creation of the custom reporting database.

The report will create a series of files to be stored in the Xfer directory of the Symphony server.

Prerequisites
-------------

- A Symphony library management system.

Files
-----

| File | Description |
| ---- | ----------- |
| lwcustomreportsdb.pl | The custom report file.  This should be installed on the Symphony server |

Install instructions
--------------------

Installing the custom report are as per Sirsi Dynix instructions for creating new reports within Symphony.

Frequency
---------

It is up to the library service implementing this functionality as to how often they wish to run the report.  The report can be scheduled using the normal Sirsi Dynix WorkFlows report scheduler.


text:
<?php

declare(strict_types=1);

namespace Zhiyi\Plus\Http\Controllers\APIs\V2;

use Illuminate\Http\Request;
use Zhiyi\Plus\Models\VerificationCode as VerificationCodeModel;
use Illuminate\Contracts\Routing\ResponseFactory as ResponseFactoryContract;

class UserEmailController extends Controller
{
    /**
     * 解除用户 E-Mail 绑定.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Illuminate\Contracts\Routing\ResponseFactory $response
     * @return mixed
     * @author Seven Du <shiweidu@outlook.com>
     */
    public function delete(Request $request, ResponseFactoryContract $response)
    {
        $rules = [
            'verifiable_code' => 'required|string',
            'password' => 'required|string',
        ];
        $this->validate($request, $rules);

        $verifiable_code = $request->input('verifiable_code');
        $password = $request->input('password');
        $user = $request->user();
        $verify = VerificationCodeModel::where('channel', 'mail')
            ->where('account', $user->email)
            ->where('code', $verifiable_code)
            ->orderby('id', 'desc')
            ->first();

        if (! $user->verifyPassword($password)) {
            return $response->json(['message' => ['密码错误']], 422);
        } elseif (! $verify) {
            return $response->json(['message' => ['验证码错误或者已失效']], 422);
        }

        $user->getConnection()->transaction(function () use ($user, $verify) {
            $user->email = null;
            $user->save();
            $verify->delete();
        });

        return $response->make('', 204);
    }
}


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

<TITLE>
Photo (OpenXava 4.9.1 API)
</TITLE>

<META NAME="keywords" CONTENT="org.openxava.util.Photo class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.openxava.util

Class Photo

java.lang.Object
  org.openxava.util.Photo

All Implemented Interfaces:
java.io.Serializable

public class Photo
extends java.lang.Object
implements java.io.Serializable

Wraps a byte array to allow store photos in
 a database with no support to byte [] o
 BLOBs, but yes java.lang.Object.

 Serialize object for long term persistence is discourage,
 hence use this class only in extreme cases.

Author:

Javier Paniza

See Also:
Serialized Form

Field Summary

 byte[]
data

Constructor Summary

Photo(byte[] data)

Method Summary

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

data

public byte[] data

Constructor Detail

Photo

public Photo(byte[] data)

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
import os

import requests

# These API methods sends something to a chat
# This list is used to filter which method to check for unavailable chats
SEND_TO_CHAT_METHODS = (
    "sendMessage",
    "forwardMessage",
    "sendPhoto",
    "sendAudio",
    "sendDocument",
    "sendSticker",
    "sendVideo",
    "sendVoice",
    "sendLocation",
    "sendChatAction",
    "getChat",
)

class APIError(Exception):
    """Something went wrong with the API"""

    def __init__(self, response):
        self.error_code = response["error_code"]
        self.description = response["description"]

        msg = "Request failed with code %s. Response from Telegram: \"%s\"" % (
            self.error_code, self.description
        )

        super(APIError, self).__init__(msg)

class ChatUnavailableError(APIError):
    """A chat is unavailable, which means you can't send messages to it"""

    def __init__(self, reason, chat_id):
        self.reason = reason
        self.chat_id = chat_id

        if reason == "blocked":
            msg = "The user with ID %s blocked your bot" % chat_id
        elif reason == "account_deleted":
            msg = "The user with ID %s deleted his account" % chat_id
        elif reason == "not_contacted":
            msg = "The user with ID %s didn't contact you before" % chat_id
        elif reason == "not_found":
            msg = "The chat with ID %s doesn't exist" % chat_id
        elif reason == "kicked":
            msg = "The bot was kicked from the group with ID %s" % chat_id
        elif reason == "chat_moved":
            msg = "The chat with ID %s moved, and the old ID is no longer " \
                  "valid" % chat_id
        else:
            raise ValueError("Unknown reason: %s" % reason)

        Exception.__init__(self, msg)

class TelegramAPI:
    """Main interface to the Telegram API"""

    def __init__(self, api_key, endpoint=None):
        # Fill the default API endpoint
        if endpoint is None:
            endpoint = "https://api.telegram.org/"

        self._api_key = api_key
        self._endpoint = endpoint

        self._session_cache = None
        self._session_pid = -1

    def _session(self):
        """Get the current requests session"""
        # Ensure a new session is created if the PID changes. This is because
        # sessions behaves badly if you use them after fork()
        if self._session_pid != os.getpid() or self._session_cache is None:
            self._session_cache = requests.Session()
            self._session_pid = os.getpid()

        return self._session_cache

    def call(self, method, params=None, files=None, expect=None):
        """Call a method of the API"""
        url = self._endpoint + "bot%s/%s" % (self._api_key, method)
        response = self._session().get(url, params=params, files=files,
                                       timeout=10)
        content = response.json()

        if not content["ok"]:
            status = content["error_code"]
            message = content["description"]

            # Special handling for unavailable chats
            if method in SEND_TO_CHAT_METHODS:
                reason = None

                # This happens when the bot tries to send messages to an user
                # who blocked the bot
                if status == 403 and "blocked" in message:
                    # Error code # 403
                    # Bot was blocked by the user
                    reason = "blocked"

                # This happens when the user deleted its account
                elif status == 403 and "deactivated" in message:
                    # Error code # 403
                    # Forbidden: user is deactivated
                    reason = "account_deleted"

                # This happens, as @BotSupport says, when the Telegram API
                # isn't able to determine why your bot can't contact an user
                elif status == 400 and "PEER_ID_INVALID" in message:
                    # Error code # 400
                    # Bad request: PEER_ID_INVALID
                    reason = "not_found"

                # This happens when the bot can't contact the user or the user
                # doesn't exist
                elif status == 400 and "not found" in message:
                    # Error code # 400
                    # Bad Request: chat not found
                    reason = "not_found"

                # This happens when the bot is kicked from the group chat it's
                # trying to send messages to
                elif status == 403 and "kicked" in message:
                    # Error code # 403
                    # Forbidden: bot was kicked from the group chat
                    # Forbidden: bot was kicked from the supergroup chat
                    reason = "kicked"

                # This happens when the ID points to a group chat, which was
                # migrated to a supergroup chat, thus changing its ID
                elif status == 400 and "migrated" in message:
                    # Error code # 400
                    # Bad Request: group chat is migrated to a supergroup chat
                    reason = "chat_moved"

                if reason is not None:
                    raise ChatUnavailableError(reason, params["chat_id"])

            raise APIError(content)

        # If no special object is expected, return the decoded json.
        # Else, return the "pythonized" result
        if expect is None:
            return content
        else:
            wrapped = expect(content["result"])
            if hasattr(wrapped, "set_api"):
                wrapped.set_api(self)
            return wrapped

    def file_content(self, path):
        """Get the content of an user-submitted file"""
        url = self._endpoint + "file/bot%s/%s" % (self._api_key, path)
        response = requests.get(url)

        return response.content

    @property
    def token(self):
        return self._api_key


text:
<?php

namespace Apigee\Edge\Api\Monetization\Controller;

use Apigee\Edge\Api\Monetization\Entity\AcceptedRatePlanInterface;
use Apigee\Edge\Api\Monetization\Entity\RatePlanInterface;
use Apigee\Edge\Api\Monetization\Serializer\AcceptedRatePlanSerializer;
use Apigee\Edge\ClientInterface;
use Apigee\Edge\Controller\EntityListingControllerTrait;
use Apigee\Edge\Controller\EntityLoadOperationControllerTrait;
use Apigee\Edge\Serializer\EntitySerializerInterface;
use DateTimeImmutable;
use Psr\Http\Message\UriInterface;
use ReflectionClass;

abstract class AcceptedRatePlanController extends OrganizationAwareEntityController implements AcceptedRatePlanControllerInterface
{
    use EntityListingControllerTrait;
    use EntityLoadOperationControllerTrait;
    use PaginatedListingHelperTrait;

    /**
     * AcceptedRatePlanController constructor.
     *
     * @param string $organization
     * @param \Apigee\Edge\ClientInterface $client
     * @param \Apigee\Edge\Serializer\EntitySerializerInterface|null $entitySerializer
     */
    public function __construct(string $organization, ClientInterface $client, ?EntitySerializerInterface $entitySerializer = null)
    {
        $entitySerializer = $entitySerializer ?? new AcceptedRatePlanSerializer();
        parent::__construct($organization, $client, $entitySerializer);
    }

    /**
     * {@inheritdoc}
     */
    public function getAllAcceptedRatePlans(): array
    {
        return $this->getAcceptedRatePlans();
    }

    /**
     * {@inheritdoc}
     */
    public function getPaginatedAcceptedRatePlanList(int $limit = null, int $page = 1): array
    {
        $query_params = [
            'page' => $page,
        ];

        if (null !== $limit) {
            $query_params['size'] = $limit;
        }

        return $this->getAcceptedRatePlans($query_params);
    }

    /**
     * {@inheritdoc}
     */
    public function acceptRatePlan(RatePlanInterface $ratePlan, DateTimeImmutable $startDate, ?DateTimeImmutable $endDate = null, ?int $quotaTarget = null, ?bool $suppressWarning = null, ?bool $waveTerminationCharge = null): AcceptedRatePlanInterface
    {
        $rc = new ReflectionClass($this->getEntityClass());
        /** @var \Apigee\Edge\Api\Monetization\Entity\AcceptedRatePlanInterface $acceptedRatePlan */
        $acceptedRatePlan = $rc->newInstance(
            [
                'ratePlan' => $ratePlan,
                'startDate' => $startDate,
            ]
        );
        if (null !== $quotaTarget) {
            $acceptedRatePlan->setQuotaTarget($quotaTarget);
        }
        if (null !== $endDate) {
            $acceptedRatePlan->setEndDate($endDate);
        }
        $payload = $this->getEntitySerializer()->serialize($acceptedRatePlan, 'json', $this->buildContextForEntityTransformerInCreate());
        $tmp = json_decode($payload, true);
        if (null !== $suppressWarning) {
            $tmp['suppressWarning'] = $suppressWarning ? 'true' : 'false';
        }
        if (null !== $waveTerminationCharge) {
            $tmp['waveTerminationCharge'] = $waveTerminationCharge ? 'true' : 'false';
        }
        $payload = json_encode($tmp);
        $response = $this->client->post($this->getBaseEndpointUri(), $payload);
        $this->getEntitySerializer()->setPropertiesFromResponse($response, $acceptedRatePlan);

        return $acceptedRatePlan;
    }

    /**
     * {@inheritdoc}
     *
     * @psalm-suppress PossiblyNullArgument - id is not null in this context.
     */
    public function updateSubscription(AcceptedRatePlanInterface $acceptedRatePlan, ?bool $suppressWarning = null, ?bool $waveTerminationCharge = null): void
    {
        $payload = $this->getEntitySerializer()->serialize($acceptedRatePlan, 'json', $this->buildContextForEntityTransformerInCreate());
        $tmp = json_decode($payload, true);
        if (null !== $suppressWarning) {
            $tmp['suppressWarning'] = $suppressWarning ? 'true' : 'false';
        }
        if (null !== $waveTerminationCharge) {
            $tmp['waveTerminationCharge'] = $waveTerminationCharge ? 'true' : 'false';
        }
        $this->alterRequestPayload($tmp, $acceptedRatePlan);
        $payload = json_encode($tmp);
        // Update an existing entity.
        $response = $this->client->put($this->getEntityEndpointUri($acceptedRatePlan->id()), $payload);
        $this->getEntitySerializer()->setPropertiesFromResponse($response, $acceptedRatePlan);
    }

    /**
     * Builds context for the entity normalizer.
     *
     * Allows controllers to add extra metadata to the payload.
     *
     * @return array
     */
    abstract protected function buildContextForEntityTransformerInCreate(): array;

    /**
     * Returns the URI for listing accepted rate plans.
     *
     * We have to introduce this because it is not regular that an entity
     * has more than one listing endpoint so getBaseEntityEndpoint() was
     * enough until this time.
     *
     * @return \Psr\Http\Message\UriInterface
     */
    abstract protected function getAcceptedRatePlansEndpoint(): UriInterface;

    /**
     * Allows to alter payload before it gets sent to the API.
     *
     * @param array $payload
     *   API request payload.
     */
    protected function alterRequestPayload(array &$payload, AcceptedRatePlanInterface $acceptedRatePlan): void
    {
    }

    /**
     * Helper function for listing accepted rate plans.
     *
     * @param array $query_params
     *   Additional query parameters.
     *
     * @return \Apigee\Edge\Api\Monetization\Entity\AcceptedRatePlanInterface[]
     *
     * @psalm-suppress PossiblyNullArrayOffset - id() does not return null here.
     */
    private function getAcceptedRatePlans(array $query_params = []): array
    {
        $entities = [];

        foreach ($this->getRawList($this->getAcceptedRatePlansEndpoint()->withQuery(http_build_query($query_params))) as $item) {
            /** @var \Apigee\Edge\Entity\EntityInterface $tmp */
            $tmp = $this->getEntitySerializer()->denormalize(
                $item,
                AcceptedRatePlanInterface::class,
                'json'
            );
            $entities[$tmp->id()] = $tmp;
        }

        return $entities;
    }
}


text:
@ECHO OFF

SETLOCAL

REM Copyright 2019-2020 Rene Rivera
REM Copyright (C) 2009 Vladimir Prus
REM
REM Distributed under the Boost Software License, Version 1.0.
REM (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)

ECHO Building Boost.Build engine
if exist ".\tools\build\src\engine\b2.exe" del tools\build\src\engine\b2.exe
pushd tools\build\src\engine

call .\build.bat
@ECHO OFF

popd

if exist ".\tools\build\src\engine\b2.exe" (
   copy .\tools\build\src\engine\b2.exe . > nul
   goto :bjam_built)

goto :bjam_failure

:bjam_built

REM Ideally, we should obtain the toolset that build.bat has
REM guessed. However, it uses setlocal at the start and does not
REM export BOOST_JAM_TOOLSET, and I don't know how to do that
REM properly. Default to msvc if not specified.

SET TOOLSET=msvc

IF "%1"=="gcc" SET TOOLSET=gcc
IF "%1"=="clang" SET TOOLSET=clang

IF "%1"=="vc71" SET TOOLSET=msvc : 7.1
IF "%1"=="vc8" SET TOOLSET=msvc : 8.0
IF "%1"=="vc9" SET TOOLSET=msvc : 9.0
IF "%1"=="vc10" SET TOOLSET=msvc : 10.0
IF "%1"=="vc11" SET TOOLSET=msvc : 11.0
IF "%1"=="vc12" SET TOOLSET=msvc : 12.0
IF "%1"=="vc14" SET TOOLSET=msvc : 14.0
IF "%1"=="vc141" SET TOOLSET=msvc : 14.1
IF "%1"=="vc142" SET TOOLSET=msvc : 14.2

ECHO.
ECHO Generating Boost.Build configuration in project-config.jam for %TOOLSET%...
ECHO # Boost.Build Configuration > project-config.jam
ECHO # Automatically generated by bootstrap.bat >> project-config.jam
ECHO. >> project-config.jam
ECHO import option ; >> project-config.jam
ECHO. >> project-config.jam
ECHO using %TOOLSET% ; >> project-config.jam
ECHO. >> project-config.jam
ECHO option.set keep-going : false ; >> project-config.jam
ECHO. >> project-config.jam

ECHO.
ECHO Bootstrapping is done. To build, run:
ECHO.
ECHO     .\b2
ECHO.

IF EXIST libs\config\include (
ECHO.    To generate header files, run:
ECHO.
ECHO.    .\b2 headers
ECHO.
)

ECHO To adjust configuration, edit 'project-config.jam'.
ECHO Further information:
ECHO.
ECHO     - Command line help:
ECHO     .\b2 --help
ECHO.
ECHO     - Getting started guide:
ECHO     http://boost.org/more/getting_started/windows.html
ECHO.
ECHO     - Boost.Build documentation:
ECHO     http://www.boost.org/build/
ECHO.

goto :end

:bjam_failure

ECHO.
ECHO Failed to build Boost.Build engine.
ECHO.

REM Set an error code to allow `bootstrap && b2`
cmd /c exit /b 1 > nul

:end


text:
@extends('layout')

@section('title', "Feature Overview -")

@section('content')

        About YEGVotes.info

        YEGVotes.info is a website made by Troy Pavlek,
        a resident of Hazeldean and a fan of municipal politics.

        Some of the things you can track on the site are:

            @include('about.attendance')

Summaries for agenda items with votes

                        Interested in what happened last meeting? Catching up on the past few months? YEGVotes includes
                        a breakdown of each item on the agenda for all Council meetings, and easily shows which motions were
                        unanimous, which motions failed, and which one had a dissenting voice.

                        Just click on any one of the motions to explore the motion text and what each councillor voted!

                    @include('agendaItemPartial')

                        You can also easily view motions in a convenient summary card

                    @include('motion.motion_card', [ 'motion' => $example_motion ])

Councillor Voting Records

                        Drill down and look at every bylaw each councillor voted on - you can also show only the votes
                        they opposed!

                    @include('councilMemberPartial', [ 'attendance_record' => $iveson_attendance ])
                    @include('councillor.votingSummaryPartial', [ 'councillor' => $councillor ])

@stop


text:
use super::ctx::Ctx;
use super::frame;

mod element;

pub type Element = element::Element;
pub type EmptyElement = element::EmptyElement;

#[derive(Clone)]
pub struct CanvasContext {
    index: i32,
    tex_size: i32,
    tex_count: i32,
    tex_max_draws: i32,
    image_id_inc: i32,
    root_element: Option<Ctx<Element>>,
}

#[derive(Clone)]
pub struct Canvas {
    context: Ctx<CanvasContext>
}

impl Canvas {
    pub fn new(index: i32) -> Self {
        lib!(bind_canvas(index));
        let context = Ctx::new(CanvasContext {
            index,
            tex_size: lib!(tex_get_size(index)) as i32,
            tex_count: lib!(tex_get_count(index)) as i32,
            tex_max_draws: lib!(tex_get_max_draws()) as i32,
            image_id_inc: 1,
            root_element: None,
        });
        context.ctx(|x| {
            println!("Canvas binded: tex_size {}; tex_count {}; tex_max_draws {}", x.tex_size, x.tex_count, x.tex_max_draws);
            let root_element = Some(element! {
                [x] EmptyElement
            });
            x.root_element = root_element;
        });
        frame::bind(context.clone());
        return Canvas {
            context
        };
    }
    pub fn destroy(&mut self) {
        frame::unbind(self.context.clone());
    }
    pub fn get_context(&self) -> Ctx<CanvasContext> {
        return self.context.clone();
    }
    pub fn context<F>(&mut self, f: F) where F: Fn(&mut CanvasContext) {
        f(&mut *self.context.get());
    }
}

impl Drop for CanvasContext {
    fn drop(&mut self) {
        lib!(unbind_canvas(self.index));
    }
}

impl frame::Frame for CanvasContext {
    fn frame(&mut self, _timestamp: f64) -> bool {
        self.clear();
        let root_element = self.root_element.as_mut().unwrap();
        root_element.get().draw();
        return true;
    }
}

impl CanvasContext {
    pub fn set_canvas_size(&mut self, w: i32, h: i32) {
        lib!(set_canvas_size(self.index, w, h));
    }
    pub fn set_clear_color(&mut self, r: f32, g: f32, b: f32, a: f32) {
        lib!(set_clear_color(self.index, r, g, b, a));
    }
    pub fn clear(&mut self) {
        lib!(clear(self.index));
    }
    pub fn get_root_element(&mut self) -> Ctx<Element> {
        self.root_element.as_mut().unwrap().clone()
    }

    pub fn alloc_image_id(&mut self) -> i32 {
        let ret = self.image_id_inc + 1;
        self.image_id_inc += 1;
        ret
    }
}

pub mod test {
    use super::super::ctx::Ctx;
    use super::Canvas;
    use super::super::frame::animation::{TimingAnimation, AnimationObject, LinearTiming};

    pub fn test() -> i32 {
        let mut canvas = Canvas::new(0);

        canvas.context(|ctx| {
            ctx.set_canvas_size(400, 300);
        });

        struct BackgroundColorAni(Canvas);
        impl TimingAnimation for BackgroundColorAni {
            fn progress(&mut self, current_value: f64, _current_time: f64, _total_time: f64) {
                self.0.context(|ctx| {
                    ctx.set_clear_color(0., current_value as f32, current_value as f32, 1.);
                })
            }
        }

        let mut ani_obj = Ctx::new(AnimationObject::new(Ctx::new(LinearTiming::new(BackgroundColorAni(canvas.clone()), 0., 1.))));
        AnimationObject::exec(&mut ani_obj, 0, 3000.);

        let mut err = 0;
        err += super::element::test::test();
        return err;
    }
}