text:
package io.reinert.requestor.core;

import java.util.concurrent.Future;

import io.reinert.requestor.core.payload.SerializedPayload;

/**
 * An HTTP response with futures.
 *
 * @author Danilo Reinert
 */
public interface IncomingResponse extends ResponseHeader {

    /**
     * Return the serialized payload future.
     *
     * @return the response's serialized payload future
     */
    Future<SerializedPayload> getSerializedPayload();

    /**
     * Return the response payload future.
     *
     * @return the response's payload future
     */
    <T> Future<T> getPayload();

}


text:
World::World():
    _win(sf::VideoMode(800, 600), "mazerun", sf::Style::Default, sf::ContextSettings(0, 0, 0)),
    _running(true), _focused(true), _do_resize(false), _use_fxaa(true),
    _sunlight(true, glm::vec3(1.0f, 1.0f, 1.0f), true, glm::normalize(glm::vec3(-1.0f))),
    // TODO: get rid of unused shader files
    _ent_prepass_prog({std::make_pair("shaders/prepass.vert", GL_VERTEX_SHADER),
        std::make_pair("shaders/prepass.frag", GL_FRAGMENT_SHADER)},
        {std::make_pair("vert_pos", 0), std::make_pair("vert_tex_coords", 1),
        std::make_pair("vert_normals", 2), std::make_pair("vert_tangents", 3)}),
    _point_light_prog({std::make_pair("shaders/lighting.vert", GL_VERTEX_SHADER),
        std::make_pair("shaders/point_light.frag", GL_FRAGMENT_SHADER),
        std::make_pair("shaders/lighting.frag", GL_FRAGMENT_SHADER)},
        {std::make_pair("vert_pos", 0)},
        {std::make_pair("diffuse", 0), std::make_pair("specular", 1)}),
    _point_light_shadow_prog({std::make_pair("shaders/lighting.vert", GL_VERTEX_SHADER),
        std::make_pair("shaders/point_light_shadow.frag", GL_FRAGMENT_SHADER),
        std::make_pair("shaders/lighting.frag", GL_FRAGMENT_SHADER)},
        {std::make_pair("vert_pos", 0)},
        {std::make_pair("diffuse", 0), std::make_pair("specular", 1)}),
    _spot_light_prog({std::make_pair("shaders/lighting.vert", GL_VERTEX_SHADER),
        std::make_pair("shaders/spot_light.frag", GL_FRAGMENT_SHADER),
        std::make_pair("shaders/lighting.frag", GL_FRAGMENT_SHADER)},
        {std::make_pair("vert_pos", 0)},
        {std::make_pair("diffuse", 0), std::make_pair("specular", 1)}),
    _spot_light_shadow_prog({std::make_pair("shaders/lighting.vert", GL_VERTEX_SHADER),
        std::make_pair("shaders/spot_light_shadow.frag", GL_FRAGMENT_SHADER),
        std::make_pair("shaders/lighting.frag", GL_FRAGMENT_SHADER)},
        {std::make_pair("vert_pos", 0)},
        {std::make_pair("diffuse", 0), std::make_pair("specular", 1)}),
    _dir_light_prog({std::make_pair("shaders/pass-through.vert", GL_VERTEX_SHADER),
        std::make_pair("shaders/dir_light.frag", GL_FRAGMENT_SHADER),
        std::make_pair("shaders/lighting.frag", GL_FRAGMENT_SHADER)},
        {std::make_pair("vert_pos", 0)},
        {std::make_pair("diffuse", 0), std::make_pair("specular", 1)}),
    _dir_light_shadow_prog({std::make_pair("shaders/lighting.vert", GL_VERTEX_SHADER),
        std::make_pair("shaders/dir_light_shadow.frag", GL_FRAGMENT_SHADER),
        std::make_pair("shaders/lighting.frag", GL_FRAGMENT_SHADER)},
        {std::make_pair("vert_pos", 0)},
        {std::make_pair("diffuse", 0), std::make_pair("specular", 1)}),
    _point_shadow_prog({std::make_pair("shaders/point_shadow.vert", GL_VERTEX_SHADER),
        std::make_pair("shaders/point_shadow.frag", GL_FRAGMENT_SHADER)},
        {std::make_pair("vert_pos", 0)}),
    _spot_dir_shadow_prog({std::make_pair("shaders/shadow.vert", GL_VERTEX_SHADER),
        std::make_pair("shaders/shadow.frag", GL_FRAGMENT_SHADER)},
        {std::make_pair("vert_pos", 0)}),
    _ent_prog({std::make_pair("shaders/ents.vert", GL_VERTEX_SHADER),
        std::make_pair("shaders/ents.frag", GL_FRAGMENT_SHADER)},
        {std::make_pair("vert_pos", 0), std::make_pair("vert_tex_coords", 1)}),
    _fxaa_prog({std::make_pair("shaders/pass-through.vert", GL_VERTEX_SHADER),
        std::make_pair("shaders/fxaa.frag", GL_FRAGMENT_SHADER)},
        {}),
    _copy_fbo_to_screen_prog({std::make_pair("shaders/pass-through.vert", GL_VERTEX_SHADER),
        std::make_pair("shaders/just-texture.frag", GL_FRAGMENT_SHADER)},
        {std::make_pair("vert_pos", 0)}),
    // TODO: what should FBO sizes be?
    _g_fbo_norm_shininess_tex(FBO::create_color_tex(800, 600, GL_RGBA32F)), // TODO: resize, TODO:, why 32F?
    _g_fbo_depth_tex(FBO::create_depth_tex(800, 600)),
    _diffuse_fbo_tex(FBO::create_color_tex(800, 600, GL_RGB8)),
    _specular_fbo_tex(FBO::create_color_tex(800, 600, GL_RGB8)),
    _point_shadow_fbo_tex(FBO::create_shadow_cube_tex(512, 512)),
    _point_shadow_fbo_depth_rbo(Renderbuffer::create_depth(512, 512)),
    _spot_dir_shadow_fbo_tex(FBO::create_shadow_tex(512, 512)),
    _fullscreen_effects_tex(FBO::create_color_tex(800, 600, GL_RGBA8)),
    _font("Symbola", 18),
    _s_text(_font, u8"🐙💩☹☢☣☠\u0301\nASDF‽", glm::vec4(1.0f, 0.0f, 0.0f, 1.0f))
{
    // TODO: gamma correction?
    // TODO: more fine-grained check_error calls
    // TODO: standardize naming
    Logger_locator::get()(Logger::TRACE, "World init starting...");
    // TODO: loading screen
    _ents.emplace_back(create_player());
    _ents.emplace_back(create_testmdl());
    _ents.emplace_back(create_testlight());
    _ents.emplace_back(create_testmonkey());
    _ents.emplace_back(create_testdoughnut());
    _ents.emplace_back(create_walls(32, 32));
    _ents.emplace_back(create_floor(32, 32));

    _cam = _player = &_ents[0];

    _win.setKeyRepeatEnabled(false);
    // _win.setFramerateLimit(60);
    // TODO _win.setIcon

    glDepthRangef(0.0f, 1.0f);
    glPolygonOffset(2.0f, 4.0f);
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
    glEnable(GL_CULL_FACE);
    glCullFace(GL_BACK);
    glFrontFace(GL_CCW);

    resize();

    const glm::vec3 cam_light_forward(0.0f, 0.0f, 1.0f); // in eye space

    // NOTE: textures have reserved attachment points, as follows:
        // 0: texture creation (unused for rendering)
        // per material textures:
            // 1:  material.ambient_map
            // 2:  material.diffuse_map
            // 3:  material.specular_map
            // 4:  material.emissive_reflectivity_map
            // 5:  material.normal_shininess_map

        // global textures:
            // 6:  _g_fbo_norm_shininess_tex
            // 7:  _g_fbo_depth_tex

            // 8:  _diffuse_fbo_tex
            // 9:  _specular_fbo_tex

            // 10: _point_shadow_fbo_tex (cubemap)
            // 11: _spot_dir_shadow_fbo_tex

            // 12: _fullscreen_effects_tex

            // 13: Skybox::_tex (cubemap)

        // font page textures
            // TODO: may want to reserve an attachment for page 0
            // 14: Font:_sys::_page_map[page].tex

    // bind static textures
    glActiveTexture(GL_TEXTURE6);
    _g_fbo_norm_shininess_tex->bind();
    glActiveTexture(GL_TEXTURE7);
    _g_fbo_depth_tex->bind();
    glActiveTexture(GL_TEXTURE8);
    _diffuse_fbo_tex->bind();
    glActiveTexture(GL_TEXTURE9);
    _specular_fbo_tex->bind();
    glActiveTexture(GL_TEXTURE10);
    _point_shadow_fbo_tex->bind();
    glActiveTexture(GL_TEXTURE11);
    _spot_dir_shadow_fbo_tex->bind();
    glActiveTexture(GL_TEXTURE12);
    _fullscreen_effects_tex->bind();

    // activate bilinear filtering for the effect tex
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

    // Uniform setup
    _ent_prepass_prog.use();
    glUniform1i(_ent_prepass_prog.get_uniform("material.normal_shininess_map"), 5);

    _point_light_prog.use();
    glUniform1i(_point_light_prog.get_uniform("normal_shininess_map"), 6);
    glUniform1i(_point_light_prog.get_uniform("depth_map"), 7);
    glUniform3fv(_point_light_prog.get_uniform("cam_light_forward"), 1, &cam_light_forward[0]);

    _point_light_shadow_prog.use();
    glUniform1i(_point_light_shadow_prog.get_uniform("normal_shininess_map"), 6);
    glUniform1i(_point_light_shadow_prog.get_uniform("depth_map"), 7);
    glUniform1i(_point_light_shadow_prog.get_uniform("shadow_map"), 10);
    glUniform3fv(_point_light_shadow_prog.get_uniform("cam_light_forward"), 1, &cam_light_forward[0]);

    _spot_light_prog.use();
    glUniform1i(_spot_light_prog.get_uniform("normal_shininess_map"), 6);
    glUniform1i(_spot_light_prog.get_uniform("depth_map"), 7);
    glUniform3fv(_spot_light_prog.get_uniform("cam_light_forward"), 1, &cam_light_forward[0]);

    _spot_light_shadow_prog.use();
    glUniform1i(_spot_light_shadow_prog.get_uniform("normal_shininess_map"), 6);
    glUniform1i(_spot_light_shadow_prog.get_uniform("depth_map"), 7);
    glUniform1i(_spot_light_shadow_prog.get_uniform("shadow_map"), 11);
    glUniform3fv(_spot_light_shadow_prog.get_uniform("cam_light_forward"), 1, &cam_light_forward[0]);

    _dir_light_prog.use();
    glUniform1i(_dir_light_prog.get_uniform("normal_shininess_map"), 6);

    _dir_light_shadow_prog.use();
    glUniform1i(_dir_light_shadow_prog.get_uniform("normal_shininess_map"), 6);
    glUniform1i(_dir_light_shadow_prog.get_uniform("depth_map"), 7);
    glUniform1i(_dir_light_shadow_prog.get_uniform("shadow_map"), 11);

    _ent_prog.use();
    glUniform1i(_ent_prog.get_uniform("material.ambient_map"), 1);
    glUniform1i(_ent_prog.get_uniform("material.diffuse_map"), 2);
    glUniform1i(_ent_prog.get_uniform("material.specular_map"), 3);
    glUniform1i(_ent_prog.get_uniform("material.emissive_reflectivity_map"), 4);
    glUniform1i(_ent_prog.get_uniform("normal_shininess_map"), 6);
    glUniform1i(_ent_prog.get_uniform("diffuse_fbo_tex"), 8);
    glUniform1i(_ent_prog.get_uniform("specular_fbo_tex"), 9);
    glUniform1i(_ent_prog.get_uniform("env_map"), 13); // TODO: uncouple. maybe pass the available texture IDs to skybox and font?

    _fxaa_prog.use();
    glUniform1i(_fxaa_prog.get_uniform("scene_tex"), 12);

    _copy_fbo_to_screen_prog.use();
    glUniform1i(_copy_fbo_to_screen_prog.get_uniform("tex"), 12);

    glUseProgram(0);

    // setup FBOs
    _g_fbo.bind();
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _g_fbo_norm_shininess_tex->get_id(), 0);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, _g_fbo_depth_tex->get_id(), 0);
    glDrawBuffer(GL_COLOR_ATTACHMENT0);
    _g_fbo.verify();

    _lighting_fbo.bind();
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _diffuse_fbo_tex->get_id(), 0);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, _specular_fbo_tex->get_id(), 0);
    const GLenum buffs[2] = {GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1};
    glDrawBuffers(2, buffs);
    _lighting_fbo.verify();

    _point_shadow_fbo.bind();
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_CUBE_MAP_POSITIVE_X, _point_shadow_fbo_tex->get_id(), 0);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _point_shadow_fbo_depth_rbo->get_id());
    glDrawBuffer(GL_COLOR_ATTACHMENT0);
    _point_shadow_fbo.verify();

    _spot_dir_shadow_fbo.bind();
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, _spot_dir_shadow_fbo_tex->get_id(), 0);
    glDrawBuffer(GL_NONE);
    _spot_dir_shadow_fbo.verify();

    _fullscreen_effects_fbo.bind();
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _fullscreen_effects_tex->get_id(), 0);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, _g_fbo_depth_tex->get_id(), 0);
    glDrawBuffer(GL_COLOR_ATTACHMENT0);
    _fullscreen_effects_fbo.verify();

    glBindFramebuffer(GL_FRAMEBUFFER, 0);

    Message_locator::get().add_callback_empty("sun_toggle", [this](){ _sunlight.enabled = !_sunlight.enabled; });
    Message_locator::get().add_callback_empty("fxaa_toggle", [this]()
    {
        _use_fxaa =! _use_fxaa;
        Logger_locator::get()(Logger::TRACE, std::string("FXAA ") + (_use_fxaa ? "on" : "off"));
    });

    Shader_prog::clear_cache();

    check_error("World::World");
}

redpajama_set_name: RedPajamaGithub


text:
[MomentJs](https://github.com/moment/moment) comes to C#!

This library is meant to bring some missing functions to .Net's DateTime object and emulate MomentJs


text:
namespace WpfTodoMvcExample.Actions
{
    /// <summary>
    /// Action to mark all todo items as completed.
    /// </summary>
    public class CompleteAllTodos
    {
    }
}


text:
layout: post
title: MEGA
tags: [Облака, Сервисы, Софт]
categories: articles
date: 2018-07-02
image:
    feature: /2018/07/01_mega_logo.svg_.png
published: true
comments: true
---
# MEGA

В [MEGA](https://mega.nz/) появились звонки и даже видеозвонки.
Если кто не знал, это облачный сервис вроде Dropbox, который рядом функций явно будет пободрее.

Во первых, если это важно, всё файлы перед отправкой на сервер шифруются. Что-то где-то читал о том, что шифрование там далеко не самое непробиваемое и в целом момент сомнительный, но я бы, пожалуй, поостерегся хранить что-либо такое в облаках вообще.
Так или иначе, оно есть и потому важно помнить пароль - здесь нет никаких двухфакторных аутентификаций через СМС для восстановления пароля, так как здесь нет восстановления пароля.

Во вторых, это то облако, в котором можно хранить, не имея копии на компе. Как правило, облачные сервисы делают полную копию синхронизируемой папки в обе стороны, но в MEGA можно создать, скажем, облачную папку "HomePC", которая будет синхронизироваться только с домашним компьютером. Если внутри облака перенести содержимое этой папки в "WorkPC" или "Kakoetogovnetso", на домашнем компьютере этих файлов уже не останется, но они появятся либо в "WorkPC" на рабочем компьютере, либо в "Kakoetogovnetso", которая вообще ни с чем не синхронизируется.

Здесь, надо заметить, есть огромный плюс. Не далее, как позавчера, у меня немного повредилась файловая система. Примерно так: лежит у меня в папке с музыкой David Bowie - Space Oddity, я включаю послушать, а там сразу кусок припева из трека с другого альбома. Прочие файлы просто не читаются, так как превратились в винегрет, и только имена и места их хранения сохранились. Конечно же, облака синхронизируют изменения и все эти битые файлы подменили собой файлы в облаках. В зависимости от облака, есть разные решения, но в случае с MEGA отдельные папки в облаке просто никак не затрагиваются, так как синхронизируется с компом только одна.

В третьих, и это тоже относится к описанному случаю, тут есть версионирование. Можно откатываться до вариантов файлов до нежелательного изменения. Есть, конечно, и корзина.

В четвертых, тут есть совместная работа и, соответственно, чат. Теперь вот и позвонить можно (пожалуйста, не делайте этого по рабочим моментам - написанное лежит неизменно, а сказанное падает, как творог, в ухо и разваливается на плесень и липовый мед внутри. большие недопонимания в результате).
Есть как совместные папки, синхронизируемые во все стороны, так и разные разграничения и права.

![Чат в MEGA](/images/2018/07/svbA6trrS0o.jpg)

В пятых, конечно же можно делиться файлами и папками из этого облака по ссылке. Здесь отродясь можно сделать ссылку для чего угодно и где угодно, чем Dropbox не радует (хотя может сделали уже). Это чтобы не пользоваться файлообменниками в 2018м году.

В шестых, 50ГБ бесплатно. Бесплатный тариф ограничивает трафик на месяц.
Просто регистрируетесь и получаете 50ГБ со всем описанным функционалом. На главной сказано что-то про дополнительные 10ГБ за инвайты, но у меня нигде никакой реферральной ссылки нет. Кто знает мой почтовый адрес и меня, добавляйте по желанию после регистрации - так удобнее кидать файлы.

К тому даются русифицированные клиенты для всех популярных платформ - мобильные (iOS, Android, WinMobile), десктопные (Windows, macOS, Linux), расширения для Chrome и Firefox, расширение для Thunderbird, а так же консольный клиент для всех трех перечисленных десктопных ОС.
Кстати, не скажу за весь их софт, но там немало опенсорса, если вам это для чего-то нужно.

Статья программная, пиар приветствуется, как говаривал Яроврат.

*P.S. Спасибо [Линусу Торвальдсу за GIT](https://ru.wikipedia.org/wiki/%D0%A2%D0%BE%D1%80%D0%B2%D0%B0%D0%BB%D1%8C%D0%B4%D1%81,_%D0%9B%D0%B8%D0%BD%D1%83%D1%81) и кому-то там за Github. Если бы не всё вот это, я бы потерял свой сайт.*


text:
import { Factory, faker } from 'ember-cli-mirage';

export default Factory.extend({
  firstName() {
    return faker.name.firstName();
  },
  lastName() {
    return faker.name.lastName();
  },
  email() {
    return `${this.firstName.toLowerCase()}.${this.lastName.toLowerCase()}@example.org`;
  },
  reference() {
    return `${faker.finance.account(4)}`;
  },
  role() {
    return faker.random.arrayElement(['employee', 'manager', 'hr', 'admin'])
  }
});


text:
package com.bms.chemtris.helpers;

import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.bms.chemtris.models.Box;
import com.bms.chemtris.models.BoxThree;
import com.bms.chemtris.models.BoxTwo;
import com.bms.chemtris.models.Column;
import com.bms.chemtris.models.ColumnTwo;
import com.bms.chemtris.models.GameModel;
import com.bms.chemtris.models.LShape;
import com.bms.chemtris.models.LShapeTwo;

import java.util.Random;

/**
 * Class to spawn game models.
 */
public class Spawner {

    private float r = 70/255f, g = 70/255f, b = 70/255f;
    private int spawn_piece;
    public GameModel current;
    public boolean done, finished_spawning;
    private float time_elasped;
    private Random random;
    private static boolean [][][] matrix;
    private PerspectiveCamera camera;

    //constructor
    public Spawner(int pieces, boolean [][][] mx, PerspectiveCamera cam){
        spawn_piece = pieces;
        done = false;
        time_elasped = 0f;
        random = new Random();
        finished_spawning = true;
        matrix = mx;
        camera = cam;

    }

    //method to get random piece
    private void getPiece(){
        finished_spawning = false;
        int randNum = random.nextInt(spawn_piece);

        switch (randNum) {
            case 0:
                current = new Box(camera, matrix);
                break;
            case 1:
                current = new BoxTwo(camera, matrix);
                break;
            case 2:
                current = new BoxThree(camera, matrix);
                break;
            case 3:
                current = new Column(camera, matrix);
                break;
            case 4:
                current = new ColumnTwo(camera, matrix);
                break;
            case 5:
                current = new LShape(camera,matrix);
                break;
            case 6:
                current = new LShapeTwo(camera,matrix);
                break;

            default:
                current = new Box(camera,matrix);
                break;
        }

        done = true;

    }

    public GameModel run(float delta) {
        //check if piece finished spawning
        if (!done) {
            getPiece();
        }

        //animate fading in effect for pieces
        if (time_elasped == 0f) {
            for (ModelInstance part : current.parts) {
                part.materials.get(0).set(ColorAttribute.createDiffuse(r, g, b, 1f));
            }

        }

        time_elasped += delta;

        if (time_elasped < 1.25f) {
            r += 10 / 255f;
            g += 10 / 255f;
            b += 10 / 255f;
            for (ModelInstance part : current.parts) {
                part.materials.get(0).set(ColorAttribute.createDiffuse(r, g, b, 1f));
            }
            return null;
        }
        else {
            r = 255 / 255f;
            g = 255 / 255f;
            b = 255 / 255f;
            for (ModelInstance part : current.parts) {
                part.materials.get(0).set(ColorAttribute.createDiffuse(r, g, b, 1f));
            }
            done = false;
            finished_spawning = true;
            time_elasped = 0f;
            r = 70/255f;
            g = 70/255f;
            b = 70/255f;

            //when animation is done return the piece
            return current;

        }
    }

}


text:
package com.hp.autonomy.searchcomponents.core.config;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.hp.autonomy.types.requests.idol.actions.tags.FieldPath;

import java.util.Set;

/**
 * Json prettification when generating config output.
 * All default values are not printed out.
 *
 * @param <T> The field value type
 */
@SuppressWarnings({"unused", "WeakerAccess"})
public interface FieldInfoConfigMixins<T> {
    @JsonIgnore
    String getId();

    @JsonProperty("type")
    String getTypeAsString();

    @JsonProperty("advanced")
    Boolean isAdvancedIfNotDefault();

    @JsonProperty("names")
    Set<FieldPath> getNamesIfNotEmpty();
}


text:
@interface NSXMLElement (Workaround_11093041)
- (void)ibSwizzledRemoveAttributeForNameAndWorkaround11093041:(id)arg1;
@end


text:
"""
Line Chart with Interpolation
-----------------------------
This chart shows a line chart with the path interpolated. A full list of interpolation methods is available `in the documentation <https://altair-viz.github.io/user_guide/generated/core/altair.LineConfig.html?highlight=interpolate#altair-lineconfig>`_.
"""
# category: line charts
import altair as alt
from vega_datasets import data

source = data.stocks()

alt.Chart(source).mark_line(interpolate="monotone").encode(
    x="date:T",
    y="price:Q",
    color="symbol:N"
)


text:
//-----------------------------------------------------------------------
// <copyright file="IFileStore.cs" company="Experian Data Quality">
//   Copyright (c) Experian. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

using System;

namespace Experian.Qas.Updates.Metadata.WebApi.V1
{
    /// <summary>
    /// Defines a file store of data files.
    /// </summary>
    public interface IFileStore : IDisposable
    {
        /// <summary>
        /// Returns whether a file with the specified hash exists in the file store.
        /// </summary>
        /// <param name="hash">The hash of the data file to check for existence.</param>
        /// <returns>
        /// <see langword="true"/> if a file with the hash specified by <paramref name="hash"/>
        /// exists in the file store; otherwise <see langword="false"/>.
        /// </returns>
        bool ContainsFile(string hash);

        /// <summary>
        /// Registers the specified file with the file store.
        /// </summary>
        /// <param name="hash">The hash of the file to register.</param>
        /// <param name="path">The path of the file to register.</param>
        void RegisterFile(string hash, string path);

        /// <summary>
        /// Attempts to retrieve the path of the file with the specified
        /// hash from the file store.
        /// </summary>
        /// <param name="hash">The hash of the file to attempt to get the path of.</param>
        /// <param name="path">
        /// When the method returns, contains the path of the file with the hash
        /// specified by <paramref name="hash"/> if found; otherwise <see langword="null"/>.
        /// </param>
        /// <returns>
        /// <see langword="true"/> if a file with the hash specified by <paramref name="hash"/>
        /// was found in the file store; otherwise <see langword="false"/>.
        /// </returns>
        bool TryGetFilePath(string hash, out string path);
    }
}


text:
package org.springboot.integration.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springboot.integration.filter.LoginInterceptor;
import org.springboot.integration.filter.Token;
import org.springboot.integration.filter.TokenSource;
import org.springboot.integration.service.RedisService;
import org.springboot.integration.service.UserService;
import org.springboot.integration.util.StringDateUtil;
import org.springboot.integration.vo.UserVO;
import org.springboot.integration.web.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by thinkpad on 2017/5/13.
 * http://localhost:8080/swagger-ui.html 访问。
 */

@Api(value = "用户操作接口API")
@RestController
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisService redisService;

    static Map<Long, UserVO> users = Collections.synchronizedMap(new HashMap<Long, UserVO>());

    @ApiOperation(value = "用户登录", notes = "根据用户名查询用户")
    @ApiImplicitParam(name = "userName", value = "用户名", paramType = "query", required = true)
    @RequestMapping(value = "/user/login", method = RequestMethod.POST)
    public Result login(String userName,HttpServletRequest request){
    	UserVO user=userService.getUserByName(userName);
    	if(user !=null){
    		request.getSession().setAttribute(LoginInterceptor.SESSION_USER, user);
    		return Result.OK;
    	}
    	return Result.fail("用户名存在");

    }
    @ApiOperation(value = "获取用户列表", notes = "查询所有用户信息")
    @RequestMapping(value = "/user/list", method = RequestMethod.GET)
    public Result getUsers(HttpServletRequest request) {
        List<UserVO>  userList= redisService.getList("userList", UserVO.class);
        if(userList == null){
        	 System.out.println("缓存中没有用户列表,准备查询数据库了。。。。。");
        	 userList=userService.findAll();
             redisService.setList("userList", userList);
        }
       /* for(UserVO x:userList){
        	System.out.println(x.getUserName()+"||"+x.getBirthDay().getTime()+"||"+StringDateUtil.dateToString(x.getBirthDay(),4));
        }*/

        return  Result.ok(userList);

    }

    @ApiOperation(value = "查询用户详情", notes = "根据url中的用户编码查询", response = UserVO.class)
    @ApiImplicitParam(name = "uid", value = "编码", paramType = "path", required = true)
    @RequestMapping(value = "/user/{uid}", method = RequestMethod.GET)
    public Result getUser(@PathVariable("uid") String userid) {
        UserVO userVo= userService.getUserById(userid);
        return  Result.ok(userVo);

    }

    @ApiOperation(value = "新增用户", notes = "根据用户信息新增用户")
    @ApiImplicitParams({
         @ApiImplicitParam(name = "userName", value = "名称", paramType = "query", required = true),
         @ApiImplicitParam(name = "age", value = "性别", paramType = "query", required = true),
         @ApiImplicitParam(name = "address", value = "地址", paramType = "query", required = true)
    })
    @RequestMapping(value = "/user", method = RequestMethod.POST)
    @Token
    public Result addUser(HttpServletRequest requst,UserVO user) {

    	UserVO vo=userService.getUserByName(user.getUserName());
    	if(vo !=null){
    		return Result.fail("用户已存在,不能重复添加");
    	}

    	user.setBirthDay(new Date());
        Long uid = userService.addUser(user);
        redisService.evict("userList");
        return Result.OK;

    }

    @ApiOperation(value = "修改用户", notes = "根据用户编码修改用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uid", value = "编码", paramType = "query", required = true),
            @ApiImplicitParam(name = "userName", value = "名称", paramType = "query", required = true),
            @ApiImplicitParam(name = "age", value = "性别", paramType = "query", required = true),
            @ApiImplicitParam(name = "address", value = "地址", paramType = "query", required = true)
    })
    @RequestMapping(value = "/user", method = RequestMethod.PUT)
    @Token
    public Result updateUser(HttpServletRequest requst,UserVO user) {
        System.out.println("用户编号||" + user.getUid());
        userService.updateUserByUid(user);
        return Result.OK;

    }

    @ApiOperation(value = "删除用户", notes = "根据用户编码删除用户")
    @ApiImplicitParam(name = "uid", value = "编码", paramType = "path", required = true)
    @RequestMapping(value = "/user/{uid}", method = RequestMethod.DELETE)
    @Token(source = TokenSource.FILED,filedIndex =1) //根据参数字段构建token,filedIndex指定具体的参数下标
    public Result delUser(HttpServletRequest requst ,@PathVariable Long uid) {
        userService.deleteUser(uid);
        return Result.OK;

    }

    @ApiOperation(value = "批量增加用户")
    @RequestMapping(value = "/user/batch", method = RequestMethod.POST)
    public Result addUserBatch() {
        List<UserVO> userVOList = new ArrayList<UserVO>();
        UserVO userVO = null;
        for (int i = 0; i < 10; i++) {
            userVO = new UserVO();
            userVO.setUserName("汪涵" + i);
            userVO.setAddress("湖南长沙");
            userVO.setBirthDay(StringDateUtil.addMonth(new Date(), -i));
            userVO.setAge(i + 1);
            userVOList.add(userVO);

        }
        int count = userService.addUsers(userVOList);
        System.out.println("批量插入用户信息结果||" + count);
        return Result.OK;

    }

    @ApiOperation(value = "退出系统")
    @RequestMapping(value = "/user/logout", method = RequestMethod.POST)
    public Result logout(HttpServletRequest request) {
    	 request.getSession().invalidate();
    	 return Result.OK;

    }

}


text:
To create an experiment using jsPsych, you need to specify a timeline that describes the structure of the experiment. The timeline is an ordered set of trials. You must create the timeline before launching the experiment. Most of the code you will write for an experiment will be code to create the timeline. This page walks through the creation of timelines, including very basic examples and more advanced features.

## A single trial

To create a trial, you need to create an object that describes the trial. The most important feature of this object is the `type` parameter. This tells jsPsych which plugin file to use to run the trial. For example, if you want to use the text plugin to display a short message, the trial object would look like this:

```javascript
var trial = {
	type: 'text',
	text: 'hello world!'
}
```

The parameters for this object will depend on the plugin that you choose. Each plugin defines the set of parameters that are needed to run a trial with that plugin. Visit the documentation for a plugin to learn about the parameters that you can use with that plugin.

To create a timeline with the single trial and run the experiment, just embed the trial object in an array. A timeline is simply an array of trials.

```javascript
var timeline = [trial];

jsPsych.init({
	timeline: timeline
});
```

To actually create and run this simple example, complete the [hello world tutorial](../tutorials/hello-world.md).

## Multiple trials

Scaling up to multiple trials is straightforward. Just create an object for each trial, and add each object to the timeline array.

```javascript
// with lots of trials, it might be easier to add the trials
// to the timeline array as they are defined.
var timeline = [];

var trial_1 = {
	type: 'text',
	text: 'This is trial 1.'
}
timeline.push(trial_1);

var trial_2 = {
	type: 'text',
	text: 'This is trial 2.'
}
timeline.push(trial_2);

var trial_3 = {
	type: 'text',
	text: 'This is trial 3.'
}
timeline.push(trial_3);
```

## Nested timelines

Each object on the timeline can also have it's own timeline. This is useful for many reasons. One is that it allows you to define common parameters across trials once and have them apply to all the trials on the nested timeline. The example below creates a series of trials using the single-stim plugin, where the only thing that changes from trial-to-trial is the image file being displayed on the screen.

```javascript
var judgment_trials = {
	type: 'single-stim',
	prompt: '<p>Press a number 1-7 to indicate how unusual the image is.</p>',
	choices: ['1','2','3','4','5','6','7'],
	timeline: [
		{stimulus: 'image1.png'},
		{stimulus: 'image2.png'},
		{stimulus: 'image3.png'}
	]
}
```

In the above code, the `type`, `prompt`, and `choices` parameters are automatically applied to all of the objects in the `timeline` array. This creates three trials with the same `type`, `prompt`, and `choices` parameters, but different values for the `stimulus` parameter.

You can also override the values by declaring a new value in the `timeline` array. In the example below, the second trial will display a different prompt message.

```javascript
var judgment_trials = {
	type: 'single-stim',
	prompt: '<p>Press a number 1-7 to indicate how unusual the image is.</p>',
	choices: ['1','2','3','4','5','6','7'],
	timeline: [
		{stimulus: 'image1.png'},
		{stimulus: 'image2.png', prompt: '<p>Press 1 for this trial.</p>'},
		{stimulus: 'image3.png'}
	]
}
```

Timelines can be nested any number of times.

## Timeline variables

A common pattern in behavioral experiments is to repeat the same procedure many times with different stimuli. A procedure might be a single trial, but it also might be a series of trials. One shortcut to implement this pattern is with the approach described in the previous section, but this only works if all the trials use the same plugin type. Timeline variables are a more general solution. With timeline variables, you define the procedure once (as a timeline), and specify a set of parameters and their values for each iteration through the timeline.

What follows is an example of how to use timeline variables. The [simple reaction time tutorial](../tutorials/rt-task.md) also explains how to use timeline variables.

Suppose we want to create an experiment where people see a set of faces with names displayed below the face. In between each face, a fixation cross is displayed on the screen. Without timeline variables, we would need to add many trials to the timeline, alternating between trials showing the fixation cross and trials showing the face and name. This could be done efficiently in a loop or function, but timeline variables make it even easier - as well as adding extra features like sampling and randomization.

Here's a basic version of the task with timeline variables.

```javascript
var face_name_procedure = {
	timeline: [
		{
			type: 'single-stim',
			stimulus: '+',
			is_html: true,
			choices: jsPsych.NO_KEYS,
			timing_response: 500
		},
		{
			type: 'single-stim',
			stimulus: jsPsych.timelineVariable('face'),
			prompt: function(){ return "This person's name is "+jsPsych.timelineVariable('name', true); },
			choices: jsPsych.NO_KEYS,
			timing_response: 2500
		}
	],
	timeline_variables: [
		{ face: 'person-1.jpg', name: 'Alex' },
		{ face: 'person-2.jpg', name: 'Beth' },
		{ face: 'person-3.jpg', name: 'Chad' },
		{ face: 'person-4.jpg', name: 'Dave' }
	]
}
```

In the above version, there are four separate trials defined in the `timeline_variables` parameter. Each trial has a variable `face` and a variable `name`. The `timeline` defines a procedure of showing a fixation cross for 500ms followed by the face and name for 2500ms.  This procedure will repeat four times, with the first trial showing Alex, the second Beth, and so on. The variables are referenced in the procedure by calling the `jsPsych.timelineVariable()` method. Note that the call to this method is wrapped in a function, as we want the method to execute during the experiment, not during the declaration of the timeline.

### Random orders of trials

If we want to randomize the order of the trials, we can set `randomize_order` to `true`.

```javascript
var face_name_procedure = {
	// timeline parameter hidden to save space ...
	timeline_variables: [
		{ face: 'person-1.jpg', name: 'Alex' },
		{ face: 'person-2.jpg', name: 'Beth' },
		{ face: 'person-3.jpg', name: 'Chad' },
		{ face: 'person-4.jpg', name: 'Dave' }
	],
	randomize_order: true
}
```

### Repeating trials

If we want to repeat the set of trials multiple times, then we can set `repetitions` to an integer. If `randomize_order` is also `true`, the order will re-randomize before every repetition.

```javascript
var face_name_procedure = {
	// timeline parameter hidden to save space ...
	timeline_variables: [
		{ face: 'person-1.jpg', name: 'Alex' },
		{ face: 'person-2.jpg', name: 'Beth' },
		{ face: 'person-3.jpg', name: 'Chad' },
		{ face: 'person-4.jpg', name: 'Dave' }
	],
	randomize_order: true,
	repetitions: 3
}
```

### Sampling methods

There are also a set of sampling methods that can be used to select a set of trials from the timeline_variables. Sampling is declared by creating a `sample` parameter.

#### Sampling with replacement
```javascript
var face_name_procedure = {
	// timeline parameter hidden to save space ...
	timeline_variables: [
		{ face: 'person-1.jpg', name: 'Alex' },
		{ face: 'person-2.jpg', name: 'Beth' },
		{ face: 'person-3.jpg', name: 'Chad' },
		{ face: 'person-4.jpg', name: 'Dave' }
	],
	sample: {
		type: 'with-replacement',
		size: 10, // 10 trials, with replacement
	}
}
```

#### Sampling without replacement
```javascript
var face_name_procedure = {
	// timeline parameter hidden to save space ...
	timeline_variables: [
		{ face: 'person-1.jpg', name: 'Alex' },
		{ face: 'person-2.jpg', name: 'Beth' },
		{ face: 'person-3.jpg', name: 'Chad' },
		{ face: 'person-4.jpg', name: 'Dave' }
	],
	sample: {
		type: 'without-replacement',
		size: 3, // 3 trials, without replacement
	}
}
```

#### Custom sampling function
```javascript
var face_name_procedure = {
	// timeline parameter hidden to save space ...
	timeline_variables: [
		{ face: 'person-1.jpg', name: 'Alex' },
		{ face: 'person-2.jpg', name: 'Beth' },
		{ face: 'person-3.jpg', name: 'Chad' },
		{ face: 'person-4.jpg', name: 'Dave' }
	],
	sample: {
		type: 'custom',
		fn: function(t){
			// the first parameter to this function call is an array of integers
			// from 0 to n-1, where n is the number of trials.
			// the method needs to return an array of integers specifying the order
			// that the trials should be executed. this array does not need to
			// contain all of the integers.

			return t.reverse(); // show the trials in the reverse order
		}
	}
}
```

## Looping timelines

Any timeline can be looped using the `loop_function` option. The loop function should be a function that evaluates to `true` if the timeline should repeat, and `false` if the timeline should end. The loop function will be evaluated after the timeline is completed.

```javascript
var trial = {
	type: 'text',
	text: 'Hello. This is in a loop. Press R to repeat this trial, or C to continue.'
}

var loop_node = {
	timeline: [trial],
	loop_function: function(data){
		if(jsPsych.pluginAPI.convertKeyCharacterToKeyCode('r') == data[0].key_press){
			return true;
		} else {
			return false;
		}
	}
}
```

## Conditional timelines

A timeline can be skipped based on the evaluation of a function using the `conditional_function` option. If the conditional function evaluates to `true`, the timeline will execute normally. If the conditional function evaluates to `false`, then the timeline will be skipped. The conditional function is evaluated whenever the timeline is about to run the first trial.

```javascript
var pre_if_trial = {
	type: 'text',
	text: 'The next trial is in a conditional statement. Press S to skip it, or V to view it.'
}

var if_trial = {
	type: 'text',
	text: 'You chose to view the trial. Press any key to continue.'
}

var if_node = {
	timeline: [if_trial],
	conditional_function: function(){
		var data = jsPsych.data.getLastTrialData();
		if(data.key_press == jsPsych.pluginAPI.convertKeyCharacterToKeyCode('s')){
			return false;
		} else {
			return true;
		}
	}
}

var after_if_trial = {
	type: 'text',
	text: 'This is the trial after the conditional.'
}

jsPsych.init({
	timeline: [pre_if_trial, if_node, after_if_trial],
	on_finish: function(){jsPsych.data.displayData(); }
});
```


text:
<?php

namespace backend\models;

use Yii;

use yii\db\Query;

/**
 * This is the model class for table "meal".
 *
 * @property string $id
 * @property string $item_id
 * @property string $name
 * @property string $day
 * @property double $meal_price
 * @property string $created_at
 * @property string $last_updated
 */
class Meal extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'meal';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['day', 'created_at', 'last_updated', 'deal_closing_time', 'deal_status'], 'safe'],
            [['meal_price'], 'number'],
            [['name'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Name',
            'day' => 'Day',
            'meal_price' => 'Meal Price',
            'created_at' => 'Created At',
            'last_updated' => 'Last Updated',
            'deal_closing_time' => 'Deal Closing Time',
            'deal_status' => 'Status',
        ];
    }

    public static function getMeal(){

        $query = new Query;
        $query  ->select(['meal.*', 'meal_image.image_new_url', 'meal_image.image_org_url'])
                ->from('meal')
                ->join( 'LEFT JOIN',
                        'meal_image',
                        'meal_image.meal_id = meal.id'
                    )
                ->where(['deal_status'=>1])
                ;
        $command = $query->createCommand();
        $data = $command->queryAll();

        return $data;

    }
}


text:
- [Static version](https://XkF21WNJ.github.io/WizardTree/)
- [Dynamic version](https://XkF21WNJ.github.io/WizardTree/Viewer.html)

## Project Description and History

The goal of this project is to convert 'choose your own adventure'-style comment chains that sometimes appear on reddit (such as on /r/playzorkwithme and /r/YouEnterADungeon) into easier to handle formats.

The inspiration for this project was the tale of /u/XiuathoTheWizard, which spontaneously grew from [this comment](https://www.reddit.com/r/talesfromtechsupport/comments/3xyesc/project_management_seems_a_lot_like_cooking_a/cy8z5uv) on the subreddit /r/TalesFromTechSupport.  Since it is hard to navigate comment chains of that size on reddit this project was started to compile the tale it into a more manageable format.

Current formats include HTML and JSON, but other formats should be possible, and can hopefully be added soon.

## Instructions

For a basic tutorial see the "tutorial.ipynb" file. To run the notebook you'll need to use the [Jupyter](http://jupyter.org/) package, but you can also copy the python code and run it directly.

The generated JSON files contain a list of all events and possible actions indexed by their comment id. This layout makes it easy to generate 'choose your own adventure'-style stories in various formats. For example 'WizardCrawler.ipynb' can convert the JSON file to a stand-alone HTML file, and 'Viewer.html' can be used to get a similar result by loading the JSON directly in the browser.

## Goals

For now the main goal is to make the code more general, allowing it to be used to (easily) crawl other stories and convert them into manageable formats. Some changes to the JSON format might be required (like the one made recently) but the current format does seem the simplest to work with, so no big changes are to be expected (though I might decide that it's better to store the text in markdown rather than HTML, but I'm not yet sure; the current viewer needs HTML).

Apart from that it would also be nice to have a broader range of formats and to improve upon the currently available ones (better styling / more functionality). Some candidates for new formats are:

- Epub
This would basically just be an extension of the currently available HTML version, adding whatever information epubs need and repackaging it into the right format. Since epubs are essentially HTML files in a zip file this should be relatively easy to do (famous last words). Once this is available the static HTML format can be deprecated, the dynamic HTML viewer is more flexible and epubs are better as a static format.

- [Twine](http://twinery.org/)
Haven't had much experience with this language but they do claim to add support for scripting so with any luck it's possible to make it load the JSON file directly, similar to how the currently available [HTML viewer](https://XkF21WNJ.github.io/WizardTree/Viewer.html) does it.

- Pdf
Not yet sure how to generate Pdf's from JSON files, but it's technically possible. Maybe there's a python package that can be used for that. Of course, things like epubs and HTML files can be converted to pdf, but it's usually better to generate them directly.

## Contributing

Yes please! Just fork the repository and add a pull request to merge your changes. The project has only just started, and there are lots of things that could be improved, so all help is appreciated.

## Credits

Thanks to /u/XiuathoTheWizard and everyone else who contributed to his story.

Code by /u/XkF21WNJ.

## License

All code is released under the MIT license.

Files containing part or all of /u/XiuathoTheWizard's comments are published with permission, but otherwise all rights are reserved.


text:
<TITLE>Package Documentation</TITLE>

Package Documentation

  fsm
  External header file for package Fsm

Last updated on 990617 11h53


text:
/*!
 * Copyright (c) 2015 by Contributors
 * \file cudnn_batch_norm-inl.h
 * \brief
 * \author Junyuan Xie
*/

#ifndef MXNET_OPERATOR_NN_CUDNN_CUDNN_BATCH_NORM_INL_H_
#define MXNET_OPERATOR_NN_CUDNN_CUDNN_BATCH_NORM_INL_H_
#include <vector>
#include <map>
#include <string>
#include <utility>
#include "../batch_norm-inl.h"

namespace mxnet {
namespace op {
#if MXNET_USE_CUDNN == 1 && CUDNN_MAJOR >= 4
namespace cudnnbatchnorm {
enum CuDNNBatchNormOpInputs {kData, kGamma, kBeta};
enum CuDNNBatchNormOpOutputs {kOut, kMean, kInvVar};
enum CuDNNBatchNormOpAuxiliary {kMovingMean, kMovingInvVar};
}  // namespace cudnnbatchnorm

#if defined(__CUDACC__)
template<typename DType>
class CuDNNBatchNormOp {
 public:
  CuDNNBatchNormOp() {
    using namespace mshadow;
    dtype_ = DataType<DType>::kCudnnFlag;
    // For float16 input type beta, gamma, mean, and average are stored in float32.
    // For other input types, these parameters have the same type as input
    dtype_param_ = (dtype_ == CUDNN_DATA_HALF) ? kFloat32 : DataType<DType>::kFlag;
    CUDNN_CALL(cudnnCreateTensorDescriptor(&io_desc_));
    CUDNN_CALL(cudnnCreateTensorDescriptor(&mean_desc_));
  }

  void Init(const BatchNormParam &param) {
    CHECK_GE(param.eps, CUDNN_BN_MIN_EPSILON)
     << "CuDNN requires eps to be no less than " << CUDNN_BN_MIN_EPSILON;
    this->param_ = param;
  }

  ~CuDNNBatchNormOp() {
    CUDNN_CALL(cudnnDestroyTensorDescriptor(io_desc_));
    CUDNN_CALL(cudnnDestroyTensorDescriptor(mean_desc_));
  }

  void Forward(const OpContext &ctx,
               const std::vector<TBlob> &in_data,
               const std::vector<OpReqType> &req,
               const std::vector<TBlob> &out_data,
               const std::vector<TBlob> &aux_states) {
    using namespace mshadow;
    using namespace mshadow::expr;
    CHECK_EQ(in_data.size(), 3U);
    CHECK_EQ(aux_states.size(), 2U);
    if (ctx.is_train) {
      CHECK_EQ(out_data.size(), 3U);
      CHECK_EQ(req.size(), 3U);
    } else {
      CHECK_GE(out_data.size(), 1U);
      CHECK_GE(req.size(), 1U);
    }
    CHECK_EQ(req[cudnnbatchnorm::kOut], kWriteTo);
    CHECK_GE(in_data[cudnnbatchnorm::kData].ndim(), 2);
    CHECK_LE(in_data[cudnnbatchnorm::kData].ndim(), 5);

    Init(in_data[cudnnbatchnorm::kData]);
    int features = in_data[cudnnbatchnorm::kData].shape_[param_.axis];

    Stream<gpu> *s = ctx.get_stream<gpu>();
    DType *x_dptr = GetNdPtr(in_data[cudnnbatchnorm::kData], dim_, s);
    DType *y_dptr = GetNdPtr(out_data[cudnnbatchnorm::kOut], dim_, s);
#if CUDNN_VERSION >= 7002
    auto mode = CUDNN_BATCHNORM_SPATIAL_PERSISTENT;
#else
    auto mode = CUDNN_BATCHNORM_SPATIAL;
#endif

    MSHADOW_REAL_TYPE_SWITCH(dtype_param_, DTypeParam, {
      Tensor<gpu, 1, DTypeParam> gamma =
        in_data[cudnnbatchnorm::kGamma].get_with_shape<gpu, 1, DTypeParam>(Shape1(features), s);
      Tensor<gpu, 1, DTypeParam> beta =
        in_data[cudnnbatchnorm::kBeta].get_with_shape<gpu, 1, DTypeParam>(Shape1(features), s);
      Tensor<gpu, 1, DTypeParam> moving_mean =
        aux_states[cudnnbatchnorm::kMovingMean]
        .get_with_shape<gpu, 1, DTypeParam>(Shape1(features), s);
      Tensor<gpu, 1, DTypeParam> moving_inv_var =
        aux_states[cudnnbatchnorm::kMovingInvVar]
        .get_with_shape<gpu, 1, DTypeParam>(Shape1(features), s);
      typename DataType<DType>::ScaleType a = 1.0f;
      typename DataType<DType>::ScaleType b = 0.0f;

      if (param_.fix_gamma) gamma = 1.f;

      if (ctx.is_train) {
        Tensor<gpu, 1, DTypeParam> save_mean =
          out_data[cudnnbatchnorm::kMean].get_with_shape<gpu, 1, DTypeParam>(Shape1(features), s);
        Tensor<gpu, 1, DTypeParam> save_inv_var =
          out_data[cudnnbatchnorm::kInvVar]
          .get_with_shape<gpu, 1, DTypeParam>(Shape1(features), s);
        CUDNN_CALL(cudnnBatchNormalizationForwardTraining(s->dnn_handle_,
                                                          mode,
                                                          &a,
                                                          &b,
                                                          io_desc_,
                                                          x_dptr,
                                                          io_desc_,
                                                          y_dptr,
                                                          mean_desc_,
                                                          gamma.dptr_,
                                                          beta.dptr_,
                                                          1 - param_.momentum,
                                                          moving_mean.dptr_,
                                                          moving_inv_var.dptr_,
                                                          param_.eps,
                                                          save_mean.dptr_,
                                                          save_inv_var.dptr_));
      } else {
        CUDNN_CALL(cudnnBatchNormalizationForwardInference(s->dnn_handle_,
                                                           CUDNN_BATCHNORM_SPATIAL,
                                                           &a,
                                                           &b,
                                                           io_desc_,
                                                           x_dptr,
                                                           io_desc_,
                                                           y_dptr,
                                                           mean_desc_,
                                                           gamma.dptr_,
                                                           beta.dptr_,
                                                           moving_mean.dptr_,
                                                           moving_inv_var.dptr_,
                                                           param_.eps));
      }
    })
  }

  void Backward(const OpContext &ctx,
                const std::vector<TBlob> &inputs,
                const std::vector<OpReqType> &req,
                const std::vector<TBlob> &outputs) {
    using namespace mshadow;
    using namespace mshadow::expr;
    CHECK_EQ(inputs.size(), 8U);
    CHECK_EQ(outputs.size(), 3U);

    // Rename the inputs and outputs.
    const TBlob &out_grad = inputs[0];
    const TBlob &out_mean = inputs[1];
    const TBlob &out_var = inputs[2];
    const TBlob &in_data = inputs[3];
    const TBlob &in_gamma = inputs[4];
    const std::vector<TBlob> &in_grad = outputs;

    Init(in_data);
    Stream<gpu> *s = ctx.get_stream<gpu>();

    DType *x_dptr = GetNdPtr(in_data, dim_, s);
    DType *dx_dptr = GetNdPtr(in_grad[cudnnbatchnorm::kData], dim_, s);
    DType *dy_dptr = GetNdPtr(out_grad, dim_, s);

    const bool global_stats = !ctx.is_train || param_.use_global_stats;

    int features = in_data.shape_[param_.axis];

#if CUDNN_VERSION >= 4007
#if CUDNN_VERSION >= 7002
    auto mode = CUDNN_BATCHNORM_SPATIAL_PERSISTENT;
#else
    auto mode = CUDNN_BATCHNORM_SPATIAL;
#endif
    MSHADOW_REAL_TYPE_SWITCH(dtype_param_, DTypeParam, {
      Tensor<gpu, 1, DTypeParam> gamma =
        in_gamma.get_with_shape<gpu, 1, DTypeParam>(Shape1(features), s);
      Tensor<gpu, 1, DTypeParam> dbeta =
        in_grad[cudnnbatchnorm::kBeta].get_with_shape<gpu, 1, DTypeParam>(Shape1(features), s);
      Tensor<gpu, 1, DTypeParam> dgamma =
        in_grad[cudnnbatchnorm::kGamma].get_with_shape<gpu, 1, DTypeParam>(Shape1(features), s);
      Tensor<gpu, 1, DTypeParam> save_mean =
        out_mean.get_with_shape<gpu, 1, DTypeParam>(Shape1(features), s);
      Tensor<gpu, 1, DTypeParam> save_inv_var =
        out_var.get_with_shape<gpu, 1, DTypeParam>(Shape1(features), s);

      typename DataType<DType>::ScaleType a = 1.0f;
      typename DataType<DType>::ScaleType b = 0.0f;
      typename DataType<DType>::ScaleType b_add = 1.0f;
      CHECK_EQ(s->dnn_handle_ownership_, mshadow::Stream<gpu>::OwnHandle);

      if (param_.fix_gamma) gamma = 1.f;

      CUDNN_CALL(cudnnBatchNormalizationBackward(
        s->dnn_handle_,
        mode,
        &a,
        &b,
        &a,
        req[cudnnbatchnorm::kGamma] == kWriteTo ? &b: &b_add,
        io_desc_,
        x_dptr,
        io_desc_,
        dy_dptr,
        io_desc_,
        dx_dptr,
        mean_desc_,
        gamma.dptr_,
        dgamma.dptr_,
        dbeta.dptr_,
        param_.eps,
        global_stats ? nullptr : save_mean.dptr_,
        global_stats ? nullptr : save_inv_var.dptr_));
      if (param_.fix_gamma) dgamma = 0.f;
    })
#else  // CUDNN_VERSION < 4007
    MSHADOW_REAL_TYPE_SWITCH(dtype_param_, DTypeParam, {
      Tensor<gpu, 1, DTypeParam> gamma =
        in_gamma.get_with_shape<gpu, 1, DTypeParam>(Shape1(features), s);
      Tensor<gpu, 1, DTypeParam> dbeta =
        in_grad[cudnnbatchnorm::kBeta].get_with_shape<gpu, 1, DTypeParam>(Shape1(features), s);
      Tensor<gpu, 1, DTypeParam> dgamma =
        in_grad[cudnnbatchnorm::kGamma].get_with_shape<gpu, 1, DTypeParam>(Shape1(features), s);
      Tensor<gpu, 1, DTypeParam> save_mean =
        out_mean.get_with_shape<gpu, 1, DTypeParam>(Shape1(features), s);
      Tensor<gpu, 1, DTypeParam> save_inv_var =
        out_var.get_with_shape<gpu, 1, DTypeParam>(Shape1(features), s);

      typename DataType<DType>::ScaleType a = 1.0f;
      typename DataType<DType>::ScaleType b = 0.0f;
      typename DataType<DType>::ScaleType b_add = 1.0f;
      CHECK_EQ(s->dnn_handle_ownership_, mshadow::Stream<gpu>::OwnHandle);

      if (param_.fix_gamma) gamma = 1.f;
      CUDNN_CALL(cudnnBatchNormalizationBackward(s->dnn_handle_,
                                                 CUDNN_BATCHNORM_SPATIAL,
                                                 &a,
                                                 &b,
                                                 io_desc_,
                                                 x.dptr_,
                                                 io_desc_,
                                                 dy.dptr_,
                                                 io_desc_,
                                                 dx.dptr_,
                                                 mean_desc_,
                                                 gamma.dptr_,
                                                 dgamma.dptr_,
                                                 dbeta.dptr_,
                                                 param_.eps,
                                                 global_stats ? nullptr : save_mean.dptr_,
                                                 global_stats ? nullptr : save_inv_var.dptr_));
      if (param_.fix_gamma) dgamma = 0.f;
    })
#endif
  }

/*!
 * \brief Returns whether the cuDNN library version supports the batchnorm
 * operation described by `param`.
 */
  static bool Supports(const BatchNormParam &param, int dtype, const TShape& shape) {
    // Axis parameters are in the range [0,shape.ndim()-1].
    int dim = shape.ndim();
    return !param.use_global_stats &&
           dim >= 2 && dim <= 5 &&
           (param.axis == 1 || param.axis == dim-1);
  }

  // Converts a TBlob to a dptr, checking for the expected dim and that it's contiguous.
  DType *GetNdPtr(const TBlob& tb, int dim, mshadow::Stream<gpu> *s) {
    DType *data_ptr = NULL;
    if (dim == 2) {
      mshadow::Tensor<gpu, 2, DType> data = tb.get<gpu, 2, DType>(s);
      CHECK_EQ(data.CheckContiguous(), true);
      data_ptr = data.dptr_;
    } else if (dim == 3) {
      mshadow::Tensor<gpu, 3, DType> data = tb.get<gpu, 3, DType>(s);
      CHECK_EQ(data.CheckContiguous(), true);
      data_ptr = data.dptr_;
    } else if (dim == 4) {
      mshadow::Tensor<gpu, 4, DType> data = tb.get<gpu, 4, DType>(s);
      CHECK_EQ(data.CheckContiguous(), true);
      data_ptr = data.dptr_;
    } else if (dim == 5) {
      mshadow::Tensor<gpu, 5, DType> data = tb.get<gpu, 5, DType>(s);
      CHECK_EQ(data.CheckContiguous(), true);
      data_ptr = data.dptr_;
    } else {
      LOG(FATAL) << "Unexpected Tensor size " << dim << ", supporting only 3, 4 or 5.";
    }
    return data_ptr;
  }

 private:
  void Init(const TBlob &in_data) {
    // From merge
    dim_ = in_data.ndim();
    TShape in_shape = in_data.shape_;
    CHECK(param_.axis == 1 || param_.axis == dim_-1)
      << "axis must be 1 or " << (dim_-1) << ", found: " << param_.axis;
    bool transposed_layout = (dim_ >= 3 && param_.axis == dim_-1);
    auto format = transposed_layout ? CUDNN_TENSOR_NHWC : CUDNN_TENSOR_NCHW;
    int n = in_shape[0];
    int c = transposed_layout ? in_shape[dim_ - 1] : in_shape[1];
    int w_index = transposed_layout ? dim_ - 2 : dim_ - 1;
    int d = dim_ >= 5 ? in_shape[w_index - 2] : 1;
    int h = dim_ >= 4 ? in_shape[w_index - 1] : 1;
    int w = dim_ >= 3 ? in_shape[w_index - 0] : 1;
     if (dim_ < 5) {
      CUDNN_CALL(cudnnSetTensor4dDescriptor(io_desc_,
                                            format,
                                            dtype_,
                                            n, c, h, w));
    } else {
      std::vector<int> ishape = {n, c, d, h, w};
      std::vector<int> istride = {c * d * h * w,
                                      d * h * w,
                                          h * w,
                                              w,
                                              1};
      if (transposed_layout)
        istride = {c * d * h * w,
                               1,
                       c * h * w,
                           c * w,
                               c};
      CUDNN_CALL(cudnnSetTensorNdDescriptor(io_desc_,
                                            dtype_,
                                            dim_,
                                            &ishape[0],
                                            &istride[0]));
    }
    CUDNN_CALL(cudnnDeriveBNTensorDescriptor(mean_desc_,
                                             io_desc_,
                                             CUDNN_BATCHNORM_SPATIAL));
  }

  int dim_;
  cudnnDataType_t dtype_;
  int dtype_param_;
  cudnnTensorDescriptor_t io_desc_, mean_desc_;
  BatchNormParam param_;
};
#endif  // defined(__CUDACC__)

#endif  // MXNET_USE_CUDNN == 1 && CUDNN_MAJOR >= 4
}  // namespace op
}  // namespace mxnet
#endif  // MXNET_OPERATOR_NN_CUDNN_CUDNN_BATCH_NORM_INL_H_


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;

namespace IronAHK.Rusty.Windows
{
    /// <summary>
    /// Implementation for native Windows Drive Operations
    /// </summary>
    class Drive : Common.Drive
    {
        static readonly string IOPathPrefix = @"\\.\";

        public Drive(DriveInfo drv)
            : base(drv) { }

        public override void Eject() {
            IntPtr fileHandle = IntPtr.Zero;
            try {
                // Create an handle to the drive
                fileHandle = WindowsAPI.CreateFile(this.CreateDeviceIOPath,
                WindowsAPI.GENERICREAD, 0, IntPtr.Zero,
                WindowsAPI.OPENEXISTING, 0, IntPtr.Zero);

                if((int)fileHandle != WindowsAPI.INVALID_HANDLE) {
                    // Eject the disk
                    uint returnedBytes;
                    WindowsAPI.DeviceIoControl(fileHandle, WindowsAPI.IOCTL_STORAGE_EJECT_MEDIA,
                    IntPtr.Zero, 0,
                    IntPtr.Zero, 0,
                    out returnedBytes,
                    IntPtr.Zero);
                }
            } catch {
                throw new Exception(Marshal.GetLastWin32Error().ToString());
            } finally {
                // Close Drive Handle
                WindowsAPI.CloseHandle(fileHandle);
                fileHandle = IntPtr.Zero;
            }
        }

        public string CreateDeviceIOPath {
            get {
                return IOPathPrefix + drive.Name.Substring(0, 1) + ":";
            }
        }

        public override void Retract() {
            throw new NotImplementedException();
        }

        public override StatusCD Status {
            get { throw new NotImplementedException(); }
        }

        public override long Serial {
            get { throw new NotImplementedException(); }
        }

        public override void Lock() {
            throw new NotImplementedException();
        }

        public override void UnLock() {
            throw new NotImplementedException();
        }
    }

}


text:
package org.elasticsearch.action.admin.indices.alias;

import com.carrotsearch.hppc.cursors.ObjectCursor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.RequestValidators;
import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest.AliasActions;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.support.master.AcknowledgedTransportMasterNodeAction;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.block.ClusterBlockException;
import org.elasticsearch.cluster.block.ClusterBlockLevel;
import org.elasticsearch.cluster.metadata.AliasAction;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.cluster.metadata.IndexAbstraction;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.cluster.metadata.MetadataIndexAliasesService;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.collect.ImmutableOpenMap;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.index.Index;
import org.elasticsearch.rest.action.admin.indices.AliasesNotFoundException;
import org.elasticsearch.tasks.Task;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportService;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;

import static java.util.Collections.unmodifiableList;

/**
 * Add/remove aliases action
 */
public class TransportIndicesAliasesAction extends AcknowledgedTransportMasterNodeAction<IndicesAliasesRequest> {

    private static final Logger logger = LogManager.getLogger(TransportIndicesAliasesAction.class);

    private final MetadataIndexAliasesService indexAliasesService;
    private final RequestValidators<IndicesAliasesRequest> requestValidators;

    @Inject
    public TransportIndicesAliasesAction(
            final TransportService transportService,
            final ClusterService clusterService,
            final ThreadPool threadPool,
            final MetadataIndexAliasesService indexAliasesService,
            final ActionFilters actionFilters,
            final IndexNameExpressionResolver indexNameExpressionResolver,
            final RequestValidators<IndicesAliasesRequest> requestValidators) {
        super(IndicesAliasesAction.NAME, transportService, clusterService, threadPool, actionFilters, IndicesAliasesRequest::new,
            indexNameExpressionResolver, ThreadPool.Names.SAME);
        this.indexAliasesService = indexAliasesService;
        this.requestValidators = Objects.requireNonNull(requestValidators);
    }

    @Override
    protected ClusterBlockException checkBlock(IndicesAliasesRequest request, ClusterState state) {
        Set<String> indices = new HashSet<>();
        for (AliasActions aliasAction : request.aliasActions()) {
            Collections.addAll(indices, aliasAction.indices());
        }
        return state.blocks().indicesBlockedException(ClusterBlockLevel.METADATA_WRITE, indices.toArray(new String[indices.size()]));
    }

    @Override
    protected void masterOperation(Task task, final IndicesAliasesRequest request, final ClusterState state,
                                   final ActionListener<AcknowledgedResponse> listener) {

        //Expand the indices names
        List<AliasActions> actions = request.aliasActions();
        List<AliasAction> finalActions = new ArrayList<>();
        // Resolve all the AliasActions into AliasAction instances and gather all the aliases
        Set<String> aliases = new HashSet<>();
        for (AliasActions action : actions) {
            List<String> concreteDataStreams =
                indexNameExpressionResolver.dataStreamNames(state, request.indicesOptions(), action.indices());
            if (concreteDataStreams.size() != 0) {
                switch (action.actionType()) {
                    case ADD:
                        for (String dataStreamName : concreteDataStreams) {
                            finalActions.add(new AliasAction.AddDataStreamAlias(action.aliases()[0], dataStreamName));
                        }
                        break;
                    case REMOVE:
                        for (String dataStreamName : concreteDataStreams) {
                            finalActions.add(
                                new AliasAction.RemoveDataStreamAlias(action.aliases()[0], dataStreamName, action.mustExist()));
                        }
                        break;
                    default:
                        throw new IllegalArgumentException("Unsupported action [" + action.actionType() + "]");
                }
                continue;
            }

            final Index[] concreteIndices = indexNameExpressionResolver.concreteIndices(state, request.indicesOptions(), false,
                action.indices());
            for (Index concreteIndex : concreteIndices) {
                IndexAbstraction indexAbstraction = state.metadata().getIndicesLookup().get(concreteIndex.getName());
                assert indexAbstraction != null : "invalid cluster metadata. index [" + concreteIndex.getName() + "] was not found";
                if (indexAbstraction.getParentDataStream() != null) {
                    throw new IllegalArgumentException("The provided expressions [" + String.join(",", action.indices())
                        + "] match a backing index belonging to data stream [" + indexAbstraction.getParentDataStream().getName()
                        + "]. Data streams and their backing indices don't support aliases.");
                }
            }
            final Optional<Exception> maybeException = requestValidators.validateRequest(request, state, concreteIndices);
            if (maybeException.isPresent()) {
                listener.onFailure(maybeException.get());
                return;
            }

            Collections.addAll(aliases, action.getOriginalAliases());
            long now = System.currentTimeMillis();
            for (final Index index : concreteIndices) {
                switch (action.actionType()) {
                case ADD:
                    for (String alias : concreteAliases(action, state.metadata(), index.getName())) {
                        String resolvedName = this.indexNameExpressionResolver.resolveDateMathExpression(alias, now);
                        finalActions.add(new AliasAction.Add(index.getName(), resolvedName,
                            action.filter(), action.indexRouting(),
                            action.searchRouting(), action.writeIndex(), action.isHidden()));
                    }
                    break;
                case REMOVE:
                    for (String alias : concreteAliases(action, state.metadata(), index.getName())) {
                        finalActions.add(new AliasAction.Remove(index.getName(), alias, action.mustExist()));
                    }
                    break;
                case REMOVE_INDEX:
                    finalActions.add(new AliasAction.RemoveIndex(index.getName()));
                    break;
                default:
                    throw new IllegalArgumentException("Unsupported action [" + action.actionType() + "]");
                }
            }
        }
        if (finalActions.isEmpty() && false == actions.isEmpty()) {
            throw new AliasesNotFoundException(aliases.toArray(new String[aliases.size()]));
        }
        request.aliasActions().clear();
        IndicesAliasesClusterStateUpdateRequest updateRequest = new IndicesAliasesClusterStateUpdateRequest(unmodifiableList(finalActions))
                .ackTimeout(request.timeout()).masterNodeTimeout(request.masterNodeTimeout());

        indexAliasesService.indicesAliases(updateRequest, listener.delegateResponse((l, e) -> {
            logger.debug("failed to perform aliases", e);
            l.onFailure(e);
        }));
    }

    private static String[] concreteAliases(AliasActions action, Metadata metadata, String concreteIndex) {
        if (action.expandAliasesWildcards()) {
            //for DELETE we expand the aliases
            String[] indexAsArray = {concreteIndex};
            ImmutableOpenMap<String, List<AliasMetadata>> aliasMetadata = metadata.findAliases(action, indexAsArray);
            List<String> finalAliases = new ArrayList<>();
            for (ObjectCursor<List<AliasMetadata>> curAliases : aliasMetadata.values()) {
                for (AliasMetadata aliasMeta: curAliases.value) {
                    finalAliases.add(aliasMeta.alias());
                }
            }
            if (finalAliases.isEmpty() && action.mustExist() != null && action.mustExist()) {
                return action.aliases();
            }
            return finalAliases.toArray(new String[finalAliases.size()]);
        } else {
            //for ADD and REMOVE_INDEX we just return the current aliases
            return action.aliases();
        }
    }
}


text:
class HttpSession : HttpListenSocket::Delegate {
 public:
  HttpSession(const std::string& ip, int port);
  virtual ~HttpSession();

  virtual void OnRequest(HttpListenSocket* connection,
                         HttpServerRequestInfo* info) OVERRIDE;

 private:
  scoped_refptr<HttpListenSocket> socket_;
  DISALLOW_COPY_AND_ASSIGN(HttpSession);
};

#endif // NET_BASE_TOOLS_HTTP_SESSION_H_


text:
package com.github.dannywe.csv.base.writer

import au.com.bytecode.opencsv.CSVWriter
import com.github.dannywe.csv.base.Next
import com.github.dannywe.csv.core.TypeAliases._

import scalaz.concurrent.Task
import scalaz.stream._

trait WriterService {

  def write[T](it: Iterator[T], f: T => StringArray, writer: java.io.Writer): Unit = {
    val csvWriter: CSVWriter = new CSVWriter(writer)

    def mapToT: Next[T] => Task[StringArray] = t => Task(f(t.get))

    val result: Process[Task, Next[T]] = Process.repeatEval(Task{it.next}).takeWhile(t => !t.shouldStop)

    val channel = Process.constant(mapToT)

    (result through channel).map(t => csvWriter.writeNext(t)).run.run

    csvWriter.close()

  }

}


text:
package uk.ac.ncl.openlab.intake24.client.survey.rules;

import org.pcollections.PSet;
import org.workcraft.gwt.shared.client.Option;
import uk.ac.ncl.openlab.intake24.client.survey.*;
import uk.ac.ncl.openlab.intake24.client.survey.prompts.SplitFoodPrompt;

public class SplitFoodFlexibleRecall implements PromptRule<FoodEntry, FoodOperation> {

    /**
     * Experimental. Flexible recall. Compared to original ignores FLAG_FREE_ENTRY_COMPLETE.
     */

    @Override
    public Option<Prompt<FoodEntry, FoodOperation>> apply(FoodEntry data, SelectionMode selectionType, PSet<String> surveyFlags) {
        return data.accept(new FoodEntry.Visitor<Option<Prompt<FoodEntry, FoodOperation>>>() {
            @Override
            public Option<Prompt<FoodEntry, FoodOperation>> visitRaw(RawFood food) {
                if (food.applySplit())
                    return Option.<Prompt<FoodEntry, FoodOperation>>some(new SplitFoodPrompt(food));
                else
                    return Option.none();
            }

            @Override
            public Option<Prompt<FoodEntry, FoodOperation>> visitEncoded(final EncodedFood food) {
                return Option.none();
            }

            @Override
            public Option<Prompt<FoodEntry, FoodOperation>> visitTemplate(TemplateFood food) {
                return Option.none();
            }

            @Override
            public Option<Prompt<FoodEntry, FoodOperation>> visitMissing(MissingFood food) {
                return Option.none();
            }

            @Override
            public Option<Prompt<FoodEntry, FoodOperation>> visitCompound(CompoundFood food) {
                return Option.none();
            }
        });

    }

    @Override
    public String toString() {
        return "Try to split the food description";
    }

    public static WithPriority<PromptRule<FoodEntry, FoodOperation>> withPriority(int priority) {
        return new WithPriority<PromptRule<FoodEntry, FoodOperation>>(new SplitFoodFlexibleRecall(), priority);
    }
}


text:
[![License MIT](https://go-shields.herokuapp.com/license-MIT-blue.png)](https://github.com/RidgeCorn/RCDraggableButton/blob/master/LICENSE)
[![Build Platform](https://cocoapod-badges.herokuapp.com/p/RCDraggableButton/badge.png)](https://github.com/RidgeCorn/RCDraggableButton)
[![Build Version](https://cocoapod-badges.herokuapp.com/v/RCDraggableButton/badge.png)](https://github.com/RidgeCorn/RCDraggableButton)
[![Build Status](https://travis-ci.org/RidgeCorn/RCDraggableButton.png?branch=master)](https://travis-ci.org/RidgeCorn/RCDraggableButton)
[![RCDraggableButton Chat](https://badges.gitter.im/RidgeCorn/RCDraggableButton.png)](https://gitter.im/RidgeCorn/RCDraggableButton)
[![Stories in Ready](https://badge.waffle.io/RidgeCorn/RCDraggableButton.png?label=ready)](https://waffle.io/RidgeCorn/RCDraggableButton)

A draggable button that appears in your view.

## Note

**RCDraggableButton is not ready for production use until version 1.0.**

## Requirements
* Xcode 5.0 or higher
* iOS 5.0 or higher
* ARC

## Demo

In your terminal,

``` bash
cd [projdir]/RCDraggableButtonDemo
pod install
```

After a cup of tea, you should be able to build and run the `RCDraggableButtonDemo` project by open `RCDraggableButtonDemo.xcworkspace` in Xcode5.

``` bash
open RCDraggableButtonDemo.xcworkspace
```

## Installation

### CocoaPods

The recommended approach for installating `RCDraggableButton` is via the [CocoaPods](http://cocoapods.org/) package manager.

In your `Podfile`, add a line shows below:

``` bash
pod 'RCDraggableButton', '~> 0.1'
```

Then,

``` bash
pod update
```

If you haven't used `CocoaPods` before, you should visit [CocoaPods](http://cocoapods.org/) for more info.

### Manual Install

All you need to do is drop `Src` files into your project, and add `#include "RCDraggableButton.h"` to the top of classes that will use it.

## Example Usage

In your AppViewController's `- (void)viewDidLoad` create draggableButton and add it to keyWindow or customView.

```objective-c
// Set view as nil, means add button to keyWindow
	RCDraggableButton *draggableButton = [[RCDraggableButton alloc] initInView:nil WithFrame:CGRectMake(120, 120, 60, 60)];

// Or add button to customView that you set in -init method
	UIView *customView = ...;
    [self.view addSubview:customView];

    RCDraggableButton *avatar = [[RCDraggableButton alloc] initInView:customView WithFrame:CGRectMake(120, 120, 60, 60)];
```

You can also use it manually:

```objective-c
	RCDraggableButton *draggableButton = [[RCDraggableButton alloc] initWithFrame:CGRectMake(0, 100, 60, 60)];
	[self.view addSubview:draggableButton];
```

For more usage example, please look up the demo project in `RCDraggableButtonDemo`, or the source files in `Src`.

## License

RCDraggableButton is available under the MIT license. See the [LICENSE](https://github.com/RidgeCorn/RCDraggableButton/blob/master/LICENSE) file for more info.


text:
<?php

namespace BW\GalleryBundle\Controller;

use BW\MainBundle\Utility\FormUtility;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use BW\GalleryBundle\Entity\Gallery;
use BW\GalleryBundle\Form\GalleryType;

/**
 * Class GalleryController
 * @package BW\GalleryBundle\Controller
 */
class GalleryController extends Controller
{

    /**
     * Lists all Gallery entities.
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('BWGalleryBundle:Gallery')->findAll();

        return $this->render('BWGalleryBundle:Gallery:index.html.twig', array(
            'entities' => $entities,
        ));
    }

    /**
     * Finds and displays a Gallery entity.
     *
     * @param $id
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('BWGalleryBundle:Gallery')->find($id);

        if ( ! $entity) {
            throw $this->createNotFoundException('Запрашиваемая галерея не существует.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return $this->render('BWGalleryBundle:Gallery:show.html.twig', array(
            'entity' => $entity,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to create a new Gallery entity.
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function newAction()
    {
        $entity = new Gallery();
        $form   = $this->createCreateForm($entity);

        return $this->render('BWGalleryBundle:Gallery:new.html.twig', array(
            'entity' => $entity,
            'form' => $form->createView(),
        ));
    }

    /**
     * Creates a new Gallery entity.
     *
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function createAction(Request $request)
    {
        $entity = new Gallery();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            if ($form->get('createAndClose')->isClicked()) {
                return $this->redirect($this->generateUrl('gallery'));
            }

            return $this->redirect($this->generateUrl('gallery_edit', array('id' => $entity->getId())));
        }

        return $this->render('BWGalleryBundle:Gallery:new.html.twig', array(
            'entity' => $entity,
            'form' => $form->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing Gallery entity.
     *
     * @param $id
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('BWGalleryBundle:Gallery')->find($id);

        if ( ! $entity) {
            throw $this->createNotFoundException('Запрашиваемая галерея не существует.');
        }

        $form = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return $this->render('BWGalleryBundle:Gallery:edit.html.twig', array(
            'entity' => $entity,
            'form' => $form->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Edits an existing Gallery entity.
     *
     * @param Request $request
     * @param $id
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('BWGalleryBundle:Gallery')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Запрашиваемая галерея не существует.');
        }

        $form = $this->createEditForm($entity);
        $form->handleRequest($request);
        if ($form->get('delete')->isClicked()) {
            $this->delete($id);

            return $this->redirect($this->generateUrl('gallery'));
        }
        if ($form->isValid()) {
            $em->flush();

            if ($form->get('updateAndClose')->isClicked()) {
                return $this->redirect($this->generateUrl('gallery'));
            }

            return $this->redirect($this->generateUrl('gallery_edit', array('id' => $id)));
        }

        $deleteForm = $this->createDeleteForm($id);

        return $this->render('BWGalleryBundle:Gallery:edit.html.twig', array(
            'entity' => $entity,
            'form' => $form->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Delete Gallery object from DB
     *
     * @param $id The Gallery id
     * @return bool
     */
    public function delete($id)
    {
        $em = $this->getDoctrine()->getManager();
        $entity = $em->getRepository('BWGalleryBundle:Gallery')->find($id);

        if ( ! $entity) {
            throw $this->createNotFoundException('Запрашиваемая галерея не существует.');
        }

        $em->remove($entity);
        $em->flush();

        return true;
    }

    /**
     * Deletes a Gallery entity.
     *
     * @param Request $request
     * @param $id
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $this->delete($id);
        }

        return $this->redirect($this->generateUrl('gallery'));
    }

    /**
     * Creates a form to create a Gallery entity.
     *
     * @param Gallery $entity The entity
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(Gallery $entity)
    {
        $form = $this->createForm(new GalleryType(), $entity, array(
            'action' => $this->generateUrl('gallery_create'),
            'method' => 'POST',
        ));

        FormUtility::addCreateButton($form);
        FormUtility::addCreateAndCloseButton($form);

        return $form;
    }

    /**
     * Creates a form to edit a Gallery entity.
     *
     * @param Gallery $entity The entity
     * @return \Symfony\Component\Form\Form The form
     */
    private function createEditForm(Gallery $entity)
    {
        $form = $this->createForm(new GalleryType(), $entity, array(
            'action' => $this->generateUrl('gallery_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        FormUtility::addUpdateButton($form);
        FormUtility::addUpdateAndCloseButton($form);
        FormUtility::addDeleteButton($form);

        return $form;
    }

    /**
     * Creates a form to delete a Gallery entity by id.
     *
     * @param mixed $id The entity id
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        $form = $this->createFormBuilder()
            ->setAction($this->generateUrl('gallery_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->getForm()
        ;

        FormUtility::addDeleteButton($form);

        return $form;
    }
}


text:
package org.cocos2dx.plugin;

import java.util.Hashtable;
import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;

import com.flurry.android.FlurryAdListener;
import com.flurry.android.FlurryAdSize;
import com.flurry.android.FlurryAdType;
import com.flurry.android.FlurryAds;
import com.flurry.android.FlurryAgent;

public class AdsFlurry implements InterfaceAds, FlurryAdListener {

    private Context mContext = null;
    protected static String TAG = "AdsFlurry";

    private FrameLayout mBannerView = null;
    private WindowManager mWm = null;
    private AdsFlurry mAdapter = null;

    protected static void LogE(String msg, Exception e) {
        Log.e(TAG, msg, e);
        e.printStackTrace();
    }

    private static boolean isDebug = false;
    protected static void LogD(String msg) {
        if (isDebug) {
            Log.d(TAG, msg);
        }
    }

    public AdsFlurry(Context context) {
        mContext = context;
        mAdapter = this;
    }

    @Override
    public void setDebugMode(boolean isDebugMode) {
        isDebug = isDebugMode;
        final boolean curDebug = isDebug;
        PluginWrapper.runOnMainThread(new Runnable(){
            @Override
            public void run() {
                FlurryAgent.setLogEnabled(curDebug);
                if (curDebug) {
                    FlurryAgent.setLogLevel(Log.DEBUG);
                }
            }
        });
    }

    @Override
    public String getSDKVersion() {
        return "3.2.1";
    }

    @Override
    public String getPluginVersion() {
        return "0.2.0";
    }

    @Override
    public void configDeveloperInfo(Hashtable<String, String> devInfo) {
        final Hashtable<String, String> curInfo = devInfo;
        PluginWrapper.runOnMainThread(new Runnable(){
            @Override
            public void run() {
                try {
                    String appKey = curInfo.get("FlurryAppKey");
                    FlurryAgent.onStartSession(mContext, appKey);
                    FlurryAds.setAdListener(mAdapter);
                    FlurryAds.initializeAds(mContext);
                } catch (Exception e) {
                    LogE("Error during configDeveloperInfo.", e);
                }
            }
        });
    }

    @Override
    public void showAds(Hashtable<String, String> adsInfo, int pos) {
        final Hashtable<String, String> curInfo = adsInfo;
        final int curPos = pos;
        PluginWrapper.runOnMainThread(new Runnable(){
            @Override
            public void run() {
                try
                {
                    String spaceID = curInfo.get("FlurryAdsID");
                    if (null == spaceID || TextUtils.isEmpty(spaceID))
                    {
                        LogD("Value of 'FlurryAdsID' should not be empty");
                        return;
                    }

                    String strSize = curInfo.get("FlurryAdsSize");
                    int size = Integer.parseInt(strSize);
                    if (size != 1 && size != 2 && size != 3) {
                        LogD("Valur of 'FlurryAdsSize' should be one of '1', '2', '3'");
                        return;
                    }

                    FlurryAdSize eSize = FlurryAdSize.BANNER_TOP;
                    switch (size)
                    {
                    case 1:
                        eSize = FlurryAdSize.BANNER_TOP;
                        break;
                    case 2:
                        eSize = FlurryAdSize.BANNER_BOTTOM;
                        break;
                    case 3:
                        eSize = FlurryAdSize.FULLSCREEN;
                        break;
                    default:
                        break;
                    }

                    if (null == mWm) {
                        mWm = (WindowManager) mContext.getSystemService("window");
                    }
                    if (null != mBannerView) {
                        mWm.removeView(mBannerView);
                        mBannerView = null;
                    }
                    mBannerView = new FrameLayout(mContext);
                    AdsWrapper.addAdView(mWm, mBannerView, curPos);

                    FlurryAds.fetchAd(mContext, spaceID, mBannerView, eSize);
                } catch (Exception e) {
                    LogE("Error during showAds", e);
                }
            }
        });
    }

    @Override
    public void hideAds(Hashtable<String, String> adsInfo) {
        final Hashtable<String, String> curInfo = adsInfo;
        PluginWrapper.runOnMainThread(new Runnable(){
            @Override
            public void run() {
                try
                {
                    String spaceID = curInfo.get("FlurryAdsID");
                    if (null == spaceID || TextUtils.isEmpty(spaceID))
                    {
                        LogD("Value of 'FlurryAdsID' should not be empty");
                        return;
                    }

                    FlurryAds.removeAd(mContext, spaceID, (ViewGroup) mBannerView);
                } catch (Exception e) {
                    LogE("Error during hideAds", e);
                }
            }
        });
    }

    @Override
    public void queryPoints() {
        // TODO Auto-generated method stub

    }

    @Override
    public void spendPoints(int points) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onAdClicked(String arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onAdClosed(String arg0) {
        AdsWrapper.onAdsResult(this, AdsWrapper.RESULT_CODE_AdsDismissed, "Ads will be dismissed");
    }

    @Override
    public void onAdOpened(String arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onApplicationExit(String arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onRenderFailed(String arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onVideoCompleted(String arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean shouldDisplayAd(String arg0, FlurryAdType arg1) {
        AdsWrapper.onAdsResult(this, AdsWrapper.RESULT_CODE_AdsShown, "Ads will be shown");
        return true;
    }

    @Override
    public void spaceDidFailToReceiveAd(String arg0) {
        LogD("param : " + arg0);
        AdsWrapper.onAdsResult(this, AdsWrapper.RESULT_CODE_UnknownError, "Failed to receive Ads of flurry");
    }

    @Override
    public void spaceDidReceiveAd(String arg0) {
        AdsWrapper.onAdsResult(this, AdsWrapper.RESULT_CODE_AdsReceived, "Ads of flurry received");
    }
}


text:
<?php

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

/* @var $this yii\web\View */
/* @var $model app\models\GacGfsListUSearch */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>

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

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

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

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

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

    <?php // echo $form->field($model, 'ItemDescription') ?>

    <?php // echo $form->field($model, 'GFSTransaction') ?>

    <?php // echo $form->field($model, 'GFSHoldingGain') ?>

    <?php // echo $form->field($model, 'GFSVolume') ?>

    <?php // echo $form->field($model, 'GFSStock') ?>

    <?php // echo $form->field($model, 'ActiveFlag') ?>

    <?php // echo $form->field($model, 'DateCreated') ?>

    <?php // echo $form->field($model, 'UserCreated') ?>

    <?php // echo $form->field($model, 'DateModified') ?>

    <?php // echo $form->field($model, 'UserModified') ?>

        <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
        <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>

    <?php ActiveForm::end(); ?>


text:
import AbstractService from './AbstractService';
import RestApiService from './RestApiService';
import ResponseUtils from '../utils/ResponseUtils';

/**
 * Validates ReCaptcha requests.
 *
 * @author Filip Mestanek
 */
export default class RecaptchaService extends AbstractService {

  getApiPath() {
    return '/public/recaptcha';
  }

  /**
   * Checks recaptcha response from Google. See https://developers.google.com/recaptcha/docs/verify for API.
   *
   * @param {string} response response from the recaptcha
   *
   * @return {Promise}
   */
  checkResponse(response) {
    const payload = {
      response
    };

    return RestApiService
      .post(this.getApiPath(), payload)
      .then(serviceResponse => {
        return serviceResponse.json();
      })
      .then(json => {
        if (ResponseUtils.hasError(json)) {
          throw ResponseUtils.getFirstError(json);
        }

        return json;
      });
  }
}


text:
export * from './grid.styles';
export * from './grid.types';