text:
<?php

/* AdminBundle:Centro:editar.html.twig */
class __TwigTemplate_db00488add0dfe19eb901c54f18fcbb6385e707e090e5251ceefdac2cad0638b extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = $this->env->loadTemplate("::admin.html.twig");

        $this->blocks = array(
            'additional_style' => array($this, 'block_additional_style'),
            'nav' => array($this, 'block_nav'),
            'breadcrumbs' => array($this, 'block_breadcrumbs'),
            'header_title' => array($this, 'block_header_title'),
            'main' => array($this, 'block_main'),
            'footerNav' => array($this, 'block_footerNav'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "::admin.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 3
    public function block_additional_style($context, array $blocks = array())
    {
        // line 4
        echo "    ";
        // line 5
        echo "    <link href=\"";
        echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("bundles/admin/css/Forms.css"), "html", null, true);
        echo "\" rel=\"stylesheet\" type=\"text/css\"/>
    <link href=\"";
        // line 6
        echo twig_escape_filter($this->env, $this->env->getExtension('assets')->getAssetUrl("bundles/admin/css/Errors.css"), "html", null, true);
        echo "\" rel=\"stylesheet\" type=\"text/css\"/>
";
    }

    // line 9
    public function block_nav($context, array $blocks = array())
    {
        // line 10
        echo "    ";
        $context["mainMenu"] = $this->env->loadTemplate("::main_admin_menu.html.twig");
        // line 11
        echo "    ";
        echo $context["mainMenu"]->getadmin_navigation("entity");
        echo "
";
    }

    // line 14
    public function block_breadcrumbs($context, array $blocks = array())
    {
        // line 15
        echo "    » env->getExtension('routing')->getPath("admin_portada");
        echo "\">Administración
    » env->getExtension('routing')->getPath("admin_centro_index");
        echo "\">Centros
";
    }

    // line 18
    public function block_header_title($context, array $blocks = array())
    {
        echo "
Editar Centro
 ";
    }

    // line 20
    public function block_main($context, array $blocks = array())
    {
        // line 21
        echo "

            <form action=\"";
        // line 24
        echo twig_escape_filter($this->env, $this->env->getExtension('routing')->getPath("admin_centro_editar", array("id" => $this->getAttribute((isset($context["centro"]) ? $context["centro"] : $this->getContext($context, "centro")), "id"))), "html", null, true);
        echo "\" method=\"post\">
                ";
        // line 26
        echo "

                    ";
        // line 27
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "nombre"), 'errors');
        echo "
                    ";
        // line 28
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "siglas"), 'errors');
        echo "
                    ";
        // line 29
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "direccion"), 'errors');
        echo "
                    ";
        // line 30
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "telefono"), 'errors');
        echo "
                    ";
        // line 31
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "email"), 'errors');
        echo "
                    ";
        // line 32
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "director"), 'errors');
        echo "
                    ";
        // line 33
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "rEEUP"), 'errors');
        echo "
                    ";
        // line 34
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "organizacion"), 'errors');
        echo "
                    ";
        // line 35
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "municipio"), 'errors');
        echo "

                    ";
        // line 38
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'errors');
        echo "

env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "nombre"), 'errors')) {
            echo " class=\"form-field error-field\" ";
        } else {
            echo " class=\"form-field\" ";
        }
        echo ">
                        ";
        // line 40
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "nombre"), 'label');
        echo "

                            ";
        // line 42
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "nombre"), 'widget');
        echo "

env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "siglas"), 'errors')) {
            echo " class=\"form-field error-field\" ";
        } else {
            echo " class=\"form-field\" ";
        }
        echo ">
                        ";
        // line 46
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "siglas"), 'label');
        echo "

                            ";
        // line 48
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "siglas"), 'widget');
        echo "

env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "direccion"), 'errors')) {
            echo " class=\"form-field error-field\" ";
        } else {
            echo " class=\"form-field\" ";
        }
        echo ">
                        ";
        // line 52
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "direccion"), 'label');
        echo "

                            ";
        // line 54
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "direccion"), 'widget');
        echo "

env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "telefono"), 'errors')) {
            echo " class=\"form-field error-field\" ";
        } else {
            echo " class=\"form-field\" ";
        }
        echo ">
                        ";
        // line 58
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "telefono"), 'label');
        echo "

                            ";
        // line 60
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "telefono"), 'widget');
        echo "

env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "email"), 'errors')) {
            echo " class=\"form-field error-field\" ";
        } else {
            echo " class=\"form-field\" ";
        }
        echo ">
                        ";
        // line 64
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "email"), 'label');
        echo "

                            ";
        // line 66
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "email"), 'widget');
        echo "

env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "director"), 'errors')) {
            echo " class=\"form-field error-field\" ";
        } else {
            echo " class=\"form-field\" ";
        }
        echo ">
                        ";
        // line 70
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "director"), 'label');
        echo "

                            ";
        // line 72
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "director"), 'widget');
        echo "

env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "rEEUP"), 'errors')) {
            echo " class=\"form-field error-field\" ";
        } else {
            echo " class=\"form-field\" ";
        }
        echo ">
                        ";
        // line 76
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "rEEUP"), 'label');
        echo "

                            ";
        // line 78
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "rEEUP"), 'widget');
        echo "

env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "organizacion"), 'errors')) {
            echo " class=\"form-field error-field\" ";
        } else {
            echo " class=\"form-field\" ";
        }
        echo ">
                        ";
        // line 82
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "organizacion"), 'label');
        echo "

                            ";
        // line 84
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "organizacion"), 'widget');
        echo "

env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "municipio"), 'errors')) {
            echo " class=\"form-field error-field\" ";
        } else {
            echo " class=\"form-field\" ";
        }
        echo ">
                        ";
        // line 88
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "municipio"), 'label');
        echo "

                            ";
        // line 90
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "municipio"), 'widget');
        echo "

                    ";
        // line 93
        echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'rest');
        echo "

                <input class=\"button button-bottom\" type=\"submit\" value=\"Modificar\" />
                env->getExtension('routing')->getPath("admin_centro_index");
        echo "\">Volver al listado
            </form>

";
    }

    // line 105
    public function block_footerNav($context, array $blocks = array())
    {
        // line 106
        echo "    ";
        $context["footerMenu"] = $this->env->loadTemplate("::footer_admin_menu.html.twig");
        // line 107
        echo "    ";
        echo $context["footerMenu"]->getadmin_footer_nav("entity", "edit");
        echo "
";
    }

    public function getTemplateName()
    {
        return "AdminBundle:Centro:editar.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  334 => 107,  331 => 106,  328 => 105,  316 => 96,  310 => 93,  304 => 90,  299 => 88,  291 => 87,  285 => 84,  280 => 82,  272 => 81,  266 => 78,  261 => 76,  253 => 75,  247 => 72,  242 => 70,  234 => 69,  228 => 66,  223 => 64,  215 => 63,  209 => 60,  204 => 58,  196 => 57,  190 => 54,  185 => 52,  177 => 51,  171 => 48,  166 => 46,  158 => 45,  152 => 42,  147 => 40,  139 => 39,  135 => 38,  129 => 35,  125 => 34,  121 => 33,  117 => 32,  113 => 31,  109 => 30,  105 => 29,  101 => 28,  97 => 27,  94 => 26,  90 => 24,  85 => 21,  82 => 20,  76 => 18,  70 => 16,  65 => 15,  62 => 14,  55 => 11,  52 => 10,  49 => 9,  43 => 6,  38 => 5,  36 => 4,  33 => 3,);
    }
}


text:
class CartsController < ApplicationController
  # GET /carts
  # GET /carts.json
  def index
    @carts = Cart.all
    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @carts }
    end
  end

  # GET /carts/1
  # GET /carts/1.json
  def show
		begin
			@cart = Cart.find(params[:id])
		rescue ActiveRecord::RecordNotFound
			logger.error "Intentando acceder a una Cesta inexistente #{params[:id]}"
			redirect_to store_url, :notice => 'Cesta de la compra NO Valida'
		else
			if @cart.line_items.size == 0
				redirect_to store_url
			else
				respond_to do |format|
					format.html # show.html.erb
					format.xml { render :xml => @cart }
			  end
			end
		end
  end

  # GET /carts/new
  # GET /carts/new.json
  def new
    @cart = Cart.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @cart }
    end
  end

  # GET /carts/1/edit
  def edit
    @cart = Cart.find(params[:id])
  end

  # POST /carts
  # POST /carts.json
  def create
    @cart = Cart.new(params[:cart])

    respond_to do |format|
      if @cart.save
        format.html { redirect_to @cart, notice: 'Cart was successfully created.' }
        format.json { render json: @cart, status: :created, location: @cart }
      else
        format.html { render action: "new" }
        format.json { render json: @cart.errors, status: :unprocessable_entity }
      end
    end
  end

  # PUT /carts/1
  # PUT /carts/1.json
  def update
    @cart = Cart.find(params[:id])

    respond_to do |format|
      if @cart.update_attributes(params[:cart])
        format.html { redirect_to @cart, notice: 'Cart was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @cart.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /carts/1
  # DELETE /carts/1.json
  def destroy
    @cart = current_cart
    @cart.destroy
		session[:cart_id]=nil

    respond_to do |format|
      format.html { redirect_to(cart_url) } #, :notice => 'Your cart is currently empty') }
      format.xml { head :ok }
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
{% extends "_layouts/cp" %}
{% import "_includes/forms" as forms %}

{% if shortcutId is defined %}
    {% set shortcut = craft.shortcuts.getShortcutById(shortcutId) %}
    {% if not shortcut %}
        {% exit 404 %}
    {% endif %}
{% endif %}

{% set groups = craft.shortcuts.getAllGroups() %}
{% if not groups %}
    {% exit 404 %}
{% endif %}

{% set groupId = craft.request.getQuery('groupId') %}

{% if not groupId %}
    {% if shortcut is defined %}
        {% set groupId = shortcut.groupId %}
    {% else %}
        {% set groupId = groups|keys[0] %}
    {% endif %}
{% endif %}

{% if groups[groupId] is not defined %}
    {% exit 404 %}
{% endif %}

{% set shortcutUri = craft.request.getQuery('uri') %}
{% set shortcutCut = craft.request.getQuery('cut') %}

{% if not shortcutUri %}
    {% set shortcutUri = "" %}
{% endif %}

{% if shortcutCut %}
    {% set shortcutUri = shortcutUri ~ '?cut=' ~ shortcutCut %}
{% endif %}

{% set crumbs = [
    { label: "Shortcuts"|t, url: url('shortcuts') },
    { label: groups[groupId].name, url: url('shortcuts/'~groupId) }
] %}

{% if shortcutId is defined %}
    {% set title = shortcut.name %}
{% else %}
    {% set title = "Create a new shortcut"|t %}
{% endif %}

{% set content %}
    <form method="post" action="" accept-charset="UTF-8" data-saveshortcut="1">
        <input type="hidden" name="action" value="shortcuts/saveShortcut">
        <input type="hidden" name="redirect" value="shortcuts/">
        {% if shortcutId is defined %}
            <input type="hidden" name="shortcutId" value="{{ shortcutId }}">
        {% endif %}

        {% set groupOptions = [] %}
        {% for group in groups %}
            {% set groupOptions = groupOptions|merge([{ label: group.name, value: group.id }]) %}
        {% endfor %}
        {{ forms.selectField({
            first: true,
            label: "Group"|t,
            instructions: "Which group should this shortcut be displayed in?"|t,
            id: 'group',
            name: 'group',
            options: groupOptions,
            value: groupId
        }) }}

        {{ forms.textField({
            label: "Name"|t,
            instructions: "What this shortcut will be called in the CP."|t,
            id: 'name',
            name: 'name',
            value: (shortcut is defined ? shortcut.name : null),
            errors: (shortcut is defined ? shortcut.getErrors('name') : null),
            required: true,
            translatable: true,
            autofocus: true
        }) }}

        {{ forms.textField({
            label: "Uri"|t,
            instructions: "Where this shortcut should redirect you."|t,
            id: 'uri',
            class: 'code',
            name: 'uri',
            value: (shortcut is defined ? shortcut.uri : shortcutUri),
            errors: (shortcut is defined ? shortcut.getErrors('uri') : null),
            required: true,
        }) }}

            <input type="submit" class="btn submit" value="{{ 'Save'|t }}">

    </form>
{% endset %}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.derbypoc.app;

import java.util.Scanner;

import com.derbypoc.bo.CadastroPessoa;
import com.derbypoc.thirdparty.Flyway3rdParty;
import com.derbypoc.thirdparty.FlywayFactory;

/**
 *
 * @author WayAmadeus
 */
public class DerbyPOC {

	private static Scanner teclado;

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String[] args) {
		flywayMigration(); // create the DB with the scripts, using flyway lib.

		teclado = new Scanner(System.in);
		CadastroPessoa c = new CadastroPessoa();
		int op = 0;
		do {
			System.out
					.println("1 - Adicionar Pessoa\n2 - Remover Pessoa\n3 - Listar Pessoas");
			System.out.println("4 - Procurar Pessoa\n0 - Sair\n");
			op = teclado.nextInt();
			switch (op) {
			case 1:
				System.out.println(c.add());
				break;
			case 2:
				System.out.println(c.remove());
				break;
			case 3:
				System.out.println(c.getPessoas());
				break;
			case 4:
				System.out.println(c.procuraPessoa());
				break;
			}
		} while (op != 0);
	}

	private static void flywayMigration() {
		/*
		 * Só é preciso antes de rodar o flyway, que o banco esteja
		 * inicializado, ou seja que ele tenha uma string de conexao, pode se
		 * possível de que ao criar a conexao seja necessario que mude a string
		 * de conxao
		 */
		FlywayFactory facotry = new FlywayFactory();
		Flyway3rdParty flyway = facotry.createFactory("Derby");
		flyway.migrate();
	}

}


text:
import * as ts from 'typescript';

import { ReferenceType } from '../../models/types/index';
import { Context } from '../context';

/**
 * Create a new reference type pointing to the given symbol.
 *
 * @param context  The context object describing the current state the converter is in.
 * @param symbol  The symbol the reference type should point to.
 * @param includeParent  Should the name of the parent be provided within the fallback name?
 * @returns A new reference type instance pointing to the given symbol.
 */
export function createReferenceType(context: Context, symbol: ts.Symbol | undefined, includeParent?: boolean): ReferenceType | undefined {
    if (!symbol) {
        return;
    }

    const checker = context.checker;
    const id = context.getSymbolID(symbol)!;
    let name = checker.symbolToString(symbol);

    if (includeParent && symbol.parent) {
        name = checker.symbolToString(symbol.parent) + '.' + name;
    }

    return new ReferenceType(name, id);
}


text:
import java.util.Scanner;

public class TextAdventureProgram
{
    private Location[] locations;
    private Location currentLocation;
    private Scanner scanner;

    public Location[] GetLocations() { return locations; }
    public Location GetCurrentLocation() { return currentLocation; }

    public TextAdventureProgram()
    {
    }

    public void Start()
    {
    }

    public void Game()
    {
    }

    public void HandleUserChoice( String choice )
    {
    }

    public void Setup()
    {
    }
}


text:
package wcdi.mymusicplayer.widget;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import wcdi.common.widget.GenericAdapter;
import wcdi.mymusicplayer.R;
import wcdi.mymusicplayer.item.Song;

public class SongAdapter extends GenericAdapter<Song> {

    public SongAdapter(Context context, int resource) {
        super(context, resource);
    }

    private ViewHolder mViewHolder;

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        Song song = getItem(position);

        if (convertView == null) {

            convertView = super.getView(position, convertView, parent);

            mViewHolder = new ViewHolder();

            mViewHolder.track = (TextView) convertView.findViewById(R.id.fragment_song_track);
            mViewHolder.title = (TextView) convertView.findViewById(R.id.fragment_song_title);
            mViewHolder.time = (TextView) convertView.findViewById(R.id.fragment_song_time);

            convertView.setTag(mViewHolder);

        } else {

            mViewHolder = (ViewHolder) convertView.getTag();
        }

        // この書き方だと、多分track番号が100の音楽ファイルがトラック0になってしまうので対応策を考える
        if (song.mTrack != null) {
            String time = String.valueOf(Long.valueOf(song.mTrack) % 100);
            mViewHolder.track.setText(time);
        } else {
            mViewHolder.track.setText("0");
        }

        mViewHolder.title.setText(song.mTitle);

        // もう少しきれいに書ける気がする
        Long time = getItem(position).mTime / 1000;
        Long minute = time / 60;
        Long second = time % 60;
        mViewHolder.time.setText(String.format("%d:%02d", minute, second));

        return convertView;
    }

    static class ViewHolder {
        TextView track;
        TextView title;
        TextView time;
    }
}


text:
import React from 'react';
import PropTypes from 'prop-types';
import {
  FormattedMessage,
  injectIntl,
} from 'react-intl';

import {
  Button,
  Col,
  Modal,
  MultiColumnList,
  Row,
} from '@folio/stripes/components';

import {
  omit,
  orderBy,
  size,
} from 'lodash';

import {
  calculateSortParams,
  isRefundAllowed,
} from '../../util';

import css from './modal.css';

class WarningModal extends React.Component {
  static propTypes = {
    accounts: PropTypes.arrayOf(PropTypes.object),
    feeFineActions: PropTypes.arrayOf(PropTypes.object),
    onChangeAccounts: PropTypes.func.isRequired,
    open: PropTypes.bool,
    label: PropTypes.string,
    onClose: PropTypes.func.isRequired,
    intl: PropTypes.object.isRequired,
  };

  constructor(props) {
    super(props);
    this.state = {
      checkedAccounts: {},
      allChecked: true,
      sortOrder: ['Alert details', 'Fee/Fine type', 'Remaining', 'Payment Status', 'Item'],
      sortDirection: ['desc', 'asc']
    };
    this.sortMap = {
      'Alert details': this.getAlertDetailsFormatter,
      'Fee/Fine type': a => a.feeFineType,
      'Remaining': a => a.remaining,
      'Payment Status': a => (a.paymentStatus || {}).name,
      'Item': a => a.title,
    };
    this.onClickContinue = this.onClickContinue.bind(this);
  }

  componentDidUpdate(prevProps) {
    const accounts = this.props.accounts;
    const prevAccounts = prevProps.accounts;
    if (accounts !== prevAccounts) {
      // eslint-disable-next-line react/no-did-update-set-state
      this.setState({
        checkedAccounts: accounts.reduce((memo, a) => (Object.assign(memo, { [a.id]: a })), {}),
        allChecked: true,
      });
    }
  }

  toggleAll = (e) => {
    const accounts = this.props.accounts;

    const checkedAccounts = (e.target.checked)
      ? accounts.reduce((memo, a) => (Object.assign(memo, { [a.id]: a })), {})
      : {};

    this.setState(({ allChecked }) => ({
      allChecked: !allChecked,
      checkedAccounts
    }));
  }

  toggleItem = (e, a) => {
    e.stopPropagation();
    const id = a.id;
    const accounts = this.state.checkedAccounts;
    const checkedAccounts = (accounts[id])
      ? omit(accounts, id)
      : { ...accounts, [id]: a };
    const allChecked = size(checkedAccounts) === this.props.accounts.length;
    this.setState({ checkedAccounts, allChecked });
  }

  onSort = (e, meta) => {
    if (!this.sortMap[meta.alias]) return;

    const {
      sortOrder,
      sortDirection,
    } = this.state;

    this.setState(calculateSortParams({
      sortOrder,
      sortDirection,
      sortValue: meta.alias,
    }));
  };

  getAlertDetailsFormatter = (a) => {
    const {
      intl: { formatMessage },
      label,
      feeFineActions,
    } = this.props;

    const warningMessage = (
      <span className={css.alertDetails}>
        <FormattedMessage id="ui-users.accounts.actions.warning.deselect" />
      </span>
    );

    const showWarning = label === formatMessage({ id: 'ui-users.accounts.actions.refundFeeFine' })
      ? !isRefundAllowed(a, feeFineActions)
      : a?.status?.name === 'Closed';

    return showWarning ? warningMessage : '';
  };

  getAccountsFormatter() {
    const { checkedAccounts } = this.state;
    return {
      ' ': a => (
        <input
          checked={!!(checkedAccounts[a.id])}
          onClick={e => this.toggleItem(e, a)}
          type="checkbox"
        />
      ),
      'Alert details': this.getAlertDetailsFormatter,
      'Fee/Fine type': a => a.feeFineType || '',
      'Remaining': a => parseFloat(a.remaining).toFixed(2) || '0.00',
      'Payment Status': a => (a.paymentStatus || {}).name || '-',
      'Item': a => a.title || '',
    };
  }

  rowUpdater = (a) => {
    const { checkedAccounts } = this.state;
    return !!(checkedAccounts[a.id]);
  }

  onClickContinue() {
    const { checkedAccounts } = this.state;
    const values = Object.values(checkedAccounts);

    this.props.onChangeAccounts(values);
  }

  renderWarningMessage() {
    const {
      label,
      accounts = [],
      intl: {
        formatMessage,
      },
      feeFineActions,
    } = this.props;

    let action;
    let invalidItemsAmount = accounts.filter(a => a.status && a.status.name === 'Closed').length;
    let reason = <FormattedMessage id="ui-users.accounts.actions.warning.closedItems" />;
    const notAllowedToRefundItemsAmount = accounts.filter(a => !isRefundAllowed(a, feeFineActions)).length;
    const selectedItemsAmount = accounts.length;

    switch (label) {
      case formatMessage({ id: 'ui-users.accounts.actions.payFeeFine' }):
        action = <FormattedMessage id="ui-users.accounts.actions.warning.paymentAction" />;
        break;
      case formatMessage({ id: 'ui-users.accounts.actions.waiveFeeFine' }):
        action = <FormattedMessage id="ui-users.accounts.actions.warning.waiveAction" />;
        break;
      case formatMessage({ id: 'ui-users.accounts.actions.transferFeeFine' }):
        action = <FormattedMessage id="ui-users.accounts.actions.warning.transferAction" />;
        break;
      default:
        action = <FormattedMessage id="ui-users.accounts.actions.warning.refundAction" />;
        invalidItemsAmount = notAllowedToRefundItemsAmount;
        reason = <FormattedMessage id="ui-users.accounts.actions.warning.unpaidItems" />;
        break;
    }

    return (
      <FormattedMessage
        id="ui-users.accounts.actions.warning.summary"
        values={{
          selectedItemsAmount,
          invalidItemsAmount,
          action,
          reason,
        }}
      />
    );
  }

  render() {
    const {
      intl: { formatMessage },
      label,
      feeFineActions,
    } = this.props;

    const {
      sortOrder,
      sortDirection,
      allChecked,
      checkedAccounts,
    } = this.state;

    const accountOrdered = orderBy(this.props.accounts, [this.sortMap[sortOrder[0]], this.sortMap[sortOrder[1]]], sortDirection);
    const columnMapping = {
      ' ': <input id="warning-checkbox" type="checkbox" checked={allChecked} name="check-all" onChange={this.toggleAll} />,
      'Alert details': formatMessage({ id: 'ui-users.accounts.actions.warning.alertDetails' }),
      'Fee/Fine type': formatMessage({ id: 'ui-users.accounts.actions.warning.feeFineType' }),
      'Remaining': formatMessage({ id: 'ui-users.accounts.actions.warning.remaining' }),
      'Payment Status': formatMessage({ id: 'ui-users.accounts.actions.warning.paymentStatus' }),
      'Item': formatMessage({ id: 'ui-users.accounts.actions.warning.item' }),
    };

    const values = Object.values(checkedAccounts);

    const hasInvalidAccounts = values.some(a => {
      return label === formatMessage({ id: 'ui-users.accounts.actions.refundFeeFine' })
        ? !isRefundAllowed(a, feeFineActions)
        : a?.status?.name === 'Closed';
    });

    return (
      <Modal
        id="warning-modal"
        open={this.props.open}
        label={this.props.label}
        onClose={this.props.onClose}
        size="medium"
        dismissible
      >
        <Row>
          <Col xs>
            {this.renderWarningMessage()}
          </Col>
        </Row>
        <Row>
          <Col xs>
            <MultiColumnList
              id="warning-mcl"
              formatter={this.getAccountsFormatter()}
              columnMapping={columnMapping}
              columnWidths={{ ' ': 28, 'Alert details':160, 'Fee/Fine type':140, 'Remaining':80, 'Payment Status':140, 'Item':160 }}
              visibleColumns={[' ', 'Alert details', 'Fee/Fine type', 'Remaining', 'Payment Status', 'Item']}
              onHeaderClick={this.onSort}
              sortOrder={sortOrder[0]}
              sortDirection={`${sortDirection[0]}ending`}
              contentData={accountOrdered}
              rowUpdater={this.rowUpdater}
            />
          </Col>
        </Row>
        <Row
          end="xs"
          className={css.lastRow}
        >
          <Col xs>
            <Button
              id="warningTransferCancel"
              onClick={this.props.onClose}
            >
              <FormattedMessage id="ui-users.feefines.modal.cancel" />
            </Button>
            <Button
              id="warningTransferContinue"
              disabled={hasInvalidAccounts || values.length === 0}
              buttonStyle="primary"
              onClick={this.onClickContinue}
            >
              <FormattedMessage id="ui-users.feefines.modal.submit" />
            </Button>
          </Col>
        </Row>
      </Modal>
    );
  }
}

export default injectIntl(WarningModal);


text:
import {ArkhamConstants} from './constants/ArkhamConstants';
import {Flux, FluxFramework} from './Flux/Flux';

export * from './Flux/Flux.types';
export {ArkhamConstants, Flux, FluxFramework};


text:
package brokers

import (
	"strconv"
	"strings"
	"time"
)

// PrepareTask is the task that prepared to join queue
type PrepareTask struct {
	ID        string      `json:"id"`
	Name      string      `json:"task"`
	Command   TaskCommand `json:"command"`
	Channel   string      `json:"chan"`
	Timestamp int64       `json:"ts"`
	ExecuteAt int64       `json:"execute_at"`
}

// Task represent a task object
type Task struct {
	ID           string      `json:"task_id"`
	TaskName     string      `json:"task_name"`
	Command      TaskCommand `json:"command"`
	Channel      string      `json:"channel"`
	Status       string      `json:"status"`
	ExecAt       time.Time   `json:"execute_at"`
	RetryCount   int         `json:"retry_count"`
	FailedAt     time.Time   `json:"failed_at"`
	WriteBackend bool        `json:"write_backend"`
}

// TaskCommand represent a task command object
type TaskCommand struct {
	Name string        `json:"name"`
	Args []interface{} `json:"args"`
}

// Channel is the command queue
type Channel struct {
	Name        string        `json:"name"`
	Task        chan Task     `json:"-"`
	Distinct    bool          `json:"distinct"`
	WorkerCount int           `json:"worker_count"`
	StopChan    chan struct{} `json:"-"`
	OutputChan  chan Output   `json:"-"`
}

// Output 任务执行输出
type Output struct {
	ProcessID string
	Type      string // 输出类型: stdout/stderr
	Task      Task
	Content   string
}

// Format format command struct to string
func (cmd TaskCommand) Format() string {
	return cmd.Name + " " + strings.Join(cmd.GetArgsString(), " ")
}

// GetArgsString 以字符串数组的形式返回参数集合
func (cmd TaskCommand) GetArgsString() []string {
	res := make([]string, len(cmd.Args))

	for i, s := range cmd.Args {
		switch s.(type) {
		case string:
			res[i] = s.(string)
		case float64:
			res[i] = strconv.FormatFloat(s.(float64), 'f', -1, 64)
		}
	}

	return res
}


text:
class ApplicationController < ActionController::Base
  before_filter :instantiate_controller_and_action_names
  filter_parameter_logging :password, :password_confirmation
  helper_method :current_user_session, :current_user

  # Pick a unique cookie name to distinguish our session data from others'
  session_options['session_key'] = '_spree_session_id'

  protect_from_forgery # See ActionController::RequestForgeryProtection for details

  #include AuthenticatedSystem
  include RoleRequirementSystem
  include EasyRoleRequirementSystem
  include SslRequirement

  private
    def current_user_session
      return @current_user_session if defined?(@current_user_session)
      @current_user_session = UserSession.find
    end

    def current_user
      return @current_user if defined?(@current_user)
      @current_user = current_user_session && current_user_session.user
    end

    def require_user
      unless current_user
        store_location
        flash[:notice] = "You must be logged in to access this page"
        redirect_to new_user_session_url
        return false
      end
    end

    def require_no_user
      if current_user
        store_location
        flash[:notice] = "You must be logged out to access this page"
        redirect_to account_url
        return false
      end
    end

    def store_location
      session[:return_to] = request.request_uri
    end

    def redirect_back_or_default(default)
      redirect_to(session[:return_to] || default)
      session[:return_to] = nil
    end

    # Redirect as appropriate when an access request fails.
    #
    # The default action is to redirect to the login screen.
    #
    # Override this method in your controllers if you want to have special
    # behavior in case the user is not authorized
    # to access the requested action.  For example, a popup window might
    # simply close itself.
    def access_denied
      respond_to do |format|
        format.html do
          if current_user
            flash[:error] = t("authorization_failure")
            redirect_to '/user_sessions/authorization_failure'
            next
          else
            store_location
            redirect_to login_path
            next
          end
        end
        format.xml do
          request_http_basic_authentication 'Web Password'
        end
      end
    end

    def instantiate_controller_and_action_names
      @current_action = action_name
      @current_controller = controller_name

      @taxonomies = Taxonomy.find(:all, :include => {:root => :children})
    end
end


text:
package com.lee.main.matrix;

import android.os.Bundle;
import android.support.annotation.Nullable;

import com.lee.base.activity.BaseActivity;

/**
 * Created by LiYang on 2019/5/5.
 */
public class MatrixActivity extends BaseActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

}


text:
import React from 'react';
import {connect} from 'react-redux';

class Details extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  render() {
    const styles = {
      fontFamily: 'Helvetica Neue',
      fontSize: 14,
      lineHeight: '10px',
      color: 'white',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
    }
    return (
      <div>
        Details
      </div>
    );
  }
}

export default Details;


text:
package org.mustbe.consulo.unity3d.shaderlab.lang.psi;

import org.jetbrains.annotations.NotNull;
import com.intellij.lang.ASTNode;

/**
 * @author VISTALL
 * @since 09.05.2015
 */
public class ShaderTag extends ShaderLabElement
{
	public ShaderTag(@NotNull ASTNode node)
	{
		super(node);
	}

	@Override
	public void accept(SharpLabElementVisitor visitor)
	{
		visitor.visitTag(this);
	}
}


text:
'use strict';

(function doNotRunInProduction() {
  var environment    = process.env.NODE_ENV || '';
  var okay_to_delete = {
    ci:        true,
    test:      true,
    localdev:  true,
    localtest: true
  };

  if (!okay_to_delete[environment]) {
    console.error("!!!\n!!! Tests should only be run in a test environment.  Aborting.\n!!!");
    process.exit(1);
  }
})();

var fs     = require('fs');
var chai   = require('chai');
var expect = exports.expect = chai.expect;
chai.use(require('dirty-chai'));
chai.use(require('sinon-chai'));
chai.use(require('chai-datetime'));
chai.config.includeStack = true;

require('mocha-sinon');

var mysql = require('mysql2');

exports.test_db_config = {
  host:             '127.0.0.1',
  user:             'root',
  password:         '',
  database:         'dbqueue_testing_db',
  connectionLimit:  10,
};

var db = exports.test_db = mysql.createPool(exports.test_db_config);

before(function(done) {
  // init the DB schema
  var table_schema;

  function createTable(table_name, done) {
    var sql = table_schema.replace('CREATE TABLE jobs', 'CREATE TABLE ' + table_name);

    return db.query(sql, function(err) {
      expect(err).to.not.exist();

      done();
    });
  }

  function lazilyCreateTable(table_name, done) {
    db.query("SHOW TABLES LIKE '" + table_name + "'", function(err, rows, fields) {
      expect(err).to.not.exist();

      if (rows.length) {
        return done();
      }

      if (table_schema) {
        return createTable(table_name, done);
      }

      fs.readFile(__dirname + '/../schema.sql', function(err, buffer) {
        expect(err).to.not.exist();

        table_schema = buffer.toString();

        return createTable(table_name, done);
      });
    });
  }

  lazilyCreateTable('jobs', function(err) {
    expect(err).to.not.exist();

    return lazilyCreateTable('custom_jobs_table', function(err) {
      expect(err).to.not.exist();

      return done();
    });
  });
});

beforeEach(function(done) {
  db.query('DELETE FROM jobs', function(err, rows, fields) {
    expect(err).to.not.exist();

    db.query('DELETE FROM custom_jobs_table', function(err, rows, fields) {
      expect(err).to.not.exist();

      return done();
    });
  });
});

/*
create table `attempt_batches` (
  `id` bigint unsigned not null auto_increment primary key,
  `payer_account_id` bigint not null,
  `proposal_id` bigint not null,
  `status` enum('pending', 'processing', 'submitted', 'failed') default 'pending',
  `create_time` timestamp default CURRENT_TIMESTAMP,
  `update_time` timestamp default '1970-01-02 00:00:00'
);
*/


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

  <title>CMAKE_MODULE_LINKER_FLAGS_INIT — CMake 3.7.1 Documentation</title>

    <link rel="stylesheet" href="../_static/cmake.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/cmake-favicon.ico"/>
    <link rel="top" title="CMake 3.7.1 Documentation" href="../index.html" />
    <link rel="up" title="cmake-variables(7)" href="../manual/cmake-variables.7.html" />
    <link rel="next" title="CMAKE_NINJA_OUTPUT_PATH_PREFIX" href="CMAKE_NINJA_OUTPUT_PATH_PREFIX.html" />
    <link rel="prev" title="CMAKE_MODULE_LINKER_FLAGS" href="CMAKE_MODULE_LINKER_FLAGS.html" />

Navigation

          index

          next |

          previous |

    CMake »

    3.7.1 Documentation »

cmake-variables(7) »

CMAKE_MODULE_LINKER_FLAGS_INIT¶

Value used to initialize the CMAKE_MODULE_LINKER_FLAGS
cache entry the first time a build tree is configured.
This variable is meant to be set by a toolchain file.  CMake may prepend or append content to
the value based on the environment and target platform.

See also the configuration-specific variable
CMAKE_MODULE_LINKER_FLAGS_<CONFIG>_INIT.

Previous topic

CMAKE_MODULE_LINKER_FLAGS

Next topic

CMAKE_NINJA_OUTPUT_PATH_PREFIX

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          next |

          previous |

    CMake »

    3.7.1 Documentation »

cmake-variables(7) »

        © Copyright 2000-2016 Kitware, Inc. and Contributors.
      Created using Sphinx 1.4a0+.


text:
package org.apache.causeway.testdomain.util;

import java.sql.SQLException;

public class Util_H2Console {

    public static void main(String[] args) throws SQLException {
        org.h2.tools.Console.main(args);
    }

}


text:
extern const struct luaL_Reg CvPoint2D64f_m[];
#endif


text:
<?php

namespace frontend\models;

use Yii;

/**
 * This is the model class for table "status_active".
 *
 * @property integer $id
 * @property string $status_name
 *
 * @property StatusDescription[] $statusDescriptions
 */
class StatusActive extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'status_active';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['status_name'], 'required'],
            [['status_name'], 'string', 'max' => 100]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'status_name' => 'สถานะการทบทวน',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getStatusDescriptions()
    {
        return $this->hasMany(StatusDescription::className(), ['status_active_id' => 'id']);
    }
}


text:
package com.jamesmorrisstudios.appbaselibrary.dialogRequests;

import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import java.util.ArrayList;

/**
 * Request to build a file browser dialog.
 * Call execute to display the dialog
 * <p/>
 * Created by James on 10/2/2015.
 */
public final class FileBrowserRequest extends AbstractDialogRequest {
    public final DirType dirType;
    public final OnFileBrowserRequestListener onFileBrowserRequestListener;
    public final boolean allowCreateDir;
    public final boolean allowMultiSelect;
    public final String extension;

    /**
     * @param dirType                      Directory type
     * @param allowCreateDir               Allow the user to create a new directory
     * @param extension                    Allowed file extensions to sort on comma separated in form of ".png,.jpg". Null will execute all files.
     * @param onFileBrowserRequestListener Listener
     */
    public FileBrowserRequest(@NonNull final DirType dirType, final boolean allowCreateDir, final boolean allowMultiSelect, @Nullable final String extension, @NonNull final OnFileBrowserRequestListener onFileBrowserRequestListener) {
        this.dirType = dirType;
        this.allowCreateDir = allowCreateDir;
        this.allowMultiSelect = allowMultiSelect;
        this.extension = extension;
        this.onFileBrowserRequestListener = onFileBrowserRequestListener;
    }

    /**
     * Possible selection types. File or directory.
     */
    public enum DirType {
        FILE, DIRECTORY
    }

    /**
     * Listener
     */
    public interface OnFileBrowserRequestListener {

        /**
         * @param path Path to the selected item
         */
        void itemSelected(@Nullable final Uri path);

        /**
         * @param path Path to the selected items
         */
        void multiItemSelected(@Nullable final ArrayList<Uri> path);

        /**
         * No item selected
         */
        void canceled();
    }

}


text:
Categories

  Electronics

  Software

  Clothes

  Food

  Deals of the day

help & Support

  Item Return Policy

  Call center

  Terms and Conditions

  Help

  Location

Join the community!

Sign up and join our wide ecosystem, become part of BlueBook.

                <button type="button" class="btn btn-primary  " data-toggle="modal" data-target="#SignUpModel">
                    Sign Up
                </button>

            <?php

            if (!empty($_SESSION["user"])) {

            ?>

Recommendation

                <?php
                //slider is our container
                //this is a biased recommendation as it favours item to item personalised
                //over content based recommendation
                //it was done in order to solve the cold start problem

                //If the user is online then we can start recommending him some items
                //we are going to use the recommendation class alongside the

                $item_to_item = new Recommendation();
                $find_item = new Product_Finder();

                $all_items = $find_item->all_products(new Product_DB_Handler());

                $user = $_SESSION["user"];

                $recommendations = array();
                $productID = array();

                //content based recommendations

                //this enables us to get all the distinct searches made by the user
                //we can compare these searches to content in our products
                //enabling us to recommend content based recommendations
                $userProfile = new UserProfile($user);
                $search = $userProfile->get_user_searches(new Product_DB_Handler());

                //first we add our personalised recommendation before
                //content in order to give them the highest priority
                //we add them in therms of their ratings so the highest first lowest last

                foreach ($all_items as $product_id => $item_data) {

                    $prediction = $item_to_item->personalised_recommendation($user, $item_data["ProductID"]);

                    if ($prediction > 0) {
                        array_push($recommendations, $prediction);
                        array_push($productID, $item_data["ProductID"]);
                    }
                }

                $personalised_Recommendations = array_combine($productID, $recommendations);

                //Personalised recommendation

                //here is were we actually populate the basket or container with our personalised recommendations
                foreach ($personalised_Recommendations as $item => $data) {

                    $find_item = new Product_Finder();
                    $personalised_item = $find_item->find_item($item, new Product_DB_Handler());

                    ?>

                    <?php //$personalised_item[0]["Name"];
                    ?><?php //echo $personalised_item[0]["ProductID"]
                    ?>
                    <?php //echo $personalised_item[0]["Category"]."/".$personalised_item[0]["Location"];
                    ?>

                    <li data-toggle="tooltip" data-placement="top" title="<?php $personalised_item[0]["Name"]; ?>"><a a
                                                                                href="Item.php?product_id=<?php echo $personalised_item[0]["ProductID"] ?>"><img
                                    src="../<?php echo $personalised_item[0]["Category"] . "/" . $personalised_item[0]["Location"]; ?>"
                                    class="img-responsive img-rounded" height="70px" width="70px">

                    <?php

                }

                //After we populated our basket with our personalised item to item recommendations
                //we simply populate our content based recommendation next
                //this creates a priority as the ones always shown first are the personalised recommendations
                foreach ($search as $query) {

                    $count = 0; // we are only adding 1 content recommendation per user search
                    $search_handler = new Search_handler($query);
                    $similarities = $search_handler->fetch_Search(new Product_DB_Handler());

                    foreach ($similarities as $similarity => $content_item) {

                        if ($count == 1) break; // only recommend 1 content based items per user search

                        ?>

                        <li data-toggle="tooltip" data-placement="top"
                            title="<?php $content_item["Name"]; ?>"><a
                                    href="Item.php?product_id=<?php echo $content_item["ProductID"] ?>"><img
                                        src="../<?php echo $content_item["Category"] . "/" . $content_item["Location"]; ?>"
                                        class="img-responsive img-rounded" height="70px" width="70px"></>

                        <?php

                        $count++;
                    }
                }

                }
            ?>

 |

            <bold style = "color: black;">Copyright  © 2017</bold> <bold style="color: blue">BlueBook</bold>


text:
<?xml version="1.0"?>
<Runs Version="1" Minor="0">
	<Run Id="impl_1" LaunchDir="D:/Documentos/Documentos/CIDIC/vivado/picorv32_vivado/picorv32_vivado.runs/impl_1" FlowId="Vivado_Implementation" FromStepId="init_design" ToStepId="write_bitstream"/>
</Runs>


text:
using System;

package com.quantconnect.lean.Indicators
{
    /**
     * This indicator computes the Kaufman Adaptive Moving Average (KAMA).
     * The Kaufman Adaptive Moving Average is calculated as explained here:
     * http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:kaufman_s_adaptive_moving_average
    */
    public class KaufmanAdaptiveMovingAverage : WindowIndicator<IndicatorDataPoint>
    {
        private static final BigDecimal ConstMax = 2m / (30m + 1m);
        private static final BigDecimal ConstDiff = 2m / (2m + 1m) - ConstMax;

        private BigDecimal _sumRoc1;
        private BigDecimal _periodRoc;
        private BigDecimal _prevKama;
        private BigDecimal _trailingValue;

        /**
         * Initializes a new instance of the <see cref="KaufmanAdaptiveMovingAverage"/> class using the specified name and period.
        */
         * @param name The name of this indicator
         * @param period The period of the KAMA
        public KaufmanAdaptiveMovingAverage( String name, int period)
            : base(name, period + 1) {
        }

        /**
         * Initializes a new instance of the <see cref="KaufmanAdaptiveMovingAverage"/> class using the specified period.
        */
         * @param period The period of the KAMA
        public KaufmanAdaptiveMovingAverage(int period)
            : this( "KAMA" + period, period) {
        }

        /**
         * Gets a flag indicating when this indicator is ready and fully initialized
        */
        public @Override boolean IsReady
        {
            get { return Samples >= Period; }
        }

        /**
         * Computes the next value of this indicator from the given state
        */
         * @param input The input given to the indicator
         * @param window The window for the input history
        @returns A new value for this indicator
        protected @Override BigDecimal ComputeNextValue(IReadOnlyWindow<IndicatorDataPoint> window, IndicatorDataPoint input) {
            if( Samples < Period) {
                if( Samples > 1) {
                    _sumRoc1 += Math.Abs(input.Value - window[1].Value);
                }

                return input.Value;
            }

            if( Samples == Period) {
                _sumRoc1 += Math.Abs(input.Value - window[1].Value);

                // At this point sumROC1 represents the
                // summation of the 1-day price difference
                // over the (optInTimePeriod-1)

                // Calculate the first KAMA
                // The yesterday price is used here as the previous KAMA.
                _prevKama = window[1].Value;
            }

            newTrailingValue = window[Period - 1];
            _periodRoc = input.Value - newTrailingValue;

            if( Samples > Period) {
                // Adjust sumROC1:
                // - Remove trailing ROC1
                // - Add new ROC1
                _sumRoc1 -= Math.Abs(_trailingValue - newTrailingValue);
                _sumRoc1 += Math.Abs(input.Value - window[1].Value);
            }

            // Save the trailing value.
            _trailingValue = newTrailingValue;

            // Calculate the efficiency ratio
            efficiencyRatio = (_sumRoc1 <= _periodRoc) || _sumRoc1 == 0 ? 1m : Math.Abs(_periodRoc / _sumRoc1);

            // Calculate the smoothing constant
            smoothingConstant = efficiencyRatio * ConstDiff + ConstMax;
            smoothingConstant *= smoothingConstant;

            // Calculate the KAMA like an EMA, using the
            // smoothing constant as the adaptive factor.
            _prevKama = (input.Value - _prevKama) * smoothingConstant + _prevKama;

            return _prevKama;
        }

        /**
         * Resets this indicator to its initial state
        */
        public @Override void Reset() {
            _sumRoc1 = 0;
            _periodRoc = 0;
            _prevKama = 0;
            _trailingValue = 0;
            base.Reset();
        }
    }
}


text:
/*******************************************************************************
 * ALGORITHM IMPLEMENTAIONS
 *
 *  /\  |  _   _  ._ o _|_ |_  ._ _   _
 * /--\ | (_| (_) |  |  |_ | | | | | _>
 *         _|
 *
 * BUBBLE SORT
 *
 *   Bubble sort, sometimes incorrectly referred to as sinking sort, is a simple
 * sorting algorithm that works by repeatedly stepping through the list to be
 * sorted, comparing each pair of adjacent items and swapping them if they are
 * in the wrong order. The pass through the list is repeated until no swaps are
 * needed, which indicates that the list is sorted. The algorithm gets its name
 * from the way smaller elements "bubble" to the top of the list. Because it
 * only uses comparisons to operate on elements, it is a comparison sort.
 * Although the algorithm is simple, most of the other sorting algorithms are
 * more efficient for large lists.
 *
 * http://en.wikipedia.org/wiki/Bubble_sort
 ******************************************************************************/

#ifndef _BUBBLE_SORT_H_
#define _BUBBLE_SORT_H_

#include <assert.h>
#include <generic.h>

namespace alg {
	template<typename T>
		static void	BubbleSort(T list[], int start, int end){
			int i;
			bool swapped;

			assert(start < end);

			do {
				swapped = false;
				for(i = start+1; i <= end; i++) {
					if(list[i-1] > list[i]) {
						// swap them and remember something changed
						swap(list[i-1], list[i]);
						swapped = true;
					}
				}
			} while(swapped);
		}
}

#endif // _BUBBLE_SORT_H_


text:
@layout('master')

@section('container')

List of modules

{{ HTML::link_to_action('modules@new', 'Create a New Module', array(), array('class' => 'btn btn-primary create-btn')) }}

			ID
			Name
			Controller
			Description
			Order
			Action

@if ($modules)
	@foreach ($modules as $module)

			{{ $module->id }}
			{{ $module->name }}
			{{ $module->controller }}
			{{ $module->description }}
			{{ $module->order }}

				{{ HTML::link_to_action('modules@edit', 'Edit', array($module->id), array('class' => 'btn btn-warning')) }}
				{{ HTML::link_to_action('modules@destroy', 'Delete', array($module->id), array('class' => 'btn btn-danger', 'data-method' => 'delete')) }}

	@endforeach
@endif

@endsection


text:
package org.apache.jackrabbit.oak.security.authorization.accesscontrol;

import javax.jcr.security.AccessControlException;

import com.google.common.collect.ImmutableList;
import org.apache.jackrabbit.oak.spi.xml.ImportBehavior;
import org.junit.Test;

public class AccessControlImporterAbortTest extends AccessControlImporterBaseTest{

    @Override
    String getImportBehavior() {
        return ImportBehavior.NAME_ABORT;
    }

    @Test(expected = AccessControlException.class)
    public void testStartAceChildInfoUnknownPrincipal() throws Exception {
        init();
        importer.start(aclTree);
        importer.startChildInfo(aceInfo, ImmutableList.of(unknownPrincipalInfo));
    }
}


text:
<?php

$mysqli = new mysqli("localhost", "php", "senha", "teste");

if ($mysqli->connect_errno) {
    die('Não foi possível conectar-se ao banco de dados: ' . $mysqli->connect_errno);
    exit();
}

$result = $mysqli->query("SELECT mensagem AS field FROM mensagem");

while($row = $result->fetch_assoc()){
    echo $row['field'] . '<br>';
}

$data = date('U');
$mysqli->query('INSERT INTO mensagem (mensagem) VALUES ("Nova Mensagem ' . $data . '")');

$mysqli->close();


text:
import argparse
import html
from net_deserializer.node import Node, LeafNode
from net_deserializer.records import deserialize

def dump(node, indent, prefix=''):
    if isinstance(node, LeafNode):
        if node.has_value():
            print(prefix + '<{name}>{value}</{name}>'.format(
                name=node.name, value=html.escape(str(node.value))))
        else:
            print(prefix + '<{name}/>'.format(name=node.name))
    elif isinstance(node, Node):
        print(prefix + '<{name}>'.format(name=node.name))
        for child in node.children:
            if child.name != 'MembersMeta':
                dump(child, indent, indent + prefix)
        print(prefix + '</{name}>'.format(name=node.name))
    else:
        print(node)
        assert False

def parse_args():
    parser = argparse.ArgumentParser(description='Deserialize .NET stream')
    parser.add_argument(
        metavar='PATH', dest='input_path',
        help='where to read the input data from')
    return parser.parse_args()

def main(args):
    with open(args.input_path, 'rb') as handle:
        root_node = deserialize(handle)
        dump(root_node, indent=' '*4)

if __name__ == '__main__':
    main(parse_args())


text:
let passport = require('passport');
let passportJWT = require('passport-jwt');

let User = require('../models/user').model;
let config = require('../config');

let ExtractJwt = passportJWT.ExtractJwt;
let JwtStrategy = passportJWT.Strategy;

let strategy = new JwtStrategy({
    jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
    secretOrKey: config.secret
}, function(jwt, next) {
    User.findOne({
        email: jwt.email
    }, (err, user) => {
        if (user) {
            next(null, user.safeToSend(true));
        } else {
            next(null, false);
        }
    });
});

passport.use(strategy);

module.exports = {
    passport: passport,
    prefix: '/api'
};


text:
package edu.umn.pubsub.common.exception;

/**
 * Thrown when the max article length is exceeded.
 * @author prashant
 *
 */
public class MaxArticleLengthExceededException extends Exception{

	private static final long serialVersionUID = 6981059015521417878L;

	public MaxArticleLengthExceededException() {
		super();
	}

	public MaxArticleLengthExceededException(String s) {
		super(s);
	}

}


text:
export default ({width, height}) => ({
  orientation: width > height ? 'landscape' :
                                width === height ? 'square' : 'portrait'
})


text: README: thermostats


text:
<form name="form" class="form-horizontal" novalidate>

    <ng-include src="pages.templateSelection"></ng-include>

    <loading-spinner size="'small'"></loading-spinner>

    <v2-modal-wizard ng-show="state.loaded" heading="{{title}}" task-monitor="taskMonitor" dismiss="$dismiss()">
      <v2-wizard-page key="location" label="Basic Settings" mark-complete-on-view="false">
        <ng-include src="pages.basicSettings"></ng-include>
      </v2-wizard-page>
      <v2-wizard-page key="load-balancers" label="Load Balancers" mark-complete-on-view="false">
        <ng-include src="pages.loadBalancers"></ng-include>
      </v2-wizard-page>
      <v2-wizard-page key="security-groups" label="{{firewallsLabel}}" done="true">
        <ng-include src="pages.securityGroups"></ng-include>
      </v2-wizard-page>
      <v2-wizard-page key="instance-type" label="Instance Type" mark-complete-on-view="false">
        <ng-include src="pages.instanceType"></ng-include>
      </v2-wizard-page>
      <v2-wizard-page key="capacity" label="Capacity" mark-complete-on-view="false">
        <ng-include src="pages.capacity"></ng-include>
      </v2-wizard-page>
      <v2-wizard-page key="autoscaling-policy" label="Autoscaling Policy" mark-complete-on-view="false">
        <ng-include src="pages.autoScalingPolicy"></ng-include>
      </v2-wizard-page>
      <v2-wizard-page key="autohealing-policy" label="Autohealing Policy" mark-complete-on-view="false">
        <ng-include src="pages.autoHealingPolicy"></ng-include>
      </v2-wizard-page>
      <v2-wizard-page key="zones" label="Zones" mark-complete-on-view="false" done="true">
        <ng-include src="pages.zones"></ng-include>
      </v2-wizard-page>
      <v2-wizard-page key="advanced" label="Advanced Settings" mandatory="false" done="true">
        <ng-include src="pages.advancedSettings"></ng-include>
      </v2-wizard-page>
    </v2-modal-wizard>

      <button ng-disabled="taskMonitor.submitting" class="btn btn-default btn-cancel" ng-click="ctrl.cancel()">
        Cancel
      </button>
      <submit-button
        ng-if="ctrl.showSubmitButton()"
        is-disabled="!ctrl.isValid() || taskMonitor.submitting"
        label="command.viewState.submitButtonLabel"
        submitting="taskMonitor.submitting"
        on-click="ctrl.submit()"
        is-new="true"
      ></submit-button>

</form>


text:
import os
import time
import sys
import uuid
from threading import Thread

import yaml
from PyQt4.QtGui import *
from PyQt4.QtCore import *
import libtorrent as lt
from pytvdbapi import api as TVDB

from tpb import TPB, ORDERS as TPB_ORDERS

from ui.mainWindow import Ui_MainWindow
from libs.progress import Progress

class ZTorrent:
    def __init__(self, handler):
        self.handler = handler
        self.data = {}

    def update(self, **kwargs):
        for key, value in kwargs.items():
            self.data[key] = value

    def get(self, key):
        try:
            return self.data[key]
        except KeyError:
            return None

class DownloadManager:
    lt_states_str = ['queued', 'checking', 'downloading metadata',
                     'downloading', 'finished', 'seeding',
                     'allocating', 'checking fast-resume']

    def __init__(self, instance):
        self.instance = instance
        self.session = lt.session()
        self.session.listen_on(6881, 6891)
        self.session.add_dht_router("router.utorrent.com", 6881)
        self.session.start_dht(self.session)

        self.torrents = {}

    def add_magnet(self, magnet, completion_callback=None, play_callback=None):
        uid = uuid.uuid4().hex
        self.torrents[uid] = ZTorrent(
            lt.add_magnet_uri(self.session, magnet, {'save_path': self.instance.settings.get('save_path')}))
        self.torrents[uid].handler.set_sequential_download(True)
        download_speed_limit = self.instance.settings.get('download_speed_limit')
        if download_speed_limit is not None and download_speed_limit > 0:
            self.torrents[uid].handler.set_download_limit(download_speed_limit * 1000)
        Thread(target=self.download_worker, args=(self.torrents[uid], completion_callback, play_callback,)).start()
        return self.torrents[uid]

    def get_torrents(self):
        return self.session.get_torrents(self.session)

    def download_worker(self, torrent, completion_callback=None, play_callback=None):
        while not torrent.handler.has_metadata():
            time.sleep(.1)
        info = torrent.handler.get_torrent_info()
        eta = Progress(info.total_size())
        launch_at = self.instance.settings.get('launch_video_percent')
        launched = False
        while not torrent.handler.is_seed():
            eta.increment()
            status = torrent.handler.status()
            torrent.update(
                progress=status.progress * 100,
                download_rate=status.download_rate / 1000,
                upload_rate=status.upload_rate / 1000,
                num_peers=status.num_peers,
                state=self.lt_states_str[status.state],
                eta=str(eta.time_remaining())
            )
            if (not launched and launch_at > 0 and status.progress >= launch_at / 100
                and status.state in [3, 4, 5]):
                if play_callback:
                    play_callback(torrent)
                launched = True
            time.sleep(1)
        torrent.update(progress=100)
        if completion_callback:
            completion_callback(torrent)

class Settings:
    class SettingsException(Exception):
        pass

    def __init__(self, path=None):
        if path is None:
            print('[WARNING] Settings: path is not set, the configuration will not be saved')
        self.path = path
        self.store = None

    def load(self):
        self.store = yaml.load(open(self.path))

    def save(self):
        yaml.dump(self.store, open(self.path, 'w'), default_flow_style=False)

    def get(self, key):
        if self.store is None:
            self.store = {}
        try:
            return self.store[key]
        except KeyError:
            return None

    def set(self, key, value):
        if self.store is None:
            self.store = {}
        self.store[key] = value

class ZTShows:
    def __init__(self):
        self.settings = Settings('config.yml')
        self.download_manager = DownloadManager(self)
        self.api_tpb = None
        self.api_tvdb = None

    def load(self):
        self.settings.load()

        tpb_base_url = self.settings.get('tpb_base_url')
        self.api_tpb = TPB('https://thepiratebay.se' if not tpb_base_url else tpb_base_url)
        tvdb_api_key = self.settings.get('tvdb_api_key')
        self.api_tvdb = TVDB.TVDB('81DD35DB106172E7' if not tvdb_api_key else tvdb_api_key)

    def unload(self):
        self.settings.save()

    def search(self, query, callback):
        def work(w_callback):
            w_callback(self.api_tvdb.search(query, 'en'))

        Thread(target=work, args=(callback,)).start()
        print(self.download_manager.get_torrents())

    def search_episode(self, episode, callback):
        def work(w_callback):
            results = self.api_tpb.search(query).order(TPB_ORDERS.SEEDERS.DES)
            w_callback(results)

        query = '{} s{:02d}e{:02d}'.format(episode.season.show.SeriesName,
                                           episode.season.season_number,
                                           episode.EpisodeNumber)
        Thread(target=work, args=(callback,)).start()

    def download(self, torrent, completion_callback=None, play_callback=None):
        self.download_manager.add_magnet(torrent.magnet_link, completion_callback, play_callback)

    def open_player(self, torrent):
        def work(path):
            os.system(path)

        player_path = self.settings.get('player_path').format(
            video='"' + self.settings.get('save_path') + torrent.handler.name() + '"', subtitles='')
        t = Thread(target=work, args=(player_path,)).start()
        t.daemon = True

class CustomProgressBar(QProgressBar):
    def __init__(self, parent=None):
        super(CustomProgressBar, self).__init__(parent)
        self.restore()

    def restore(self):
        self.setTextVisible(False)
        self.setValue(0)
        self.setRange(0, 1)

    def indeterminate(self):
        self.setTextVisible(False)
        self.setValue(0)
        self.setRange(0, 0)

    def start(self, max_value):
        self.setTextVisible(True)
        self.setValue(0)
        self.setRange(0, max_value)

    def progress(self, current_value):
        self.setTextVisible(True)
        self.setValue(current_value)

class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, instance):
        super(MainWindow, self).__init__()
        self.instance = instance
        self.instance.load()
        self.progress = None

        self.setupUi(self)
        self.init_ui()

    def init_ui(self):
        self.init_menu()
        self.init_tabs()
        self.setCentralWidget(self.tabWidget)
        self.setMinimumSize(600, 400)
        self.init_status_bar()
        self.setWindowTitle('ZTShows - Be simple')
        self.show()

    def init_status_bar(self):
        self.progress = CustomProgressBar()
        self.statusBar().showMessage('Ready')
        self.statusBar().addPermanentWidget(self.progress)

    def init_menu(self):
        def exit_now():
            self.instance.unload()
            qApp.quit()

        self.actionExit.triggered.connect(exit_now)
        self.actionSoftExit.triggered.connect(exit_now)

    def init_tabs(self):
        self.search_series_tab_init()
        self.settings_tab_init()

    def search_series_tab_init(self):
        def populate_shows(shows):
            self.resultList.clear()
            for show in shows:
                show_row = QTreeWidgetItem(self.resultList)
                show_row.setText(0, show.SeriesName)
                for season in show:
                    season_row = QTreeWidgetItem(show_row)
                    if season.season_number == 0:
                        season_row.setText(0, 'Special')
                    else:
                        season_row.setText(0, 'Season {:02d}'.format(season.season_number))
                    season_row.setData(0, Qt.UserRole + 1, season)
                    show_row.addChild(season_row)
                    for episode in season:
                        episode_row = QTreeWidgetItem(season_row)
                        episode_row.setText(0, '{:02d} - {}'.format(episode.EpisodeNumber, episode.EpisodeName))
                        episode_row.setData(0, Qt.UserRole + 1, episode)
                        season_row.addChild(episode_row)
                self.resultList.addTopLevelItem(show_row)
                if len(shows) == 1:
                    self.resultList.expandItem(self.resultList.topLevelItem(0))

        def populate_torrents(item, torrents):
            for torrent in torrents:
                row = QTreeWidgetItem(item)
                row.setText(0, '{} : {}'.format(torrent.title, torrent.seeders))
                row.setData(0, Qt.UserRole + 1, torrent)
                item.addChild(row)

        def launch_download(item, completion_callback=None, play_callback=None):
            torrent = item.data(0, Qt.UserRole + 1)
            if not hasattr(torrent, 'title'):
                return
            print('[INFO] Starting downloading')
            self.instance.download(torrent, completion_callback, play_callback)

        def get_shows_results():
            def done(shows):
                self.progress.restore()
                populate_shows(shows)

            self.progress.indeterminate()
            self.instance.search(self.searchField.text(), done)

        def get_torrents_results(item):
            def done(torrents):
                self.progress.restore()
                populate_torrents(item, torrents)
                self.resultList.expandItem(item)

            episode = item.data(0, Qt.UserRole + 1)
            if not hasattr(episode, 'season'):
                return
            self.progress.indeterminate()
            self.instance.search_episode(episode, done)

        def open_menu(position):
            def trigger_play():
                item = self.resultList.selectedItems()[0]
                launch_download(item, None, self.instance.open_player)

            def trigger_download():
                item = self.resultList.selectedItems()[0]
                launch_download(item, None, None)

            def trigger_load():
                item = self.resultList.selectedItems()[0]
                get_torrents_results(item)

            indexes = self.resultList.selectedIndexes()
            level = 0
            if len(indexes) > 0:
                index = indexes[0]
                while index.parent().isValid():
                    index = index.parent()
                    level += 1
            menu = QMenu()
            if level == 2:
                load_action = QAction("Load torrents", self)
                load_action.triggered.connect(trigger_load)
                menu.addAction(load_action)
            elif level == 3:
                play_action = QAction("Play", self)
                play_action.triggered.connect(trigger_play)
                menu.addAction(play_action)
                download_action = QAction("Download", self)
                download_action.triggered.connect(trigger_download)
                menu.addAction(download_action)
            menu.exec_(self.resultList.viewport().mapToGlobal(position))

        self.searchField.returnPressed.connect(get_shows_results)
        QTimer.singleShot(0, self.searchField.setFocus)

        self.searchButton.clicked.connect(get_shows_results)

        self.resultList.header().close()
        self.resultList.itemClicked.connect(get_torrents_results)
        self.resultList.itemDoubleClicked.connect(launch_download)
        self.resultList.setContextMenuPolicy(Qt.CustomContextMenu)
        self.resultList.customContextMenuRequested.connect(open_menu)

    def settings_tab_init(self):
        def text_item(node, key, data_type):
            def update(u_value):
                self.instance.settings.set(key, data_type(u_value))

            value = self.instance.settings.get(key)
            if value is not None:
                node.setText(str(value))
            node.textChanged.connect(update)

        def numeric_item(node, key):
            def update(u_value):
                self.instance.settings.set(key, float(u_value))

            value = self.instance.settings.get(key)
            if value is not None:
                node.setValue(float(value))
            node.valueChanged.connect(update)

        def check_item(node, key):
            def update(u_value):
                u_value = True if u_value == Qt.Checked else False
                self.instance.settings.set(key, u_value)

            value = self.instance.settings.get(key)
            if value is not None and value is True:
                node.setCheckState(Qt.Checked)
            node.stateChanged.connect(update)

        def combo_item(node, key):
            def update(u_value):
                self.instance.settings.set(key, str(u_value))

            value = self.instance.settings.get(key)
            if value is not None:
                idx = node.findText(value)
                if idx > -1:
                    node.setCurrentIndex(idx)
            node.currentIndexChanged.connect(update)

        text_item(self.launchCommandValue, "player_path", str)
        text_item(self.savePathValue, "save_path", str)
        combo_item(self.subtitlesLanguageValue, "subtitle_language")
        text_item(self.tpbUrlValue, "tpb_base_url", str)
        text_item(self.tvdbApiKeyValue, "tvdb_api_key", str)
        numeric_item(self.speedLimitValue, "download_speed_limit")
        numeric_item(self.launchAfterValue, "launch_video_percent")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ztshows = ZTShows()
    window = MainWindow(ztshows)
    window.show()
    sys.exit(app.exec_())


text:
/* jshint esnext: true */
/* jslint node: true */

module.exports = ()=> {
    var winston = require('winston');
    winston.emitErrs = true;

    var logger = new winston.Logger({
        transports: [
            /*new winston.transports.File({
             level: 'info',
             filename: './log/chirp-all-logs.log',
             handleExceptions: true,
             json: true,
             maxsize: 5242880, //5MB
             maxFiles: 5,
             colorize: false
             }),*/
            new winston.transports.Console({
                level: 'debug',
                handleExceptions: false,
                json: false,
                colorize: true,
                timestamp: true
            })
        ],
        exitOnError: false
    });

    logger.stream = {
        write: (message, encoding)=> {
            logger.info(message);
        }
    };

    return logger;
};


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

// bthread - A M:N threading library to make applications more concurrent.

// Date: 2016/04/16 18:43:24

#include "bthread/execution_queue.h"

#include "butil/memory/singleton_on_pthread_once.h"
#include "butil/object_pool.h"           // butil::get_object
#include "butil/resource_pool.h"         // butil::get_resource

namespace bthread {

//May be false on different platforms
//BAIDU_CASSERT(sizeof(TaskNode) == 128, sizeof_TaskNode_must_be_128);
//BAIDU_CASSERT(offsetof(TaskNode, static_task_mem) + sizeof(TaskNode().static_task_mem) == 128, sizeof_TaskNode_must_be_128);
BAIDU_CASSERT(sizeof(ExecutionQueue<int>) == sizeof(ExecutionQueueBase),
              sizeof_ExecutionQueue_must_be_the_same_with_ExecutionQueueBase);
BAIDU_CASSERT(sizeof(TaskIterator<int>) == sizeof(TaskIteratorBase),
              sizeof_TaskIterator_must_be_the_same_with_TaskIteratorBase);
namespace /*anonymous*/ {
typedef butil::ResourceId<ExecutionQueueBase> slot_id_t;

inline slot_id_t WARN_UNUSED_RESULT slot_of_id(uint64_t id) {
    slot_id_t slot = { (id & 0xFFFFFFFFul) };
    return slot;
}

inline uint64_t make_id(uint32_t version, slot_id_t slot) {
    return (((uint64_t)version) << 32) | slot.value;
}
}  // namespace anonymous

struct ExecutionQueueVars {
    bvar::Adder<int64_t> running_task_count;
    bvar::Adder<int64_t> execq_count;
    bvar::Adder<int64_t> execq_active_count;

    ExecutionQueueVars();
};

ExecutionQueueVars::ExecutionQueueVars()
    : running_task_count("bthread_execq_running_task_count")
    , execq_count("bthread_execq_count")
    , execq_active_count("bthread_execq_active_count") {
}

inline ExecutionQueueVars* get_execq_vars() {
    return butil::get_leaky_singleton<ExecutionQueueVars>();
}

void ExecutionQueueBase::start_execute(TaskNode* node) {
    node->next = TaskNode::UNCONNECTED;
    node->status = UNEXECUTED;
    node->iterated = false;
    if (node->high_priority) {
        // Add _high_priority_tasks before pushing this task into queue to
        // make sure that _execute_tasks sees the newest number when this
        // task is in the queue. Althouth there might be some useless for
        // loops in _execute_tasks if this thread is scheduled out at this
        // point, we think it's just fine.
        _high_priority_tasks.fetch_add(1, butil::memory_order_relaxed);
    }
    TaskNode* const prev_head = _head.exchange(node, butil::memory_order_release);
    if (prev_head != NULL) {
        node->next = prev_head;
        return;
    }
    // Get the right to execute the task, start a bthread to avoid deadlock
    // or stack overflow
    node->next = NULL;
    node->q = this;

    ExecutionQueueVars* const vars = get_execq_vars();
    vars->execq_active_count << 1;
    if (node->in_place) {
        int niterated = 0;
        _execute(node, node->high_priority, &niterated);
        TaskNode* tmp = node;
        // return if no more
        if (node->high_priority) {
            _high_priority_tasks.fetch_sub(niterated, butil::memory_order_relaxed);
        }
        if (!_more_tasks(tmp, &tmp, !node->iterated)) {
            vars->execq_active_count << -1;
            return_task_node(node);
            return;
        }
    }

    if (nullptr == _options.executor) {
        bthread_t tid;
        // We start the execution thread in background instead of foreground as
        // we can't determine whether the code after execute() is urgent (like
        // unlock a pthread_mutex_t) in which case implicit context switch may
        // cause undefined behavior (e.g. deadlock)
        if (bthread_start_background(&tid, &_options.bthread_attr,
                                     _execute_tasks, node) != 0) {
            PLOG(FATAL) << "Fail to start bthread";
            _execute_tasks(node);
        }
    } else {
        if (_options.executor->submit(_execute_tasks, node) != 0) {
            PLOG(FATAL) << "Fail to submit task";
            _execute_tasks(node);
        }
    }
}

void* ExecutionQueueBase::_execute_tasks(void* arg) {
    ExecutionQueueVars* vars = get_execq_vars();
    TaskNode* head = (TaskNode*)arg;
    ExecutionQueueBase* m = (ExecutionQueueBase*)head->q;
    TaskNode* cur_tail = NULL;
    bool destroy_queue = false;
    for (;;) {
        if (head->iterated) {
            CHECK(head->next != NULL);
            TaskNode* saved_head = head;
            head = head->next;
            m->return_task_node(saved_head);
        }
        int rc = 0;
        if (m->_high_priority_tasks.load(butil::memory_order_relaxed) > 0) {
            int nexecuted = 0;
            // Don't care the return value
            rc = m->_execute(head, true, &nexecuted);
            m->_high_priority_tasks.fetch_sub(
                    nexecuted, butil::memory_order_relaxed);
            if (nexecuted == 0) {
                // Some high_priority tasks are not in queue
                sched_yield();
            }
        } else {
            rc = m->_execute(head, false, NULL);
        }
        if (rc == ESTOP) {
            destroy_queue = true;
        }
        // Release TaskNode until uniterated task or last task
        while (head->next != NULL && head->iterated) {
            TaskNode* saved_head = head;
            head = head->next;
            m->return_task_node(saved_head);
        }
        if (cur_tail == NULL) {
            for (cur_tail = head; cur_tail->next != NULL;
                    cur_tail = cur_tail->next) {}
        }
        // break when no more tasks and head has been executed
        if (!m->_more_tasks(cur_tail, &cur_tail, !head->iterated)) {
            CHECK_EQ(cur_tail, head);
            CHECK(head->iterated);
            m->return_task_node(head);
            break;
        }
    }
    if (destroy_queue) {
        CHECK(m->_head.load(butil::memory_order_relaxed) == NULL);
        CHECK(m->_stopped);
        // Add _join_butex by 2 to make it equal to the next version of the
        // ExecutionQueue from the same slot so that join with old id would
        // return immediatly.
        //
        // 1: release fence to make join sees the newst changes when it sees
        //    the newst _join_butex
        m->_join_butex->fetch_add(2, butil::memory_order_release/*1*/);
        butex_wake_all(m->_join_butex);
        vars->execq_count << -1;
        butil::return_resource(slot_of_id(m->_this_id));
    }
    vars->execq_active_count << -1;
    return NULL;
}

void ExecutionQueueBase::return_task_node(TaskNode* node) {
    node->clear_before_return(_clear_func);
    butil::return_object<TaskNode>(node);
    get_execq_vars()->running_task_count << -1;
}

void ExecutionQueueBase::_on_recycle() {
    // Push a closed tasks
    while (true) {
        TaskNode* node = butil::get_object<TaskNode>();
        if (BAIDU_LIKELY(node != NULL)) {
            get_execq_vars()->running_task_count << 1;
            node->stop_task = true;
            node->high_priority = false;
            node->in_place = false;
            start_execute(node);
            break;
        }
        CHECK(false) << "Fail to create task_node_t, " << berror();
        ::bthread_usleep(1000);
    }
}

int ExecutionQueueBase::join(uint64_t id) {
    const slot_id_t slot = slot_of_id(id);
    ExecutionQueueBase* const m = butil::address_resource(slot);
    if (m == NULL) {
        // The queue is not created yet, this join is definitely wrong.
        return EINVAL;
    }
    int expected = _version_of_id(id);
    // acquire fence makes this thread see changes before changing _join_butex.
    while (expected == m->_join_butex->load(butil::memory_order_acquire)) {
        if (butex_wait(m->_join_butex, expected, NULL) < 0 &&
            errno != EWOULDBLOCK && errno != EINTR) {
            return errno;
        }
    }
    return 0;
}

int ExecutionQueueBase::stop() {
    const uint32_t id_ver = _version_of_id(_this_id);
    uint64_t vref = _versioned_ref.load(butil::memory_order_relaxed);
    for (;;) {
        if (_version_of_vref(vref) != id_ver) {
            return EINVAL;
        }
        // Try to set version=id_ver+1 (to make later address() return NULL),
        // retry on fail.
        if (_versioned_ref.compare_exchange_strong(
                    vref, _make_vref(id_ver + 1, _ref_of_vref(vref)),
                    butil::memory_order_release,
                    butil::memory_order_relaxed)) {
            // Set _stopped to make lattern execute() fail immediately
            _stopped.store(true, butil::memory_order_release);
            // Deref additionally which is added at creation so that this
            // queue's reference will hit 0(recycle) when no one addresses it.
            _release_additional_reference();
            // NOTE: This queue may be recycled at this point, don't
            // touch anything.
            return 0;
        }
    }
}

int ExecutionQueueBase::_execute(TaskNode* head, bool high_priority, int* niterated) {
    if (head != NULL && head->stop_task) {
        CHECK(head->next == NULL);
        head->iterated = true;
        head->status = EXECUTED;
        TaskIteratorBase iter(NULL, this, true, false);
        _execute_func(_meta, _type_specific_function, iter);
        if (niterated) {
            *niterated = 1;
        }
        return ESTOP;
    }
    TaskIteratorBase iter(head, this, false, high_priority);
    if (iter) {
        _execute_func(_meta, _type_specific_function, iter);
    }
    // We must assign |niterated| with num_iterated even if we couldn't peek
    // any task to execute at the begining, in which case all the iterated
    // tasks have been cancelled at this point. And we must return the
    // correct num_iterated() to the caller to update the counter correctly.
    if (niterated) {
        *niterated = iter.num_iterated();
    }
    return 0;
}

TaskNode* ExecutionQueueBase::allocate_node() {
    get_execq_vars()->running_task_count << 1;
    return butil::get_object<TaskNode>();
}

TaskNode* const TaskNode::UNCONNECTED = (TaskNode*)-1L;

ExecutionQueueBase::scoped_ptr_t ExecutionQueueBase::address(uint64_t id) {
    scoped_ptr_t ret;
    const slot_id_t slot = slot_of_id(id);
    ExecutionQueueBase* const m = butil::address_resource(slot);
    if (BAIDU_LIKELY(m != NULL)) {
        // acquire fence makes sure this thread sees latest changes before
        // _dereference()
        const uint64_t vref1 = m->_versioned_ref.fetch_add(
            1, butil::memory_order_acquire);
        const uint32_t ver1 = _version_of_vref(vref1);
        if (ver1 == _version_of_id(id)) {
            ret.reset(m);
            return ret.Pass();
        }

        const uint64_t vref2 = m->_versioned_ref.fetch_sub(
            1, butil::memory_order_release);
        const int32_t nref = _ref_of_vref(vref2);
        if (nref > 1) {
            return ret.Pass();
        } else if (__builtin_expect(nref == 1, 1)) {
            const uint32_t ver2 = _version_of_vref(vref2);
            if ((ver2 & 1)) {
                if (ver1 == ver2 || ver1 + 1 == ver2) {
                    uint64_t expected_vref = vref2 - 1;
                    if (m->_versioned_ref.compare_exchange_strong(
                            expected_vref, _make_vref(ver2 + 1, 0),
                            butil::memory_order_acquire,
                            butil::memory_order_relaxed)) {
                        m->_on_recycle();
                        // We don't return m immediatly when the reference count
                        // reaches 0 as there might be in processing tasks. Instead
                        // _on_recycle would push a `stop_task', after which
                        // is excuted m would be finally reset and returned
                    }
                } else {
                    CHECK(false) << "ref-version=" << ver1
                                 << " unref-version=" << ver2;
                }
            } else {
                CHECK_EQ(ver1, ver2);
                // Addressed a free slot.
            }
        } else {
            CHECK(false) << "Over dereferenced id=" << id;
        }
    }
    return ret.Pass();
}

int ExecutionQueueBase::create(uint64_t* id, const ExecutionQueueOptions* options,
                               execute_func_t execute_func,
                               clear_task_mem clear_func,
                               void* meta, void* type_specific_function) {
    if (execute_func == NULL || clear_func == NULL) {
        return EINVAL;
    }

    slot_id_t slot;
    ExecutionQueueBase* const m = butil::get_resource(&slot, Forbidden());
    if (BAIDU_LIKELY(m != NULL)) {
        m->_execute_func = execute_func;
        m->_clear_func = clear_func;
        m->_meta = meta;
        m->_type_specific_function = type_specific_function;
        CHECK(m->_head.load(butil::memory_order_relaxed) == NULL);
        CHECK_EQ(0, m->_high_priority_tasks.load(butil::memory_order_relaxed));
        ExecutionQueueOptions opt;
        if (options != NULL) {
            opt = *options;
        }
        m->_options = opt;
        m->_stopped.store(false, butil::memory_order_relaxed);
        m->_this_id = make_id(
                _version_of_vref(m->_versioned_ref.fetch_add(
                                    1, butil::memory_order_release)), slot);
        *id = m->_this_id;
        get_execq_vars()->execq_count << 1;
        return 0;
    }
    return ENOMEM;
}

inline bool TaskIteratorBase::should_break_for_high_priority_tasks() {
    if (!_high_priority &&
            _q->_high_priority_tasks.load(butil::memory_order_relaxed) > 0) {
        _should_break = true;
        return true;
    }
    return false;
}

void TaskIteratorBase::operator++() {
    if (!(*this)) {
        return;
    }
    if (_cur_node->iterated) {
        _cur_node = _cur_node->next;
    }
    if (should_break_for_high_priority_tasks()) {
        return;
    }  // else the next high_priority_task would be delayed for at most one task

    while (_cur_node && !_cur_node->stop_task) {
        if (_high_priority == _cur_node->high_priority) {
            if (!_cur_node->iterated && _cur_node->peek_to_execute()) {
                ++_num_iterated;
                _cur_node->iterated = true;
                return;
            }
            _num_iterated += !_cur_node->iterated;
            _cur_node->iterated = true;
        }
        _cur_node = _cur_node->next;
    }
    return;
}

TaskIteratorBase::~TaskIteratorBase() {
    // Set the iterated tasks as EXECUTED here instead of waiting them to be
    // returned in _start_execute as the high_priority_task might be in the
    // middle of the linked list and is not going to be returned soon
    if (_is_stopped) {
        return;
    }
    while (_head != _cur_node) {
        if (_head->iterated && _head->high_priority == _high_priority) {
            _head->set_executed();
        }
        _head = _head->next;
    }
    if (_should_break && _cur_node != NULL
            && _cur_node->high_priority == _high_priority && _cur_node->iterated) {
        _cur_node->set_executed();
    }
}

} // namespace bthread


text:
"""
Unit tests for ABCPRC module
Created on Fri Apr  1 16:08:31 2016

@author: u1472179
"""

from nose import with_setup
from nose.tools import *
import ABCPRC as prc

def setup():
    pass

def tear_down():
    pass

def test_load_package():
    import ABCPRC

@with_setup(setup)
def test_data_import():
    m = prc.ABC()
    assert (m.parameters.xs.size > 0)

@with_setup(setup)
@raises(NameError)
def test_run_before_trace():
    m = prc.ABC()
    m.trace()

@raises(NameError)
def test_run_before_paramMAP():
    m = prc.ABC()
    m.paramMAP()

@raises(NameError)
def test_run_before_fitSummary():
    m = prc.ABC()
    m.fitSummary()


text:
<ng-sidebar-container style="height:100vh" [animate]="true">

      <command-bar>
        <command [displayText]="'refresh' | translate"
          (click)="refresh()"
          iconUrl="image/reset.svg"></command>
      </command-bar>

      <info-box
        *ngIf="showDelayWarning"
        typeClass="info"
        [infoText]="'appInsightsDelay' | translate"
        dismissable=true,
        [dismissId]="componentId">
      </info-box>

            {{ 'appInsightsInstance' | translate }}

                  {{applicationInsightsInstanceName}}

            {{ 'functionMonitor_successAggregate_30days' | translate }}

                  {{successCount}}

            {{ 'functionMonitor_errorsAggregate_30days' | translate }}

                  {{errorsCount}}

            {{appInsightsQueryReturnedTitle}}

                  {{'runInAppInsights' | translate}}

            {{'troubleshootYourApp' | translate}}

                  {{'diagnoseAndSolveProblems' | translate}}

          <tbl *ngIf="invocationTraces.length > 0" [items]="invocationTraces" #table="tbl" [name]="'invocationTraces' | translate">

                <tbl-th name="timestampFriendly">{{ 'date' | translate }}</tbl-th>
                <tbl-th name="success">{{ 'success' | translate }}</tbl-th>
                <tbl-th name="resultCode">{{ 'resultCode' | translate }}</tbl-th>
                <tbl-th name="duration">{{ 'duration' | translate }}</tbl-th>
                <tbl-th name="operationId">{{ 'operationId' | translate }}</tbl-th>

                {{trace.timestampFriendly}}

                {{trace.resultCode}}
                {{trace.duration}}
                {{trace.operationId}}

          </tbl>

          <tbl *ngIf="invocationTraces.length === 0" [items]="invocationTraces" #table="tbl" [name]="'invocationTraces' | translate">

                {{ 'date' | translate }}
                {{ 'success' | translate }}
                {{ 'resultCode' | translate }}
                {{ 'duration' | translate }}
                {{ 'operationId' | translate }}

                {{'functionMonitor_loading' | translate}}
                {{'noResults' | translate}}

          </tbl>

    <ng-sidebar #sidebar [(opened)]="sidePanelOpened"
      [mode]="'over'"
      [position]="'right'"
      [closeOnClickOutside]="false"
      [trapFocus]="false"
      [autoFocus]="true"
      [sidebarClass]="'sidebar-monitor-details'"
      [ariaLabel]="'Trace Details'"
      [animate]="true"
      [closeOnClickBackdrop]="false"
      [showBackdrop]="false">

      <monitor-details *ngIf="sidePanelOpened" [monitorDetailsInfoInput]="monitorDetailsInfo" (closePanel)="closeSidePanel()">
      </monitor-details>

    </ng-sidebar>
</ng-sidebar-container>